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(core): consume connector webhooks carrying associated data for settled payments (#14093)
Vani Gupta48e0ff94c439
diff --git a/Cargo.lock b/Cargo.lockindex f72f71fcdd..3513b9e367 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2288,7 +2288,7 @@ dependencies = [[[package]]name = "config_patch_derive"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?tag=2026.09.08.0#04befffdc53dfc81f9ac533671c8f35b9c652093"+source = "git+https://github.com/juspay/connector-service?tag=2026.09.15.0#8992aabf3ecf237f583b3ae2862f56049e89dace"dependencies = ["proc-macro2","quote",@@ -4262,7 +4262,7 @@ checksum = "32619942b8be646939eaf3db0602b39f5229b74575b67efc897811ded1db4e57"[[package]]name = "grpc-api-types"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?tag=2026.09.08.0#04befffdc53dfc81f9ac533671c8f35b9c652093"+source = "git+https://github.com/juspay/connector-service?tag=2026.09.15.0#8992aabf3ecf237f583b3ae2862f56049e89dace"dependencies = ["axum 0.8.4","bytes 1.10.1",@@ -8584,7 +8584,7 @@ dependencies = [[[package]]name = "rust-grpc-client"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?tag=2026.09.08.0#04befffdc53dfc81f9ac533671c8f35b9c652093"+source = "git+https://github.com/juspay/connector-service?tag=2026.09.15.0#8992aabf3ecf237f583b3ae2862f56049e89dace"dependencies = ["grpc-api-types",]@@ -11425,7 +11425,7 @@ checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9"[[package]]name = "ucs_cards"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?tag=2026.09.08.0#04befffdc53dfc81f9ac533671c8f35b9c652093"+source = "git+https://github.com/juspay/connector-service?tag=2026.09.15.0#8992aabf3ecf237f583b3ae2862f56049e89dace"dependencies = ["bytes 1.10.1","error-stack 0.4.1",@@ -11441,7 +11441,7 @@ dependencies = [[[package]]name = "ucs_common_enums"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?tag=2026.09.08.0#04befffdc53dfc81f9ac533671c8f35b9c652093"+source = "git+https://github.com/juspay/connector-service?tag=2026.09.15.0#8992aabf3ecf237f583b3ae2862f56049e89dace"dependencies = ["serde","strum 0.26.3",@@ -11452,7 +11452,7 @@ dependencies = [[[package]]name = "ucs_common_utils"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?tag=2026.09.08.0#04befffdc53dfc81f9ac533671c8f35b9c652093"+source = "git+https://github.com/juspay/connector-service?tag=2026.09.15.0#8992aabf3ecf237f583b3ae2862f56049e89dace"dependencies = ["anyhow","base64 0.21.7",diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rsindex 0586db7c3e..e3dbe4d902 100644--- a/crates/api_models/src/payouts.rs+++ b/crates/api_models/src/payouts.rs@@ -272,6 +272,10 @@ impl PayoutMethodData {other => Ok(other),}}++ pub fn is_passthrough(&self) -> bool {+ matches!(self, Self::Passthrough(_))+ }}impl TryFrom<Bank> for BankTransfer {diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rsindex d296193a39..f6b3397351 100644--- a/crates/api_models/src/webhooks.rs+++ b/crates/api_models/src/webhooks.rs@@ -26,6 +26,9 @@ pub enum IncomingWebhookEvent {PaymentIntentCaptureFailure,PaymentIntentExpired,PaymentActionRequired,+ /// Associated data about a payment shared by the connector out of band, typically after+ /// the payment has reached a terminal state+ PaymentAssociatedDataUpdate,EventNotSupported,SourceChargeable,SourceTransactionCreated,@@ -129,6 +132,8 @@ impl IncomingWebhookEvent {35 => Self::PayoutExpired,#[cfg(feature = "payouts")]36 => Self::PayoutReversed,+ // Associated data events+ 43 => Self::PaymentAssociatedDataUpdate,_ => Self::EventNotSupported,}}@@ -145,6 +150,7 @@ pub enum WebhookFlow {ReturnResponse,BankTransfer,Mandate,+ AssociatedDataUpdate,ExternalAuthentication,FraudCheck,#[cfg(all(feature = "revenue_recovery", feature = "v2"))]@@ -295,6 +301,7 @@ impl From<IncomingWebhookEvent> for WebhookFlow {IncomingWebhookEvent::MandateActive | IncomingWebhookEvent::MandateRevoked => {Self::Mandate}+ IncomingWebhookEvent::PaymentAssociatedDataUpdate => Self::AssociatedDataUpdate,IncomingWebhookEvent::DisputeOpened| IncomingWebhookEvent::DisputeAccepted| IncomingWebhookEvent::DisputeExpireddiff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rsindex abe60ba3fd..e70f855c61 100644--- a/crates/common_enums/src/connector_enums.rs+++ b/crates/common_enums/src/connector_enums.rs@@ -241,11 +241,16 @@ impl Connector {)}#[cfg(feature = "payouts")]- pub fn supports_create_recipient(self, payout_method: Option<PayoutType>) -> bool {- matches!(- (self, payout_method),- (_, Some(PayoutType::Bank)) | (Self::Trustly, _)- )+ pub fn supports_create_recipient(+ self,+ payout_method: Option<PayoutType>,+ is_passthrough: bool,+ ) -> bool {+ if matches!(self, Self::Trustly) {+ !is_passthrough+ } else {+ matches!(payout_method, Some(PayoutType::Bank))+ }}#[cfg(feature = "payouts")]pub fn supports_payout_eligibility(self, payout_method: Option<PayoutType>) -> bool {diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rsindex 1bf2a92e5d..a51449c275 100644--- a/crates/diesel_models/src/payment_attempt.rs+++ b/crates/diesel_models/src/payment_attempt.rs@@ -683,6 +683,10 @@ pub enum PaymentAttemptUpdate {tokenization: Option<common_enums::Tokenization>,updated_by: String,},+ AssociatedDataUpdate {+ sender_payment_instrument_id: Option<String>,+ updated_by: String,+ },BlocklistUpdate {status: storage_enums::AttemptStatus,error_code: Option<Option<String>>,@@ -3129,6 +3133,88 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {applied_offer_details: None,payment_account_reference: None,},+ PaymentAttemptUpdate::AssociatedDataUpdate {+ sender_payment_instrument_id,+ updated_by,+ } => Self {+ payment_method_id: None,+ modified_at: common_utils::date_time::now(),+ updated_by,+ amount: None,+ net_amount: None,+ currency: None,+ status: None,+ connector_transaction_id: None,+ amount_to_capture: None,+ connector: None,+ authentication_type: None,+ payment_method: None,+ error_message: None,+ cancellation_reason: None,+ mandate_id: None,+ tokenization: None,+ browser_info: None,+ payment_token: None,+ error_code: 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,+ error_reason: 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,+ unified_code: None,+ unified_message: None,+ external_three_ds_authentication_attempted: None,+ external_threeds_authentication_type: None,+ authentication_connector: None,+ authentication_id: None,+ fingerprint_id: None,+ fingerprint_type: 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,+ 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,+ encrypted_payment_method_data: None,+ error_details: None,+ installment_data: None,+ sender_payment_instrument_id,+ external_surcharge_details: None,+ applied_offer_details: None,+ payment_account_reference: None,+ },PaymentAttemptUpdate::PaymentMethodDetailsUpdate {payment_method_id,updated_by,diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.tomlindex c7c58553ee..fb02ad7b81 100644--- a/crates/external_services/Cargo.toml+++ b/crates/external_services/Cargo.toml@@ -94,7 +94,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.09.08.0", package = "rust-grpc-client" }+unified-connector-service-client = { git = "https://github.com/juspay/connector-service", tag = "2026.09.15.0", package = "rust-grpc-client" }open-feature = { version = "0.2.5", optional = true }bytes = { version = "1.10.1", optional = true }superposition_provider = { version = "0.115.5", optional = true }diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rsindex ab8911354b..39a722aba6 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs@@ -2099,6 +2099,10 @@ pub enum PaymentAttemptUpdate {tokenization: Option<common_enums::Tokenization>,updated_by: String,},+ AssociatedDataUpdate {+ sender_payment_instrument_id: Option<String>,+ updated_by: String,+ },VoidUpdate {status: storage_enums::AttemptStatus,cancellation_reason: Option<String>,@@ -2365,6 +2369,13 @@ impl PaymentAttemptUpdate {tokenization,updated_by,},+ Self::AssociatedDataUpdate {+ sender_payment_instrument_id,+ updated_by,+ } => DieselPaymentAttemptUpdate::AssociatedDataUpdate {+ sender_payment_instrument_id,+ updated_by,+ },Self::PaymentMethodDetailsUpdate {payment_method_id,updated_by,@@ -2872,6 +2883,7 @@ impl PaymentAttemptUpdate {| Self::BlocklistUpdate { .. }| Self::PaymentMethodDetailsUpdate { .. }| Self::ConnectorMandateDetailUpdate { .. }+ | Self::AssociatedDataUpdate { .. }| Self::VoidUpdate { .. }| Self::UnresolvedResponseUpdate { .. }| Self::StatusUpdate { .. }diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/webhooks.rs b/crates/hyperswitch_domain_models/src/router_flow_types/webhooks.rsindex bca67675f3..80031cca46 100644--- a/crates/hyperswitch_domain_models/src/router_flow_types/webhooks.rs+++ b/crates/hyperswitch_domain_models/src/router_flow_types/webhooks.rs@@ -19,3 +19,17 @@ impl ConnectorNetworkTxnId {&self.0}}++/// Associated data about a payment shared by a connector over a webhook.+/// Fields are grouped by the record they are written to, so that support for further records+/// (payment methods, for instance) can be added without changing the flow's signature.+#[derive(Debug, Clone, Serialize)]+pub struct WebhookAssociatedData {+ pub payment_attempt: PaymentAttemptAssociatedData,+}++/// Associated data written to the payment attempt.+#[derive(Debug, Clone, Serialize)]+pub struct PaymentAttemptAssociatedData {+ pub sender_payment_instrument_id: Option<hyperswitch_masking::Secret<String>>,+}diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.tomlindex 5e479e9c30..3eb80c88a6 100644--- a/crates/hyperswitch_interfaces/Cargo.toml+++ b/crates/hyperswitch_interfaces/Cargo.toml@@ -35,7 +35,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.09.08.0", package = "rust-grpc-client" }+unified-connector-service-client = { git = "https://github.com/juspay/connector-service", tag = "2026.09.15.0", package = "rust-grpc-client" }tokio = { version = "1.45.1", features = ["macros", "rt-multi-thread"] }# First party cratesdiff --git a/crates/hyperswitch_interfaces/src/webhooks.rs b/crates/hyperswitch_interfaces/src/webhooks.rsindex fa1a4add42..c99aebe5ea 100644--- a/crates/hyperswitch_interfaces/src/webhooks.rs+++ b/crates/hyperswitch_interfaces/src/webhooks.rs@@ -385,6 +385,17 @@ pub trait IncomingWebhook: ConnectorCommon + Sync {Ok(None)}+ /// fn to get associated data about a payment from the webhook body, if any+ fn get_associated_data(+ &self,+ _request: &IncomingWebhookRequestDetails<'_>,+ ) -> CustomResult<+ Option<hyperswitch_domain_models::router_flow_types::WebhookAssociatedData>,+ errors::ConnectorError,+ > {+ Ok(None)+ }+/// fn to get additional payment method data from connector if anyfn get_additional_payment_method_data(&self,diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.tomlindex 9c65693421..665cf7dcc7 100644--- a/crates/router/Cargo.toml+++ b/crates/router/Cargo.toml@@ -243,8 +243,8 @@ rust_decimal = { version = "1.37.1", features = [] }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.09.08.0", package = "rust-grpc-client" }-unified-connector-service-cards = { git = "https://github.com/juspay/connector-service", tag = "2026.09.08.0", package = "ucs_cards" }+unified-connector-service-client = { git = "https://github.com/juspay/connector-service", tag = "2026.09.15.0", package = "rust-grpc-client" }+unified-connector-service-cards = { git = "https://github.com/juspay/connector-service", tag = "2026.09.15.0", package = "ucs_cards" }rustc-hash = "1.1.0"rustls = { version = "0.23", default-features = false, features = ["aws-lc-rs",diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rsindex 12d15df24b..0f6c62b245 100644--- a/crates/router/src/core/payouts.rs+++ b/crates/router/src/core/payouts.rs@@ -1338,6 +1338,11 @@ pub async fn complete_create_recipient(connector_data: &api::ConnectorData,payout_data: &mut PayoutData,) -> RouterResult<()> {+ let is_passthrough = payout_data+ .payout_method_data+ .as_ref()+ .is_some_and(|payout_method_data| payout_method_data.is_passthrough());+if !payout_data.should_terminate&& matches!(payout_data.payout_attempt.status,@@ -1347,7 +1352,7 @@ pub async fn complete_create_recipient()&& connector_data.connector_name- .supports_create_recipient(payout_data.payouts.payout_type)+ .supports_create_recipient(payout_data.payouts.payout_type, is_passthrough){Box::pin(create_recipient(state,diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rsindex 78c9b750f1..7299c7fd3b 100644--- a/crates/router/src/core/unified_connector_service/transformers.rs+++ b/crates/router/src/core/unified_connector_service/transformers.rs@@ -8726,7 +8726,11 @@ implmerchant_payout_id: router_data.payout_id.clone(),address: Some(address),amount: Some(money),- payout_connector_metadata: None,+ payout_connector_metadata: router_data+ .request+ .payout_connector_metadata+ .clone()+ .map(|metadata| Secret::new(metadata.expose().to_string())),destination_currency: destination_currency.into(),customer: Some(customer),access_token: router_data.access_token.clone().map(|at| at.token),@@ -8982,6 +8986,11 @@ impl#[cfg(feature = "payouts")]macro_rules! impl_ucs_payout_response_transformation {($response_type:ty, $merchant_id_field:ident) => {+ impl_ucs_payout_response_transformation!($response_type, $merchant_id_field, |_response| {+ None+ });+ };+ ($response_type:ty, $merchant_id_field:ident, $connector_metadata:expr) => {impl transformers::ForeignTryFrom<($response_type, common_enums::PayoutStatus)>for Result<PayoutsResponseData, ErrorResponse>{@@ -8993,6 +9002,15 @@ macro_rules! impl_ucs_payout_response_transformation {let status = common_enums::PayoutStatus::foreign_try_from(response.payout_status()).unwrap_or(prev_status);+ let connector_metadata: fn(&$response_type) -> Option<&Secret<String>> =+ $connector_metadata;+ let payout_connector_metadata = connector_metadata(&response)+ .and_then(|metadata| {+ serde_json::from_str::<serde_json::Value>(metadata.peek()).ok()+ })+ .filter(|value| value.as_object().is_some_and(|details| !details.is_empty()))+ .map(Secret::new);+let router_response = if let Some(error_info) = response.error {Ok(PayoutsResponseData {status: Some(status),@@ -9018,7 +9036,7 @@ macro_rules! impl_ucs_payout_response_transformation {should_add_next_step_to_process_tracker: false,error_code: None,error_message: None,- payout_connector_metadata: None,+ payout_connector_metadata,connector_eligibility_reference_id: None,})};@@ -9098,11 +9116,14 @@ impl_ucs_payout_response_transformation!(payments_grpc::PayoutServiceStageResponse,merchant_payout_id);+#[cfg(feature = "payouts")]impl_ucs_payout_response_transformation!(payments_grpc::PayoutServiceCreateRecipientResponse,- merchant_payout_id+ merchant_payout_id,+ |response| response.connector_metadata.as_ref());+#[cfg(feature = "payouts")]impl_ucs_payout_response_transformation!(payments_grpc::PayoutServiceEnrollDisburseAccountResponse,@@ -9143,12 +9164,11 @@ impl transformers::ForeignTryFrom<&api_models::payouts::PayoutMethodData>payments_grpc::PixBankTransferPayout::foreign_try_from(pix)?,)}- api_models::payouts::Bank::Trustly(_) => Err(error_stack::Report::new(- UnifiedConnectorServiceError::RequestEncodingFailedWithReason(- "Trustly bank transfer not supported for Unified Connector Service"- .to_string(),- ),- ))?,+ api_models::payouts::Bank::Trustly(trustly) => {+ payments_grpc::payout_method::PayoutMethodData::Trustly(+ payments_grpc::TrustlyBankTransferPayout::foreign_try_from(trustly)?,+ )+ }api_models::payouts::Bank::OpenBanking(_) => Err(error_stack::Report::new(UnifiedConnectorServiceError::RequestEncodingFailedWithReason("OpenBanking bank transfer not supported for Unified Connector Service"@@ -9188,13 +9208,10 @@ impl transformers::ForeignTryFrom<&api_models::payouts::PayoutMethodData>payments_grpc::PixBankTransferPayout::foreign_try_from(pix)?,)}- api_models::payouts::BankTransfer::Trustly(_) => {- Err(error_stack::Report::new(- UnifiedConnectorServiceError::RequestEncodingFailedWithReason(- "Trustly bank transfer not supported for Unified Connector Service"- .to_string(),- ),- ))?+ api_models::payouts::BankTransfer::Trustly(trustly) => {+ payments_grpc::payout_method::PayoutMethodData::Trustly(+ payments_grpc::TrustlyBankTransferPayout::foreign_try_from(trustly)?,+ )}api_models::payouts::BankTransfer::PixKey(pix_key) => {payments_grpc::payout_method::PayoutMethodData::PixKey(@@ -9363,6 +9380,64 @@ impl transformers::ForeignTryFrom<&api_models::payouts::SepaBankTransfer>}}+#[cfg(feature = "payouts")]+impl transformers::ForeignTryFrom<&api_models::payouts::TrustlyBankTransfer>+ for payments_grpc::TrustlyBankTransferPayout+{+ type Error = error_stack::Report<UnifiedConnectorServiceError>;++ fn foreign_try_from(+ item: &api_models::payouts::TrustlyBankTransfer,+ ) -> Result<Self, Self::Error> {+ Ok(Self {+ iban: item.iban.clone(),+ bank_account_number: item.account_number.clone(),+ bank_number: item.bank_number.clone(),+ bank_country_code: payments_grpc::CountryAlpha2::from_str_name(+ &item.country_code.to_string(),+ )+ .map(|country| country.into())+ .ok_or_else(|| {+ error_stack::Report::new(+ UnifiedConnectorServiceError::RequestEncodingFailedWithReason(format!(+ "Unsupported bank country code for Trustly payout: {}",+ item.country_code+ )),+ )+ })?,+ })+ }+}++#[cfg(feature = "payouts")]+impl transformers::ForeignTryFrom<&api_models::payouts::TrustlyBankTransferData>+ for payments_grpc::TrustlyBankTransferPayout+{+ type Error = error_stack::Report<UnifiedConnectorServiceError>;++ fn foreign_try_from(+ item: &api_models::payouts::TrustlyBankTransferData,+ ) -> Result<Self, Self::Error> {+ Ok(Self {+ iban: item.iban.clone(),+ bank_account_number: item.bank_account_number.clone(),+ bank_number: item.bank_number.clone(),+ bank_country_code: payments_grpc::CountryAlpha2::from_str_name(+ &item.bank_country_code.to_string(),+ )+ .map(|country| country.into())+ .ok_or_else(|| {+ error_stack::Report::new(+ UnifiedConnectorServiceError::RequestEncodingFailedWithReason(format!(+ "Unsupported bank country code for Trustly payout: {}",+ item.bank_country_code+ )),+ )+ })?,+ })+ }+}+#[cfg(feature = "payouts")]impl ForeignFrom<&common_enums::BankType> for payments_grpc::BankType {fn foreign_from(item: &common_enums::BankType) -> Self {@@ -9558,11 +9633,11 @@ impl transformers::ForeignTryFrom<&api_models::payouts::BankTransfer>payments_grpc::PixEmvBankTransferPayout::foreign_from(pix_emv),))}- api_models::payouts::BankTransfer::Trustly(_) => Err(error_stack::Report::new(- UnifiedConnectorServiceError::RequestEncodingFailedWithReason(- "Trustly bank transfer not supported for Unified Connector Service".to_string(),- ),- ))?,+ api_models::payouts::BankTransfer::Trustly(trustly) => {+ Some(payments_grpc::source_bank_data::SourceBankData::Trustly(+ payments_grpc::TrustlyBankTransferPayout::foreign_try_from(trustly)?,+ ))+ }api_models::payouts::BankTransfer::OpenBanking(_) => Err(error_stack::Report::new(UnifiedConnectorServiceError::RequestEncodingFailedWithReason("OpenBanking bank transfer not supported for Unified Connector Service"diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rsindex b1490c0f8c..cdd22a7ecc 100644--- a/crates/router/src/core/webhooks/incoming.rs+++ b/crates/router/src/core/webhooks/incoming.rs@@ -22,13 +22,19 @@ use hyperswitch_domain_models::{api::{IncomingWebhookEventMetadata, WebhookResponse},mandates::CommonMandateReference,payments::{payment_attempt::PaymentAttempt, HeaderPayload},+ router_flow_types::{PaymentAttemptAssociatedData, WebhookAssociatedData},router_request_types::unified_authentication_service::UasAuthenticationResponseData,};-use hyperswitch_interfaces::webhooks::{- IncomingWebhookFlowError, IncomingWebhookRequestDetails, WebhookContext, WebhookResourceData,+use hyperswitch_interfaces::{+ unified_connector_service::get_payments_response_from_ucs_webhook_content,+ webhooks::{+ IncomingWebhookFlowError, IncomingWebhookRequestDetails, WebhookContext,+ WebhookResourceData,+ },};use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};use router_env::{instrument, tracing, tracing::Instrument};+use unified_connector_service_client::payments as payments_grpc;use super::{types, MERCHANT_ID};use crate::{@@ -641,6 +647,20 @@ async fn process_webhook_business_logic(.await.attach_printable("Incoming webhook flow for mandates failed"),+ api::WebhookFlow::AssociatedDataUpdate => {+ Box::pin(associated_data_incoming_webhook_flow(+ state.clone(),+ platform.clone(),+ webhook_details,+ source_verified,+ connector,+ request_details,+ &content,+ ))+ .await+ .attach_printable("Incoming webhook flow for associated data failed")+ }+api::WebhookFlow::ExternalAuthentication => {Box::pin(external_authentication_incoming_webhook_flow(state.clone(),@@ -1720,6 +1740,7 @@ async fn relay_incoming_webhook_flow(| webhooks::WebhookFlow::ReturnResponse| webhooks::WebhookFlow::BankTransfer| webhooks::WebhookFlow::Mandate+ | webhooks::WebhookFlow::AssociatedDataUpdate| webhooks::WebhookFlow::Setup| webhooks::WebhookFlow::ExternalAuthentication| webhooks::WebhookFlow::FraudCheck => Err(errors::ApiErrorResponse::NotSupported {@@ -2303,6 +2324,193 @@ async fn mandates_incoming_webhook_flow(}}+#[instrument(skip_all)]+async fn associated_data_incoming_webhook_flow(+ state: SessionState,+ platform: domain::Platform,+ webhook_details: api::IncomingWebhookDetails,+ source_verified: bool,+ connector: &ConnectorEnum,+ request_details: &IncomingWebhookRequestDetails<'_>,+ content: &super::gateway::WebhookContent,+) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {+ if source_verified {+ let associated_data = match content {+ super::gateway::WebhookContent::Direct(_) => connector+ .get_associated_data(request_details)+ .switch()+ .attach_printable("Could not find associated data in incoming webhook body")?,+ super::gateway::WebhookContent::UnifiedConnectorService(bytes) => {+ associated_data_from_ucs_event_content(bytes)?+ }+ };++ match associated_data {+ Some(associated_data) => {+ let processor = platform.get_processor();+ let merchant_id = processor.get_account().get_id().to_owned();++ // Resolve the payment once to derive the locking key.+ let payment_id = get_payment_attempt_from_object_reference_id(+ &state,+ webhook_details.object_reference_id.clone(),+ processor,+ )+ .await?+ .payment_id;++ let lock_action = api_locking::LockAction::Hold {+ input: api_locking::LockingInput {+ unique_locking_key: payment_id.get_string_repr().to_owned(),+ api_identifier: lock_utils::ApiIdentifier::Payments,+ override_lock_retries: None,+ },+ };+ lock_action+ .clone()+ .perform_locking_action(&state, merchant_id.clone())+ .await?;++ let payment_attempt = get_payment_attempt_from_object_reference_id(+ &state,+ webhook_details.object_reference_id.clone(),+ processor,+ )+ .await?;++ let update_result = update_payment_attempt_associated_data(+ &state,+ processor,+ payment_attempt,+ associated_data.payment_attempt,+ )+ .await;++ lock_action+ .free_lock_action(&state, merchant_id.clone())+ .await?;++ update_result?;++ let payment_intent = state+ .store+ .find_payment_intent_by_payment_id_processor_merchant_id(+ &payment_id,+ &merchant_id,+ processor.get_key_store(),+ processor.get_account().storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;++ Ok(WebhookResponseTracker::Payment {+ payment_id,+ status: payment_intent.status,+ })+ }+ // Acknowledge webhooks that carry nothing to write so the connector does not retry them.+ None => {+ logger::info!("No associated data in incoming webhook body, skipping update");+ Ok(WebhookResponseTracker::NoEffect)+ }+ }+ } else {+ logger::error!("Webhook source verification failed for associated data webhook flow");+ Err(report!(+ errors::ApiErrorResponse::WebhookAuthenticationFailed+ ))+ }+}++fn associated_data_from_ucs_event_content(+ bytes: &[u8],+) -> CustomResult<Option<WebhookAssociatedData>, errors::ApiErrorResponse> {+ let event_content: payments_grpc::EventContent = serde_json::from_slice(bytes)+ .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)+ .attach_printable("Failed to deserialize unified connector service event content")?;++ let payments_response = get_payments_response_from_ucs_webhook_content(event_content)+ .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)+ .attach_printable(+ "Failed to read the payments response from unified connector service event content",+ )?;++ match payments_response.sender_payment_instrument_id {+ None => Ok(None),+ Some(sender_payment_instrument_id) => Ok(Some(WebhookAssociatedData {+ payment_attempt: PaymentAttemptAssociatedData {+ sender_payment_instrument_id: Some(Secret::new(sender_payment_instrument_id)),+ },+ })),+ }+}++fn resolve_write_once_field(+ stored: Option<&str>,+ incoming: Option<&str>,+ field_name: &'static str,+ payment_id: &common_utils::id_type::PaymentId,+) -> Option<String> {+ match (stored, incoming) {+ (None, Some(incoming)) => Some(incoming.to_owned()),+ (Some(stored), Some(incoming)) if stored != incoming => {+ logger::warn!(+ payment_id = ?payment_id,+ field = field_name,+ "Received associated data that differs from the stored value, retaining the stored value"+ );+ None+ }+ _ => None,+ }+}++/// Writes associated data onto the payment attempt.+async fn update_payment_attempt_associated_data(+ state: &SessionState,+ processor: &domain::Processor,+ payment_attempt: PaymentAttempt,+ associated_data: PaymentAttemptAssociatedData,+) -> CustomResult<(), errors::ApiErrorResponse> {+ let sender_payment_instrument_id = resolve_write_once_field(+ payment_attempt.sender_payment_instrument_id.as_deref(),+ associated_data+ .sender_payment_instrument_id+ .as_ref()+ .map(|id| id.peek().as_str()),+ "sender_payment_instrument_id",+ &payment_attempt.payment_id,+ );++ match sender_payment_instrument_id {+ Some(sender_payment_instrument_id) => {+ let attempt_update = storage::PaymentAttemptUpdate::AssociatedDataUpdate {+ sender_payment_instrument_id: Some(sender_payment_instrument_id),+ updated_by: processor.get_account().storage_scheme.to_string(),+ };++ state+ .store+ .update_payment_attempt_with_attempt_id(+ payment_attempt,+ attempt_update,+ processor.get_account().storage_scheme,+ processor.get_key_store(),+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;++ Ok(())+ }+ None => {+ logger::info!(+ "No new associated data to write to the payment attempt, skipping update"+ );+ Ok(())+ }+ }+}+#[allow(clippy::too_many_arguments)]#[instrument(skip_all)]async fn frm_incoming_webhook_flow(diff --git a/crates/router/src/core/webhooks/incoming_v2.rs b/crates/router/src/core/webhooks/incoming_v2.rsindex c7ce7d6478..a773450bc5 100644--- a/crates/router/src/core/webhooks/incoming_v2.rs+++ b/crates/router/src/core/webhooks/incoming_v2.rs@@ -339,6 +339,8 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(api::WebhookFlow::Mandate => todo!(),+ api::WebhookFlow::AssociatedDataUpdate => todo!(),+api::WebhookFlow::ExternalAuthentication => todo!(),api::WebhookFlow::FraudCheck => todo!(),api::WebhookFlow::Setup => WebhookResponseTracker::NoEffect,diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rsindex bf8546e20d..33ac3733b3 100644--- a/crates/router/src/core/webhooks/recovery_incoming.rs+++ b/crates/router/src/core/webhooks/recovery_incoming.rs@@ -1598,7 +1598,8 @@ impl RecoveryAction {| webhooks::IncomingWebhookEvent::PayoutExpired| webhooks::IncomingWebhookEvent::PayoutReversed| webhooks::IncomingWebhookEvent::InvoiceGenerated- | webhooks::IncomingWebhookEvent::SetupWebhook => {+ | webhooks::IncomingWebhookEvent::SetupWebhook+ | webhooks::IncomingWebhookEvent::PaymentAssociatedDataUpdate => {common_types::payments::RecoveryAction::InvalidAction}webhooks::IncomingWebhookEvent::RecoveryPaymentFailure => match attempt_triggered_by {