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(webhooks): add generic outgoing webhook event configuration (#13649)
Kashif1cb3c9e11ffc
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex fff515d1a9..31550403c0 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -48605,7 +48605,7 @@"refund_statuses_enabled": {"type": "array","items": {- "$ref": "#/components/schemas/IntentStatus"+ "$ref": "#/components/schemas/RefundStatus"},"description": "List of refund statuses that triggers a webhook for refunds","example": [@@ -48624,6 +48624,41 @@"failed"],"nullable": true+ },+ "dispute_statuses_enabled": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/DisputeStatus"+ },+ "description": "List of dispute statuses that trigger outgoing webhooks for disputes",+ "example": [+ "dispute_opened",+ "dispute_won"+ ],+ "nullable": true+ },+ "mandate_statuses_enabled": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/MandateStatus"+ },+ "description": "List of mandate statuses that trigger outgoing webhooks for mandates",+ "example": [+ "active",+ "inactive"+ ],+ "nullable": true+ },+ "invoice_statuses_enabled": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/InvoiceStatus"+ },+ "description": "List of invoice statuses that trigger outgoing webhooks for subscriptions",+ "example": [+ "invoice_paid"+ ],+ "nullable": true}},"additionalProperties": falsediff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex 574a447e38..5b515b2548 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -17620,6 +17620,20 @@}}},+ "InvoiceStatus": {+ "type": "string",+ "enum": [+ "invoice_created",+ "payment_pending",+ "payment_pending_timeout",+ "payment_succeeded",+ "payment_failed",+ "payment_canceled",+ "invoice_paid",+ "manual_review",+ "voided"+ ]+ },"JCSVoucherData": {"type": "object","properties": {@@ -35492,7 +35506,7 @@"refund_statuses_enabled": {"type": "array","items": {- "$ref": "#/components/schemas/IntentStatus"+ "$ref": "#/components/schemas/RefundStatus"},"description": "List of refund statuses that triggers a webhook for refunds","example": [@@ -35511,6 +35525,41 @@"failed"],"nullable": true+ },+ "dispute_statuses_enabled": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/DisputeStatus"+ },+ "description": "List of dispute statuses that trigger outgoing webhooks for disputes",+ "example": [+ "dispute_opened",+ "dispute_won"+ ],+ "nullable": true+ },+ "mandate_statuses_enabled": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/MandateStatus"+ },+ "description": "List of mandate statuses that trigger outgoing webhooks for mandates",+ "example": [+ "active",+ "inactive"+ ],+ "nullable": true+ },+ "invoice_statuses_enabled": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/InvoiceStatus"+ },+ "description": "List of invoice statuses that trigger outgoing webhooks for subscriptions",+ "example": [+ "invoice_paid"+ ],+ "nullable": true}},"additionalProperties": falsediff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rsindex 8f2d4293f1..95706fd86a 100644--- a/crates/api_models/src/admin.rs+++ b/crates/api_models/src/admin.rs@@ -898,16 +898,28 @@ pub struct WebhookDetails {/// List of payment statuses that triggers a webhook for payment intents#[schema(value_type = Vec<IntentStatus>, example = json!(["succeeded", "failed", "partially_captured", "requires_merchant_action"]))]- pub payment_statuses_enabled: Option<Vec<api_enums::IntentStatus>>,+ pub payment_statuses_enabled: Option<HashSet<api_enums::IntentStatus>>,/// List of refund statuses that triggers a webhook for refunds- #[schema(value_type = Vec<IntentStatus>, example = json!(["success", "failure"]))]- pub refund_statuses_enabled: Option<Vec<api_enums::RefundStatus>>,+ #[schema(value_type = Vec<RefundStatus>, example = json!(["success", "failure"]))]+ pub refund_statuses_enabled: Option<HashSet<api_enums::RefundStatus>>,/// List of payout statuses that triggers a webhook for payouts#[cfg(feature = "payouts")]#[schema(value_type = Option<Vec<PayoutStatus>>, example = json!(["success", "failed"]))]- pub payout_statuses_enabled: Option<Vec<api_enums::PayoutStatus>>,+ pub payout_statuses_enabled: Option<HashSet<api_enums::PayoutStatus>>,++ /// List of dispute statuses that trigger outgoing webhooks for disputes+ #[schema(value_type = Option<Vec<DisputeStatus>>, example = json!(["dispute_opened", "dispute_won"]))]+ pub dispute_statuses_enabled: Option<HashSet<api_enums::DisputeStatus>>,++ /// List of mandate statuses that trigger outgoing webhooks for mandates+ #[schema(value_type = Option<Vec<MandateStatus>>, example = json!(["active", "inactive"]))]+ pub mandate_statuses_enabled: Option<HashSet<api_enums::MandateStatus>>,++ /// List of invoice statuses that trigger outgoing webhooks for subscriptions+ #[schema(value_type = Option<Vec<InvoiceStatus>>, example = json!(["invoice_paid"]))]+ pub invoice_statuses_enabled: Option<HashSet<api_enums::InvoiceStatus>>,}impl WebhookDetails {@@ -934,24 +946,33 @@ impl WebhookDetails {payout_statuses_enabled: other.payout_statuses_enabled.or(self.payout_statuses_enabled),+ dispute_statuses_enabled: other+ .dispute_statuses_enabled+ .or(self.dispute_statuses_enabled),+ mandate_statuses_enabled: other+ .mandate_statuses_enabled+ .or(self.mandate_statuses_enabled),+ invoice_statuses_enabled: other+ .invoice_statuses_enabled+ .or(self.invoice_statuses_enabled),}}- fn validate_statuses<T>(statuses: &[T], status_type_name: &str) -> Result<(), String>+ fn validate_statuses<T>(statuses: &HashSet<T>, status_type_name: &str) -> Result<(), String>where- T: strum::IntoEnumIterator + Copy + PartialEq + std::fmt::Debug,+ T: strum::IntoEnumIterator + Copy + Eq + std::hash::Hash + std::fmt::Debug,T: Into<Option<api_enums::EventType>>,{- let valid_statuses: Vec<T> = T::iter().filter(|s| (*s).into().is_some()).collect();+ let valid_statuses: HashSet<T> = T::iter().filter(|s| (*s).into().is_some()).collect();- for status in statuses {- if !valid_statuses.contains(status) {- return Err(format!(+ statuses+ .iter()+ .find(|status| !valid_statuses.contains(status))+ .map_or(Ok(()), |status| {+ Err(format!("Invalid {status_type_name} webhook status provided: {status:?}"- ));- }- }- Ok(())+ ))+ })}pub fn validate(&self) -> Result<(), String> {@@ -970,6 +991,18 @@ impl WebhookDetails {}}+ if let Some(dispute_statuses) = &self.dispute_statuses_enabled {+ Self::validate_statuses(dispute_statuses, "dispute")?;+ }++ if let Some(mandate_statuses) = &self.mandate_statuses_enabled {+ Self::validate_statuses(mandate_statuses, "mandate")?;+ }++ if let Some(invoice_statuses) = &self.invoice_statuses_enabled {+ Self::validate_statuses(invoice_statuses, "invoice")?;+ }+Ok(())}}diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rsindex 3f54766d38..7bb32c762d 100644--- a/crates/common_enums/src/connector_enums.rs+++ b/crates/common_enums/src/connector_enums.rs@@ -516,11 +516,14 @@ impl Connector {#[derive(Debug,Clone,+ Copy,PartialEq,Eq,+ Hash,serde::Deserialize,serde::Serialize,strum::Display,+ strum::EnumIter,strum::EnumString,ToSchema,)]diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 5729410fb9..738c11b36c 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -1871,6 +1871,7 @@ pub enum EventObjectType {serde::Deserialize,serde::Serialize,strum::Display,+ strum::EnumIter,strum::EnumString,ToSchema,)]@@ -3363,6 +3364,7 @@ pub enum FrmTransactionType {Copy,Debug,Eq,+ Hash,PartialEq,Default,serde::Deserialize,diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rsindex 1824a86aea..ea331e2392 100644--- a/crates/common_enums/src/transformers.rs+++ b/crates/common_enums/src/transformers.rs@@ -4,9 +4,13 @@ use serde::{Deserialize, Serialize};#[cfg(feature = "payouts")]use crate::enums::PayoutStatus;-use crate::enums::{- AttemptStatus, Country, CountryAlpha2, CountryAlpha3, DisputeStatus, EventType, IntentStatus,- MandateStatus, PaymentMethod, PaymentMethodType, RefundStatus, SubscriptionStatus,+use crate::{+ enums::{+ AttemptStatus, Country, CountryAlpha2, CountryAlpha3, DisputeStatus, EventType,+ IntentStatus, MandateStatus, PaymentMethod, PaymentMethodType, RefundStatus,+ SubscriptionStatus,+ },+ InvoiceStatus,};impl Display for NumericCountryCodeParseError {@@ -2221,6 +2225,12 @@ impl From<DisputeStatus> for EventType {}}+impl From<DisputeStatus> for Option<EventType> {+ fn from(value: DisputeStatus) -> Self {+ Some(EventType::from(value))+ }+}+impl From<MandateStatus> for Option<EventType> {fn from(value: MandateStatus) -> Self {match value {@@ -2240,6 +2250,22 @@ impl From<SubscriptionStatus> for Option<EventType> {}}+impl From<InvoiceStatus> for Option<EventType> {+ fn from(value: InvoiceStatus) -> Self {+ match value {+ InvoiceStatus::InvoicePaid => Some(EventType::InvoicePaid),+ InvoiceStatus::InvoiceCreated+ | InvoiceStatus::PaymentPending+ | InvoiceStatus::PaymentPendingTimeout+ | InvoiceStatus::PaymentSucceeded+ | InvoiceStatus::PaymentFailed+ | InvoiceStatus::PaymentCanceled+ | InvoiceStatus::ManualReview+ | InvoiceStatus::Voided => None,+ }+ }+}+#[cfg(test)]mod tests {use super::*;diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rsindex 3b80da7a39..c427629fb3 100644--- a/crates/diesel_models/src/business_profile.rs+++ b/crates/diesel_models/src/business_profile.rs@@ -573,9 +573,12 @@ pub struct WebhookDetails {pub payment_created_enabled: Option<bool>,pub payment_succeeded_enabled: Option<bool>,pub payment_failed_enabled: Option<bool>,- pub payment_statuses_enabled: Option<Vec<common_enums::IntentStatus>>,- pub refund_statuses_enabled: Option<Vec<common_enums::RefundStatus>>,- pub payout_statuses_enabled: Option<Vec<common_enums::PayoutStatus>>,+ pub payment_statuses_enabled: Option<HashSet<common_enums::IntentStatus>>,+ pub refund_statuses_enabled: Option<HashSet<common_enums::RefundStatus>>,+ pub payout_statuses_enabled: Option<HashSet<common_enums::PayoutStatus>>,+ pub dispute_statuses_enabled: Option<HashSet<common_enums::DisputeStatus>>,+ pub mandate_statuses_enabled: Option<HashSet<common_enums::MandateStatus>>,+ pub invoice_statuses_enabled: Option<HashSet<common_enums::InvoiceStatus>>,pub multiple_webhooks_list: Option<Vec<MultipleWebhookDetail>>,}diff --git a/crates/euclid_wasm/src/lib.rs b/crates/euclid_wasm/src/lib.rsindex 6cd523dc47..b6c01c8505 100644--- a/crates/euclid_wasm/src/lib.rs+++ b/crates/euclid_wasm/src/lib.rs@@ -38,8 +38,8 @@ use api_models::payment_methods::CountryCodeWithName;use common_enums::PayoutStatus;use common_enums::{CardSegmentType, CardType, CountryAlpha2, DisputeStatus, EventClass, EventType, FundingSource,- IntentStatus, MandateStatus, MerchantCategoryCode, MerchantCategoryCodeWithName, RefundStatus,- SubscriptionStatus,+ IntentStatus, InvoiceStatus, MandateStatus, MerchantCategoryCode, MerchantCategoryCodeWithName,+ RefundStatus,};use strum::IntoEnumIterator;@@ -573,41 +573,70 @@ pub fn get_valid_webhook_status(key: &str) -> JsResult {.map_err(|_| "Invalid webhook event type received".to_string()).err_to_js()?;+ let statuses: Vec<String> = webhook_status_config(event_class)+ .statuses+ .into_iter()+ .map(|status| status.value)+ .collect();++ Ok(serde_wasm_bindgen::to_value(&statuses)?)+}++#[wasm_bindgen(js_name = getWebhookStatusConfig)]+pub fn get_webhook_status_config() -> JsResult {+ let config: Vec<types::WebhookEventClassConfig> =+ EventClass::iter().map(webhook_status_config).collect();++ Ok(serde_wasm_bindgen::to_value(&config)?)+}++fn webhook_status_metadata<T>(+ event_type_from_status: impl Fn(T) -> Option<EventType>,+) -> Vec<types::WebhookStatusConfig>+where+ T: IntoEnumIterator + ToString,+{+ T::iter()+ .filter_map(|status| {+ let value = status.to_string();+ event_type_from_status(status)+ .map(|event_type| types::WebhookStatusConfig { value, event_type })+ })+ .collect()+}++fn webhook_status_config(event_class: EventClass) -> types::WebhookEventClassConfig {match event_class {- EventClass::Payments => {- let statuses: Vec<IntentStatus> = IntentStatus::iter()- .filter(|intent_status| Into::<Option<EventType>>::into(*intent_status).is_some())- .collect();- Ok(serde_wasm_bindgen::to_value(&statuses)?)- }- EventClass::Refunds => {- let statuses: Vec<RefundStatus> = RefundStatus::iter()- .filter(|status| Into::<Option<EventType>>::into(*status).is_some())- .collect();- Ok(serde_wasm_bindgen::to_value(&statuses)?)- }- EventClass::Disputes => {- let statuses: Vec<DisputeStatus> = DisputeStatus::iter().collect();- Ok(serde_wasm_bindgen::to_value(&statuses)?)- }- EventClass::Mandates => {- let statuses: Vec<MandateStatus> = MandateStatus::iter()- .filter(|status| Into::<Option<EventType>>::into(*status).is_some())- .collect();- Ok(serde_wasm_bindgen::to_value(&statuses)?)- }+ EventClass::Payments => types::WebhookEventClassConfig {+ event_class,+ api_field: "payment_statuses_enabled",+ statuses: webhook_status_metadata::<IntentStatus>(Into::<Option<EventType>>::into),+ },+ EventClass::Refunds => types::WebhookEventClassConfig {+ event_class,+ api_field: "refund_statuses_enabled",+ statuses: webhook_status_metadata::<RefundStatus>(Into::<Option<EventType>>::into),+ },+ EventClass::Disputes => types::WebhookEventClassConfig {+ event_class,+ api_field: "dispute_statuses_enabled",+ statuses: webhook_status_metadata::<DisputeStatus>(Into::<Option<EventType>>::into),+ },+ EventClass::Mandates => types::WebhookEventClassConfig {+ event_class,+ api_field: "mandate_statuses_enabled",+ statuses: webhook_status_metadata::<MandateStatus>(Into::<Option<EventType>>::into),+ },#[cfg(feature = "payouts")]- EventClass::Payouts => {- let statuses: Vec<PayoutStatus> = PayoutStatus::iter()- .filter(|status| Into::<Option<EventType>>::into(*status).is_some())- .collect();- Ok(serde_wasm_bindgen::to_value(&statuses)?)- }- EventClass::Subscriptions => {- let statuses: Vec<SubscriptionStatus> = SubscriptionStatus::iter()- .filter(|status| Into::<Option<EventType>>::into(*status).is_some())- .collect();- Ok(serde_wasm_bindgen::to_value(&statuses)?)- }+ EventClass::Payouts => types::WebhookEventClassConfig {+ event_class,+ api_field: "payout_statuses_enabled",+ statuses: webhook_status_metadata::<PayoutStatus>(Into::<Option<EventType>>::into),+ },+ EventClass::Subscriptions => types::WebhookEventClassConfig {+ event_class,+ api_field: "invoice_statuses_enabled",+ statuses: webhook_status_metadata::<InvoiceStatus>(Into::<Option<EventType>>::into),+ },}}diff --git a/crates/euclid_wasm/src/types.rs b/crates/euclid_wasm/src/types.rsindex aac0fed1f8..3eec198d4a 100644--- a/crates/euclid_wasm/src/types.rs+++ b/crates/euclid_wasm/src/types.rs@@ -3,6 +3,19 @@ use euclid::frontend::dir::DirKeyKind;use euclid::frontend::dir::PayoutDirKeyKind;use serde::Serialize;+#[derive(Serialize, Clone)]+pub struct WebhookStatusConfig {+ pub value: String,+ pub event_type: common_enums::EventType,+}++#[derive(Serialize, Clone)]+pub struct WebhookEventClassConfig {+ pub event_class: common_enums::EventClass,+ pub api_field: &'static str,+ pub statuses: Vec<WebhookStatusConfig>,+}+#[derive(Serialize, Clone)]pub struct Details<'a> {pub description: Option<&'a str>,diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rsindex fb5f6fc63c..429b413fe0 100644--- a/crates/hyperswitch_domain_models/src/business_profile.rs+++ b/crates/hyperswitch_domain_models/src/business_profile.rs@@ -1,4 +1,4 @@-use std::borrow::Cow;+use std::collections::HashSet;use common_enums::enums as api_enums;use common_types::{domain::AcquirerConfig, primitive_wrappers};@@ -1127,32 +1127,56 @@ impl Profile {pub fn get_configured_payment_webhook_statuses(&self,- ) -> Option<Cow<'_, [common_enums::IntentStatus]>> {+ ) -> Option<&HashSet<common_enums::IntentStatus>> {self.webhook_details.as_ref().and_then(|details| details.payment_statuses_enabled.as_ref())- .filter(|statuses_vec| !statuses_vec.is_empty())- .map(|statuses_vec| Cow::Borrowed(statuses_vec.as_slice()))+ .filter(|statuses| !statuses.is_empty())}pub fn get_configured_refund_webhook_statuses(&self,- ) -> Option<Cow<'_, [common_enums::RefundStatus]>> {+ ) -> Option<&HashSet<common_enums::RefundStatus>> {self.webhook_details.as_ref().and_then(|details| details.refund_statuses_enabled.as_ref())- .filter(|statuses_vec| !statuses_vec.is_empty())- .map(|statuses_vec| Cow::Borrowed(statuses_vec.as_slice()))+ .filter(|statuses| !statuses.is_empty())}pub fn get_configured_payout_webhook_statuses(&self,- ) -> Option<Cow<'_, [common_enums::PayoutStatus]>> {+ ) -> Option<&HashSet<common_enums::PayoutStatus>> {self.webhook_details.as_ref().and_then(|details| details.payout_statuses_enabled.as_ref())- .filter(|statuses_vec| !statuses_vec.is_empty())- .map(|statuses_vec| Cow::Borrowed(statuses_vec.as_slice()))+ .filter(|statuses| !statuses.is_empty())+ }++ pub fn get_configured_dispute_webhook_statuses(+ &self,+ ) -> Option<&HashSet<common_enums::DisputeStatus>> {+ self.webhook_details+ .as_ref()+ .and_then(|details| details.dispute_statuses_enabled.as_ref())+ .filter(|statuses| !statuses.is_empty())+ }++ pub fn get_configured_mandate_webhook_statuses(+ &self,+ ) -> Option<&HashSet<common_enums::MandateStatus>> {+ self.webhook_details+ .as_ref()+ .and_then(|details| details.mandate_statuses_enabled.as_ref())+ .filter(|statuses| !statuses.is_empty())+ }++ pub fn get_configured_invoice_webhook_statuses(+ &self,+ ) -> Option<&HashSet<common_enums::InvoiceStatus>> {+ self.webhook_details+ .as_ref()+ .and_then(|details| details.invoice_statuses_enabled.as_ref())+ .filter(|statuses| !statuses.is_empty())}pub fn get_billing_processor_id(diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rsindex cf35019a2c..0b1bd82b12 100644--- a/crates/openapi/src/openapi_v2.rs+++ b/crates/openapi/src/openapi_v2.rs@@ -378,6 +378,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::enums::PaymentMethod,api_models::enums::PaymentMethodIssuerCode,api_models::enums::MandateStatus,+ api_models::enums::InvoiceStatus,api_models::enums::MerchantProductType,api_models::enums::PaymentExperience,api_models::enums::CustomerAcceptanceSupport,diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rsindex 5bdaf0574e..fc096428dd 100644--- a/crates/router/src/core/admin.rs+++ b/crates/router/src/core/admin.rs@@ -817,12 +817,12 @@ impl CreateProfile {merchant_account: domain::MerchantAccount,key_store: &domain::MerchantKeyStore,) -> RouterResult<domain::Profile> {- let business_profile = create_and_insert_business_profile(+ let business_profile = Box::pin(create_and_insert_business_profile(state,api_models::admin::ProfileCreate::default(),merchant_account.clone(),key_store,- )+ )).await?;Ok(business_profile)@@ -851,12 +851,12 @@ impl CreateProfile {..Default::default()};- create_and_insert_business_profile(+ Box::pin(create_and_insert_business_profile(state,profile_create_request,merchant_account.clone(),key_store,- )+ )).await.map_err(|profile_insert_error| {logger::warn!("Profile already exists {profile_insert_error:?}");@@ -1084,12 +1084,12 @@ pub async fn create_profile_from_business_labels(..Default::default()};- let profile_create_result = create_and_insert_business_profile(+ let profile_create_result = Box::pin(create_and_insert_business_profile(state,profile_create_request,merchant_account.clone(),key_store,- )+ )).await.map_err(|profile_insert_error| {// If there is any duplicate error, we need not take any actiondiff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rsindex cbcd6e3be5..26c862a20e 100644--- a/crates/router/src/core/webhooks/outgoing.rs+++ b/crates/router/src/core/webhooks/outgoing.rs@@ -49,6 +49,53 @@ use crate::{workflows::outgoing_webhook_retry,};+trait OutgoingWebhookContentStatusExt {+ const DEFAULT_STATUS_ENABLED: bool = true;++ fn is_status_enabled(&self, profile: &domain::Profile) -> bool;+}++impl OutgoingWebhookContentStatusExt for api::OutgoingWebhookContent {+ fn is_status_enabled(&self, profile: &domain::Profile) -> bool {+ match self {+ Self::PaymentDetails(response) => profile+ .get_configured_payment_webhook_statuses()+ .map(|statuses| statuses.contains(&response.status))+ .unwrap_or(Self::DEFAULT_STATUS_ENABLED),+ Self::RefundDetails(response) => {+ let status = common_enums::RefundStatus::from(response.status);+ profile+ .get_configured_refund_webhook_statuses()+ .map(|statuses| statuses.contains(&status))+ .unwrap_or(Self::DEFAULT_STATUS_ENABLED)+ }+ Self::DisputeDetails(response) => profile+ .get_configured_dispute_webhook_statuses()+ .map(|statuses| statuses.contains(&response.dispute_status))+ .unwrap_or(Self::DEFAULT_STATUS_ENABLED),+ Self::MandateDetails(response) => profile+ .get_configured_mandate_webhook_statuses()+ .map(|statuses| statuses.contains(&response.status))+ .unwrap_or(Self::DEFAULT_STATUS_ENABLED),+ #[cfg(feature = "payouts")]+ Self::PayoutDetails(response) => profile+ .get_configured_payout_webhook_statuses()+ .map(|statuses| statuses.contains(&response.status))+ .unwrap_or(Self::DEFAULT_STATUS_ENABLED),+ Self::SubscriptionDetails(response) => response+ .invoice+ .as_ref()+ .map(|invoice| {+ profile+ .get_configured_invoice_webhook_statuses()+ .map(|statuses| statuses.contains(&invoice.status))+ .unwrap_or(Self::DEFAULT_STATUS_ENABLED)+ })+ .unwrap_or(Self::DEFAULT_STATUS_ENABLED),+ }+ }+}+pub(crate) async fn get_webhook_events(state: &SessionState,platform: domain::Platform,@@ -170,45 +217,51 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(business_profile_id=?webhook_recipient.profile.get_id(),"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 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,+ } else if !primary_content.is_status_enabled(&provider_profile) {+ logger::debug!(+ business_profile_id = ?provider_profile.get_id(),+ %event_class,+ %primary_event_type,+ "Outgoing webhook is disabled for the current resource status"+ );+ } else {+ let events_to_trigger = get_webhook_events(+ &state,+ platform.clone(),+ primary_event_type,+ &primary_content,+ webhook_resource_data,+ &provider_profile,&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- );- });+ .await?;++ 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(())diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rsindex 1b0a18542b..e192d40061 100644--- a/crates/router/src/db/events.rs+++ b/crates/router/src/db/events.rs@@ -1967,6 +1967,9 @@ mod tests {payment_statuses_enabled: None,refund_statuses_enabled: None,payout_statuses_enabled: None,+ dispute_statuses_enabled: None,+ mandate_statuses_enabled: None,+ invoice_statuses_enabled: None,multiple_webhooks_list: None,}),sub_merchants_enabled: None,@@ -2037,6 +2040,9 @@ mod tests {payment_statuses_enabled: None,refund_statuses_enabled: None,payout_statuses_enabled: None,+ dispute_statuses_enabled: None,+ mandate_statuses_enabled: None,+ invoice_statuses_enabled: None,multiple_webhooks_list: None,}),metadata: None,diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rsindex 2066a37b65..2bdd3b8fc2 100644--- a/crates/router/src/types/transformers.rs+++ b/crates/router/src/types/transformers.rs@@ -2544,6 +2544,9 @@ impl ForeignFrom<api_models::admin::WebhookDetails>payment_statuses_enabled: item.payment_statuses_enabled,refund_statuses_enabled: item.refund_statuses_enabled,payout_statuses_enabled: item.payout_statuses_enabled,+ dispute_statuses_enabled: item.dispute_statuses_enabled,+ mandate_statuses_enabled: item.mandate_statuses_enabled,+ invoice_statuses_enabled: item.invoice_statuses_enabled,multiple_webhooks_list: None,}}@@ -2564,6 +2567,9 @@ impl ForeignFrom<diesel_models::business_profile::WebhookDetails>payment_statuses_enabled: item.payment_statuses_enabled,refund_statuses_enabled: item.refund_statuses_enabled,payout_statuses_enabled: item.payout_statuses_enabled,+ dispute_statuses_enabled: item.dispute_statuses_enabled,+ mandate_statuses_enabled: item.mandate_statuses_enabled,+ invoice_statuses_enabled: item.invoice_statuses_enabled,}}}diff --git a/crates/subscriptions/src/core/subscription_handler.rs b/crates/subscriptions/src/core/subscription_handler.rsindex b7fde54ecd..f1526fb5e6 100644--- a/crates/subscriptions/src/core/subscription_handler.rs+++ b/crates/subscriptions/src/core/subscription_handler.rs@@ -452,7 +452,7 @@ impl ForeignTryFrom<&hyperswitch_domain_models::invoice::Invoice> for subscripti"unable to parse currency name {currency:?}",currency = invoice.currency))?,- status: invoice.status.clone(),+ status: invoice.status,billing_processor_invoice_id: invoice.connector_invoice_id.as_ref()diff --git a/cypress-tests/cypress/e2e/configs/Payment/Commons.js b/cypress-tests/cypress/e2e/configs/Payment/Commons.jsindex 79545253ee..d816392601 100644--- a/cypress-tests/cypress/e2e/configs/Payment/Commons.js+++ b/cypress-tests/cypress/e2e/configs/Payment/Commons.js@@ -4081,6 +4081,9 @@ export const connectorDetails = {payment_statuses_enabled: ["succeeded", "failed"],refund_statuses_enabled: ["success", "failure"],payout_statuses_enabled: ["success", "failed"],+ dispute_statuses_enabled: ["dispute_opened", "dispute_won"],+ mandate_statuses_enabled: ["active"],+ invoice_statuses_enabled: ["invoice_paid"],},},Response: {@@ -4091,6 +4094,9 @@ export const connectorDetails = {payment_statuses_enabled: ["succeeded", "failed"],refund_statuses_enabled: ["success", "failure"],payout_statuses_enabled: ["success", "failed"],+ dispute_statuses_enabled: ["dispute_opened", "dispute_won"],+ mandate_statuses_enabled: ["active"],+ invoice_statuses_enabled: ["invoice_paid"],},},},@@ -4113,6 +4119,17 @@ export const connectorDetails = {],refund_statuses_enabled: ["success", "failure"],payout_statuses_enabled: ["success", "failed", "initiated"],+ dispute_statuses_enabled: [+ "dispute_opened",+ "dispute_expired",+ "dispute_accepted",+ "dispute_cancelled",+ "dispute_challenged",+ "dispute_won",+ "dispute_lost",+ ],+ mandate_statuses_enabled: ["active", "revoked"],+ invoice_statuses_enabled: ["invoice_paid"],},},Response: {@@ -4128,6 +4145,17 @@ export const connectorDetails = {],refund_statuses_enabled: ["success", "failure"],payout_statuses_enabled: ["success", "failed", "initiated"],+ dispute_statuses_enabled: [+ "dispute_opened",+ "dispute_expired",+ "dispute_accepted",+ "dispute_cancelled",+ "dispute_challenged",+ "dispute_won",+ "dispute_lost",+ ],+ mandate_statuses_enabled: ["active", "revoked"],+ invoice_statuses_enabled: ["invoice_paid"],},},},diff --git a/cypress-tests/cypress/e2e/spec/Payment/28-BusinessProfileConfigs.cy.js b/cypress-tests/cypress/e2e/spec/Payment/28-BusinessProfileConfigs.cy.jsindex a59ce9931b..03306fb4fe 100644--- a/cypress-tests/cypress/e2e/spec/Payment/28-BusinessProfileConfigs.cy.js+++ b/cypress-tests/cypress/e2e/spec/Payment/28-BusinessProfileConfigs.cy.js@@ -560,10 +560,64 @@ describe("Config Tests", () => {);});+ it("Create Business Profile with invalid dispute_statuses_enabled — expect error", () => {+ const createBody = {+ ...fixtures.businessProfile.bpCreate,+ profile_name: "neg_dispute_status_test",+ webhook_details: {+ webhook_version: "1.0.2",+ dispute_statuses_enabled: ["invalid_dispute"],+ },+ };+ cy.createBusinessProfileTest(+ createBody,+ globalState,+ "webhookNegDisputeProfile",+ 400+ );+ });++ it("Create Business Profile with unsupported mandate_statuses_enabled — expect error", () => {+ const createBody = {+ ...fixtures.businessProfile.bpCreate,+ profile_name: "neg_mandate_status_test",+ webhook_details: {+ webhook_version: "1.0.2",+ mandate_statuses_enabled: ["inactive"],+ },+ };+ cy.createBusinessProfileTest(+ createBody,+ globalState,+ "webhookNegMandateProfile",+ 422+ );+ });++ it("Create Business Profile with unsupported invoice_statuses_enabled — expect error", () => {+ const createBody = {+ ...fixtures.businessProfile.bpCreate,+ profile_name: "neg_invoice_status_test",+ webhook_details: {+ webhook_version: "1.0.2",+ invoice_statuses_enabled: ["payment_failed"],+ },+ };+ cy.createBusinessProfileTest(+ createBody,+ globalState,+ "webhookNegInvoiceProfile",+ 422+ );+ });+after("cleanup negative-case profiles", () => {cy.deleteBusinessProfileTest(globalState, "webhookNegativeProfile");cy.deleteBusinessProfileTest(globalState, "webhookNegPaymentProfile");cy.deleteBusinessProfileTest(globalState, "webhookNegPayoutProfile");+ cy.deleteBusinessProfileTest(globalState, "webhookNegDisputeProfile");+ cy.deleteBusinessProfileTest(globalState, "webhookNegMandateProfile");+ cy.deleteBusinessProfileTest(globalState, "webhookNegInvoiceProfile");});});});diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.jsindex 4ce23334b3..97e6567cf2 100644--- a/cypress-tests/cypress/support/commands.js+++ b/cypress-tests/cypress/support/commands.js@@ -124,6 +124,34 @@ function getExpectedMerchantConnectorId(return merchantConnectorId;}+// Assert set-backed API arrays without depending on serialization order.+function expectSameMembers(actual, expected, fieldName) {+ expect(actual, fieldName).to.be.an("array");+ expect(actual, fieldName).to.have.members(expected);+}++const WEBHOOK_STATUS_FIELDS = [+ "payment_statuses_enabled",+ "refund_statuses_enabled",+ "payout_statuses_enabled",+ "dispute_statuses_enabled",+ "mandate_statuses_enabled",+ "invoice_statuses_enabled",+];++// Verify every configured webhook status collection returned by the API.+function expectWebhookStatusMembers(actualWebhook, expectedWebhook) {+ WEBHOOK_STATUS_FIELDS.forEach((fieldName) => {+ if (expectedWebhook[fieldName]) {+ expectSameMembers(+ actualWebhook[fieldName],+ expectedWebhook[fieldName],+ fieldName+ );+ }+ });+}+// Helper function for creating individual rollout configfunction createIndividualRolloutConfig(methodFlow,@@ -881,7 +909,7 @@ Cypress.Commands.add(* @param {Object} createBusinessProfile - The business profile creation request body* @param {Object} globalState - The global state object* @param {string} [profilePrefix="profile"] - Prefix used to namespace the stored profile ID in globalState (e.g. "webhookConfigProfile" stores as globalState.set("webhookConfigProfileId", ...)). Defaults to "profile" for backward compatibility.- * @param {number} [expectedStatus=200] - Expected HTTP status code. Use 400 for negative test cases that assert validation errors.+ * @param {number} [expectedStatus=200] - Expected HTTP status code (400 for malformed values, 422 for semantic validation errors).*/Cypress.Commands.add("createBusinessProfileTest",@@ -925,21 +953,7 @@ Cypress.Commands.add(const reqWebhook = createBusinessProfile.webhook_details;const respWebhook = response.body.webhook_details;expect(respWebhook).to.not.be.undefined;- if (reqWebhook.payment_statuses_enabled) {- expect(respWebhook.payment_statuses_enabled).to.deep.equal(- reqWebhook.payment_statuses_enabled- );- }- if (reqWebhook.refund_statuses_enabled) {- expect(respWebhook.refund_statuses_enabled).to.deep.equal(- reqWebhook.refund_statuses_enabled- );- }- if (reqWebhook.payout_statuses_enabled) {- expect(respWebhook.payout_statuses_enabled).to.deep.equal(- reqWebhook.payout_statuses_enabled- );- }+ expectWebhookStatusMembers(respWebhook, reqWebhook);if (reqWebhook.payment_failed_enabled !== undefined) {expect(respWebhook.payment_failed_enabled).to.equal(reqWebhook.payment_failed_enabled@@ -1218,21 +1232,10 @@ Cypress.Commands.add(expect(response.status).to.equal(200);const webhookDetails = response.body.webhook_details;expect(webhookDetails).to.not.be.undefined;- if (webhookConfigBody.webhook_details.payment_statuses_enabled) {- expect(webhookDetails.payment_statuses_enabled).to.deep.equal(- webhookConfigBody.webhook_details.payment_statuses_enabled- );- }- if (webhookConfigBody.webhook_details.refund_statuses_enabled) {- expect(webhookDetails.refund_statuses_enabled).to.deep.equal(- webhookConfigBody.webhook_details.refund_statuses_enabled- );- }- if (webhookConfigBody.webhook_details.payout_statuses_enabled) {- expect(webhookDetails.payout_statuses_enabled).to.deep.equal(- webhookConfigBody.webhook_details.payout_statuses_enabled- );- }+ expectWebhookStatusMembers(+ webhookDetails,+ webhookConfigBody.webhook_details+ );if (webhookConfigBody.webhook_details.payment_failed_enabled !== undefined) {