Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat: add support to notify connectors (#12502)
Akshaya Shankar96a4e857e259
diff --git a/Cargo.lock b/Cargo.lockindex 6438d3c95a..d7aa909579 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2264,7 +2264,7 @@ dependencies = [[[package]]name = "config_patch_derive"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?tag=2026.06.23.1#2a748b69578e5d61c4586b30aabddad0ed7fd88a"+source = "git+https://github.com/juspay/connector-service?tag=2026.06.24.0#cd7b17474c6c6be70f8be9a493c34bb98d8557bb"dependencies = ["proc-macro2","quote",@@ -3981,7 +3981,7 @@ checksum = "32619942b8be646939eaf3db0602b39f5229b74575b67efc897811ded1db4e57"[[package]]name = "grpc-api-types"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?tag=2026.06.23.1#2a748b69578e5d61c4586b30aabddad0ed7fd88a"+source = "git+https://github.com/juspay/connector-service?tag=2026.06.24.0#cd7b17474c6c6be70f8be9a493c34bb98d8557bb"dependencies = ["axum 0.8.4","bytes 1.10.1",@@ -8176,7 +8176,7 @@ dependencies = [[[package]]name = "rust-grpc-client"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?tag=2026.06.23.1#2a748b69578e5d61c4586b30aabddad0ed7fd88a"+source = "git+https://github.com/juspay/connector-service?tag=2026.06.24.0#cd7b17474c6c6be70f8be9a493c34bb98d8557bb"dependencies = ["grpc-api-types",]@@ -11010,7 +11010,7 @@ checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9"[[package]]name = "ucs_cards"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?tag=2026.06.23.1#2a748b69578e5d61c4586b30aabddad0ed7fd88a"+source = "git+https://github.com/juspay/connector-service?tag=2026.06.24.0#cd7b17474c6c6be70f8be9a493c34bb98d8557bb"dependencies = ["bytes 1.10.1","error-stack 0.4.1",@@ -11026,7 +11026,7 @@ dependencies = [[[package]]name = "ucs_common_enums"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?tag=2026.06.23.1#2a748b69578e5d61c4586b30aabddad0ed7fd88a"+source = "git+https://github.com/juspay/connector-service?tag=2026.06.24.0#cd7b17474c6c6be70f8be9a493c34bb98d8557bb"dependencies = ["serde","strum 0.26.3",@@ -11037,7 +11037,7 @@ dependencies = [[[package]]name = "ucs_common_utils"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?tag=2026.06.23.1#2a748b69578e5d61c4586b30aabddad0ed7fd88a"+source = "git+https://github.com/juspay/connector-service?tag=2026.06.24.0#cd7b17474c6c6be70f8be9a493c34bb98d8557bb"dependencies = ["anyhow","base64 0.21.7",diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex 4dd2239a9d..3de4553942 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -21347,7 +21347,9 @@"payout_cancelled","payout_expired","payout_reversed",- "invoice_paid"+ "invoice_paid",+ "surcharge_payment_succeeded",+ "surcharge_refund_succeeded"]},"EvidenceType": {diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex 8827b34619..deaa302f46 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -14240,7 +14240,9 @@"payout_cancelled","payout_expired","payout_reversed",- "invoice_paid"+ "invoice_paid",+ "surcharge_payment_succeeded",+ "surcharge_refund_succeeded"]},"ExemptionIndicator": {diff --git a/config/superposition_seed.toml b/config/superposition_seed.tomlindex 77ab7aa316..e6f0f9243c 100644--- a/config/superposition_seed.toml+++ b/config/superposition_seed.toml@@ -218,6 +218,15 @@ change_reason = "Initial setup"start_after = 60frequencies = [[300, 2], [600, 5], [3600, 5], [21600, 3]]+[default-configs.pt_mapping_outgoing_connector_webhooks]+schema = { type = "object" }+description = "Outgoing connector webhook retry process tracker mapping configuration"+change_reason = "Initial setup"++[default-configs.pt_mapping_outgoing_connector_webhooks.value.default_mapping]+start_after = 60+frequencies = [[300, 2], [600, 5], [3600, 5], [21600, 3]]+[default-configs.pt_mapping_pcr_retries]schema = { type = "object" }description = "Revenue recovery (PCR) payment retry process tracker mapping configuration"diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rsindex d1574efccc..6d05f3abdf 100644--- a/crates/api_models/src/enums.rs+++ b/crates/api_models/src/enums.rs@@ -228,6 +228,20 @@ pub enum SurchargeConnectors {Interpayments,}+impl SurchargeConnectors {+ pub fn should_notify_connector(&self, primary_event: EventType) -> bool {+ match primary_event {+ EventType::PaymentSucceeded => {+ matches!(self, Self::Interpayments)+ }+ EventType::RefundSucceeded => {+ matches!(self, Self::Interpayments)+ }+ _ => false,+ }+ }+}+pub fn convert_surcharge_connector(connector_name: &str) -> Option<SurchargeConnectors> {SurchargeConnectors::from_str(connector_name).ok()}diff --git a/crates/api_models/src/webhook_events.rs b/crates/api_models/src/webhook_events.rsindex f7878b1693..538836df96 100644--- a/crates/api_models/src/webhook_events.rs+++ b/crates/api_models/src/webhook_events.rs@@ -156,7 +156,7 @@ impl common_utils::events::ApiEventMetric for EventRetrieveResponse {}/// The request information (headers and body) sent in the webhook.-#[derive(Debug, Serialize, Deserialize, ToSchema)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub struct OutgoingWebhookRequestContent {/// The request body sent in the webhook.#[schema(value_type = String)]@@ -172,7 +172,7 @@ pub struct OutgoingWebhookRequestContent {}/// The response information (headers, body and status code) received for the webhook sent.-#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]pub struct OutgoingWebhookResponseContent {/// The response body received for the webhook sent.#[schema(value_type = Option<String>)]diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex d2cef5d367..de117c69b2 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -1750,6 +1750,25 @@ impl Currency {}}+#[derive(+ Clone,+ Copy,+ Debug,+ Eq,+ PartialEq,+ serde::Deserialize,+ serde::Serialize,+ strum::Display,+ strum::EnumString,+)]+#[router_derive::diesel_enum(storage_type = "text")]+#[serde(rename_all = "snake_case")]+#[strum(serialize_all = "snake_case")]+pub enum EventRecipient {+ Merchant,+ Connector,+}+#[derive(Clone,Copy,@@ -1813,8 +1832,13 @@ impl EventClass {EventType::PaymentCaptured,EventType::PaymentExpired,EventType::ActionRequired,+ EventType::SurchargePaymentSucceeded,+ ]),+ Self::Refunds => HashSet::from([+ EventType::RefundSucceeded,+ EventType::RefundFailed,+ EventType::SurchargeRefundSucceeded,]),- Self::Refunds => HashSet::from([EventType::RefundSucceeded, EventType::RefundFailed]),Self::Disputes => HashSet::from([EventType::DisputeOpened,EventType::DisputeExpired,@@ -1896,6 +1920,24 @@ pub enum EventType {#[cfg(feature = "payouts")]PayoutReversed,InvoicePaid,+ SurchargePaymentSucceeded,+ SurchargeRefundSucceeded,+}++/// Maps primary payment/refund events to their corresponding surcharge events+pub trait SurchargeEventMapper {+ /// Returns the surcharge event type corresponding to this primary event+ fn to_surcharge_event(&self) -> Option<EventType>;+}++impl SurchargeEventMapper for EventType {+ fn to_surcharge_event(&self) -> Option<Self> {+ match self {+ Self::PaymentSucceeded => Some(Self::SurchargePaymentSucceeded),+ Self::RefundSucceeded => Some(Self::SurchargeRefundSucceeded),+ _ => None,+ }+ }}#[derive(diff --git a/crates/common_utils/src/id_type/merchant_connector_account.rs b/crates/common_utils/src/id_type/merchant_connector_account.rsindex df8d1c3b3a..d3255bf7a9 100644--- a/crates/common_utils/src/id_type/merchant_connector_account.rs+++ b/crates/common_utils/src/id_type/merchant_connector_account.rs@@ -31,3 +31,10 @@ impl FromStr for MerchantConnectorAccountId {Self::try_from(std::borrow::Cow::Owned(s.to_string())).map_err(|_| std::fmt::Error)}}++#[cfg(feature = "metrics")]+impl From<MerchantConnectorAccountId> for router_env::opentelemetry::Value {+ fn from(val: MerchantConnectorAccountId) -> Self {+ Self::from(val.0 .0 .0)+ }+}diff --git a/crates/diesel_models/src/events.rs b/crates/diesel_models/src/events.rsindex 305a276a63..c7b7ab33c3 100644--- a/crates/diesel_models/src/events.rs+++ b/crates/diesel_models/src/events.rs@@ -29,6 +29,7 @@ pub struct EventNew {pub is_overall_delivery_successful: Option<bool>,pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,pub initiator_merchant_id: Option<common_utils::id_type::MerchantId>,+ pub recipient: Option<storage_enums::EventRecipient>,}#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]@@ -64,6 +65,7 @@ pub struct Event {pub is_overall_delivery_successful: Option<bool>,pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,pub initiator_merchant_id: Option<common_utils::id_type::MerchantId>,+ pub recipient: Option<storage_enums::EventRecipient>,}#[derive(Clone, Debug, Deserialize, Serialize, AsExpression, diesel::FromSqlRow)]@@ -111,6 +113,11 @@ pub enum EventMetadata {invoice_id: Option<common_utils::id_type::InvoiceId>,payment_id: Option<common_utils::id_type::PaymentId>,},+ #[cfg(feature = "v1")]+ Surcharge {+ payment_id: common_utils::id_type::PaymentId,+ attempt_id: String,+ },}common_utils::impl_to_sql_from_sql_json!(EventMetadata);diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rsindex f534c2936f..4daf45f0c6 100644--- a/crates/diesel_models/src/payment_attempt.rs+++ b/crates/diesel_models/src/payment_attempt.rs@@ -812,6 +812,10 @@ pub enum PaymentAttemptUpdate {updated_by: String,connector_mandate_detail: Option<ConnectorMandateReferenceId>,},+ ExternalSurchargeUpdate {+ external_surcharge_details: common_types::payments::ExternalSurchargeDetails,+ updated_by: String,+ },}#[cfg(feature = "v2")]@@ -4397,6 +4401,85 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {sender_payment_instrument_id: None,external_surcharge_details: None,},+ PaymentAttemptUpdate::ExternalSurchargeUpdate {+ updated_by,+ external_surcharge_details,+ } => Self {+ status: None,+ error_code: None,+ modified_at: common_utils::date_time::now(),+ error_message: None,+ error_reason: None,+ updated_by,+ unified_code: None,+ unified_message: None,+ amount: None,+ net_amount: None,+ currency: None,+ connector_transaction_id: None,+ amount_to_capture: None,+ connector: None,+ authentication_type: None,+ payment_method: None,+ payment_method_id: None,+ cancellation_reason: None,+ mandate_id: None,+ browser_info: None,+ payment_token: None,+ connector_metadata: None,+ payment_method_data: None,+ payment_method_type: None,+ payment_experience: None,+ business_sub_label: None,+ straight_through_algorithm: None,+ preprocessing_step_id: None,+ capture_method: None,+ connector_response_reference_id: None,+ multiple_capture_count: None,+ surcharge_amount: None,+ tax_amount: None,+ amount_capturable: None,+ merchant_connector_id: None,+ authentication_data: None,+ encoded_data: None,+ external_three_ds_authentication_attempted: None,+ authentication_connector: None,+ authentication_id: None,+ fingerprint_id: None,+ payment_method_billing_address_id: None,+ client_source: None,+ client_version: None,+ customer_acceptance: None,+ card_network: None,+ shipping_cost: None,+ order_tax_amount: None,+ capture_before: None,+ extended_authorization_applied: None,+ extended_authorization_last_applied_at: None,+ tokenization: None,+ processor_transaction_data: None,+ connector_mandate_detail: None,+ card_discovery: None,+ charges: None,+ issuer_error_code: None,+ issuer_error_message: None,+ setup_future_usage_applied: None,+ routing_approach: None,+ connector_request_reference_id: None,+ network_transaction_id: None,+ network_transaction_link_id: None,+ is_overcapture_enabled: None,+ network_details: None,+ is_stored_credential: None,+ request_extended_authorization: None,+ authorized_amount: None,+ installment_data: None,+ encrypted_payment_method_data: None,+ error_details: None,+ sender_payment_instrument_id: None,+ external_surcharge_details: Some(external_surcharge_details),+ external_threeds_authentication_type: None,+ },}}}diff --git a/crates/diesel_models/src/query/events.rs b/crates/diesel_models/src/query/events.rsindex 173d57a9e3..e0e288b26e 100644--- a/crates/diesel_models/src/query/events.rs+++ b/crates/diesel_models/src/query/events.rs@@ -88,19 +88,29 @@ impl Event {conn: &PgPooledConn,merchant_id: &common_utils::id_type::MerchantId,primary_object_id: &str,+ event_recipient: Option<common_enums::EventRecipient>,) -> StorageResult<Vec<Self>> {- generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(- conn,- dsl::event_id- .nullable()- .eq(dsl::initial_attempt_id) // Filter initial attempts only- .and(dsl::merchant_id.eq(merchant_id.to_owned()))- .and(dsl::primary_object_id.eq(primary_object_id.to_owned())),- None,- None,- Some(dsl::created_at.desc()),- )- .await+ let mut query = Self::table()+ .filter(+ dsl::event_id+ .nullable()+ .eq(dsl::initial_attempt_id) // Filter initial attempts only+ .and(dsl::merchant_id.eq(merchant_id.to_owned()))+ .and(dsl::primary_object_id.eq(primary_object_id.to_owned())),+ )+ .order(dsl::created_at.desc())+ .into_boxed();++ if let Some(recipient) = event_recipient {+ query = query.filter(dsl::recipient.eq(recipient.to_string()));+ };++ logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());++ track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)+ .await+ .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found+ .attach_printable("Error filtering events by constraints")}pub async fn find_initial_attempt_by_merchant_id_initial_attempt_id(@@ -134,6 +144,7 @@ impl Event {offset: Option<i64>,event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,+ event_recipient: Option<common_enums::EventRecipient>,) -> StorageResult<Vec<Self>> {let mut query = Self::table().filter(@@ -153,6 +164,7 @@ impl Event {offset,event_types,is_delivered,+ event_recipient,);logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());@@ -167,17 +179,27 @@ impl Event {conn: &PgPooledConn,merchant_id: &common_utils::id_type::MerchantId,initial_attempt_id: &str,+ event_recipient: Option<common_enums::EventRecipient>,) -> StorageResult<Vec<Self>> {- generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(- conn,- dsl::merchant_id- .eq(merchant_id.to_owned())- .and(dsl::initial_attempt_id.eq(initial_attempt_id.to_owned())),- None,- None,- Some(dsl::created_at.desc()),- )- .await+ let mut query = Self::table()+ .filter(+ dsl::merchant_id+ .eq(merchant_id.to_owned())+ .and(dsl::initial_attempt_id.eq(initial_attempt_id.to_owned())),+ )+ .order(dsl::created_at.desc())+ .into_boxed();++ if let Some(recipient) = event_recipient {+ query = query.filter(dsl::recipient.eq(recipient.to_string()));+ };++ logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());++ track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)+ .await+ .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found+ .attach_printable("Error filtering events by constraints")}pub async fn list_initial_attempts_by_initiator_merchant_id_primary_object_id(@@ -185,6 +207,7 @@ impl Event {initiator_merchant_id: &common_utils::id_type::MerchantId,primary_object_id: &str,profile_id: Option<common_utils::id_type::ProfileId>,+ recipient: Option<common_enums::EventRecipient>,) -> StorageResult<Vec<Self>> {// Fallback on merchant_id for rows with NULL initiator_merchant_id to// handle events created during staggered rollout by older code. This@@ -207,6 +230,10 @@ impl Event {.order(dsl::created_at.desc()).into_boxed();+ if let Some(recipient) = recipient {+ query = query.filter(dsl::recipient.eq(recipient.to_string()));+ }+if let Some(profile_id) = profile_id {query = query.filter(dsl::business_profile_id.eq(profile_id));}@@ -231,6 +258,7 @@ impl Event {offset: Option<i64>,event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,+ event_recipient: Option<common_enums::EventRecipient>,) -> StorageResult<Vec<Self>> {// Fallback on merchant_id for rows with NULL initiator_merchant_id to// handle events created during staggered rollout by older code. This@@ -260,6 +288,7 @@ impl Event {offset,event_types,is_delivered,+ event_recipient,);logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());@@ -274,44 +303,65 @@ impl Event {conn: &PgPooledConn,initial_attempt_id: &str,initiator_merchant_id: &common_utils::id_type::MerchantId,+ event_recipient: Option<common_enums::EventRecipient>,) -> StorageResult<Vec<Self>> {// Fallback on merchant_id for rows with NULL initiator_merchant_id to// handle events created during staggered rollout by older code.- generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(- conn,- dsl::initial_attempt_id- .eq(initial_attempt_id.to_owned())- .and(- dsl::initiator_merchant_id- .eq(initiator_merchant_id.to_owned())- .or(dsl::initiator_merchant_id- .is_null()- .and(dsl::merchant_id.eq(initiator_merchant_id.to_owned()))),- ),- None,- None,- Some(dsl::created_at.desc()),- )- .await++ let mut query = Self::table()+ .filter(+ dsl::initial_attempt_id+ .eq(initial_attempt_id.to_owned())+ .and(+ dsl::initiator_merchant_id+ .eq(initiator_merchant_id.to_owned())+ .or(dsl::initiator_merchant_id+ .is_null()+ .and(dsl::merchant_id.eq(initiator_merchant_id.to_owned()))),+ ),+ )+ .order(dsl::created_at.desc())+ .into_boxed();++ if let Some(recipient) = event_recipient {+ query = query.filter(dsl::recipient.eq(recipient.to_string()));+ };++ logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());++ track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)+ .await+ .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found+ .attach_printable("Error filtering events by constraints")}pub async fn list_initial_attempts_by_profile_id_primary_object_id(conn: &PgPooledConn,profile_id: &common_utils::id_type::ProfileId,primary_object_id: &str,+ event_recipient: Option<common_enums::EventRecipient>,) -> StorageResult<Vec<Self>> {- generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(- conn,- dsl::event_id- .nullable()- .eq(dsl::initial_attempt_id) // Filter initial attempts only- .and(dsl::business_profile_id.eq(profile_id.to_owned()))- .and(dsl::primary_object_id.eq(primary_object_id.to_owned())),- None,- None,- Some(dsl::created_at.desc()),- )- .await+ let mut query = Self::table()+ .filter(+ dsl::event_id+ .nullable()+ .eq(dsl::initial_attempt_id) // Filter initial attempts only+ .and(dsl::business_profile_id.eq(profile_id.to_owned()))+ .and(dsl::primary_object_id.eq(primary_object_id.to_owned())),+ )+ .order(dsl::created_at.desc())+ .into_boxed();++ if let Some(recipient) = event_recipient {+ query = query.filter(dsl::recipient.eq(recipient.to_string()));+ };++ logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());++ track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)+ .await+ .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found+ .attach_printable("Error filtering events by constraints")}pub async fn find_initial_attempt_by_profile_id_initial_attempt_id(@@ -345,6 +395,7 @@ impl Event {offset: Option<i64>,event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,+ event_recipient: Option<common_enums::EventRecipient>,) -> StorageResult<Vec<Self>> {let mut query = Self::table().filter(@@ -364,6 +415,7 @@ impl Event {offset,event_types,is_delivered,+ event_recipient,);logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());@@ -426,6 +478,7 @@ impl Event {.await}+ #[allow(clippy::too_many_arguments)]fn apply_filters<T>(mut query: T,profile_id: Option<common_utils::id_type::ProfileId>,@@ -438,6 +491,7 @@ impl Event {offset: Option<i64>,event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,+ event_recipient: Option<common_enums::EventRecipient>,) -> TwhereT: diesel::query_dsl::methods::LimitDsl<Output = T>@@ -462,6 +516,10 @@ impl Event {diesel::dsl::Eq<dsl::is_overall_delivery_successful, bool>,Output = T,>,+ T: diesel::query_dsl::methods::FilterDsl<+ diesel::dsl::Eq<dsl::recipient, String>,+ Output = T,+ >,{if let Some(profile_id) = profile_id {query = query.filter(dsl::business_profile_id.eq(profile_id));@@ -487,9 +545,14 @@ impl Event {query = query.filter(dsl::is_overall_delivery_successful.eq(is_delivered));}+ if let Some(recipient) = event_recipient {+ query = query.filter(dsl::recipient.eq(recipient.to_string()));+ }+query}+ #[allow(clippy::too_many_arguments)]pub async fn count_initial_attempts_by_constraints(conn: &PgPooledConn,merchant_id: &common_utils::id_type::MerchantId,@@ -498,6 +561,7 @@ impl Event {created_before: time::PrimitiveDateTime,event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,+ event_recipient: Option<common_enums::EventRecipient>,) -> StorageResult<i64> {let mut query = Self::table().count()@@ -517,6 +581,7 @@ impl Event {None,event_types,is_delivered,+ event_recipient,);logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());@@ -537,6 +602,7 @@ impl Event {created_before: time::PrimitiveDateTime,event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,+ event_recipient: Option<common_enums::EventRecipient>,) -> StorageResult<i64> {let mut query = Self::table().count()@@ -556,6 +622,7 @@ impl Event {None,event_types,is_delivered,+ event_recipient,);logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());@@ -569,6 +636,7 @@ impl Event {.attach_printable("Error counting events by profile_id constraints")}+ #[allow(clippy::too_many_arguments)]pub async fn count_initial_attempts_by_initiator_merchant_id_constraints(conn: &PgPooledConn,initiator_merchant_id: &common_utils::id_type::MerchantId,@@ -577,6 +645,7 @@ impl Event {created_before: time::PrimitiveDateTime,event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,+ event_recipient: Option<common_enums::EventRecipient>,) -> StorageResult<i64> {// Fallback on merchant_id for rows with NULL initiator_merchant_id to// handle events created during staggered rollout by older code. This@@ -606,6 +675,7 @@ impl Event {None,event_types,is_delivered,+ event_recipient,);logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rsindex d256b80b20..2931555ce5 100644--- a/crates/diesel_models/src/schema.rs+++ b/crates/diesel_models/src/schema.rs@@ -611,6 +611,8 @@ diesel::table! {processor_merchant_id -> Nullable<Varchar>,#[max_length = 64]initiator_merchant_id -> Nullable<Varchar>,+ #[max_length = 32]+ recipient -> Nullable<Varchar>,}}diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rsindex 2566723946..c4c4c179ee 100644--- a/crates/diesel_models/src/schema_v2.rs+++ b/crates/diesel_models/src/schema_v2.rs@@ -622,6 +622,8 @@ diesel::table! {processor_merchant_id -> Nullable<Varchar>,#[max_length = 64]initiator_merchant_id -> Nullable<Varchar>,+ #[max_length = 32]+ recipient -> Nullable<Varchar>,}}diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.tomlindex a1626a62c9..b6b843501b 100644--- a/crates/external_services/Cargo.toml+++ b/crates/external_services/Cargo.toml@@ -80,7 +80,7 @@ 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", tag = "2026.06.23.1", package = "rust-grpc-client" }+unified-connector-service-client = { git = "https://github.com/juspay/connector-service", tag = "2026.06.24.0", 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 c629351180..e5e3e1b21e 100644--- a/crates/external_services/src/grpc_client/unified_connector_service.rs+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs@@ -1346,6 +1346,41 @@ impl UnifiedConnectorServiceClient {)})}++ /// Performs notify connector via the Event Service+ pub async fn notify_connector(+ &self,+ notify_connector_request: payments_grpc::NotifyConnectorRequest,+ connector_auth_metadata: ConnectorAuthMetadata,+ grpc_headers: GrpcHeadersUcs,+ event_type: payments_grpc::NotifyEventType,+ ) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::NotifyConnectorResponse>>+ {+ let mut request = tonic::Request::new(notify_connector_request);++ let connector_name = connector_auth_metadata.connector_name.clone();+ let metadata = build_unified_connector_service_grpc_headers_for_notify_connector(+ connector_auth_metadata,+ grpc_headers,+ event_type,+ )?;++ *request.metadata_mut() = metadata;++ self.event_service_client+ .clone()+ .notify_connector(request)+ .await+ .change_context(UnifiedConnectorServiceError::NotifyConnectorFailure)+ .inspect_err(|error| {+ logger::error!(+ grpc_error=?error,+ method="notify_connector",+ connector_name=?connector_name,+ "UCS notify_connector gRPC call failed"+ )+ })+ }}/// Build the gRPC Headers for Unified Connector Service Request@@ -1557,3 +1592,49 @@ pub fn build_unified_connector_service_grpc_headers_for_surcharge(Ok(metadata)}++/// Build gRPC headers for UCS notify requests.+/// Build gRPC headers for UCS notify requests.+/// Same as [`build_unified_connector_service_grpc_headers`] but uses+/// `x-surcharge-connector` for surcharge events and `x-connector` for other events.+pub fn build_unified_connector_service_grpc_headers_for_notify_connector(+ meta: ConnectorAuthMetadata,+ grpc_headers: GrpcHeadersUcs,+ event_type: payments_grpc::NotifyEventType,+) -> Result<MetadataMap, UnifiedConnectorServiceError> {+ let mut metadata = build_unified_connector_service_grpc_headers(meta.clone(), grpc_headers)?;++ // Remove the default connector header+ metadata.remove(consts::UCS_HEADER_CONNECTOR);++ // Choose header based on event type+ let is_surcharge_event = matches!(+ event_type,+ payments_grpc::NotifyEventType::SurchargePaymentSucceeded+ | payments_grpc::NotifyEventType::SurchargeRefundSucceeded+ );++ let connector_name = meta.connector_name.clone();+ let connector_value = connector_name+ .parse::<MetadataValue<_>>()+ .map_err(|error| {+ logger::error!(?error);+ if is_surcharge_event {+ UnifiedConnectorServiceError::HeaderInjectionFailed(+ consts::UCS_HEADER_SURCHARGE_CONNECTOR.to_string(),+ )+ } else {+ UnifiedConnectorServiceError::HeaderInjectionFailed(+ consts::UCS_HEADER_CONNECTOR.to_string(),+ )+ }+ })?;++ if is_surcharge_event {+ metadata.append(consts::UCS_HEADER_SURCHARGE_CONNECTOR, connector_value);+ } else {+ metadata.append(consts::UCS_HEADER_CONNECTOR, connector_value);+ }++ Ok(metadata)+}diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rsindex ae6e204fd2..645b6ddd0d 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs@@ -2186,6 +2186,10 @@ pub enum PaymentAttemptUpdate {updated_by: String,connector_mandate_detail: Option<ConnectorMandateReferenceId>,},+ ExternalSurchargeUpdate {+ external_surcharge_details: common_types::payments::ExternalSurchargeDetails,+ updated_by: String,+ },}#[cfg(feature = "v1")]@@ -2769,6 +2773,13 @@ impl PaymentAttemptUpdate {updated_by,connector_mandate_detail,},+ Self::ExternalSurchargeUpdate {+ external_surcharge_details,+ updated_by,+ } => DieselPaymentAttemptUpdate::ExternalSurchargeUpdate {+ external_surcharge_details,+ updated_by,+ },}}@@ -2798,7 +2809,8 @@ impl PaymentAttemptUpdate {| Self::AuthenticationUpdate { .. }| Self::ManualUpdate { .. }| Self::PostSessionTokensUpdate { .. }- | Self::RecurrenceUpdate { .. } => None,+ | Self::RecurrenceUpdate { .. }+ | Self::ExternalSurchargeUpdate { .. } => None,}}}diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rsindex d6d222d3f5..ecf806d667 100644--- a/crates/hyperswitch_domain_models/src/router_response_types.rs+++ b/crates/hyperswitch_domain_models/src/router_response_types.rs@@ -152,6 +152,15 @@ pub struct SurchargeCalculationResponseData {pub error_message: Option<String>,}+#[derive(Debug, Clone, serde::Serialize)]+pub struct NotifyConnectorResponseData {+ pub status_code: u16,+ /// Error code if calculation failed or returned 0+ pub error_code: Option<String>,+ /// Additional error codes+ pub error_message: Option<String>,+}+/// Response data for completing surcharge (sale notification)#[derive(Debug, Clone)]pub struct CompleteSurchargeResponseData {diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.tomlindex 0d2303463d..fc2cb3a0c5 100644--- a/crates/hyperswitch_interfaces/Cargo.toml+++ b/crates/hyperswitch_interfaces/Cargo.toml@@ -33,7 +33,7 @@ time = "0.3.41"tonic = "0.14"url = { version = "2.5.4", features = ["serde"] }-unified-connector-service-client = { git = "https://github.com/juspay/connector-service", tag = "2026.06.23.1", package = "rust-grpc-client" }+unified-connector-service-client = { git = "https://github.com/juspay/connector-service", tag = "2026.06.24.0", package = "rust-grpc-client" }tokio = { version = "1.45.1", features = ["macros", "rt-multi-thread"] }# First party cratesdiff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rsindex 8ffa0a7b78..ddbef3b6e9 100644--- a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs@@ -222,6 +222,10 @@ pub enum UnifiedConnectorServiceError {/// Failed to perform Surcharge Calculate from gRPC Server#[error("Failed to perform Surcharge Calculate from gRPC Server")]SurchargeCalculateFailure,++ /// Failed to perform Notify Connector via gRPC Server+ #[error("Failed to perform Notify Connector from gRPC Server")]+ NotifyConnectorFailure,}/// Inner data for [`UnifiedConnectorServiceError::ConnectorError`].@@ -1123,7 +1127,8 @@ impl ErrorSwitch<ConnectorError> for UnifiedConnectorServiceError {| Self::PayoutStageFailure| Self::PayoutCreateRecipientFailure| Self::SurchargeCalculateFailure- | Self::PayoutEnrollDisburseAccountFailure => ConnectorError::ResponseHandlingFailed,+ | Self::PayoutEnrollDisburseAccountFailure+ | Self::NotifyConnectorFailure => ConnectorError::ResponseHandlingFailed,}}}diff --git a/crates/hyperswitch_interfaces/src/webhooks.rs b/crates/hyperswitch_interfaces/src/webhooks.rsindex 97951d93c5..6fa8007a26 100644--- a/crates/hyperswitch_interfaces/src/webhooks.rs+++ b/crates/hyperswitch_interfaces/src/webhooks.rs@@ -56,6 +56,11 @@ pub enum WebhookResourceData {/// The previous payment attempt details before processing this webhookpayment_attempt: hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,},+ /// Context for Refund-related webhooks+ Refund {+ /// The payment attempt details attached with the refund+ payment_attempt: hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,+ },}impl WebhookResourceData {@@ -65,6 +70,7 @@ impl WebhookResourceData {) -> &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt {match self {Self::Payment { payment_attempt } => payment_attempt,+ Self::Refund { payment_attempt } => payment_attempt,}}}@@ -107,7 +113,8 @@ impl WebhookContext {impl From<&WebhookResourceData> for WebhookContext {fn from(data: &WebhookResourceData) -> Self {match data {- WebhookResourceData::Payment { payment_attempt } => {+ WebhookResourceData::Payment { payment_attempt }+ | WebhookResourceData::Refund { payment_attempt } => {Self::Payment(PaymentWebhookContext {previous_status: payment_attempt.status,payment_method: payment_attempt.payment_method,@@ -124,7 +131,8 @@ impl From<&WebhookResourceData> for WebhookContext {impl From<&WebhookResourceData> for WebhookContext {fn from(data: &WebhookResourceData) -> Self {match data {- WebhookResourceData::Payment { payment_attempt } => {+ WebhookResourceData::Payment { payment_attempt }+ | WebhookResourceData::Refund { payment_attempt } => {Self::Payment(PaymentWebhookContext {previous_status: payment_attempt.status,payment_method: payment_attempt.get_payment_method(),diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.tomlindex 22f5393f37..57d1fe94c5 100644--- a/crates/router/Cargo.toml+++ b/crates/router/Cargo.toml@@ -91,8 +91,8 @@ ring = "0.17.14"rust_decimal = { version = "1.37.1", features = ["serde-with-float", "serde-with-str"] }rust-i18n = { git = "https://github.com/kashif-m/rust-i18n", rev = "f2d8096aaaff7a87a847c35a5394c269f75e077a" }-unified-connector-service-client = { git = "https://github.com/juspay/connector-service", tag = "2026.06.23.1", package = "rust-grpc-client" }-unified-connector-service-cards = { git = "https://github.com/juspay/connector-service", tag = "2026.06.23.1", package = "ucs_cards" }+unified-connector-service-client = { git = "https://github.com/juspay/connector-service", tag = "2026.06.24.0", package = "rust-grpc-client" }+unified-connector-service-cards = { git = "https://github.com/juspay/connector-service", tag = "2026.06.24.0", package = "ucs_cards" }rustc-hash = "1.1.0"rustls = "0.22"rustls-pemfile = "2"diff --git a/crates/router/src/compatibility/stripe/webhooks.rs b/crates/router/src/compatibility/stripe/webhooks.rsindex 3e2913f4fc..4ab7e0d346 100644--- a/crates/router/src/compatibility/stripe/webhooks.rs+++ b/crates/router/src/compatibility/stripe/webhooks.rs@@ -304,6 +304,9 @@ fn get_stripe_event_type(event_type: api_models::enums::EventType) -> &'static sapi_models::enums::EventType::PayoutExpired => "payout.failed",api_models::enums::EventType::PayoutReversed => "payout.reconciliation_completed",api_models::enums::EventType::InvoicePaid => "invoice.paid",+ // surcharge events+ api_models::enums::EventType::SurchargePaymentSucceeded => "surcharge_payment.succeeded",+ api_models::enums::EventType::SurchargeRefundSucceeded => "surcharge_refund.succeeded",}}diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex a7c5b0a0b2..365f1d3aee 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -375,6 +375,9 @@ pub mod superposition {pub const POLL_CONFIG_EXTERNAL_THREE_DS: &str = "poll_config_external_three_ds";/// Outgoing webhook retry process tracker mapping keypub const PT_MAPPING_OUTGOING_WEBHOOKS: &str = "pt_mapping_outgoing_webhooks";+ /// Outgoing connector webhook retry process tracker mapping key+ pub const PT_MAPPING_OUTGOING_CONNECTOR_WEBHOOKS: &str =+ "pt_mapping_outgoing_connector_webhooks";/// PCR (Revenue Recovery) payments retry process tracker mapping keypub const PT_MAPPING_PCR_RETRIES: &str = "pt_mapping_pcr_retries";/// Payment sync (psync) retry process tracker mapping keydiff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex 86acda4601..7f15a7163f 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -584,6 +584,25 @@ impl DatabaseBackedConfig for PollConfigExternalThreeDs {}}+config! {+ superposition_key = PT_MAPPING_OUTGOING_CONNECTOR_WEBHOOKS,+ output = scheduler::types::process_data::OutgoingWebhookRetryProcessTrackerMapping,+ default = scheduler::types::process_data::OutgoingWebhookRetryProcessTrackerMapping::default(),+ object = true,+ requires = dimension_state::DimensionsWithProcessorMerchantIdAndConnector,+ targeting_key = id_type::MerchantId+}++impl DatabaseBackedConfig for PtMappingOutgoingConnectorWebhooks {+ const KEY: &'static str = "pt_mapping_outgoing_connector_webhooks";++ fn db_key(dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {+ dimensions+ .get_connector()+ .map(|connector| format!("{}_{}", Self::KEY, connector))+ }+}+config! {superposition_key = PT_MAPPING_OUTGOING_WEBHOOKS,output = scheduler::types::process_data::OutgoingWebhookRetryProcessTrackerMapping,diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rsindex 12f57d1139..56e16d29c1 100644--- a/crates/router/src/core/disputes.rs+++ b/crates/router/src/core/disputes.rs@@ -13,6 +13,7 @@ use strum::IntoEnumIterator;pub mod transformers;use common_enums;+use hyperswitch_interfaces::webhooks::WebhookResourceData;use super::{errors::{self, ConnectorErrorExt, RouterResponse, StorageErrorExt},@@ -957,6 +958,8 @@ pub async fn update_dispute_data(api::OutgoingWebhookContent::DisputeDetails(Box::new(disputes_response.clone())),Some(dispute_object.created_at),webhook_recipient,+ Some(WebhookResourceData::Payment { payment_attempt }),+ business_profile,)).await?;Ok(disputes_response)diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rsindex 7fb2ce5ede..53f3467b05 100644--- a/crates/router/src/core/errors.rs+++ b/crates/router/src/core/errors.rs@@ -149,6 +149,8 @@ pub enum WebhooksFlowError {CallToMerchantFailed,#[error("Webhook not received by merchant")]NotReceivedByMerchant,+ #[error("Webhook not received by recipient")]+ NotReceivedByRecipient,#[error("Dispute webhook status validation failed")]DisputeWebhookValidationFailed,#[error("Outgoing webhook body encoding failed")]@@ -161,6 +163,10 @@ pub enum WebhooksFlowError {OutgoingWebhookResponseEncodingFailed,#[error("ID generation failed")]IdGenerationFailed,+ #[error("Webhook API call failed")]+ WebhookCallFailed,+ #[error("Webhook request construction failed")]+ WebhookRequestConstructionFailed,}impl WebhooksFlowError {@@ -169,7 +175,8 @@ impl WebhooksFlowError {Self::MerchantConfigNotFound| Self::MerchantWebhookDetailsNotFound| Self::MerchantWebhookUrlNotConfigured- | Self::OutgoingWebhookResponseEncodingFailed => false,+ | Self::OutgoingWebhookResponseEncodingFailed+ | Self::WebhookRequestConstructionFailed => false,Self::WebhookEventUpdationFailed| Self::OutgoingWebhookSigningFailed@@ -179,7 +186,9 @@ impl WebhooksFlowError {| Self::OutgoingWebhookEncodingFailed| Self::OutgoingWebhookProcessTrackerTaskUpdateFailed| Self::OutgoingWebhookRetrySchedulingFailed- | Self::IdGenerationFailed => true,+ | Self::IdGenerationFailed+ | Self::WebhookCallFailed+ | Self::NotReceivedByRecipient => true,}}}diff --git a/crates/router/src/core/payments/access_token.rs b/crates/router/src/core/payments/access_token.rsindex 068b659aaf..07c1a67ce7 100644--- a/crates/router/src/core/payments/access_token.rs+++ b/crates/router/src/core/payments/access_token.rs@@ -372,7 +372,7 @@ async fn fetch_access_token_from_ucs(let connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(mca_type,- processor,+ processor.get_account().get_id(),connector_name.to_string(),).change_context(errors::ApiErrorResponse::InternalServerError)diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rsindex 93bed6e4b0..3745e6564a 100644--- a/crates/router/src/core/payments/flows/authorize_flow.rs+++ b/crates/router/src/core/payments/flows/authorize_flow.rs@@ -1590,7 +1590,7 @@ pub async fn call_unified_connector_service_pre_authenticate(let connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(interface_errors::ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rsindex 3e1a086978..2430c3e745 100644--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs@@ -777,7 +777,7 @@ pub async fn call_unified_connector_service_authenticate(let connector_auth_metadata = ucs_core::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(interface_errors::ConnectorError::RequestEncodingFailed)@@ -890,7 +890,7 @@ pub async fn call_unified_connector_service_post_authenticate(let connector_auth_metadata = ucs_core::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(interface_errors::ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payments/flows/external_proxy_flow.rs b/crates/router/src/core/payments/flows/external_proxy_flow.rsindex d13fbee232..3a5f03d6dc 100644--- a/crates/router/src/core/payments/flows/external_proxy_flow.rs+++ b/crates/router/src/core/payments/flows/external_proxy_flow.rs@@ -423,7 +423,7 @@ impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>let connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),self.connector.clone(),).change_context(ApiErrorResponse::InternalServerError)@@ -529,7 +529,7 @@ impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>let connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account.clone(),- processor,+ processor.get_account().get_id(),self.connector.clone(),).change_context(ApiErrorResponse::InternalServerError)diff --git a/crates/router/src/core/payments/gateway/access_token_gateway.rs b/crates/router/src/core/payments/gateway/access_token_gateway.rsindex 4a8439f916..c68af058cd 100644--- a/crates/router/src/core/payments/gateway/access_token_gateway.rs+++ b/crates/router/src/core/payments/gateway/access_token_gateway.rs@@ -97,7 +97,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account.clone(),- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payments/gateway/authorize_gateway.rs b/crates/router/src/core/payments/gateway/authorize_gateway.rsindex c517de8955..0841c4bc4b 100644--- a/crates/router/src/core/payments/gateway/authorize_gateway.rs+++ b/crates/router/src/core/payments/gateway/authorize_gateway.rs@@ -92,7 +92,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payments/gateway/cancel_gateway.rs b/crates/router/src/core/payments/gateway/cancel_gateway.rsindex 6180cad8f3..b32a1e7c07 100644--- a/crates/router/src/core/payments/gateway/cancel_gateway.rs+++ b/crates/router/src/core/payments/gateway/cancel_gateway.rs@@ -80,7 +80,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payments/gateway/capture_gateway.rs b/crates/router/src/core/payments/gateway/capture_gateway.rsindex 6de2a378e1..d4d5c08e24 100644--- a/crates/router/src/core/payments/gateway/capture_gateway.rs+++ b/crates/router/src/core/payments/gateway/capture_gateway.rs@@ -80,7 +80,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payments/gateway/complete_authorize_gateway.rs b/crates/router/src/core/payments/gateway/complete_authorize_gateway.rsindex ec9abb084d..c1e8516af5 100644--- a/crates/router/src/core/payments/gateway/complete_authorize_gateway.rs+++ b/crates/router/src/core/payments/gateway/complete_authorize_gateway.rs@@ -86,7 +86,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payments/gateway/create_customer_gateway.rs b/crates/router/src/core/payments/gateway/create_customer_gateway.rsindex d3d84c3e02..17ec391349 100644--- a/crates/router/src/core/payments/gateway/create_customer_gateway.rs+++ b/crates/router/src/core/payments/gateway/create_customer_gateway.rs@@ -92,7 +92,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payments/gateway/create_order_gateway.rs b/crates/router/src/core/payments/gateway/create_order_gateway.rsindex 4b9e2e4d97..a87b1028ed 100644--- a/crates/router/src/core/payments/gateway/create_order_gateway.rs+++ b/crates/router/src/core/payments/gateway/create_order_gateway.rs@@ -84,7 +84,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payments/gateway/incremental_authorization_gateway.rs b/crates/router/src/core/payments/gateway/incremental_authorization_gateway.rsindex 69ebd3fb40..c83f4dcb59 100644--- a/crates/router/src/core/payments/gateway/incremental_authorization_gateway.rs+++ b/crates/router/src/core/payments/gateway/incremental_authorization_gateway.rs@@ -94,7 +94,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- &processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rs b/crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rsindex 860104fc99..4b692c229b 100644--- a/crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rs+++ b/crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rs@@ -90,7 +90,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payments/gateway/pre_authorize_void_gateway.rs b/crates/router/src/core/payments/gateway/pre_authorize_void_gateway.rsindex 109e8f77fe..21ac77e3c4 100644--- a/crates/router/src/core/payments/gateway/pre_authorize_void_gateway.rs+++ b/crates/router/src/core/payments/gateway/pre_authorize_void_gateway.rs@@ -87,7 +87,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payments/gateway/psync_gateway.rs b/crates/router/src/core/payments/gateway/psync_gateway.rsindex 35e9f0488e..5328fc2afc 100644--- a/crates/router/src/core/payments/gateway/psync_gateway.rs+++ b/crates/router/src/core/payments/gateway/psync_gateway.rs@@ -160,7 +160,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payments/gateway/session_gateway.rs b/crates/router/src/core/payments/gateway/session_gateway.rsindex 966a4e200e..e3d6a6b4a4 100644--- a/crates/router/src/core/payments/gateway/session_gateway.rs+++ b/crates/router/src/core/payments/gateway/session_gateway.rs@@ -84,7 +84,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payments/gateway/session_token_gateway.rs b/crates/router/src/core/payments/gateway/session_token_gateway.rsindex af4a094cc7..0275e420b8 100644--- a/crates/router/src/core/payments/gateway/session_token_gateway.rs+++ b/crates/router/src/core/payments/gateway/session_token_gateway.rs@@ -87,7 +87,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payments/gateway/setup_mandate.rs b/crates/router/src/core/payments/gateway/setup_mandate.rsindex 7553080108..c55203a739 100644--- a/crates/router/src/core/payments/gateway/setup_mandate.rs+++ b/crates/router/src/core/payments/gateway/setup_mandate.rs@@ -82,7 +82,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 1206cccc60..d78351d837 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -8747,6 +8747,10 @@ pub fn get_redis_key_for_extended_card_info()}+pub fn get_external_surcharge_redis_key(payment_id: &id_type::PaymentId) -> String {+ format!("{}_external_surcharge", payment_id.get_string_repr())+}+pub fn check_integrity_based_on_flow<T, Request>(request: &Request,payment_response_data: &Result<PaymentsResponseData, ErrorResponse>,diff --git a/crates/router/src/core/payouts/gateway/cancel_gateway.rs b/crates/router/src/core/payouts/gateway/cancel_gateway.rsindex e9e862d6bd..ff76a9bc68 100644--- a/crates/router/src/core/payouts/gateway/cancel_gateway.rs+++ b/crates/router/src/core/payouts/gateway/cancel_gateway.rs@@ -73,7 +73,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payouts/gateway/create_gateway.rs b/crates/router/src/core/payouts/gateway/create_gateway.rsindex f82296b95c..df8b9492dd 100644--- a/crates/router/src/core/payouts/gateway/create_gateway.rs+++ b/crates/router/src/core/payouts/gateway/create_gateway.rs@@ -73,7 +73,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payouts/gateway/fulfill_gateway.rs b/crates/router/src/core/payouts/gateway/fulfill_gateway.rsindex 061b274f2d..3186a94a7a 100644--- a/crates/router/src/core/payouts/gateway/fulfill_gateway.rs+++ b/crates/router/src/core/payouts/gateway/fulfill_gateway.rs@@ -73,7 +73,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payouts/gateway/quote_gateway.rs b/crates/router/src/core/payouts/gateway/quote_gateway.rsindex e32cd3b2e3..e8bf52cd9a 100644--- a/crates/router/src/core/payouts/gateway/quote_gateway.rs+++ b/crates/router/src/core/payouts/gateway/quote_gateway.rs@@ -73,7 +73,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payouts/gateway/recipient_account_gateway.rs b/crates/router/src/core/payouts/gateway/recipient_account_gateway.rsindex 675486ff0d..30bfc740e0 100644--- a/crates/router/src/core/payouts/gateway/recipient_account_gateway.rs+++ b/crates/router/src/core/payouts/gateway/recipient_account_gateway.rs@@ -73,7 +73,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payouts/gateway/recipient_gateway.rs b/crates/router/src/core/payouts/gateway/recipient_gateway.rsindex 7b859012a5..cada638327 100644--- a/crates/router/src/core/payouts/gateway/recipient_gateway.rs+++ b/crates/router/src/core/payouts/gateway/recipient_gateway.rs@@ -73,7 +73,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/payouts/gateway/sync_gateway.rs b/crates/router/src/core/payouts/gateway/sync_gateway.rsindex 040859014c..d5757dbc23 100644--- a/crates/router/src/core/payouts/gateway/sync_gateway.rs+++ b/crates/router/src/core/payouts/gateway/sync_gateway.rs@@ -73,7 +73,7 @@ wherelet connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(ConnectorError::RequestEncodingFailed)diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rsindex 77cee546f1..9629b3a188 100644--- a/crates/router/src/core/refunds.rs+++ b/crates/router/src/core/refunds.rs@@ -483,15 +483,10 @@ pub async fn trigger_refund_to_gateway(refund.refund_id)})?;- utils::trigger_refund_outgoing_webhook(- state,- platform,- &response,- payment_attempt.profile_id.clone(),- )- .await- .map_err(|error| logger::warn!(refunds_outgoing_webhook_error=?error))- .ok();+ utils::trigger_refund_outgoing_webhook(state, platform, &response, payment_attempt)+ .await+ .map_err(|error| logger::warn!(refunds_outgoing_webhook_error=?error))+ .ok();Ok((response, router_data_res.raw_connector_response))}@@ -1116,15 +1111,10 @@ pub async fn sync_refund_with_gateway(refund.refund_id)})?;- utils::trigger_refund_outgoing_webhook(- state,- platform,- &response,- payment_attempt.profile_id.clone(),- )- .await- .map_err(|error| logger::warn!(refunds_outgoing_webhook_error=?error))- .ok();+ utils::trigger_refund_outgoing_webhook(state, platform, &response, payment_attempt)+ .await+ .map_err(|error| logger::warn!(refunds_outgoing_webhook_error=?error))+ .ok();Ok((response, router_data_res.raw_connector_response))}diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex 9e1580c8ff..8c24d2b7f0 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -53,11 +53,13 @@ use crate::{OperationSessionGetters, OperationSessionSetters,},utils::get_flow_name,+ webhooks::types::FeatureTrackingData,},events::connector_api_logs::ConnectorEvent,routes::SessionState,types::{api::enums as api_enums,+ domain::Event,transformers::{ForeignFrom, ForeignTryFrom},UcsPaymentAuthorizeResponseData, UcsPaymentCaptureResponseData,UcsPaymentSetupRecurringResponseData, UcsRecurringPaymentChargeResponseData,@@ -1758,7 +1760,7 @@ fn get_ucs_client(pub fn build_unified_connector_service_auth_metadata(#[cfg(feature = "v1")] merchant_connector_account: MerchantConnectorAccountType,#[cfg(feature = "v2")] merchant_connector_account: MerchantConnectorAccountTypeDetails,- processor: &Processor,+ processor_merchant_id: &id_type::MerchantId,connector_name: String,) -> CustomResult<ConnectorAuthMetadata, UnifiedConnectorServiceError> {#[cfg(feature = "v1")]@@ -1773,9 +1775,7 @@ pub fn build_unified_connector_service_auth_metadata(.get_connector_account_details().change_context(UnifiedConnectorServiceError::FailedToObtainAuthType).attach_printable("Failed to obtain ConnectorAuthType")?;-- let merchant_id = processor.get_account().get_id().get_string_repr();-+ let merchant_id = processor_merchant_id.get_string_repr();// Extract connector metadata from MCA for connector-specific configlet merchant_account_metadata = merchant_connector_account.get_metadata();let merchant_account_metadata_value = merchant_account_metadata@@ -3032,7 +3032,7 @@ pub async fn call_unified_connector_service_for_refund_execute(// Build auth metadata using standard UCS functionlet connector_auth_metadata = build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(errors::ApiErrorResponse::InternalServerError)@@ -3166,7 +3166,7 @@ pub async fn call_unified_connector_service_for_refund_sync(// Build auth metadata using standard UCS functionlet connector_auth_metadata = build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),router_data.connector.clone(),).change_context(errors::ApiErrorResponse::InternalServerError)@@ -3306,7 +3306,7 @@ pub async fn call_unified_connector_service_for_surcharge_calculate(let connector_auth_metadata = build_unified_connector_service_auth_metadata(merchant_connector_account,- processor,+ processor.get_account().get_id(),connector_name.clone(),).change_context(errors::ApiErrorResponse::InternalServerError)@@ -3370,3 +3370,134 @@ pub async fn call_unified_connector_service_for_surcharge_calculate(.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to parse UCS surcharge calculate response")}++#[cfg(feature = "v1")]+fn extract_notify_connector_content_from_request(+ feature_data: FeatureTrackingData,+) -> CustomResult<payments_grpc::NotifyConnectorContent, errors::ApiErrorResponse> {+ match feature_data {+ FeatureTrackingData::SurchargeDetails(details) => {+ Ok(payments_grpc::NotifyConnectorContent {+ content: Some(+ payments_grpc::notify_connector_content::Content::SurchargeContent(+ payments_grpc::SurchargeContent {+ connector_surcharge_id: details.external_surcharge_id.clone(),+ },+ ),+ ),+ })+ }+ }+}++#[cfg(all(feature = "oltp", feature = "v1"))]+#[instrument(skip_all, fields(connector_name))]+pub fn build_notify_connector_request(+ event: &Event,+ merchant_id: &id_type::MerchantId,+ merchant_connector_account: MerchantConnectorAccountType,+ connector_name: String,+ notify_feature_data: FeatureTrackingData,+) -> RouterResult<(+ payments_grpc::NotifyConnectorRequest,+ ConnectorAuthMetadata,+ payments_grpc::NotifyEventType,+)> {+ let connector_auth_metadata: ConnectorAuthMetadata =+ build_unified_connector_service_auth_metadata(+ merchant_connector_account,+ merchant_id,+ connector_name.clone(),+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to build UCS auth metadata for surcharge calculate")?;++ let notify_event_type = match event.event_type {+ api_models::enums::EventType::SurchargePaymentSucceeded => {+ payments_grpc::NotifyEventType::SurchargePaymentSucceeded+ }+ api_models::enums::EventType::SurchargeRefundSucceeded => {+ payments_grpc::NotifyEventType::SurchargeRefundSucceeded+ }+ _ => {+ return Err(errors::ApiErrorResponse::InternalServerError).attach_printable(format!(+ "Unsupported event type for connector notification: {:?}",+ event.event_type+ ))+ }+ };++ // Build NotifyConnectorRequest+ Ok((+ payments_grpc::NotifyConnectorRequest {+ event_id: event.event_id.clone(),+ event_type: notify_event_type.into(),+ content: Some(extract_notify_connector_content_from_request(+ notify_feature_data,+ )?),+ timestamp: event.created_at.assume_utc().unix_timestamp(),+ state: None,+ },+ connector_auth_metadata,+ notify_event_type,+ ))+}++/// Execute a notify connector call via UCS EventService.NotifyConnector.+///+/// This sends event notifications (e.g. surcharge payment succeeded) to the+/// unified connector service so that downstream connectors can act on them.+/// It does not go through the full RouterData machinery.+#[cfg(all(feature = "oltp", feature = "v1"))]+#[instrument(skip_all, fields(connector_name))]+pub async fn call_unified_connector_service_for_notify_connector(+ state: &SessionState,+ event: &Event,+ connector_auth_metadata: ConnectorAuthMetadata,+ notify_request: payments_grpc::NotifyConnectorRequest,+ notify_event_type: payments_grpc::NotifyEventType,+ merchant_id: &id_type::MerchantId,+ profile_id: &id_type::ProfileId,+) -> CustomResult<+ hyperswitch_domain_models::router_response_types::NotifyConnectorResponseData,+ errors::ApiClientError,+> {+ let lineage_ids = LineageIds::new(merchant_id.clone(), profile_id.clone());+ let merchant_reference_id = id_type::PaymentReferenceId::from_str(&event.primary_object_id)+ .inspect_err(+ |err| logger::warn!(error=?err, "Invalid primary_object_id for UCS reference id"),+ )+ .ok()+ .map(ucs_types::UcsReferenceId::Payment);++ let grpc_header_builder = state+ .get_grpc_headers_ucs(ExecutionMode::Primary)+ .lineage_ids(lineage_ids)+ .external_vault_proxy_metadata(None)+ .merchant_reference_id(merchant_reference_id)+ .resource_id(None);++ let grpc_headers = grpc_header_builder.build();+ let ucs_client =+ get_ucs_client(state).change_context(errors::ApiClientError::ClientConstructionFailed)?;++ let response = ucs_client+ .notify_connector(+ notify_request,+ connector_auth_metadata,+ grpc_headers,+ notify_event_type,+ )+ .await+ .change_context(errors::ApiClientError::UnexpectedServerResponse)+ .attach_printable("UCS notify_connector gRPC call failed")?;++ let notify_connector_response_data =+ hyperswitch_domain_models::router_response_types::NotifyConnectorResponseData::foreign_try_from(+ response.into_inner(),+ )+ .change_context(errors::ApiClientError::ResponseDecodingFailed)+ .attach_printable("Failed to parse UCS notify_connector response")?;++ Ok(notify_connector_response_data)+}diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rsindex e9ffd02f0e..d2f61791c4 100644--- a/crates/router/src/core/unified_connector_service/transformers.rs+++ b/crates/router/src/core/unified_connector_service/transformers.rs@@ -35,7 +35,8 @@ use hyperswitch_domain_models::{SetupMandateRequestData, SyncRequestType,},router_response_types::{- PaymentsResponseData, PayoutsResponseData, RedirectForm, RefundsResponseData,+ NotifyConnectorResponseData, PaymentsResponseData, PayoutsResponseData, RedirectForm,+ RefundsResponseData,},};pub use hyperswitch_interfaces::{@@ -8003,3 +8004,31 @@ impl ForeignFrom<&common_types::payments::StripeSplitPaymentRequest>}}}++impl transformers::ForeignTryFrom<payments_grpc::NotifyConnectorResponse>+ for NotifyConnectorResponseData+{+ type Error = error_stack::Report<UnifiedConnectorServiceError>;++ fn foreign_try_from(+ grpc_response: payments_grpc::NotifyConnectorResponse,+ ) -> Result<Self, Self::Error> {+ Ok(Self {+ status_code: u16::try_from(grpc_response.status_code)+ .change_context(UnifiedConnectorServiceError::ParsingFailed)+ .attach_printable("Failed to parse status code from UCS response")?,+ error_code: grpc_response.error.as_ref().and_then(|error_info| {+ error_info+ .connector_details+ .as_ref()+ .and_then(|cd| cd.code.clone())+ }),+ error_message: grpc_response.error.as_ref().and_then(|error_info| {+ error_info+ .connector_details+ .as_ref()+ .and_then(|cd| cd.message.clone())+ }),+ })+ }+}diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rsindex 69334e3b47..0705bf8616 100644--- a/crates/router/src/core/webhooks.rs+++ b/crates/router/src/core/webhooks.rs@@ -31,3 +31,4 @@ pub(crate) use self::{};const MERCHANT_ID: &str = "merchant_id";+const MERCHANT_CONNECTOR_ACCOUNT_ID: &str = "merchant_connector_account_id";diff --git a/crates/router/src/core/webhooks/gateway.rs b/crates/router/src/core/webhooks/gateway.rsindex 594428aafd..dca224cad9 100644--- a/crates/router/src/core/webhooks/gateway.rs+++ b/crates/router/src/core/webhooks/gateway.rs@@ -759,7 +759,7 @@ fn build_ucs_auth_metadata(#[cfg(feature = "v1")]let auth_metadata = build_unified_connector_service_auth_metadata(MerchantConnectorAccountType::DbVal(Box::new(mca.clone())),- ctx.platform.get_processor(),+ ctx.platform.get_processor().get_account().get_id(),ctx.connector_name.to_string(),);#[cfg(feature = "v2")]@@ -767,7 +767,7 @@ fn build_ucs_auth_metadata(domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(mca.clone(),)),- ctx.platform.get_processor(),+ ctx.platform.get_processor().get_account().get_id(),ctx.connector_name.to_string(),);auth_metadatadiff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rsindex ebd51e3199..3d0ef35f72 100644--- a/crates/router/src/core/webhooks/incoming.rs+++ b/crates/router/src/core/webhooks/incoming.rs@@ -593,6 +593,7 @@ async fn process_webhook_business_logic(connector_name,source_verified,event_type,+ webhook_resource_data,)).await.attach_printable("Incoming webhook flow for refunds failed"),@@ -1035,6 +1036,8 @@ async fn payments_incoming_webhook_flow(api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),primary_object_created_at,webhook_recipient,+ Some(WebhookResourceData::Payment { payment_attempt }),+ business_profile,)).await?;};@@ -1351,6 +1354,8 @@ async fn payout_incoming_webhook_update_status(api::OutgoingWebhookContent::PayoutDetails(Box::new(payout_create_response)),Some(payout_data.payout_attempt.created_at),webhook_recipient,+ None,+ business_profile,)).await?;}@@ -1429,6 +1434,8 @@ async fn payout_incoming_webhook_retrieve_status(api::OutgoingWebhookContent::PayoutDetails(Box::new(payout_response)),Some(payout_data.payout_attempt.created_at),webhook_recipient,+ None,+ business_profile,)).await?;}@@ -1535,6 +1542,7 @@ async fn refunds_incoming_webhook_flow(connector_name: &str,source_verified: bool,event_type: webhooks::IncomingWebhookEvent,+ webhook_resource_data: Option<WebhookResourceData>,) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {let db = &*state.store;//find refund by connector refund id@@ -1663,6 +1671,8 @@ async fn refunds_incoming_webhook_flow(api::OutgoingWebhookContent::RefundDetails(Box::new(refund_response)),Some(updated_refund.created_at),webhook_recipient,+ webhook_resource_data,+ business_profile,)).await?;}@@ -2067,6 +2077,8 @@ async fn external_authentication_incoming_webhook_flow()),primary_object_created_at,webhook_recipient,+ None,+ business_profile,)).await?;};@@ -2170,6 +2182,8 @@ async fn mandates_incoming_webhook_flow(api::OutgoingWebhookContent::MandateDetails(mandates_response),Some(updated_mandate.created_at),webhook_recipient,+ None,+ business_profile,)).await?;}@@ -2288,6 +2302,8 @@ async fn frm_incoming_webhook_flow(api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),primary_object_created_at,webhook_recipient,+ None,+ business_profile,)).await?;};@@ -2425,6 +2441,8 @@ async fn disputes_incoming_webhook_flow(api::OutgoingWebhookContent::DisputeDetails(disputes_response),Some(dispute_object.created_at),webhook_recipient,+ None,+ business_profile,)).await?;metrics::INCOMING_DISPUTE_WEBHOOK_MERCHANT_NOTIFIED_METRIC.add(1, &[]);@@ -2450,20 +2468,20 @@ async fn bank_transfer_webhook_flow(webhook_details: api::IncomingWebhookDetails,source_verified: bool,) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {- let (response, created_by) = if source_verified {+ let (response, created_by, payment_attempt) = if source_verified {let payment_attempt = get_payment_attempt_from_object_reference_id(&state,webhook_details.object_reference_id,platform.get_processor(),).await?;- let payment_id = payment_attempt.payment_id;+ let payment_id = payment_attempt.payment_id.clone();let created_by = payment_attempt.created_by.clone();let request = api::PaymentsRequest {payment_id: Some(api_models::payments::PaymentIdType::PaymentIntentId(payment_id,)),- payment_token: payment_attempt.payment_token,+ payment_token: payment_attempt.payment_token.clone(),..Default::default()};let response = Box::pin(payments::payments_core::<@@ -2488,13 +2506,14 @@ async fn bank_transfer_webhook_flow(None,)).await;- (response, created_by)+ (response, created_by, Some(payment_attempt.clone()))} else {(Err(report!(errors::ApiErrorResponse::WebhookAuthenticationFailed)),None,+ None,)};@@ -2525,6 +2544,10 @@ async fn bank_transfer_webhook_flow(api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),primary_object_created_at,webhook_recipient,+ payment_attempt.map(|pa| WebhookResourceData::Payment {+ payment_attempt: pa,+ }),+ business_profile,)).await?;}diff --git a/crates/router/src/core/webhooks/incoming_v2.rs b/crates/router/src/core/webhooks/incoming_v2.rsindex 88ee3e094a..ac138364df 100644--- a/crates/router/src/core/webhooks/incoming_v2.rs+++ b/crates/router/src/core/webhooks/incoming_v2.rs@@ -11,7 +11,7 @@ use hyperswitch_domain_models::{router_request_types::VerifyWebhookSourceRequestData,router_response_types::{VerifyWebhookSourceResponseData, VerifyWebhookStatus},};-use hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails;+use hyperswitch_interfaces::webhooks::{IncomingWebhookRequestDetails, WebhookResourceData};use router_env::{instrument, tracing, RequestId};use super::{types, utils, MERCHANT_ID};diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rsindex 56b620ee9d..d71a21ccae 100644--- a/crates/router/src/core/webhooks/outgoing.rs+++ b/crates/router/src/core/webhooks/outgoing.rs@@ -1,32 +1,36 @@-use std::collections::HashMap;+use std::{collections::HashMap, str::FromStr};use api_models::{webhook_events::{OutgoingWebhookRequestContent, OutgoingWebhookResponseContent},webhooks,};+use common_enums::SurchargeEventMapper;use common_utils::{+ errors::CustomResult,ext_traits::{Encode, StringExt},request::RequestContent,type_name,types::keymanager::Identifier,};use diesel_models::process_tracker::business_status;-use error_stack::{report, ResultExt};+use error_stack::{report, Report, ResultExt};use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation};-use hyperswitch_interfaces::consts;+use hyperswitch_interfaces::{consts, webhooks::WebhookResourceData};use hyperswitch_masking::{ExposeInterface, Mask, PeekInterface, Secret};use router_env::{instrument,tracing::{self, Instrument},};-use super::{types, utils, MERCHANT_ID};+use super::{types, utils, MERCHANT_CONNECTOR_ACCOUNT_ID, MERCHANT_ID};#[cfg(feature = "stripe")]use crate::compatibility::stripe::webhooks as stripe_webhooks;use crate::{core::{- errors::{self, CustomResult},+ errors::{self, utils::StorageErrorExt},metrics,+ payments::helpers::MerchantConnectorAccountType,+ webhooks::types::WebhookDeliveryResponse,},db::StorageInterface,events::outgoing_webhook_logs::{@@ -39,75 +43,276 @@ use crate::{api,domain::{self},storage::{self, enums},- transformers::ForeignFrom,+ transformers::{ForeignFrom, ForeignTryFrom},},utils::{OptionExt, ValueExt},workflows::outgoing_webhook_retry,};+pub(crate) async fn get_webhook_events(+ state: &SessionState,+ platform: domain::Platform,+ primary_event_type: enums::EventType,+ primary_content: &api::OutgoingWebhookContent,+ webhook_resource_data: Option<WebhookResourceData>,+ provider_profile: &domain::Profile,+ webhook_recipient: &utils::WebhookRecipientContext,+) -> CustomResult<Vec<types::WebhookPayload>, errors::ApiErrorResponse> {+ let mut webhook_events = vec![types::WebhookPayload {+ event_type: primary_event_type,+ event_content: Some(primary_content.clone()),+ recipient_data: types::WebhookRecipientData::Merchant {+ merchant_id: webhook_recipient.merchant_account.get_id().clone(),+ },+ }];++ #[cfg(feature = "v1")]+ if let Some(surcharge_connector_id) = provider_profile+ .surcharge_connector_details+ .as_ref()+ .and_then(|details| details.surcharge_connector_id.clone())+ {+ match get_surcharge_webhook_event(+ state,+ platform,+ primary_event_type,+ webhook_resource_data,+ surcharge_connector_id,+ )+ .await+ {+ Ok(Some(event_data)) => webhook_events.push(event_data),+ Ok(None) => {+ logger::debug!(+ "No surcharge webhook event generated for primary event type {}",+ primary_event_type+ );+ }+ Err(error) => {+ logger::error!(+ ?error,+ "Failed to fetch surcharge connector or build surcharge webhook event"+ );+ }+ }+ }++ Ok(webhook_events)+}++/// Fetches surcharge connector and builds surcharge webhook event if applicable.+#[cfg(feature = "v1")]+async fn get_surcharge_webhook_event(+ state: &SessionState,+ platform: domain::Platform,+ primary_event_type: enums::EventType,+ webhook_resource_data: Option<WebhookResourceData>,+ merchant_surcharge_connector_id: common_utils::id_type::MerchantConnectorAccountId,+) -> CustomResult<Option<types::WebhookPayload>, errors::ApiErrorResponse> {+ let merchant_surcharge_connector = state+ .store+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(+ platform.get_provider().get_account().get_id(),+ &merchant_surcharge_connector_id,+ platform.get_provider().get_key_store(),+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {+ id: merchant_surcharge_connector_id+ .get_string_repr()+ .to_string(),+ })?;++ let connector_name =+ api::enums::SurchargeConnectors::from_str(&merchant_surcharge_connector.connector_name)+ .change_context(errors::ApiErrorResponse::InvalidDataValue {+ field_name: "connector",+ })?;++ let surcharge_event = match primary_event_type.to_surcharge_event() {+ Some(event) => event,+ None => return Ok(None),+ };++ if !connector_name.should_notify_connector(primary_event_type) {+ return Ok(None);+ }++ let resource = match webhook_resource_data {+ Some(r) => r,+ None => return Ok(None),+ };++ let payment_attempt = resource.get_payment_attempt();++ types::WebhookPayload::build_surcharge_payload(+ surcharge_event,+ payment_attempt,+ &merchant_surcharge_connector,+ )+}+#[allow(clippy::too_many_arguments)]#[instrument(skip_all)]pub(crate) async fn create_event_and_trigger_outgoing_webhook(state: SessionState,platform: domain::Platform,- event_type: enums::EventType,+ primary_event_type: enums::EventType,event_class: enums::EventClass,primary_object_id: String,primary_object_type: enums::EventObjectType,- content: api::OutgoingWebhookContent,+ primary_content: api::OutgoingWebhookContent,primary_object_created_at: Option<time::PrimitiveDateTime>,webhook_recipient: utils::WebhookRecipientContext,+ webhook_resource_data: Option<WebhookResourceData>,+ provider_profile: domain::Profile,) -> CustomResult<(), errors::ApiErrorResponse> {- let delivery_attempt = enums::WebhookDeliveryAttempt::InitialAttempt;- let idempotent_event_id =- utils::get_idempotent_event_id(&primary_object_id, event_type, delivery_attempt)- .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)- .attach_printable("Failed to generate idempotent event ID")?;- let webhook_url_result = get_webhook_url_from_business_profile(&webhook_recipient.profile);-- if !state.conf.webhooks.outgoing_enabled- || webhook_url_result.is_err()- || webhook_url_result.as_ref().is_ok_and(String::is_empty)- {+ if !state.conf.webhooks.outgoing_enabled {logger::debug!(business_profile_id=?webhook_recipient.profile.get_id(),- %idempotent_event_id,- "Outgoing webhooks are disabled in application configuration, or merchant webhook URL \- could not be obtained; skipping outgoing webhooks for event"+ "Outgoing webhooks are disabled in application configuration");return Ok(());- }+ };++ let events_to_trigger = get_webhook_events(+ &state,+ platform.clone(),+ primary_event_type,+ &primary_content,+ webhook_resource_data,+ &provider_profile,+ &webhook_recipient,+ )+ .await?;- let event_id = utils::generate_event_id();let provider_merchant_id = platform.get_provider().get_account().get_id().clone();let processor_merchant_id = platform.get_processor().get_account().get_id().clone();++ for event_data in events_to_trigger {+ let event_type = event_data.event_type;+ let _ = insert_event_and_spawn_webhook_delivery(+ state.clone(),+ &platform,+ event_data,+ &webhook_recipient,+ provider_merchant_id.clone(),+ processor_merchant_id.clone(),+ primary_object_id.clone(),+ primary_object_type,+ primary_object_created_at,+ event_class,+ )+ .await+ .inspect_err(|error| {+ logger::error!(+ ?error,+ "Failed to insert event and spawn webhook delivery for event type {}",+ event_type+ );+ });+ }++ Ok(())+}++#[allow(clippy::too_many_arguments)]+async fn insert_event_and_spawn_webhook_delivery(+ state: SessionState,+ platform: &domain::Platform,+ event_data: types::WebhookPayload,+ webhook_recipient: &utils::WebhookRecipientContext,+ provider_merchant_id: common_utils::id_type::MerchantId,+ processor_merchant_id: common_utils::id_type::MerchantId,+ primary_object_id: String,+ primary_object_type: enums::EventObjectType,+ primary_object_created_at: Option<time::PrimitiveDateTime>,+ event_class: enums::EventClass,+) -> CustomResult<(), errors::ApiErrorResponse> {let now = common_utils::date_time::now();+ let delivery_attempt = enums::WebhookDeliveryAttempt::InitialAttempt;+ let idempotent_event_id =+ utils::get_idempotent_event_id(&primary_object_id, event_data.event_type, delivery_attempt)+ .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)+ .attach_printable("Failed to generate idempotent event ID")?;- let outgoing_webhook = api::OutgoingWebhook {- merchant_id: provider_merchant_id.clone(),- event_id: event_id.clone(),- event_type,- content: content.clone(),- timestamp: now,- processor_merchant_id: Some(processor_merchant_id.clone()),+ if let types::WebhookRecipientData::Merchant { .. } = event_data.recipient_data {+ let webhook_url_result = get_webhook_url_from_business_profile(&webhook_recipient.profile);+ if webhook_url_result.is_err() || webhook_url_result.as_ref().is_ok_and(String::is_empty) {+ logger::debug!(+ business_profile_id=?webhook_recipient.profile.get_id(),+ %idempotent_event_id,+ "merchant webhook URL \+ could not be obtained; skipping outgoing webhooks for event"+ );+ }};- let request_content = get_outgoing_webhook_request(- &webhook_recipient.merchant_account,- outgoing_webhook,- &webhook_recipient.profile,- )- .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)- .attach_printable("Failed to construct outgoing webhook request content")?;+ let event_id = utils::generate_event_id();+ let event_type = event_data.event_type;+ let content = event_data.event_content.clone();++ let outgoing_webhook =+ content+ .as_ref()+ .map(+ |event_content_data: &webhooks::OutgoingWebhookContent| api::OutgoingWebhook {+ merchant_id: provider_merchant_id.clone(),+ event_id: event_id.clone(),+ event_type,+ content: event_content_data.clone(),+ timestamp: now,+ processor_merchant_id: Some(processor_merchant_id.clone()),+ },+ );++ let request_content = outgoing_webhook+ .map(|outgoing_webhook_data| {+ get_outgoing_webhook_request(+ &webhook_recipient.merchant_account,+ outgoing_webhook_data,+ &webhook_recipient.profile,+ )+ })+ .transpose()+ .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)+ .attach_printable("Failed to construct outgoing webhook request content")?;- let event_metadata = storage::EventMetadata::foreign_from(&content);let key_manager_state = &(&state).into();+ let encrypted_content = match request_content {+ Some(ref request_content_data) => {+ let encoded = request_content_data+ .clone()+ .encode_to_string_of_json()+ .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)+ .attach_printable("Failed to encode outgoing webhook request content")+ .map(Secret::new)?;++ let encrypted = crypto_operation(+ key_manager_state,+ type_name!(domain::Event),+ CryptoOperation::Encrypt(encoded),+ Identifier::Merchant(webhook_recipient.key_store.merchant_id.clone()),+ webhook_recipient.key_store.key.get_inner().peek(),+ )+ .await+ .and_then(|val| val.try_into_operation())+ .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)+ .attach_printable("Failed to encrypt outgoing webhook request content")?;++ Some(encrypted)+ }+ None => None,+ };++ let recipient = event_data.recipient_data.get_event_recipient();+ let event_metadata = storage::EventMetadata::foreign_try_from(&event_data)?;let new_event = domain::Event {event_id: event_id.clone(),event_type,event_class,is_webhook_notified: false,- primary_object_id,+ primary_object_id: primary_object_id.clone(),primary_object_type,created_at: now,merchant_id: Some(provider_merchant_id.clone()),@@ -115,31 +320,14 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(primary_object_created_at,idempotent_event_id: Some(idempotent_event_id.clone()),initial_attempt_id: Some(event_id.clone()),- request: Some(- crypto_operation(- key_manager_state,- type_name!(domain::Event),- CryptoOperation::Encrypt(- request_content- .encode_to_string_of_json()- .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)- .attach_printable("Failed to encode outgoing webhook request content")- .map(Secret::new)?,- ),- Identifier::Merchant(webhook_recipient.key_store.merchant_id.clone()),- webhook_recipient.key_store.key.get_inner().peek(),- )- .await- .and_then(|val| val.try_into_operation())- .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)- .attach_printable("Failed to encrypt outgoing webhook request content")?,- ),+ request: encrypted_content,response: None,delivery_attempt: Some(delivery_attempt),metadata: Some(event_metadata),is_overall_delivery_successful: Some(false),processor_merchant_id: Some(processor_merchant_id.clone()),initiator_merchant_id: Some(webhook_recipient.key_store.merchant_id.clone()),+ recipient: Some(recipient),};let lock_value = utils::perform_redis_lock(@@ -202,10 +390,11 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(let process_tracker = add_outgoing_webhook_retry_task_to_process_tracker(&*state.store,state.superposition_service.as_ref(),- &platform,- &webhook_recipient,+ platform,+ webhook_recipient,&event,state.conf.application_source,+ event_data.recipient_data.clone(),).await.inspect_err(|error| {@@ -216,24 +405,28 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(}).ok();+ let cloned_state = state.clone();let cloned_key_store = webhook_recipient.key_store.clone();let cloned_provider_merchant_id = provider_merchant_id.clone();let cloned_processor_merchant_id = processor_merchant_id.clone();+ let cloned_profile = webhook_recipient.profile.clone();+ let cloned_content = content.clone();// Using a tokio spawn here and not arbiter because not all caller of this function// may have an actix arbitertokio::spawn(async move {Box::pin(trigger_webhook_and_raise_event(- state,- webhook_recipient.profile,+ cloned_state,+ cloned_profile,&cloned_key_store,cloned_provider_merchant_id,cloned_processor_merchant_id,event,request_content,delivery_attempt,- Some(content),+ cloned_content,process_tracker,+ event_data.recipient_data,)).await;}@@ -243,6 +436,30 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(Ok(())}+/// Trait for dispatching outgoing webhook delivery.+///+/// Two concrete implementations exist:+/// - [`MerchantWebhook`]: delivers webhooks to merchant-configured URLs+/// - [`ConnectorWebhook`]: reserved for delivering connector-facing webhooks+#[async_trait::async_trait]+trait WebhookTrigger: Send + Sync {+ #[allow(clippy::too_many_arguments)]+ async fn trigger_and_raise(+ &self,+ state: SessionState,+ business_profile: domain::Profile,+ merchant_key_store: domain::MerchantKeyStore,+ provider_merchant_id: common_utils::id_type::MerchantId,+ processor_merchant_id: common_utils::id_type::MerchantId,+ event: domain::Event,+ request_content: Option<OutgoingWebhookRequestContent>,+ delivery_attempt: enums::WebhookDeliveryAttempt,+ content: Option<api::OutgoingWebhookContent>,+ process_tracker: Option<storage::ProcessTracker>,+ recipient_data: types::WebhookRecipientData,+ );+}+#[allow(clippy::too_many_arguments)]#[instrument(skip_all)]pub(crate) async fn trigger_webhook_and_raise_event(@@ -252,50 +469,362 @@ pub(crate) async fn trigger_webhook_and_raise_event(provider_merchant_id: common_utils::id_type::MerchantId,processor_merchant_id: common_utils::id_type::MerchantId,event: domain::Event,- request_content: OutgoingWebhookRequestContent,+ request_content: Option<OutgoingWebhookRequestContent>,delivery_attempt: enums::WebhookDeliveryAttempt,content: Option<api::OutgoingWebhookContent>,process_tracker: Option<storage::ProcessTracker>,+ recipient_data: types::WebhookRecipientData,) {- logger::debug!(- event_id=%event.event_id,- idempotent_event_id=?event.idempotent_event_id,- initial_attempt_id=?event.initial_attempt_id,- "Attempting to send webhook"+ let trigger: Box<dyn WebhookTrigger> = match event.recipient {+ Some(enums::EventRecipient::Connector) => Box::new(types::ConnectorWebhook),+ Some(enums::EventRecipient::Merchant) | None => Box::new(types::MerchantWebhook),+ };++ trigger+ .trigger_and_raise(+ state,+ business_profile,+ merchant_key_store.clone(),+ provider_merchant_id,+ processor_merchant_id,+ event,+ request_content,+ delivery_attempt,+ content,+ process_tracker,+ recipient_data,+ )+ .await;+}++#[async_trait::async_trait]+impl WebhookTrigger for types::MerchantWebhook {+ async fn trigger_and_raise(+ &self,+ state: SessionState,+ business_profile: domain::Profile,+ merchant_key_store: domain::MerchantKeyStore,+ provider_merchant_id: common_utils::id_type::MerchantId,+ processor_merchant_id: common_utils::id_type::MerchantId,+ event: domain::Event,+ request_content: Option<OutgoingWebhookRequestContent>,+ delivery_attempt: enums::WebhookDeliveryAttempt,+ content: Option<api::OutgoingWebhookContent>,+ process_tracker: Option<storage::ProcessTracker>,+ recipient_data: types::WebhookRecipientData,+ ) {+ logger::debug!(+ event_id=%event.event_id,+ idempotent_event_id=?event.idempotent_event_id,+ initial_attempt_id=?event.initial_attempt_id,+ "Attempting to send webhook"+ );++ let trigger_webhook_result = Box::pin(trigger_webhook_to_merchant(+ state.clone(),+ business_profile,+ &merchant_key_store,+ event.clone(),+ request_content,+ delivery_attempt,+ process_tracker,+ recipient_data,+ ))+ .await;++ let _ = raise_webhooks_analytics_event(+ state,+ trigger_webhook_result,+ content,+ provider_merchant_id,+ processor_merchant_id,+ event,+ )+ .await;+ }+}++#[async_trait::async_trait]+impl WebhookTrigger for types::ConnectorWebhook {+ async fn trigger_and_raise(+ &self,+ state: SessionState,+ business_profile: domain::Profile,+ merchant_key_store: domain::MerchantKeyStore,+ provider_merchant_id: common_utils::id_type::MerchantId,+ processor_merchant_id: common_utils::id_type::MerchantId,+ event: domain::Event,+ _request_content: Option<OutgoingWebhookRequestContent>,+ delivery_attempt: enums::WebhookDeliveryAttempt,+ content: Option<api::OutgoingWebhookContent>,+ process_tracker: Option<storage::ProcessTracker>,+ recipient_data: types::WebhookRecipientData,+ ) {+ logger::debug!(+ event_id=%event.event_id,+ "Attempting to notify connector via UCS"+ );++ let trigger_webhook_result = Box::pin(trigger_webhook_to_connector(+ state.clone(),+ business_profile,+ merchant_key_store.clone(),+ event.clone(),+ delivery_attempt,+ process_tracker,+ recipient_data,+ ))+ .await;++ let _ = raise_webhooks_analytics_event(+ state,+ trigger_webhook_result,+ content,+ provider_merchant_id,+ processor_merchant_id,+ event,+ )+ .await;+ }+}++#[allow(clippy::too_many_arguments)]+async fn trigger_webhook_to_connector(+ state: SessionState,+ business_profile: domain::Profile,+ merchant_key_store: domain::MerchantKeyStore,+ event: domain::Event,+ delivery_attempt: enums::WebhookDeliveryAttempt,+ process_tracker: Option<storage::ProcessTracker>,+ recipient_data: types::WebhookRecipientData,+) -> CustomResult<+ (domain::Event, Option<Report<errors::WebhooksFlowError>>),+ errors::WebhooksFlowError,+> {+ let provider_merchant_id = business_profile.merchant_id.clone();++ let merchant_connector_id = match &recipient_data {+ types::WebhookRecipientData::Connector {+ merchant_connector_id,+ ..+ } => merchant_connector_id,+ _ => {+ logger::error!("Missing merchant_connector_id for connector webhook");+ return Err(errors::WebhooksFlowError::MerchantConfigNotFound.into());+ }+ };++ let notify_feature_data = match &recipient_data {+ types::WebhookRecipientData::Connector { feature_data, .. } => feature_data.clone(),+ _ => {+ logger::error!("Missing merchant_connector_id for connector webhook");+ return Err(errors::WebhooksFlowError::MerchantConfigNotFound.into());+ }+ };++ let mca_result = state+ .store+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(+ &provider_merchant_id,+ merchant_connector_id,+ &merchant_key_store,+ )+ .await;++ let mca = match mca_result {+ Ok(mca) => mca,+ Err(err) => {+ logger::error!(?err, "Failed to find merchant connector account");+ return Err(errors::WebhooksFlowError::MerchantConfigNotFound.into());+ }+ };++ let connector_name = mca.connector_name.clone();++ let (notify_request, connector_auth_metadata, notify_event_type) =+ crate::core::unified_connector_service::build_notify_connector_request(+ &event,+ &provider_merchant_id,+ MerchantConnectorAccountType::DbVal(Box::new(mca)),+ connector_name,+ notify_feature_data,+ )+ .change_context(errors::WebhooksFlowError::WebhookRequestConstructionFailed)?;++ let response = crate::core::unified_connector_service::call_unified_connector_service_for_notify_connector(+ &state,+ &event,+ connector_auth_metadata,+ notify_request,+ notify_event_type,+ &provider_merchant_id,+ business_profile.get_id(),+ )+ .await;++ metrics::WEBHOOK_OUTGOING_COUNT.add(+ 1,+ router_env::metric_attributes!((+ MERCHANT_CONNECTOR_ACCOUNT_ID,+ merchant_connector_id.clone()+ )),);+ logger::debug!(outgoing_webhook_response=?response);- let trigger_webhook_result = trigger_webhook_to_merchant(- state.clone(),- business_profile,- merchant_key_store,- event.clone(),- request_content,- delivery_attempt,- process_tracker,- )- .await;+ match response {+ Ok(ref resp) if resp.is_success() => {+ update_payment_attempt_from_webhook_response(+ &state,+ &event,+ &provider_merchant_id,+ &merchant_key_store,+ )+ .await;+ }+ _ => {}+ };- let _ = raise_webhooks_analytics_event(- state,- trigger_webhook_result,- content,- provider_merchant_id,- processor_merchant_id,- event,- merchant_key_store,- )- .await;+ match response {+ Ok(response) => {+ delivery_attempt+ .handle_success_response(+ state,+ merchant_key_store.clone(),+ &provider_merchant_id,+ &event.event_id,+ process_tracker,+ response,+ recipient_data,+ )+ .await+ }+ Err(client_error) => {+ delivery_attempt+ .handle_error_response(+ state,+ merchant_key_store.clone(),+ &business_profile.merchant_id,+ &event.event_id,+ process_tracker,+ client_error,+ recipient_data,+ )+ .await+ }+ }+}++async fn update_payment_attempt_from_webhook_response(+ state: &SessionState,+ event: &domain::Event,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ merchant_key_store: &domain::MerchantKeyStore,+) {+ if event.event_type == enums::EventType::SurchargePaymentSucceeded {+ let merchant_account = state+ .store+ .find_merchant_account_by_merchant_id(processor_merchant_id, merchant_key_store)+ .await;++ let storage_scheme = match &merchant_account {+ Ok(ma) => ma.storage_scheme,+ Err(err) => {+ logger::warn!(?err, "Using default PostgresOnly storage scheme");+ enums::MerchantStorageScheme::PostgresOnly+ }+ };++ let attempt_id = match &event.metadata {+ Some(diesel_models::EventMetadata::Surcharge {+ payment_id: _,+ attempt_id,+ }) => attempt_id,+ _ => {+ logger::debug!(+ "Could not find attempt_id in event metadata for event_id: {}, skipping payment attempt update",+ event.event_id+ );+ return;+ }+ };++ let payment_attempt_result = state+ .store+ .find_payment_attempt_by_attempt_id_processor_merchant_id(+ attempt_id,+ processor_merchant_id,+ storage_scheme,+ merchant_key_store,+ )+ .await;+ let payment_attempt = match payment_attempt_result {+ Ok(pa) => pa,+ Err(err) => {+ logger::warn!(+ ?err,+ attempt_id = %attempt_id,+ "Could not find payment attempt for sale_notified update"+ );+ return;+ }+ };+ let existing_details = match payment_attempt.external_surcharge_details.clone() {+ Some(details) => details,+ None => {+ logger::debug!(+ attempt_id = %attempt_id,+ "No external_surcharge_details found; nothing to update"+ );+ return;+ }+ };+ let updated_details = common_types::payments::ExternalSurchargeDetails {+ external_surcharge_id: existing_details.external_surcharge_id,+ external_surcharge_amount: existing_details.external_surcharge_amount,+ sale_notified: true,+ };+ let update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ExternalSurchargeUpdate {+ external_surcharge_details: updated_details,+ updated_by: storage_scheme.to_string(),+ };+ let _ = state+ .store+ .update_payment_attempt_with_attempt_id(+ payment_attempt,+ update,+ storage_scheme,+ merchant_key_store,+ )+ .await+ .inspect_err(|err| {+ logger::error!(+ ?err,+ attempt_id = %attempt_id,+ "Failed to update sale_notified on payment attempt"+ );+ });+ }+ logger::info!("Successfully updated payment attempt");}+#[allow(clippy::too_many_arguments)]async fn trigger_webhook_to_merchant(state: SessionState,business_profile: domain::Profile,merchant_key_store: &domain::MerchantKeyStore,event: domain::Event,- request_content: OutgoingWebhookRequestContent,+ request_content: Option<OutgoingWebhookRequestContent>,delivery_attempt: enums::WebhookDeliveryAttempt,process_tracker: Option<storage::ProcessTracker>,-) -> CustomResult<(), errors::WebhooksFlowError> {+ recipient_data: types::WebhookRecipientData,+) -> CustomResult<+ (domain::Event, Option<Report<errors::WebhooksFlowError>>),+ errors::WebhooksFlowError,+> {+ let request_content = request_content+ .ok_or(errors::WebhooksFlowError::WebhookRequestConstructionFailed)+ .attach_printable("OutgoingWebhookRequestContent not found")?;+let webhook_url = match (get_webhook_url_from_business_profile(&business_profile),process_tracker.clone(),@@ -349,172 +878,52 @@ async fn trigger_webhook_to_merchant();logger::debug!(outgoing_webhook_response=?response);- let webhook_recipient_merchant_id = &business_profile.merchant_id;-- match delivery_attempt {- enums::WebhookDeliveryAttempt::InitialAttempt => match response {- Err(client_error) => {- api_client_error_handler(- state.clone(),- merchant_key_store.clone(),- webhook_recipient_merchant_id,- &event_id,- client_error,- delivery_attempt,- ScheduleWebhookRetry::NoSchedule,- )- .await?- }- Ok(response) => {- let status_code = response.status();- let updated_event = update_event_in_storage(- state.clone(),+ match response {+ Ok(response) => {+ delivery_attempt+ .handle_success_response(+ state,merchant_key_store.clone(),- &event_id,+ &business_profile.merchant_id,+ &event_id.clone(),+ process_tracker,response,+ recipient_data,)- .await?;-- if status_code.is_success() {- update_overall_delivery_status_in_storage(- state.clone(),- merchant_key_store.clone(),- updated_event,- )- .await?;-- success_response_handler(- state.clone(),- webhook_recipient_merchant_id,- process_tracker,- business_status::INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL,- )- .await?;- } else {- error_response_handler(- state.clone(),- webhook_recipient_merchant_id,- delivery_attempt,- status_code.as_u16(),- "Ignoring error when sending webhook to merchant",- ScheduleWebhookRetry::NoSchedule,- )- .await?;- }- }- },- enums::WebhookDeliveryAttempt::AutomaticRetry => {- let process_tracker = process_tracker- .get_required_value("process_tracker")- .change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)- .attach_printable("`process_tracker` is unavailable in automatic retry flow")?;- match response {- Err(client_error) => {- api_client_error_handler(- state.clone(),- merchant_key_store.clone(),- webhook_recipient_merchant_id,- &event_id,- client_error,- delivery_attempt,- ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)),- )- .await?;- }- Ok(response) => {- let status_code = response.status();- let updated_event = update_event_in_storage(- state.clone(),- merchant_key_store.clone(),- &event_id,- response,- )- .await?;-- if status_code.is_success() {- update_overall_delivery_status_in_storage(- state.clone(),- merchant_key_store.clone(),- updated_event,- )- .await?;-- success_response_handler(- state.clone(),- webhook_recipient_merchant_id,- Some(process_tracker),- "COMPLETED_BY_PT",- )- .await?;- } else {- error_response_handler(- state.clone(),- webhook_recipient_merchant_id,- delivery_attempt,- status_code.as_u16(),- "An error occurred when sending webhook to merchant",- ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)),- )- .await?;- }- }- }+ .await}- enums::WebhookDeliveryAttempt::ManualRetry => match response {- Err(client_error) => {- api_client_error_handler(- state.clone(),+ Err(client_error) => {+ delivery_attempt+ .handle_error_response(+ state,merchant_key_store.clone(),- webhook_recipient_merchant_id,- &event_id,+ &business_profile.merchant_id,+ &event_id.clone(),+ process_tracker,client_error,- delivery_attempt,- ScheduleWebhookRetry::NoSchedule,- )- .await?- }- Ok(response) => {- let status_code = response.status();- let _updated_event = update_event_in_storage(- state.clone(),- merchant_key_store.clone(),- &event_id,- response,+ recipient_data,)- .await?;-- if status_code.is_success() {- increment_webhook_outgoing_received_count(webhook_recipient_merchant_id);- } else {- error_response_handler(- state,- webhook_recipient_merchant_id,- delivery_attempt,- status_code.as_u16(),- "Ignoring error when sending webhook to merchant",- ScheduleWebhookRetry::NoSchedule,- )- .await?;- }- }- },+ .await+ }}-- Ok(())}async fn raise_webhooks_analytics_event(state: SessionState,- trigger_webhook_result: CustomResult<(), errors::WebhooksFlowError>,+ trigger_webhook_result: CustomResult<+ (domain::Event, Option<Report<errors::WebhooksFlowError>>),+ errors::WebhooksFlowError,+ >,content: Option<api::OutgoingWebhookContent>,provider_merchant_id: common_utils::id_type::MerchantId,processor_merchant_id: common_utils::id_type::MerchantId,- event: domain::Event,- merchant_key_store: &domain::MerchantKeyStore,+ fallback_event: domain::Event,) {- let event_id = event.event_id;-- let error = if let Err(error) = trigger_webhook_result {+ let (updated_event, optional_error) = match trigger_webhook_result {+ Ok((updated_event, error)) => (updated_event, error),+ Err(error) => (fallback_event, Some(error)),+ };+ let error = optional_error.and_then(|error| {logger::error!(?error, "Failed to send webhook to merchant");serde_json::to_value(error.current_context())@@ -523,54 +932,42 @@ async fn raise_webhooks_analytics_event(logger::error!(?error, "Failed to serialize outgoing webhook error as JSON");}).ok()- } else {- None- };+ });let outgoing_webhook_event_content = content.as_ref()- .and_then(api::OutgoingWebhookContent::get_outgoing_webhook_event_content)- .or_else(|| get_outgoing_webhook_event_content_from_event_metadata(event.metadata));-- // Fetch updated_event from db (event_id is globally unique)- let updated_event = state- .store- .find_event_by_event_id(&event_id, merchant_key_store)- .await- .attach_printable_lazy(|| format!("event not found for id: {}", &event_id))- .map_err(|error| {- logger::error!(?error);- error- })- .ok();+ .and_then(OutgoingWebhookEventMetric::get_outgoing_webhook_event_content)+ .or_else(|| get_outgoing_webhook_event_content_from_event_metadata(updated_event.metadata));// Get status_code from webhook response- let status_code = updated_event.and_then(|updated_event| {+ let status_code = {let webhook_response: Option<OutgoingWebhookResponseContent> =updated_event.response.and_then(|res| {- res.peek()- .parse_struct("OutgoingWebhookResponseContent")- .map_err(|error| {- logger::error!(?error, "Error deserializing webhook response");- error- })- .ok()+ StringExt::parse_struct(+ PeekInterface::peek(res.get_inner()),+ "OutgoingWebhookResponseContent",+ )+ .map_err(|error| {+ logger::error!(?error, "Error deserializing webhook response");+ error+ })+ .ok()});webhook_response.and_then(|res| res.status_code)- });+ };let webhook_event = OutgoingWebhookEvent::new(state.tenant.tenant_id.clone(),provider_merchant_id,Some(processor_merchant_id),- event.initiator_merchant_id,- event_id,- event.event_type,+ updated_event.initiator_merchant_id,+ updated_event.event_id,+ updated_event.event_type,outgoing_webhook_event_content,error,- event.initial_attempt_id,+ updated_event.initial_attempt_id,status_code,- event.delivery_attempt,+ updated_event.delivery_attempt,);state.event_handler().log_event(&webhook_event);}@@ -582,6 +979,7 @@ pub(crate) async fn add_outgoing_webhook_retry_task_to_process_tracker(webhook_recipient: &utils::WebhookRecipientContext,event: &domain::Event,application_source: common_enums::ApplicationSource,+ webhook_recipient_data: types::WebhookRecipientData,) -> CustomResult<storage::ProcessTracker, errors::StorageError> {let processor_merchant_id = platform.get_processor().get_account().get_id().clone();let provider_merchant_id = platform.get_provider().get_account().get_id().clone();@@ -609,6 +1007,7 @@ pub(crate) async fn add_outgoing_webhook_retry_task_to_process_tracker(primary_object_id: event.primary_object_id.clone(),primary_object_type: event.primary_object_type,initial_attempt_id: event.initial_attempt_id.clone(),+ recipient_data: Some(webhook_recipient_data),};let runner = storage::ProcessTrackerRunner::OutgoingWebhookRetryWorkflow;@@ -783,30 +1182,35 @@ async fn update_event_if_client_error(.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)}+#[allow(clippy::too_many_arguments)]async fn api_client_error_handler(state: SessionState,merchant_key_store: domain::MerchantKeyStore,webhook_recipient_merchant_id: &common_utils::id_type::MerchantId,event_id: &str,- client_error: error_stack::Report<errors::ApiClientError>,+ client_error: Report<errors::ApiClientError>,delivery_attempt: enums::WebhookDeliveryAttempt,schedule_webhook_retry: ScheduleWebhookRetry,-) -> CustomResult<(), errors::WebhooksFlowError> {+ recipient_data: types::WebhookRecipientData,+) -> CustomResult<+ (domain::Event, Option<Report<errors::WebhooksFlowError>>),+ errors::WebhooksFlowError,+> {// Not including detailed error message in response information since it contains too// much of diagnostic information to be exposed to the merchant.- update_event_if_client_error(+ let updated_event = update_event_if_client_error(state.clone(),merchant_key_store,event_id,- "Unable to send request to merchant server".to_string(),+ "Unable to send request to merchant/connector server".to_string(),).await?;- let error = client_error.change_context(errors::WebhooksFlowError::CallToMerchantFailed);+ let error = client_error.change_context(errors::WebhooksFlowError::WebhookCallFailed);logger::error!(?error,?delivery_attempt,- "An error occurred when sending webhook to merchant"+ "An error occurred when sending webhook to merchant/connector");if let ScheduleWebhookRetry::WithProcessTracker(process_tracker) = schedule_webhook_retry {@@ -814,58 +1218,35 @@ async fn api_client_error_handler(// merchant_id for retry schedule lookup, consistent with initial scheduling.outgoing_webhook_retry::retry_webhook_delivery_task(&*state.store,- state.superposition_service.as_ref(),webhook_recipient_merchant_id,+ state.superposition_service.as_ref(),*process_tracker,+ recipient_data,).await.change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)?;}- Err(error)+ Ok((updated_event, Some(error)))}-async fn update_event_in_storage(+async fn update_webhook_response_in_storage<R: WebhookDeliveryResponse>(state: SessionState,merchant_key_store: domain::MerchantKeyStore,event_id: &str,- response: reqwest::Response,+ response: R,+ status_code: u16,+ is_webhook_notified: bool,) -> CustomResult<domain::Event, errors::WebhooksFlowError> {- let status_code = response.status();- let is_webhook_notified = status_code.is_success();let key_manager_state = &(&state).into();- let response_headers = response- .headers()- .iter()- .map(|(name, value)| {- (- name.as_str().to_owned(),- value- .to_str()- .map(|s| Secret::from(String::from(s)))- .unwrap_or_else(|error| {- logger::warn!(- "Response header {} contains non-UTF-8 characters: {error:?}",- name.as_str()- );- Secret::from(String::from("Non-UTF-8 header value"))- }),- )- })- .collect::<Vec<_>>();- let response_body = response- .text()- .await- .map(Secret::from)- .unwrap_or_else(|error| {- logger::warn!("Response contains non-UTF-8 characters: {error:?}");- Secret::from(String::from("Non-UTF-8 response body"))- });+ let response_headers = response.get_response_headers();+ let error_message = response.get_error_message();+ let response_body = response.get_response_body().await;let response_to_store = OutgoingWebhookResponseContent {body: Some(response_body),headers: Some(response_headers),- status_code: Some(status_code.as_u16()),- error_message: None,+ status_code: Some(status_code),+ error_message,};let event_update = domain::EventUpdate::UpdateResponse {@@ -901,7 +1282,7 @@ async fn update_event_in_storage(async fn update_overall_delivery_status_in_storage(state: SessionState,merchant_key_store: domain::MerchantKeyStore,- updated_event: domain::Event,+ updated_event: &domain::Event,) -> CustomResult<(), errors::WebhooksFlowError> {let update_overall_delivery_status = domain::EventUpdate::OverallDeliveryStatusUpdate {is_overall_delivery_successful: true,@@ -931,20 +1312,13 @@ async fn update_overall_delivery_status_in_storage(Ok(())}-fn increment_webhook_outgoing_received_count(merchant_id: &common_utils::id_type::MerchantId) {- metrics::WEBHOOK_OUTGOING_RECEIVED_COUNT.add(- 1,- router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())),- )-}--async fn success_response_handler(+pub(crate) async fn success_response_handler(state: SessionState,- merchant_id: &common_utils::id_type::MerchantId,+ recipient_data: &types::WebhookRecipientData,process_tracker: Option<storage::ProcessTracker>,business_status: &'static str,) -> CustomResult<(), errors::WebhooksFlowError> {- increment_webhook_outgoing_received_count(merchant_id);+ utils::increment_webhook_outgoing_received_count(recipient_data);match process_tracker {Some(process_tracker) => state@@ -959,72 +1333,6 @@ async fn success_response_handler(}}-async fn error_response_handler(- state: SessionState,- webhook_recipient_merchant_id: &common_utils::id_type::MerchantId,- delivery_attempt: enums::WebhookDeliveryAttempt,- status_code: u16,- log_message: &'static str,- schedule_webhook_retry: ScheduleWebhookRetry,-) -> CustomResult<(), errors::WebhooksFlowError> {- metrics::WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT.add(- 1,- router_env::metric_attributes!((MERCHANT_ID, webhook_recipient_merchant_id.clone())),- );-- let error = report!(errors::WebhooksFlowError::NotReceivedByMerchant);- logger::warn!(?error, ?delivery_attempt, status_code, %log_message);-- if let ScheduleWebhookRetry::WithProcessTracker(process_tracker) = schedule_webhook_retry {- // Schedule a retry attempt for webhook delivery using the webhook recipient's- // merchant_id for retry schedule lookup, consistent with initial scheduling.- outgoing_webhook_retry::retry_webhook_delivery_task(- &*state.store,- state.superposition_service.as_ref(),- webhook_recipient_merchant_id,- *process_tracker,- )- .await- .change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)?;- }-- Err(error)-}--impl ForeignFrom<&api::OutgoingWebhookContent> for storage::EventMetadata {- fn foreign_from(content: &api::OutgoingWebhookContent) -> Self {- match content {- webhooks::OutgoingWebhookContent::PaymentDetails(payments_response) => Self::Payment {- payment_id: payments_response.payment_id.clone(),- },- webhooks::OutgoingWebhookContent::RefundDetails(refund_response) => Self::Refund {- payment_id: refund_response.payment_id.clone(),- refund_id: refund_response.refund_id.clone(),- },- webhooks::OutgoingWebhookContent::DisputeDetails(dispute_response) => Self::Dispute {- payment_id: dispute_response.payment_id.clone(),- attempt_id: dispute_response.attempt_id.clone(),- dispute_id: dispute_response.dispute_id.clone(),- },- webhooks::OutgoingWebhookContent::MandateDetails(mandate_response) => Self::Mandate {- payment_method_id: mandate_response.payment_method_id.clone(),- mandate_id: mandate_response.mandate_id.clone(),- },- #[cfg(feature = "payouts")]- webhooks::OutgoingWebhookContent::PayoutDetails(payout_response) => Self::Payout {- payout_id: payout_response.payout_id.clone(),- },- webhooks::OutgoingWebhookContent::SubscriptionDetails(subscription) => {- Self::Subscription {- subscription_id: subscription.id.clone(),- invoice_id: subscription.get_optional_invoice_id(),- payment_id: subscription.get_optional_payment_id(),- }- }- }- }-}-fn get_outgoing_webhook_event_content_from_event_metadata(event_metadata: Option<storage::EventMetadata>,) -> Option<OutgoingWebhookEventContent> {@@ -1075,5 +1383,419 @@ fn get_outgoing_webhook_event_content_from_event_metadata(payment_id,content: serde_json::Value::Null,},+ diesel_models::EventMetadata::Surcharge {+ payment_id,+ attempt_id,+ } => OutgoingWebhookEventContent::Surcharge {+ payment_id,+ attempt_id,+ },})}++impl ForeignFrom<&api::OutgoingWebhookContent> for storage::EventMetadata {+ fn foreign_from(content: &api::OutgoingWebhookContent) -> Self {+ match content {+ webhooks::OutgoingWebhookContent::PaymentDetails(payments_response) => Self::Payment {+ payment_id: payments_response.payment_id.clone(),+ },+ webhooks::OutgoingWebhookContent::RefundDetails(refund_response) => Self::Refund {+ payment_id: refund_response.payment_id.clone(),+ refund_id: refund_response.refund_id.clone(),+ },+ webhooks::OutgoingWebhookContent::DisputeDetails(dispute_response) => Self::Dispute {+ payment_id: dispute_response.payment_id.clone(),+ attempt_id: dispute_response.attempt_id.clone(),+ dispute_id: dispute_response.dispute_id.clone(),+ },+ webhooks::OutgoingWebhookContent::MandateDetails(mandate_response) => Self::Mandate {+ payment_method_id: mandate_response.payment_method_id.clone(),+ mandate_id: mandate_response.mandate_id.clone(),+ },+ #[cfg(feature = "payouts")]+ webhooks::OutgoingWebhookContent::PayoutDetails(payout_response) => Self::Payout {+ payout_id: payout_response.payout_id.clone(),+ },+ webhooks::OutgoingWebhookContent::SubscriptionDetails(subscription) => {+ Self::Subscription {+ subscription_id: subscription.id.clone(),+ invoice_id: subscription.get_optional_invoice_id(),+ payment_id: subscription.get_optional_payment_id(),+ }+ }+ }+ }+}++impl ForeignFrom<&types::FeatureTrackingData> for storage::EventMetadata {+ fn foreign_from(content: &types::FeatureTrackingData) -> Self {+ match content {+ types::FeatureTrackingData::SurchargeDetails(surcharge_details) => Self::Surcharge {+ payment_id: surcharge_details.payment_id.clone(),+ attempt_id: surcharge_details.attempt_id.clone(),+ },+ }+ }+}++impl ForeignTryFrom<&types::WebhookPayload> for storage::EventMetadata {+ type Error = errors::ApiErrorResponse;++ fn foreign_try_from(webhook_payload: &types::WebhookPayload) -> Result<Self, Self::Error> {+ match &webhook_payload.recipient_data {+ types::WebhookRecipientData::Merchant { .. } => webhook_payload+ .event_content+ .as_ref()+ .map(Self::foreign_from)+ .ok_or(errors::ApiErrorResponse::WebhookResourceNotFound),+ types::WebhookRecipientData::Connector { feature_data, .. } => {+ Ok(Self::foreign_from(feature_data))+ }+ }+ }+}++async fn handle_successful_delivery(+ state: SessionState,+ merchant_key_store: domain::MerchantKeyStore,+ updated_event: &domain::Event,+ process_tracker: Option<storage::ProcessTracker>,+ business_status: &'static str,+ recipient_data: types::WebhookRecipientData,+) -> CustomResult<(), errors::WebhooksFlowError> {+ update_overall_delivery_status_in_storage(+ state.clone(),+ merchant_key_store.clone(),+ updated_event,+ )+ .await?;++ success_response_handler(+ state.clone(),+ &recipient_data,+ process_tracker,+ business_status,+ )+ .await+}++#[cfg(feature = "v1")]+trait OutgoingWebhookResponseHandlerV1 {+ #[allow(clippy::too_many_arguments)]+ async fn handle_success_response<R: WebhookDeliveryResponse>(+ &self,+ state: SessionState,+ merchant_key_store: domain::MerchantKeyStore,+ merchant_id: &common_utils::id_type::MerchantId,+ event_id: &str,+ process_tracker: Option<storage::ProcessTracker>,+ response: R,+ recipient_data: types::WebhookRecipientData,+ ) -> CustomResult<+ (domain::Event, Option<Report<errors::WebhooksFlowError>>),+ errors::WebhooksFlowError,+ >;++ #[allow(clippy::too_many_arguments)]+ async fn handle_error_response(+ &self,+ state: SessionState,+ merchant_key_store: domain::MerchantKeyStore,+ merchant_id: &common_utils::id_type::MerchantId,+ event_id: &str,+ process_tracker: Option<storage::ProcessTracker>,+ client_error: Report<errors::ApiClientError>,+ recipient_data: types::WebhookRecipientData,+ ) -> CustomResult<+ (domain::Event, Option<Report<errors::WebhooksFlowError>>),+ errors::WebhooksFlowError,+ >;+}++#[cfg(feature = "v1")]+impl OutgoingWebhookResponseHandlerV1 for enums::WebhookDeliveryAttempt {+ async fn handle_success_response<R: WebhookDeliveryResponse>(+ &self,+ state: SessionState,+ merchant_key_store: domain::MerchantKeyStore,+ merchant_id: &common_utils::id_type::MerchantId,+ event_id: &str,+ process_tracker: Option<storage::ProcessTracker>,+ response: R,+ recipient_data: types::WebhookRecipientData,+ ) -> CustomResult<+ (domain::Event, Option<Report<errors::WebhooksFlowError>>),+ errors::WebhooksFlowError,+ > {+ let status_code = response.status();+ let is_webhook_notified = response.is_success();++ let updated_event = update_webhook_response_in_storage(+ state.clone(),+ merchant_key_store.clone(),+ event_id,+ response,+ status_code,+ is_webhook_notified,+ )+ .await?;++ let webhook_action_handler = get_action_handler(*self);+ let result = if is_webhook_notified {+ webhook_action_handler+ .notified_action(+ state,+ merchant_key_store,+ &updated_event,+ process_tracker,+ recipient_data,+ )+ .await+ } else {+ webhook_action_handler+ .not_notified_action(+ state,+ merchant_id,+ status_code,+ recipient_data,+ process_tracker,+ )+ .await+ };++ Ok((updated_event, result))+ }+ async fn handle_error_response(+ &self,+ state: SessionState,+ merchant_key_store: domain::MerchantKeyStore,+ merchant_id: &common_utils::id_type::MerchantId,+ event_id: &str,+ process_tracker: Option<storage::ProcessTracker>,+ client_error: Report<errors::ApiClientError>,+ recipient_data: types::WebhookRecipientData,+ ) -> CustomResult<+ (domain::Event, Option<Report<errors::WebhooksFlowError>>),+ errors::WebhooksFlowError,+ > {+ let schedule_webhook_retry = match self {+ Self::InitialAttempt | Self::ManualRetry => ScheduleWebhookRetry::NoSchedule,+ Self::AutomaticRetry => ScheduleWebhookRetry::WithProcessTracker(Box::new(+ process_tracker+ .get_required_value("process_tracker")+ .change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)+ .attach_printable("`process_tracker` is unavailable in automatic retry flow")?,+ )),+ };++ api_client_error_handler(+ state,+ merchant_key_store,+ merchant_id,+ event_id,+ client_error,+ *self,+ schedule_webhook_retry,+ recipient_data,+ )+ .await+ }+}++#[cfg(feature = "v1")]+#[async_trait::async_trait]+trait WebhookNotificationHandlerV1: Send + Sync {+ async fn notified_action(+ &self,+ state: SessionState,+ merchant_key_store: domain::MerchantKeyStore,+ updated_event: &domain::Event,+ process_tracker: Option<storage::ProcessTracker>,+ recipient_data: types::WebhookRecipientData,+ ) -> Option<Report<errors::WebhooksFlowError>>;++ async fn not_notified_action(+ &self,+ state: SessionState,+ merchant_id: &common_utils::id_type::MerchantId,+ status_code: u16,+ recipient_data: types::WebhookRecipientData,+ process_tracker: Option<storage::ProcessTracker>,+ ) -> Option<Report<errors::WebhooksFlowError>>;+}++#[cfg(feature = "v1")]+#[async_trait::async_trait]+impl WebhookNotificationHandlerV1 for types::InitialAttempt {+ async fn notified_action(+ &self,+ state: SessionState,+ merchant_key_store: domain::MerchantKeyStore,+ updated_event: &domain::Event,+ process_tracker: Option<storage::ProcessTracker>,+ recipient_data: types::WebhookRecipientData,+ ) -> Option<Report<errors::WebhooksFlowError>> {+ handle_successful_delivery(+ state,+ merchant_key_store,+ updated_event,+ process_tracker,+ business_status::INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL,+ recipient_data,+ )+ .await+ .err()+ .map(|error: Report<errors::WebhooksFlowError>| report!(error))+ }++ async fn not_notified_action(+ &self,+ state: SessionState,+ merchant_id: &common_utils::id_type::MerchantId,+ status_code: u16,+ recipient_data: types::WebhookRecipientData,+ _process_tracker: Option<storage::ProcessTracker>,+ ) -> Option<Report<errors::WebhooksFlowError>> {+ handle_failed_delivery(+ state.clone(),+ merchant_id,+ status_code,+ recipient_data,+ ScheduleWebhookRetry::NoSchedule,+ "Ignoring error when sending webhook to merchant",+ )+ .await+ .err()+ .map(|error| report!(error))+ }+}++#[cfg(feature = "v1")]+#[async_trait::async_trait]+impl WebhookNotificationHandlerV1 for types::AutomaticRetry {+ async fn notified_action(+ &self,+ state: SessionState,+ merchant_key_store: domain::MerchantKeyStore,+ updated_event: &domain::Event,+ process_tracker: Option<storage::ProcessTracker>,+ recipient_data: types::WebhookRecipientData,+ ) -> Option<Report<errors::WebhooksFlowError>> {+ handle_successful_delivery(+ state,+ merchant_key_store,+ updated_event,+ process_tracker,+ business_status::COMPLETED_BY_PT,+ recipient_data,+ )+ .await+ .err()+ .map(|error: Report<errors::WebhooksFlowError>| report!(error))+ }++ async fn not_notified_action(+ &self,+ state: SessionState,+ merchant_id: &common_utils::id_type::MerchantId,+ status_code: u16,+ recipient_data: types::WebhookRecipientData,+ process_tracker: Option<storage::ProcessTracker>,+ ) -> Option<Report<errors::WebhooksFlowError>> {+ let process_tracker = match process_tracker+ .get_required_value("process_tracker")+ .change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)+ .attach_printable("`process_tracker` is unavailable in automatic retry flow")+ {+ Ok(process_tracker) => process_tracker,+ Err(err) => return Some(err),+ };++ handle_failed_delivery(+ state.clone(),+ merchant_id,+ status_code,+ recipient_data,+ ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)),+ "Ignoring error when sending webhook to merchant",+ )+ .await+ .err()+ .map(|error| report!(error))+ }+}++#[cfg(feature = "v1")]+#[async_trait::async_trait]+impl WebhookNotificationHandlerV1 for types::ManualRetry {+ async fn notified_action(+ &self,+ _state: SessionState,+ _merchant_key_store: domain::MerchantKeyStore,+ _updated_event: &domain::Event,+ _process_tracker: Option<storage::ProcessTracker>,+ recipient_data: types::WebhookRecipientData,+ ) -> Option<Report<errors::WebhooksFlowError>> {+ utils::increment_webhook_outgoing_received_count(&recipient_data);+ None+ }++ async fn not_notified_action(+ &self,+ state: SessionState,+ merchant_id: &common_utils::id_type::MerchantId,+ status_code: u16,+ recipient_data: types::WebhookRecipientData,+ _process_tracker: Option<storage::ProcessTracker>,+ ) -> Option<Report<errors::WebhooksFlowError>> {+ handle_failed_delivery(+ state.clone(),+ merchant_id,+ status_code,+ recipient_data,+ ScheduleWebhookRetry::NoSchedule,+ "Ignoring error when sending webhook to merchant",+ )+ .await+ .err()+ .map(|error| report!(error))+ }+}++async fn handle_failed_delivery(+ state: SessionState,+ merchant_id: &common_utils::id_type::MerchantId,+ status_code: u16,+ recipient_data: types::WebhookRecipientData,+ schedule_webhook_retry: ScheduleWebhookRetry,+ log_message: &'static str,+) -> CustomResult<(), errors::WebhooksFlowError> {+ utils::increment_webhook_outgoing_not_received_count(&recipient_data);++ let error = report!(errors::WebhooksFlowError::NotReceivedByRecipient);+ logger::warn!(?error, status_code, %log_message);++ if let ScheduleWebhookRetry::WithProcessTracker(process_tracker) = schedule_webhook_retry {+ outgoing_webhook_retry::retry_webhook_delivery_task(+ &*state.store,+ merchant_id,+ state.superposition_service.as_ref(),+ *process_tracker,+ recipient_data,+ )+ .await+ .change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)?;+ }++ Err(error)+}++fn get_action_handler(+ attempt: enums::WebhookDeliveryAttempt,+) -> Box<dyn WebhookNotificationHandlerV1> {+ match attempt {+ enums::WebhookDeliveryAttempt::InitialAttempt => Box::new(types::InitialAttempt),+ enums::WebhookDeliveryAttempt::AutomaticRetry => Box::new(types::AutomaticRetry),+ enums::WebhookDeliveryAttempt::ManualRetry => Box::new(types::ManualRetry),+ }+}diff --git a/crates/router/src/core/webhooks/outgoing_v2.rs b/crates/router/src/core/webhooks/outgoing_v2.rsindex 74c90626d1..bfd9fed74b 100644--- a/crates/router/src/core/webhooks/outgoing_v2.rs+++ b/crates/router/src/core/webhooks/outgoing_v2.rs@@ -124,6 +124,7 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(is_overall_delivery_successful: Some(false),processor_merchant_id: Some(processor_merchant_id.clone()),initiator_merchant_id: Some(webhook_recipient.key_store.merchant_id.clone()),+ recipient: None,};let event_insert_result = state@@ -568,7 +569,9 @@ async fn handle_successful_delivery().await?;- increment_webhook_outgoing_received_count(merchant_id);+ increment_webhook_outgoing_received_count(&types::WebhookRecipientData::Merchant {+ merchant_id: merchant_id.clone(),+ });match process_tracker {Some(process_tracker) => state@@ -591,7 +594,9 @@ async fn handle_failed_delivery(log_message: &'static str,_schedule_webhook_retry: types::ScheduleWebhookRetry,) -> CustomResult<(), errors::WebhooksFlowError> {- utils::increment_webhook_outgoing_not_received_count(merchant_id);+ utils::increment_webhook_outgoing_not_received_count(&types::WebhookRecipientData::Merchant {+ merchant_id: merchant_id.clone(),+ });let error = report!(errors::WebhooksFlowError::NotReceivedByMerchant);logger::warn!(?error, ?delivery_attempt, status_code, %log_message);@@ -688,6 +693,10 @@ impl ForeignFrom<storage::EventMetadata> for outgoing_webhook_logs::OutgoingWebh}}+struct InitialAttempt;+struct AutomaticRetry;+struct ManualRetry;+trait OutgoingWebhookResponseHandler {async fn handle_error_response(&self,@@ -815,12 +824,8 @@ trait WebhookNotificationHandler: Send + Sync {) -> Option<Report<errors::WebhooksFlowError>>;}-struct InitialAttempt;-struct AutomaticRetry;-struct ManualRetry;-#[async_trait::async_trait]-impl WebhookNotificationHandler for InitialAttempt {+impl WebhookNotificationHandler for types::InitialAttempt {async fn notified_action(&self,state: SessionState,@@ -863,7 +868,7 @@ impl WebhookNotificationHandler for InitialAttempt {}#[async_trait::async_trait]-impl WebhookNotificationHandler for AutomaticRetry {+impl WebhookNotificationHandler for types::AutomaticRetry {async fn notified_action(&self,_state: SessionState,@@ -886,7 +891,7 @@ impl WebhookNotificationHandler for AutomaticRetry {}#[async_trait::async_trait]-impl WebhookNotificationHandler for ManualRetry {+impl WebhookNotificationHandler for types::ManualRetry {async fn notified_action(&self,_state: SessionState,@@ -895,7 +900,9 @@ impl WebhookNotificationHandler for ManualRetry {merchant_id: &common_utils::id_type::MerchantId,_process_tracker: Option<storage::ProcessTracker>,) -> Option<Report<errors::WebhooksFlowError>> {- increment_webhook_outgoing_received_count(merchant_id);+ increment_webhook_outgoing_received_count(&types::WebhookRecipientData::Merchant {+ merchant_id: merchant_id.clone(),+ });None}@@ -923,8 +930,8 @@ fn get_action_handler(attempt: enums::WebhookDeliveryAttempt,) -> Box<dyn WebhookNotificationHandler> {match attempt {- enums::WebhookDeliveryAttempt::InitialAttempt => Box::new(InitialAttempt),- enums::WebhookDeliveryAttempt::AutomaticRetry => Box::new(AutomaticRetry),- enums::WebhookDeliveryAttempt::ManualRetry => Box::new(ManualRetry),+ enums::WebhookDeliveryAttempt::InitialAttempt => Box::new(types::InitialAttempt),+ enums::WebhookDeliveryAttempt::AutomaticRetry => Box::new(types::AutomaticRetry),+ enums::WebhookDeliveryAttempt::ManualRetry => Box::new(types::ManualRetry),}}diff --git a/crates/router/src/core/webhooks/types.rs b/crates/router/src/core/webhooks/types.rsindex a0e3c662df..99b4a89f0f 100644--- a/crates/router/src/core/webhooks/types.rs+++ b/crates/router/src/core/webhooks/types.rs@@ -1,6 +1,9 @@+use std::str::FromStr;+use api_models::{webhook_events, webhooks};use common_utils::{crypto::SignMessage, ext_traits::Encode};use error_stack::ResultExt;+use hyperswitch_domain_models::router_response_types::NotifyConnectorResponseData;use hyperswitch_masking::Secret;use serde::Serialize;@@ -8,7 +11,12 @@ use crate::{core::errors,headers, logger,services::request::Maskable,- types::storage::{self, enums},+ types::{+ api::OutgoingWebhookContent,+ domain::MerchantConnectorAccount,+ storage::{self, enums},+ MinorUnit,+ },};#[derive(Debug)]@@ -90,6 +98,7 @@ pub(crate) struct OutgoingWebhookTrackingData {pub(crate) primary_object_id: String,pub(crate) primary_object_type: enums::EventObjectType,pub(crate) initial_attempt_id: Option<String>,+ pub(crate) recipient_data: Option<WebhookRecipientData>,}pub struct WebhookResponse {@@ -138,3 +147,176 @@ impl WebhookResponse {}}}++/// Unified interface for webhook delivery responses from different sources.+///+/// Implemented for [`reqwest::Response`] (merchant webhook path) and+/// [`NotifyConnectorResponseData`] (UCS connector notification path).+#[async_trait::async_trait]+pub(crate) trait WebhookDeliveryResponse: Send {+ fn status(&self) -> u16;+ fn is_success(&self) -> bool;+ fn get_response_headers(&self) -> Vec<(String, Secret<String>)>;+ fn get_error_message(&self) -> Option<String>;+ async fn get_response_body(self) -> Secret<String>;+}++#[async_trait::async_trait]+impl WebhookDeliveryResponse for reqwest::Response {+ fn status(&self) -> u16 {+ self.status().as_u16()+ }++ fn is_success(&self) -> bool {+ self.status().is_success()+ }++ fn get_response_headers(&self) -> Vec<(String, Secret<String>)> {+ self.headers()+ .iter()+ .map(|(name, value)| {+ (+ name.as_str().to_owned(),+ value+ .to_str()+ .map(|s| Secret::from(String::from(s)))+ .unwrap_or_else(|error| {+ logger::warn!(+ "Response header {} contains non-UTF-8 characters: {error:?}",+ name.as_str()+ );+ Secret::from(String::from("Non-UTF-8 header value"))+ }),+ )+ })+ .collect::<Vec<_>>()+ }++ async fn get_response_body(self) -> Secret<String> {+ self.text().await.map(Secret::from).unwrap_or_else(|error| {+ logger::warn!("Response contains non-UTF-8 characters: {error:?}");+ Secret::from(String::from("Non-UTF-8 response body"))+ })+ }++ fn get_error_message(&self) -> Option<String> {+ None+ }+}++#[async_trait::async_trait]+impl WebhookDeliveryResponse for NotifyConnectorResponseData {+ fn status(&self) -> u16 {+ self.status_code+ }++ fn is_success(&self) -> bool {+ self.status_code >= 200 && self.status_code < 300+ }++ fn get_response_headers(&self) -> Vec<(String, Secret<String>)> {+ vec![]+ }++ fn get_error_message(&self) -> Option<String> {+ self.error_message.clone()+ }++ async fn get_response_body(self) -> Secret<String> {+ Secret::from(serde_json::to_string(&self).unwrap_or_else(|error| {+ logger::warn!("Failed to serialize response: {error:?}");+ String::from("Failed to serialize response")+ }))+ }+}++pub(crate) struct MerchantWebhook;+pub(crate) struct ConnectorWebhook;+pub(crate) struct InitialAttempt;+pub(crate) struct AutomaticRetry;+pub(crate) struct ManualRetry;++pub(crate) struct WebhookPayload {+ pub event_type: enums::EventType,+ pub event_content: Option<OutgoingWebhookContent>,+ pub recipient_data: WebhookRecipientData,+}++impl WebhookPayload {+ /// Builds a surcharge webhook payload if the primary event supports surcharge notification+ /// and the payment attempt has external surcharge details.+ #[cfg(feature = "v1")]+ pub fn build_surcharge_payload(+ surcharge_event: enums::EventType,+ payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,+ merchant_surcharge_connector: &MerchantConnectorAccount,+ ) -> errors::CustomResult<Option<Self>, errors::ApiErrorResponse> {+ let connector = common_enums::connector_enums::Connector::from_str(+ &merchant_surcharge_connector.connector_name,+ )+ .change_context(errors::ApiErrorResponse::InvalidDataValue {+ field_name: "connector",+ })?;++ Ok(payment_attempt+ .external_surcharge_details+ .as_ref()+ .map(|external_surcharge_details| {+ let feature_specific_data = SurchargeDetails {+ surcharge_amount: external_surcharge_details.external_surcharge_amount,+ external_surcharge_id: external_surcharge_details.external_surcharge_id.clone(),+ payment_id: payment_attempt.payment_id.clone(),+ attempt_id: payment_attempt.attempt_id.clone(),+ };+ Self {+ event_type: surcharge_event,+ event_content: None,+ recipient_data: WebhookRecipientData::Connector {+ connector,+ merchant_connector_id: merchant_surcharge_connector+ .merchant_connector_id+ .clone(),+ feature_data: FeatureTrackingData::SurchargeDetails(Box::new(+ feature_specific_data,+ )),+ },+ }+ }))+ }+}++#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]+pub(crate) enum WebhookRecipientData {+ Merchant {+ merchant_id: common_utils::id_type::MerchantId,+ },+ Connector {+ connector: common_enums::connector_enums::Connector,+ merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,+ feature_data: FeatureTrackingData,+ },+}++impl WebhookRecipientData {+ pub fn get_event_recipient(&self) -> common_enums::EventRecipient {+ match self {+ Self::Merchant { .. } => common_enums::EventRecipient::Merchant,+ Self::Connector { .. } => common_enums::EventRecipient::Connector,+ }+ }+}++#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum FeatureTrackingData {+ SurchargeDetails(Box<SurchargeDetails>),+}++/// Details of surcharge applied on this payment, if applicable+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]+pub struct SurchargeDetails {+ pub surcharge_amount: MinorUnit,+ pub external_surcharge_id: String,+ pub payment_id: common_utils::id_type::PaymentId,+ pub attempt_id: String,+}diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rsindex ee3a4fba20..838ac61b04 100644--- a/crates/router/src/core/webhooks/utils.rs+++ b/crates/router/src/core/webhooks/utils.rs@@ -17,7 +17,7 @@ use hyperswitch_interfaces::webhooks::IncomingWebhook;use redis_interface as redis;use router_env::tracing;-use super::MERCHANT_ID;+use super::{types as webhook_types, MERCHANT_ID};use crate::{core::{configs::dimension_state,@@ -250,20 +250,43 @@ pub(crate) fn generate_event_id() -> String {common_utils::generate_time_ordered_id("evt")}-pub fn increment_webhook_outgoing_received_count(merchant_id: &common_utils::id_type::MerchantId) {- metrics::WEBHOOK_OUTGOING_RECEIVED_COUNT.add(- 1,- router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())),- )+pub(crate) fn increment_webhook_outgoing_received_count(+ recipient_data: &webhook_types::WebhookRecipientData,+) {+ let attributes = match recipient_data {+ webhook_types::WebhookRecipientData::Connector {+ merchant_connector_id,+ ..+ } => router_env::metric_attributes!((+ crate::core::webhooks::MERCHANT_CONNECTOR_ACCOUNT_ID,+ merchant_connector_id.clone()+ )),++ webhook_types::WebhookRecipientData::Merchant { merchant_id, .. } => {+ router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone()))+ }+ };++ metrics::WEBHOOK_OUTGOING_RECEIVED_COUNT.add(1, attributes);}-pub fn increment_webhook_outgoing_not_received_count(- merchant_id: &common_utils::id_type::MerchantId,+pub(crate) fn increment_webhook_outgoing_not_received_count(+ recipient_data: &webhook_types::WebhookRecipientData,) {- metrics::WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT.add(- 1,- router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())),- );+ let attributes = match recipient_data {+ webhook_types::WebhookRecipientData::Connector {+ merchant_connector_id,+ ..+ } => router_env::metric_attributes!((+ crate::core::webhooks::MERCHANT_CONNECTOR_ACCOUNT_ID,+ merchant_connector_id.clone()+ )),++ webhook_types::WebhookRecipientData::Merchant { merchant_id } => {+ router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone()))+ }+ };+ metrics::WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT.add(1, attributes);}pub fn is_outgoing_webhook_disabled(diff --git a/crates/router/src/core/webhooks/webhook_events.rs b/crates/router/src/core/webhooks/webhook_events.rsindex a6ecb14246..87f9991b26 100644--- a/crates/router/src/core/webhooks/webhook_events.rs+++ b/crates/router/src/core/webhooks/webhook_events.rs@@ -62,6 +62,7 @@ pub async fn list_initial_delivery_attempts(object_id.as_str(),profile_id.clone(),&key_store,+ Some(common_enums::EventRecipient::Merchant),).await.change_context(errors::ApiErrorResponse::InternalServerError)@@ -177,6 +178,7 @@ pub async fn list_initial_delivery_attempts(event_types.clone(),is_delivered,&key_store,+ Some(common_enums::EventRecipient::Merchant),).await}@@ -191,6 +193,7 @@ pub async fn list_initial_delivery_attempts(event_types.clone(),is_delivered,&key_store,+ Some(common_enums::EventRecipient::Merchant),).await}@@ -207,6 +210,7 @@ pub async fn list_initial_delivery_attempts(created_before,event_types,is_delivered,+ Some(common_enums::EventRecipient::Merchant),).await}@@ -219,6 +223,7 @@ pub async fn list_initial_delivery_attempts(created_before,event_types,is_delivered,+ Some(common_enums::EventRecipient::Merchant),).await}@@ -264,6 +269,7 @@ pub async fn list_delivery_attempts(&initial_attempt_id,&merchant_id,&key_store,+ Some(common_enums::EventRecipient::Merchant),).await.change_context(errors::ApiErrorResponse::InternalServerError)@@ -373,6 +379,7 @@ pub async fn retry_delivery_attempt(is_overall_delivery_successful: Some(false),processor_merchant_id: Some(processor_merchant_id.clone()),initiator_merchant_id: Some(merchant_id.clone()),+ recipient: event_to_retry.recipient,};let event = store@@ -403,6 +410,7 @@ pub async fn retry_delivery_attempt(delivery_attempt,None,None,+ super::types::WebhookRecipientData::Merchant { merchant_id },)).await;diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rsindex d04ca419dc..56e65d6d50 100644--- a/crates/router/src/db/events.rs+++ b/crates/router/src/db/events.rs@@ -68,6 +68,7 @@ whereevent_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError>;#[allow(clippy::too_many_arguments)]@@ -81,6 +82,7 @@ whereevent_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError>;async fn list_events_by_initiator_merchant_id_initial_attempt_id(@@ -88,6 +90,7 @@ whereinitial_attempt_id: &str,initiator_merchant_id: &common_utils::id_type::MerchantId,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError>;async fn list_events_by_merchant_id_initial_attempt_id(@@ -95,6 +98,7 @@ wheremerchant_id: &common_utils::id_type::MerchantId,initial_attempt_id: &str,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError>;async fn list_initial_events_by_initiator_merchant_id_primary_object_id(@@ -103,6 +107,7 @@ whereprimary_object_id: &str,profile_id: Option<common_utils::id_type::ProfileId>,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError>;async fn list_initial_events_by_merchant_id_primary_object_id(@@ -110,6 +115,7 @@ wheremerchant_id: &common_utils::id_type::MerchantId,primary_object_id: &str,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError>;async fn find_initial_event_by_merchant_id_initial_attempt_id(@@ -130,6 +136,7 @@ whereevent_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError>;async fn list_initial_events_by_profile_id_primary_object_id(@@ -137,6 +144,7 @@ whereprofile_id: &common_utils::id_type::ProfileId,primary_object_id: &str,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError>;async fn find_initial_event_by_profile_id_initial_attempt_id(@@ -161,6 +169,7 @@ wheremerchant_key_store: &domain::MerchantKeyStore,) -> CustomResult<domain::Event, errors::StorageError>;+ #[allow(clippy::too_many_arguments)]async fn count_initial_events_by_initiator_merchant_id_constraints(&self,initiator_merchant_id: &common_utils::id_type::MerchantId,@@ -169,6 +178,7 @@ wherecreated_before: time::PrimitiveDateTime,event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<i64, errors::StorageError>;async fn count_initial_events_by_profile_id_constraints(@@ -178,8 +188,10 @@ wherecreated_before: time::PrimitiveDateTime,event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<i64, errors::StorageError>;+ #[allow(clippy::too_many_arguments)]async fn count_initial_events_by_constraints(&self,merchant_id: &common_utils::id_type::MerchantId,@@ -188,6 +200,7 @@ wherecreated_before: time::PrimitiveDateTime,event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<i64, errors::StorageError>;}@@ -319,6 +332,7 @@ impl EventInterface for Store {event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;storage::Event::list_initial_attempts_by_initiator_merchant_id_constraints(@@ -330,6 +344,7 @@ impl EventInterface for Store {offset,event_types,is_delivered,+ event_recipient,).await.map_err(|error| report!(errors::StorageError::from(error)))@@ -360,6 +375,7 @@ impl EventInterface for Store {event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;storage::Event::list_initial_attempts_by_merchant_id_constraints(@@ -371,6 +387,7 @@ impl EventInterface for Store {offset,event_types,is_delivered,+ event_recipient,).await.map_err(|error| report!(errors::StorageError::from(error)))@@ -396,12 +413,14 @@ impl EventInterface for Store {initial_attempt_id: &str,initiator_merchant_id: &common_utils::id_type::MerchantId,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;storage::Event::list_by_initiator_merchant_id_initial_attempt_id(&conn,initial_attempt_id,initiator_merchant_id,+ event_recipient,).await.map_err(|error| report!(errors::StorageError::from(error)))@@ -427,12 +446,14 @@ impl EventInterface for Store {merchant_id: &common_utils::id_type::MerchantId,initial_attempt_id: &str,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;storage::Event::list_by_merchant_id_initial_attempt_id(&conn,merchant_id,initial_attempt_id,+ event_recipient,).await.map_err(|error| report!(errors::StorageError::from(error)))@@ -459,6 +480,7 @@ impl EventInterface for Store {primary_object_id: &str,profile_id: Option<common_utils::id_type::ProfileId>,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;storage::Event::list_initial_attempts_by_initiator_merchant_id_primary_object_id(@@ -466,6 +488,7 @@ impl EventInterface for Store {initiator_merchant_id,primary_object_id,profile_id,+ event_recipient,).await.map_err(|error| report!(errors::StorageError::from(error)))@@ -491,12 +514,14 @@ impl EventInterface for Store {merchant_id: &common_utils::id_type::MerchantId,primary_object_id: &str,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;storage::Event::list_initial_attempts_by_merchant_id_primary_object_id(&conn,merchant_id,primary_object_id,+ event_recipient,).await.map_err(|error| report!(errors::StorageError::from(error)))@@ -561,6 +586,7 @@ impl EventInterface for Store {event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;storage::Event::list_initial_attempts_by_profile_id_constraints(@@ -572,6 +598,7 @@ impl EventInterface for Store {offset,event_types,is_delivered,+ event_recipient,).await.map_err(|error| report!(errors::StorageError::from(error)))@@ -599,12 +626,14 @@ impl EventInterface for Store {profile_id: &common_utils::id_type::ProfileId,primary_object_id: &str,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;storage::Event::list_initial_attempts_by_profile_id_primary_object_id(&conn,profile_id,primary_object_id,+ event_recipient,).await.map_err(|error| report!(errors::StorageError::from(error)))@@ -710,6 +739,7 @@ impl EventInterface for Store {created_before: time::PrimitiveDateTime,event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<i64, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;storage::Event::count_initial_attempts_by_profile_id_constraints(@@ -719,11 +749,13 @@ impl EventInterface for Store {created_before,event_types,is_delivered,+ event_recipient,).await.map_err(|error| report!(errors::StorageError::from(error)))}+ #[allow(clippy::too_many_arguments)]async fn count_initial_events_by_initiator_merchant_id_constraints(&self,initiator_merchant_id: &common_utils::id_type::MerchantId,@@ -732,6 +764,7 @@ impl EventInterface for Store {created_before: time::PrimitiveDateTime,event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<i64, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;storage::Event::count_initial_attempts_by_initiator_merchant_id_constraints(@@ -742,6 +775,7 @@ impl EventInterface for Store {created_before,event_types,is_delivered,+ event_recipient,).await.map_err(|error| report!(errors::StorageError::from(error)))@@ -755,6 +789,7 @@ impl EventInterface for Store {created_before: time::PrimitiveDateTime,event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<i64, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;storage::Event::count_initial_attempts_by_constraints(@@ -765,6 +800,7 @@ impl EventInterface for Store {created_before,event_types,is_delivered,+ event_recipient,).await.map_err(|error| report!(errors::StorageError::from(error)))@@ -941,6 +977,7 @@ impl EventInterface for MockDb {event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {let locked_events = self.events.lock().await;let events_iter = locked_events.iter().filter(|event| {@@ -949,8 +986,8 @@ impl EventInterface for MockDb {&& (event.created_at >= created_after)&& (event.created_at <= created_before)&& (event_types.is_empty() || event_types.contains(&event.event_type))- && (event.is_overall_delivery_successful == is_delivered);-+ && (event.is_overall_delivery_successful == is_delivered)+ && (event_recipient.is_none() || event_recipient == event.recipient);check});@@ -1004,6 +1041,7 @@ impl EventInterface for MockDb {merchant_id: &common_utils::id_type::MerchantId,initial_attempt_id: &str,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {let locked_events = self.events.lock().await;let events = locked_events@@ -1011,6 +1049,7 @@ impl EventInterface for MockDb {.filter(|event| {event.merchant_id == Some(merchant_id.to_owned())&& event.initial_attempt_id == Some(initial_attempt_id.to_owned())+ && (event_recipient.is_none() || event_recipient == event.recipient)}).cloned().collect::<Vec<_>>();@@ -1037,6 +1076,7 @@ impl EventInterface for MockDb {merchant_id: &common_utils::id_type::MerchantId,primary_object_id: &str,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {let locked_events = self.events.lock().await;let events = locked_events@@ -1045,6 +1085,7 @@ impl EventInterface for MockDb {event.merchant_id == Some(merchant_id.to_owned())&& event.initial_attempt_id.as_deref() == Some(&event.event_id)&& event.primary_object_id.as_str() == primary_object_id+ && (event_recipient.is_none() || event_recipient == event.recipient)}).cloned().collect::<Vec<_>>();@@ -1108,6 +1149,7 @@ impl EventInterface for MockDb {event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {let locked_events = self.events.lock().await;let events_iter = locked_events.iter().filter(|event| {@@ -1116,7 +1158,8 @@ impl EventInterface for MockDb {&& (event.created_at >= created_after)&& (event.created_at <= created_before)&& (event_types.is_empty() || event_types.contains(&event.event_type))- && (event.is_overall_delivery_successful == is_delivered);+ && (event.is_overall_delivery_successful == is_delivered)+ && (event_recipient.is_none() || event_recipient == event.recipient);check});@@ -1171,6 +1214,7 @@ impl EventInterface for MockDb {profile_id: &common_utils::id_type::ProfileId,primary_object_id: &str,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {let locked_events = self.events.lock().await;let events = locked_events@@ -1179,6 +1223,7 @@ impl EventInterface for MockDb {event.business_profile_id == Some(profile_id.to_owned())&& event.initial_attempt_id.as_deref() == Some(&event.event_id)&& event.primary_object_id.as_str() == primary_object_id+ && (event_recipient.is_none() || event_recipient == event.recipient)}).cloned().collect::<Vec<_>>();@@ -1283,6 +1328,7 @@ impl EventInterface for MockDb {created_before: time::PrimitiveDateTime,event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<i64, errors::StorageError> {let locked_events = self.events.lock().await;@@ -1293,8 +1339,8 @@ impl EventInterface for MockDb {&& (event.created_at >= created_after)&& (event.created_at <= created_before)&& (event_types.is_empty() || event_types.contains(&event.event_type))- && (event.is_overall_delivery_successful == is_delivered);-+ && (event.is_overall_delivery_successful == is_delivered)+ && (event_recipient.is_none() || event_recipient == event.recipient);check});@@ -1315,6 +1361,7 @@ impl EventInterface for MockDb {event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {let locked_events = self.events.lock().await;let events_iter = locked_events.iter().filter(|event| {@@ -1329,7 +1376,8 @@ impl EventInterface for MockDb {&& (event.created_at >= created_after)&& (event.created_at <= created_before)&& (event_types.is_empty() || event_types.contains(&event.event_type))- && (event.is_overall_delivery_successful == is_delivered);+ && (event.is_overall_delivery_successful == is_delivered)+ && (event_recipient.is_none() || event_recipient == event.recipient);check});@@ -1384,6 +1432,7 @@ impl EventInterface for MockDb {initial_attempt_id: &str,initiator_merchant_id: &common_utils::id_type::MerchantId,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {let locked_events = self.events.lock().await;let events = locked_events@@ -1393,7 +1442,9 @@ impl EventInterface for MockDb {== Some(initiator_merchant_id)|| (event.initiator_merchant_id.is_none()&& event.merchant_id.as_ref() == Some(initiator_merchant_id));- event.initial_attempt_id.as_deref() == Some(initial_attempt_id) && matches_initiator+ event.initial_attempt_id.as_deref() == Some(initial_attempt_id)+ && matches_initiator+ && (event_recipient.is_none() || event_recipient == event.recipient)}).cloned().collect::<Vec<_>>();@@ -1421,6 +1472,7 @@ impl EventInterface for MockDb {primary_object_id: &str,profile_id: Option<common_utils::id_type::ProfileId>,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {let locked_events = self.events.lock().await;let events = locked_events@@ -1438,6 +1490,7 @@ impl EventInterface for MockDb {&& matches_profile&& event.initial_attempt_id.as_deref() == Some(&event.event_id)&& event.primary_object_id.as_str() == primary_object_id+ && (event_recipient.is_none() || event_recipient == event.recipient)}).cloned().collect::<Vec<_>>();@@ -1507,6 +1560,7 @@ impl EventInterface for MockDb {created_before: time::PrimitiveDateTime,event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<i64, errors::StorageError> {let locked_events = self.events.lock().await;@@ -1516,7 +1570,8 @@ impl EventInterface for MockDb {&& (event.created_at >= created_after)&& (event.created_at <= created_before)&& (event_types.is_empty() || event_types.contains(&event.event_type))- && (event.is_overall_delivery_successful == is_delivered);+ && (event.is_overall_delivery_successful == is_delivered)+ && (event_recipient.is_none() || event_recipient == event.recipient);check});@@ -1528,6 +1583,7 @@ impl EventInterface for MockDb {.attach_printable("Failed to convert usize to i64")}+ #[allow(clippy::too_many_arguments)]async fn count_initial_events_by_initiator_merchant_id_constraints(&self,initiator_merchant_id: &common_utils::id_type::MerchantId,@@ -1536,6 +1592,7 @@ impl EventInterface for MockDb {created_before: time::PrimitiveDateTime,event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<i64, errors::StorageError> {let locked_events = self.events.lock().await;@@ -1551,7 +1608,8 @@ impl EventInterface for MockDb {&& (event.created_at >= created_after)&& (event.created_at <= created_before)&& (event_types.is_empty() || event_types.contains(&event.event_type))- && (event.is_overall_delivery_successful == is_delivered);+ && (event.is_overall_delivery_successful == is_delivered)+ && (event_recipient.is_none() || event_recipient == event.recipient);check});@@ -1693,6 +1751,7 @@ mod tests {is_overall_delivery_successful: Some(false),processor_merchant_id: Some(merchant_id.to_owned()),initiator_merchant_id: Some(merchant_id.to_owned()),+ recipient: Some(enums::EventRecipient::Merchant),},&merchant_key_store,)@@ -1809,6 +1868,7 @@ mod tests {is_overall_delivery_successful: Some(false),processor_merchant_id: Some(merchant_id.to_owned()),initiator_merchant_id: Some(merchant_id.to_owned()),+ recipient: Some(enums::EventRecipient::Merchant),},&merchant_key_store,)@@ -2191,6 +2251,8 @@ mod tests {content_clone,primary_object_created_at,webhook_recipient,+ None,+ business_profile_clone,)).await.map_err(|e| format!("create_event_and_trigger_outgoing_webhook failed: {e}"))@@ -2217,6 +2279,7 @@ mod tests {&business_profile.merchant_id,primary_object_id.as_str(),&merchant_key_store,+ Some(enums::EventRecipient::Merchant),).await?;diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex d10617e28d..025285aff6 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -807,6 +807,7 @@ impl EventInterface for KafkaStore {event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {self.diesel_store.list_initial_events_by_initiator_merchant_id_constraints(@@ -818,6 +819,7 @@ impl EventInterface for KafkaStore {event_types,is_delivered,merchant_key_store,+ event_recipient,).await}@@ -832,6 +834,7 @@ impl EventInterface for KafkaStore {event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {self.diesel_store.list_initial_events_by_merchant_id_constraints(@@ -843,6 +846,7 @@ impl EventInterface for KafkaStore {event_types,is_delivered,merchant_key_store,+ event_recipient,).await}@@ -852,12 +856,14 @@ impl EventInterface for KafkaStore {initial_attempt_id: &str,initiator_merchant_id: &id_type::MerchantId,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {self.diesel_store.list_events_by_initiator_merchant_id_initial_attempt_id(initial_attempt_id,initiator_merchant_id,merchant_key_store,+ event_recipient,).await}@@ -867,12 +873,14 @@ impl EventInterface for KafkaStore {merchant_id: &id_type::MerchantId,initial_attempt_id: &str,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {self.diesel_store.list_events_by_merchant_id_initial_attempt_id(merchant_id,initial_attempt_id,merchant_key_store,+ event_recipient,).await}@@ -883,6 +891,7 @@ impl EventInterface for KafkaStore {primary_object_id: &str,profile_id: Option<id_type::ProfileId>,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {self.diesel_store.list_initial_events_by_initiator_merchant_id_primary_object_id(@@ -890,6 +899,7 @@ impl EventInterface for KafkaStore {primary_object_id,profile_id,merchant_key_store,+ event_recipient,).await}@@ -899,12 +909,14 @@ impl EventInterface for KafkaStore {merchant_id: &id_type::MerchantId,primary_object_id: &str,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {self.diesel_store.list_initial_events_by_merchant_id_primary_object_id(merchant_id,primary_object_id,merchant_key_store,+ event_recipient,).await}@@ -934,6 +946,7 @@ impl EventInterface for KafkaStore {event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {self.diesel_store.list_initial_events_by_profile_id_constraints(@@ -945,6 +958,7 @@ impl EventInterface for KafkaStore {event_types,is_delivered,merchant_key_store,+ event_recipient,).await}@@ -954,12 +968,14 @@ impl EventInterface for KafkaStore {profile_id: &id_type::ProfileId,primary_object_id: &str,merchant_key_store: &domain::MerchantKeyStore,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<Vec<domain::Event>, errors::StorageError> {self.diesel_store.list_initial_events_by_profile_id_primary_object_id(profile_id,primary_object_id,merchant_key_store,+ event_recipient,).await}@@ -1009,6 +1025,7 @@ impl EventInterface for KafkaStore {created_before: PrimitiveDateTime,event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<i64, errors::StorageError> {self.diesel_store.count_initial_events_by_profile_id_constraints(@@ -1017,6 +1034,7 @@ impl EventInterface for KafkaStore {created_before,event_types,is_delivered,+ event_recipient,).await}@@ -1029,6 +1047,7 @@ impl EventInterface for KafkaStore {created_before: PrimitiveDateTime,event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<i64, errors::StorageError> {self.diesel_store.count_initial_events_by_initiator_merchant_id_constraints(@@ -1038,6 +1057,7 @@ impl EventInterface for KafkaStore {created_before,event_types,is_delivered,+ event_recipient,).await}@@ -1050,6 +1070,7 @@ impl EventInterface for KafkaStore {created_before: PrimitiveDateTime,event_types: HashSet<common_enums::EventType>,is_delivered: Option<bool>,+ event_recipient: Option<common_enums::EventRecipient>,) -> CustomResult<i64, errors::StorageError> {self.diesel_store.count_initial_events_by_constraints(@@ -1059,6 +1080,7 @@ impl EventInterface for KafkaStore {created_before,event_types,is_delivered,+ event_recipient,).await}diff --git a/crates/router/src/events/outgoing_webhook_logs.rs b/crates/router/src/events/outgoing_webhook_logs.rsindex 3e62ff4787..95250a53b5 100644--- a/crates/router/src/events/outgoing_webhook_logs.rs+++ b/crates/router/src/events/outgoing_webhook_logs.rs@@ -80,6 +80,11 @@ pub enum OutgoingWebhookEventContent {payment_id: Option<common_utils::id_type::PaymentId>,content: Value,},+ #[cfg(feature = "v1")]+ Surcharge {+ payment_id: common_utils::id_type::PaymentId,+ attempt_id: String,+ },}pub trait OutgoingWebhookEventMetric {fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent>;diff --git a/crates/router/src/types/domain/event.rs b/crates/router/src/types/domain/event.rsindex 3141758451..aea2461eae 100644--- a/crates/router/src/types/domain/event.rs+++ b/crates/router/src/types/domain/event.rs@@ -5,7 +5,7 @@ use common_utils::{types::keymanager::{KeyManagerState, ToEncryptable},};use diesel_models::{- enums::{EventClass, EventObjectType, EventType, WebhookDeliveryAttempt},+ enums::{EventClass, EventObjectType, EventRecipient, EventType, WebhookDeliveryAttempt},events::{EventMetadata, EventUpdateInternal},};use error_stack::ResultExt;@@ -78,6 +78,9 @@ pub struct Event {/// The merchant_id of the merchant that initiated the operation for which this event was/// generated. This is also the webhook recipient.pub initiator_merchant_id: Option<common_utils::id_type::MerchantId>,++ /// The intended recipient of the webhook event.+ pub recipient: Option<EventRecipient>,}#[derive(Debug)]@@ -139,6 +142,7 @@ impl super::behaviour::Conversion for Event {is_overall_delivery_successful: self.is_overall_delivery_successful,processor_merchant_id: self.processor_merchant_id,initiator_merchant_id: self.initiator_merchant_id,+ recipient: self.recipient,})}@@ -191,6 +195,7 @@ impl super::behaviour::Conversion for Event {is_overall_delivery_successful: item.is_overall_delivery_successful,processor_merchant_id: item.processor_merchant_id,initiator_merchant_id: item.initiator_merchant_id,+ recipient: item.recipient,})}@@ -215,6 +220,7 @@ impl super::behaviour::Conversion for Event {is_overall_delivery_successful: self.is_overall_delivery_successful,processor_merchant_id: self.processor_merchant_id,initiator_merchant_id: self.initiator_merchant_id,+ recipient: self.recipient,})}}diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rsindex 06567bef36..59e0b41f9b 100644--- a/crates/router/src/utils.rs+++ b/crates/router/src/utils.rs@@ -39,6 +39,7 @@ pub use hyperswitch_connectors::utils::QrImage;use hyperswitch_domain_models::payments::PaymentIntent;#[cfg(feature = "v1")]use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation};+use hyperswitch_interfaces::webhooks::WebhookResourceData;use hyperswitch_masking::{ExposeInterface, SwitchStrategy};use nanoid::nanoid;use serde::de::DeserializeOwned;@@ -1202,7 +1203,8 @@ where.collect()});let payment_id = payment_data.get_payment_intent().get_id().to_owned();- let created_by = payment_data.get_payment_attempt().created_by.clone();+ let payment_attempt = payment_data.get_payment_attempt().clone();+ let created_by = payment_attempt.created_by.clone();let payments_response = crate::core::payments::transformers::payments_to_payments_response(payment_data,captures,@@ -1240,6 +1242,9 @@ wheretokio::spawn(async move {let primary_object_created_at = payments_response_json.created;+ let webhook_resource_data =+ WebhookResourceData::Payment { payment_attempt };+Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook(cloned_state,cloned_platform,@@ -1252,6 +1257,8 @@ where)),primary_object_created_at,webhook_recipient,+ Some(webhook_resource_data),+ business_profile,)).await}@@ -1285,8 +1292,9 @@ pub async fn trigger_refund_outgoing_webhook(state: &SessionState,platform: &domain::Platform,refund: &diesel_models::Refund,- profile_id: id_type::ProfileId,+ payment_attempt: &domain::PaymentAttempt,) -> RouterResult<()> {+ let profile_id = payment_attempt.profile_id.clone();let refund_status = refund.refund_status;let business_profile = state@@ -1308,6 +1316,7 @@ pub async fn trigger_refund_outgoing_webhook(let refund_response: api_models::refunds::RefundResponse = refund.clone().foreign_into();let refund_id = refund_response.refund_id.clone();let cloned_state = state.clone();+ let cloned_payment_attempt = payment_attempt.clone();let primary_object_created_at = refund_response.created_at;if let Some(outgoing_event_type) = event_type {let created_by = refund@@ -1325,6 +1334,9 @@ pub async fn trigger_refund_outgoing_webhook(let cloned_platform = platform.clone();tokio::spawn(async move {+ let webhook_resource_data = WebhookResourceData::Refund {+ payment_attempt: cloned_payment_attempt,+ };Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook(cloned_state,cloned_platform,@@ -1335,6 +1347,8 @@ pub async fn trigger_refund_outgoing_webhook(webhooks::OutgoingWebhookContent::RefundDetails(Box::new(refund_response)),primary_object_created_at,webhook_recipient,+ Some(webhook_resource_data),+ business_profile,)).await}@@ -1421,6 +1435,8 @@ pub async fn trigger_payouts_webhook(webhooks::OutgoingWebhookContent::PayoutDetails(Box::new(cloned_response)),primary_object_created_at,webhook_recipient,+ None,+ business_profile,)).await}@@ -1476,6 +1492,7 @@ pub async fn trigger_subscriptions_outgoing_webhook(let cloned_state = state.clone();let invoice_id = invoice.id.get_string_repr().to_owned();let created_at = subscription.created_at;+ let business_profile = profile.clone();tokio::spawn(async move {Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook(@@ -1488,6 +1505,8 @@ pub async fn trigger_subscriptions_outgoing_webhook(webhooks::OutgoingWebhookContent::SubscriptionDetails(Box::new(response)),Some(created_at),webhook_recipient,+ None,+ business_profile,)).await});diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rsindex 6744acbd3a..27bb2cd5b5 100644--- a/crates/router/src/workflows/outgoing_webhook_retry.rs+++ b/crates/router/src/workflows/outgoing_webhook_retry.rs@@ -26,7 +26,10 @@ use crate::core::payouts;use crate::{core::{payments,- webhooks::{self as webhooks_core, types::OutgoingWebhookTrackingData},+ webhooks::{+ self as webhooks_core,+ types::{OutgoingWebhookTrackingData, WebhookRecipientData},+ },},db::StorageInterface,errors, logger,@@ -67,6 +70,12 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {.clone().unwrap_or_else(|| tracking_data.merchant_id.clone());+ let recipient_data = tracking_data.recipient_data.clone().unwrap_or_else(|| {+ WebhookRecipientData::Merchant {+ merchant_id: processor_merchant_id.clone(),+ }+ });+let webhook_key_store = db.get_merchant_key_store_by_merchant_id(&webhook_recipient_merchant_id, master_key).await?;@@ -124,6 +133,7 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {initiator_merchant_id: initial_event.initiator_merchant_id.or(Some(webhook_key_store.merchant_id.clone())),+ recipient: initial_event.recipient,};let event = db@@ -147,10 +157,11 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {provider_merchant_id,processor_merchant_id,event,- request_content,+ Some(request_content),delivery_attempt,None,Some(process),+ recipient_data,)).await;}@@ -196,25 +207,33 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {);// TODO: Add request state for the PT flows as well- let (content, event_type) = Box::pin(get_outgoing_webhook_content_and_event_type(- state.clone(),- state.get_req_state(),- &platform,- &tracking_data,- ))- .await?;+ let (content, event_type) =+ if let WebhookRecipientData::Merchant { .. } = recipient_data.clone() {+ let (content, event_type) =+ Box::pin(get_outgoing_webhook_content_and_event_type(+ state.clone(),+ state.get_req_state(),+ &platform,+ &tracking_data,+ ))+ .await?;++ (Some(content), event_type)+ } else {+ (None, None)+ };match event_type {// Resource status is same as the event type of the current eventSome(event_type) if event_type == tracking_data.event_type => {- let outgoing_webhook = OutgoingWebhook {+ let outgoing_webhook = content.as_ref().map(|content| OutgoingWebhook {merchant_id: provider_merchant_id.clone(),event_id: event.event_id.clone(),event_type,content: content.clone(),timestamp: event.created_at,processor_merchant_id: Some(processor_merchant_id.clone()),- };+ });// Use the webhook recipient's merchant account for request construction.// If the recipient is the provider, use the provider account (platform-initiated);@@ -226,18 +245,22 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {platform.get_processor().get_account()};- let request_content = webhooks_core::get_outgoing_webhook_request(- webhook_recipient_account,- outgoing_webhook,- &business_profile,- )- .map_err(|error| {- logger::error!(- ?error,- "Failed to obtain outgoing webhook request content"- );- errors::ProcessTrackerError::EApiErrorResponse- })?;+ let request_content = outgoing_webhook+ .map(|outgoing_webhook_data| {+ webhooks_core::get_outgoing_webhook_request(+ webhook_recipient_account,+ outgoing_webhook_data,+ &business_profile,+ )+ })+ .transpose()+ .map_err(|error| {+ logger::error!(+ ?error,+ "Failed to obtain outgoing webhook request content"+ );+ errors::ProcessTrackerError::EApiErrorResponse+ })?;Box::pin(webhooks_core::trigger_webhook_and_raise_event(state.clone(),@@ -248,8 +271,9 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {event,request_content,delivery_attempt,- Some(content),+ content,Some(process),+ recipient_data,)).await;}@@ -333,24 +357,65 @@ pub(crate) async fn get_webhook_delivery_retry_schedule_time(scheduler_utils::get_time_from_delta(time_delta)}+/// This configuration value represents:+/// - `default_mapping.start_after`: The first retry attempt should happen after 60 seconds by+/// default.+/// - `default_mapping.frequency` and `count`: The next 5 retries should have an interval of 300+/// seconds between them by default.+#[cfg(feature = "v1")]+#[instrument(skip_all)]+pub(crate) async fn get_connector_webhook_delivery_retry_schedule_time(+ db: &dyn StorageInterface,+ superposition_client: &external_services::superposition::SuperpositionClient,+ dimensions: &crate::core::configs::dimension_state::DimensionsWithProcessorMerchantIdAndConnector,+ retry_count: i32,+) -> Option<time::PrimitiveDateTime> {+ let mapping = dimensions+ .get_pt_mapping_outgoing_connector_webhooks(db, superposition_client, None)+ .await;++ let time_delta =+ scheduler_utils::get_outgoing_webhook_retry_schedule_time(mapping, retry_count);++ scheduler_utils::get_time_from_delta(time_delta)+}+/// Schedule the webhook delivery task for retry#[cfg(feature = "v1")]#[instrument(skip_all)]pub(crate) async fn retry_webhook_delivery_task(db: &dyn StorageInterface,- superposition_client: &external_services::superposition::SuperpositionClient,merchant_id: &id_type::MerchantId,+ superposition_client: &external_services::superposition::SuperpositionClient,process: storage::ProcessTracker,+ recipient_data: WebhookRecipientData,) -> errors::CustomResult<(), errors::StorageError> {- let dimensions = crate::core::configs::dimension_state::Dimensions::new()- .with_processor_merchant_id(merchant_id.clone().into());- let schedule_time = get_webhook_delivery_retry_schedule_time(- db,- superposition_client,- &dimensions,- process.retry_count + 1,- )- .await;+ let schedule_time = match recipient_data {+ WebhookRecipientData::Merchant { merchant_id } => {+ let dimensions = crate::core::configs::dimension_state::Dimensions::new()+ .with_processor_merchant_id(merchant_id.clone().into());+ get_webhook_delivery_retry_schedule_time(+ db,+ superposition_client,+ &dimensions,+ process.retry_count + 1,+ )+ .await+ }+ WebhookRecipientData::Connector { connector, .. } => {+ let dimensions = crate::core::configs::dimension_state::Dimensions::new()+ .with_processor_merchant_id(merchant_id.clone().into())+ .with_connector(connector);++ get_connector_webhook_delivery_retry_schedule_time(+ db,+ superposition_client,+ &dimensions,+ process.retry_count + 1,+ )+ .await+ }+ };match schedule_time {Some(schedule_time) => {diff --git a/crates/router/src/workflows/payout_sync.rs b/crates/router/src/workflows/payout_sync.rsindex a9d2e6d3b6..b998d8290a 100644--- a/crates/router/src/workflows/payout_sync.rs+++ b/crates/router/src/workflows/payout_sync.rs@@ -291,6 +291,8 @@ impl PayoutSyncWorkFlow {api::OutgoingWebhookContent::PayoutDetails(Box::new(payout_response)),Some(payout_data.payout_attempt.created_at),webhook_recipient,+ None,+ business_profile,)).await?;}diff --git a/migrations/2026-06-25-000001_add_recipient_to_events/down.sql b/migrations/2026-06-25-000001_add_recipient_to_events/down.sqlnew file mode 100644index 0000000000..62803ee50e--- /dev/null+++ b/migrations/2026-06-25-000001_add_recipient_to_events/down.sql@@ -0,0 +1,2 @@+-- This file should undo anything in `up.sql`+ALTER TABLE events DROP COLUMN IF EXISTS recipient;diff --git a/migrations/2026-06-25-000001_add_recipient_to_events/up.sql b/migrations/2026-06-25-000001_add_recipient_to_events/up.sqlnew file mode 100644index 0000000000..dbcdf259a4--- /dev/null+++ b/migrations/2026-06-25-000001_add_recipient_to_events/up.sql@@ -0,0 +1,2 @@+-- Your SQL goes here+ALTER TABLE events ADD COLUMN IF NOT EXISTS recipient VARCHAR(32);\ No newline at end of filediff --git a/migrations/2026-06-25-054230_add_surcharge_event_types/down.sql b/migrations/2026-06-25-054230_add_surcharge_event_types/down.sqlnew file mode 100644index 0000000000..e0ac49d1ec--- /dev/null+++ b/migrations/2026-06-25-054230_add_surcharge_event_types/down.sql@@ -0,0 +1 @@+SELECT 1;diff --git a/migrations/2026-06-25-054230_add_surcharge_event_types/up.sql b/migrations/2026-06-25-054230_add_surcharge_event_types/up.sqlnew file mode 100644index 0000000000..ebcff68dcf--- /dev/null+++ b/migrations/2026-06-25-054230_add_surcharge_event_types/up.sql@@ -0,0 +1,3 @@+-- Add surcharge event types for connector notifications+ALTER TYPE "EventType" ADD VALUE IF NOT EXISTS 'surcharge_payment_succeeded';+ALTER TYPE "EventType" ADD VALUE IF NOT EXISTS 'surcharge_refund_succeeded';