Skip to content

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

feat(revenue_recovery): add the recovery webhook event types and payload (#15207)

CHALLA NISHANTH BABU7013b0aea70e
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index fda40fe036..eacb5cdd31 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -22676,6 +22676,25 @@
"$ref": "#/components/schemas/PayoutCreateResponse"
}
}
+ },
+ {
+ "type": "object",
+ "title": "RecoveryRetryWebhookDetails",
+ "required": [
+ "type",
+ "object"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "recovery_retry_details"
+ ]
+ },
+ "object": {
+ "$ref": "#/components/schemas/RecoveryRetryWebhookDetails"
+ }
+ }
}
],
"discriminator": {
@@ -32164,8 +32183,8 @@
"enum": [
"recovered",
"retries_exhausted",
- "grace_period_exceeded",
- "hard_decline",
+ "grace_period_expired",
+ "hard_declined",
"monitoring",
"cancelled",
"below_retry_threshold"
@@ -32361,6 +32380,37 @@
}
}
},
+ "RecoveryRetryWebhookDetails": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/RecoveryNextRetry"
+ },
+ {
+ "type": "object",
+ "required": [
+ "id",
+ "merchant_reference_id"
+ ],
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "Unique identifier of the invoice in Hyperswitch.",
+ "example": "pay_mbabizu24mvu3mela5njyhpit4",
+ "maxLength": 30,
+ "minLength": 30
+ },
+ "merchant_reference_id": {
+ "type": "string",
+ "description": "Unique identifier of the invoice in the merchant's billing system.",
+ "example": "invoice_mbabizu24mvu3mela5njyh",
+ "maxLength": 30,
+ "minLength": 30
+ }
+ }
+ }
+ ],
+ "description": "The next retry of an invoice whose retries the merchant triggers, sent by webhook after each\ntransaction the merchant reports."
+ },
"RecoveryTransactionStatus": {
"type": "string",
"description": "Status of the transaction reported.",
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 0553c83ae1..30fc8d75a0 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -2422,6 +2422,35 @@ pub struct RecoveryPaymentsResponse {
pub next_retry: Option<common_payments_types::RecoveryNextRetry>,
}
+/// The next retry of an invoice whose retries the merchant triggers, sent by webhook after each
+/// transaction the merchant reports.
+#[cfg(feature = "v2")]
+#[derive(Debug, serde::Serialize, Clone, ToSchema)]
+pub struct RecoveryRetryWebhookDetails {
+ /// Unique identifier of the invoice in Hyperswitch.
+ #[schema(
+ min_length = 30,
+ max_length = 30,
+ example = "pay_mbabizu24mvu3mela5njyhpit4",
+ value_type = String,
+ )]
+ pub id: id_type::GlobalPaymentId,
+
+ /// Unique identifier of the invoice in the merchant's billing system.
+ #[schema(
+ value_type = String,
+ min_length = 30,
+ max_length = 30,
+ example = "invoice_mbabizu24mvu3mela5njyh"
+ )]
+ pub merchant_reference_id: id_type::PaymentReferenceId,
+
+ /// When to trigger the next retry, or why none is scheduled.
+ #[schema(value_type = RecoveryNextRetry)]
+ #[serde(flatten)]
+ pub next_retry: common_payments_types::RecoveryNextRetry,
+}
+
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)]
pub struct PaymentAttemptFeatureMetadata {
diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs
index ab4a42feb7..e4c3ed954f 100644
--- a/crates/api_models/src/webhooks.rs
+++ b/crates/api_models/src/webhooks.rs
@@ -516,6 +516,8 @@ pub enum OutgoingWebhookContent {
#[cfg(feature = "payouts")]
#[schema(value_type = PayoutCreateResponse, title = "PayoutCreateResponse")]
PayoutDetails(Box<payouts::PayoutCreateResponse>),
+ #[schema(value_type = RecoveryRetryWebhookDetails, title = "RecoveryRetryWebhookDetails")]
+ RecoveryRetryDetails(Box<payments::RecoveryRetryWebhookDetails>),
}
#[derive(Debug, Clone, Serialize)]
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 77fb8995a3..4c10233dd8 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2003,7 +2003,11 @@ pub enum EventRecipient {
strum::EnumString,
)]
#[cfg_attr(
- feature = "diesel",
+ all(feature = "diesel", feature = "v2"),
+ router_derive::diesel_enum(storage_type = "text")
+)]
+#[cfg_attr(
+ all(feature = "diesel", not(feature = "v2")),
router_derive::diesel_enum(storage_type = "db_enum")
)]
#[serde(rename_all = "snake_case")]
@@ -2015,6 +2019,8 @@ pub enum EventObjectType {
MandateDetails,
PayoutDetails,
SubscriptionDetails,
+ #[cfg(feature = "v2")]
+ RecoveryRetryDetails,
}
#[derive(
@@ -2032,7 +2038,11 @@ pub enum EventObjectType {
ToSchema,
)]
#[cfg_attr(
- feature = "diesel",
+ all(feature = "diesel", feature = "v2"),
+ router_derive::diesel_enum(storage_type = "text")
+)]
+#[cfg_attr(
+ all(feature = "diesel", not(feature = "v2")),
router_derive::diesel_enum(storage_type = "db_enum")
)]
#[serde(rename_all = "snake_case")]
@@ -2045,6 +2055,9 @@ pub enum EventClass {
#[cfg(feature = "payouts")]
Payouts,
Subscriptions,
+ /// The next retry of a revenue recovery invoice whose retries the merchant triggers.
+ #[cfg(feature = "v2")]
+ RevenueRecovery,
}
impl EventClass {
@@ -2091,6 +2104,11 @@ impl EventClass {
EventType::PayoutNotPermitted,
]),
Self::Subscriptions => HashSet::from([EventType::InvoicePaid]),
+ #[cfg(feature = "v2")]
+ Self::RevenueRecovery => HashSet::from([
+ EventType::RecoveryRetryScheduled,
+ EventType::RecoveryLimitsExhausted,
+ ]),
}
}
}
@@ -2109,7 +2127,11 @@ impl EventClass {
ToSchema,
)]
#[cfg_attr(
- feature = "diesel",
+ all(feature = "diesel", feature = "v2"),
+ router_derive::diesel_enum(storage_type = "text")
+)]
+#[cfg_attr(
+ all(feature = "diesel", not(feature = "v2")),
router_derive::diesel_enum(storage_type = "db_enum")
)]
#[serde(rename_all = "snake_case")]
@@ -2159,6 +2181,14 @@ pub enum EventType {
InvoicePaid,
SurchargePaymentSucceeded,
SurchargeRefundSucceeded,
+ /// The next retry of a revenue recovery invoice whose retries the merchant triggers is
+ /// scheduled.
+ #[cfg(feature = "v2")]
+ RecoveryRetryScheduled,
+ /// No further retry of a revenue recovery invoice whose retries the merchant triggers is
+ /// scheduled, because a limit of the profile is reached.
+ #[cfg(feature = "v2")]
+ RecoveryLimitsExhausted,
}
/// Maps primary payment/refund events to their corresponding surcharge events
diff --git a/crates/common_types/src/payments.rs b/crates/common_types/src/payments.rs
index 7a2847e49c..87b99cfe44 100644
--- a/crates/common_types/src/payments.rs
+++ b/crates/common_types/src/payments.rs
@@ -1135,9 +1135,11 @@ pub enum RecoveryNoRetryReason {
/// The invoice has used every retry it is allowed.
RetriesExhausted,
/// The grace period of the invoice is over, or would be over by the time of the next retry.
- GracePeriodExceeded,
+ #[serde(alias = "grace_period_exceeded")]
+ GracePeriodExpired,
/// The card was hard declined, and the retries the profile allows after that are used up.
- HardDecline,
+ #[serde(alias = "hard_decline")]
+ HardDeclined,
/// The retry algorithm of the profile is `monitoring`, so transactions are only recorded.
Monitoring,
/// The invoice is cancelled.
diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml
index d141b18331..797b2eb2fc 100644
--- a/crates/diesel_models/Cargo.toml
+++ b/crates/diesel_models/Cargo.toml
@@ -11,7 +11,7 @@ license.workspace = true
default = ["kv_store"]
kv_store = []
v1 = ["common_utils/v1", "common_types/v1"]
-v2 = ["common_utils/v2", "common_types/v2"]
+v2 = ["common_utils/v2", "common_types/v2", "common_enums/v2"]
tokenization_v2 = []
deja = ["dep:deja", "deja/diesel-pg"]
diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs
index 4c116dece8..55203014bb 100644
--- a/crates/diesel_models/src/enums.rs
+++ b/crates/diesel_models/src/enums.rs
@@ -1,5 +1,12 @@
#[doc(hidden)]
pub mod diesel_exports {
+ // Event types, classes and object types are stored as text in v2, where the v1 schema, which
+ // every build compiles and the events model reads, takes those columns as text too.
+ #[cfg(feature = "v2")]
+ pub use diesel::sql_types::{
+ Varchar as EventClass, Varchar as EventObjectType, Varchar as EventType,
+ };
+
pub use super::{
DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus,
DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind,
@@ -8,7 +15,6 @@ pub mod diesel_exports {
DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency,
DbDashboardMetadata as DashboardMetadata, DbDeleteStatus as DeleteStatus,
DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus,
- DbEventClass as EventClass, DbEventObjectType as EventObjectType, DbEventType as EventType,
DbFraudCheckStatus as FraudCheckStatus, DbFraudCheckType as FraudCheckType,
DbFutureUsage as FutureUsage, DbGenericLinkType as GenericLinkType,
DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus,
@@ -28,6 +34,10 @@ pub mod diesel_exports {
DbTransactionType as TransactionType, DbUserRoleVersion as UserRoleVersion,
DbUserStatus as UserStatus, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt,
};
+ #[cfg(not(feature = "v2"))]
+ pub use super::{
+ DbEventClass as EventClass, DbEventObjectType as EventObjectType, DbEventType as EventType,
+ };
}
pub use common_enums::*;
diff --git a/crates/diesel_models/src/events.rs b/crates/diesel_models/src/events.rs
index c7b7ab33c3..79d8bc3d48 100644
--- a/crates/diesel_models/src/events.rs
+++ b/crates/diesel_models/src/events.rs
@@ -118,6 +118,10 @@ pub enum EventMetadata {
payment_id: common_utils::id_type::PaymentId,
attempt_id: String,
},
+ #[cfg(feature = "v2")]
+ RevenueRecovery {
+ payment_id: common_utils::id_type::GlobalPaymentId,
+ },
}
common_utils::impl_to_sql_from_sql_json!(EventMetadata);
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 6362f95058..c1555366ea 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -627,12 +627,15 @@ diesel::table! {
events (event_id) {
#[max_length = 64]
event_id -> Varchar,
- event_type -> EventType,
- event_class -> EventClass,
+ #[max_length = 64]
+ event_type -> Varchar,
+ #[max_length = 64]
+ event_class -> Varchar,
is_webhook_notified -> Bool,
#[max_length = 64]
primary_object_id -> Varchar,
- primary_object_type -> EventObjectType,
+ #[max_length = 64]
+ primary_object_type -> Varchar,
created_at -> Timestamp,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
diff --git a/crates/euclid_wasm/src/lib.rs b/crates/euclid_wasm/src/lib.rs
index b6c01c8505..925b68449b 100644
--- a/crates/euclid_wasm/src/lib.rs
+++ b/crates/euclid_wasm/src/lib.rs
@@ -638,5 +638,11 @@ fn webhook_status_config(event_class: EventClass) -> types::WebhookEventClassCon
api_field: "invoice_statuses_enabled",
statuses: webhook_status_metadata::<InvoiceStatus>(Into::<Option<EventType>>::into),
},
+ #[cfg(feature = "v2")]
+ EventClass::RevenueRecovery => types::WebhookEventClassConfig {
+ event_class,
+ api_field: "",
+ statuses: Vec::new(),
+ },
}
}
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 940169a99f..e32488246c 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -1031,6 +1031,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::process_tracker::revenue_recovery::RevenueRecoveryResponse,
api_models::payments::RecoveryPaymentsCreate,
api_models::payments::RecoveryPaymentsResponse,
+ api_models::payments::RecoveryRetryWebhookDetails,
api_models::payments::CustomRecoveryPaymentMethodData,
api_models::payments::AdditionalCardInfo,
common_types::payments::RecoveryTransactionStatus,
diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rs
index 63f1e4a0e4..961a37997c 100644
--- a/crates/router/src/core/revenue_recovery.rs
+++ b/crates/router/src/core/revenue_recovery.rs
@@ -2138,8 +2138,8 @@ fn map_external_trigger_recovery_status(
RecoveryStatus::Monitoring
}
RecoveryNoRetryReason::RetriesExhausted
- | RecoveryNoRetryReason::GracePeriodExceeded
- | RecoveryNoRetryReason::HardDecline
+ | RecoveryNoRetryReason::GracePeriodExpired
+ | RecoveryNoRetryReason::HardDeclined
| RecoveryNoRetryReason::Cancelled => RecoveryStatus::Terminated,
},
}
diff --git a/crates/router/src/core/revenue_recovery/external_triggers.rs b/crates/router/src/core/revenue_recovery/external_triggers.rs
index d508ed54ff..1df0bbed1f 100644
--- a/crates/router/src/core/revenue_recovery/external_triggers.rs
+++ b/crates/router/src/core/revenue_recovery/external_triggers.rs
@@ -365,7 +365,7 @@ async fn decide_next_retry(
let Some(grace_window_end) = grace_window_end else {
return NextRetryDecision::not_scheduled(
retry_count,
- RecoveryNoRetryReason::GracePeriodExceeded,
+ RecoveryNoRetryReason::GracePeriodExpired,
);
};
@@ -602,9 +602,9 @@ fn get_no_retry_reason(
} else if limit_checks.is_retry_budget_spent {
Some(RecoveryNoRetryReason::RetriesExhausted)
} else if limit_checks.is_grace_window_over {
- Some(RecoveryNoRetryReason::GracePeriodExceeded)
+ Some(RecoveryNoRetryReason::GracePeriodExpired)
} else if limit_checks.is_hard_decline_limit_reached {
- Some(RecoveryNoRetryReason::HardDecline)
+ Some(RecoveryNoRetryReason::HardDeclined)
} else if limit_checks.is_below_retry_threshold {
Some(RecoveryNoRetryReason::BelowRetryThreshold)
} else {
@@ -633,7 +633,7 @@ fn get_next_retry(
};
if schedule_time >= grace_window_end {
- RecoveryNextRetry::not_scheduled(retry_count, RecoveryNoRetryReason::GracePeriodExceeded)
+ RecoveryNextRetry::not_scheduled(retry_count, RecoveryNoRetryReason::GracePeriodExpired)
} else {
RecoveryNextRetry::scheduled(retry_count, schedule_time)
}
diff --git a/crates/router/src/core/webhooks/outgoing_v2.rs b/crates/router/src/core/webhooks/outgoing_v2.rs
index ecbd839f29..da2bfc8044 100644
--- a/crates/router/src/core/webhooks/outgoing_v2.rs
+++ b/crates/router/src/core/webhooks/outgoing_v2.rs
@@ -738,6 +738,11 @@ impl ForeignFrom<&api::OutgoingWebhookContent> for storage::EventMetadata {
webhooks::OutgoingWebhookContent::PayoutDetails(payout_response) => Self::Payout {
payout_id: payout_response.payout_id.clone(),
},
+ webhooks::OutgoingWebhookContent::RecoveryRetryDetails(retry_details) => {
+ Self::RevenueRecovery {
+ payment_id: retry_details.id.clone(),
+ }
+ }
}
}
}
@@ -789,6 +794,10 @@ impl ForeignFrom<storage::EventMetadata> for outgoing_webhook_logs::OutgoingWebh
payment_id,
content: serde_json::Value::Null,
},
+ diesel_models::EventMetadata::RevenueRecovery { payment_id } => Self::RevenueRecovery {
+ payment_id,
+ content: serde_json::Value::Null,
+ },
}
}
}
diff --git a/crates/router/src/events/outgoing_webhook_logs.rs b/crates/router/src/events/outgoing_webhook_logs.rs
index 4c1024c022..1f243d5aec 100644
--- a/crates/router/src/events/outgoing_webhook_logs.rs
+++ b/crates/router/src/events/outgoing_webhook_logs.rs
@@ -84,6 +84,11 @@ pub enum OutgoingWebhookEventContent {
payment_id: common_utils::id_type::PaymentId,
attempt_id: String,
},
+ #[cfg(feature = "v2")]
+ RevenueRecovery {
+ payment_id: common_utils::id_type::GlobalPaymentId,
+ content: Value,
+ },
}
pub trait OutgoingWebhookEventMetric {
fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent>;
@@ -167,6 +172,13 @@ impl OutgoingWebhookEventMetric for OutgoingWebhookContent {
content: hyperswitch_masking::masked_serialize(&payout_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
+ Self::RecoveryRetryDetails(retry_payload) => {
+ Some(OutgoingWebhookEventContent::RevenueRecovery {
+ payment_id: retry_payload.id.clone(),
+ content: hyperswitch_masking::masked_serialize(&retry_payload)
+ .unwrap_or(serde_json::json!({"error":"failed to serialize"})),
+ })
+ }
}
}
}
diff --git a/v2_compatible_migrations/2026-11-11-000001_store_event_types_as_text/down.sql b/v2_compatible_migrations/2026-11-11-000001_store_event_types_as_text/down.sql
new file mode 100644
index 0000000000..3e389a8eb5
--- /dev/null
+++ b/v2_compatible_migrations/2026-11-11-000001_store_event_types_as_text/down.sql
@@ -0,0 +1,6 @@
+-- Fails while any event holds a type, class or object type that the database enums do not list,
+-- such as the revenue recovery ones.
+ALTER TABLE events
+ ALTER COLUMN event_type TYPE "EventType" USING event_type::"EventType",
+ ALTER COLUMN event_class TYPE "EventClass" USING event_class::"EventClass",
+ ALTER COLUMN primary_object_type TYPE "EventObjectType" USING primary_object_type::"EventObjectType";
diff --git a/v2_compatible_migrations/2026-11-11-000001_store_event_types_as_text/up.sql b/v2_compatible_migrations/2026-11-11-000001_store_event_types_as_text/up.sql
new file mode 100644
index 0000000000..e72692cc37
--- /dev/null
+++ b/v2_compatible_migrations/2026-11-11-000001_store_event_types_as_text/up.sql
@@ -0,0 +1,6 @@
+-- Event types, classes and object types are stored as text and typed in the application, so a new
+-- one needs no migration.
+ALTER TABLE events
+ ALTER COLUMN event_type TYPE VARCHAR(64) USING event_type::TEXT,
+ ALTER COLUMN event_class TYPE VARCHAR(64) USING event_class::TEXT,
+ ALTER COLUMN primary_object_type TYPE VARCHAR(64) USING primary_object_type::TEXT;