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(connector): Add support for passive churn recovery webhooks (#7109)

chikke srujan0688972814cf
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 06796b4486..16fcefac0e 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -13397,6 +13397,19 @@
}
}
},
+ "PaymentAttemptFeatureMetadata": {
+ "type": "object",
+ "properties": {
+ "revenue_recovery": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentAttemptRevenueRecoveryData"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
"PaymentAttemptResponse": {
"type": "object",
"required": [
@@ -13405,7 +13418,8 @@
"amount",
"authentication_type",
"created_at",
- "modified_at"
+ "modified_at",
+ "connector_payment_id"
],
"properties": {
"id": {
@@ -13501,9 +13515,7 @@
},
"connector_payment_id": {
"type": "string",
- "description": "A unique identifier for a payment provided by the connector",
- "example": "993672945374576J",
- "nullable": true
+ "description": "A unique identifier for a payment provided by the connector"
},
"payment_method_id": {
"type": "string",
@@ -13520,6 +13532,27 @@
"type": "string",
"description": "Value passed in X-CLIENT-VERSION header during payments confirm request by the client",
"nullable": true
+ },
+ "feature_metadata": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentAttemptFeatureMetadata"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
+ "PaymentAttemptRevenueRecoveryData": {
+ "type": "object",
+ "properties": {
+ "attempt_triggered_by": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/TriggeredBy"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -21526,6 +21559,13 @@
"payout"
]
},
+ "TriggeredBy": {
+ "type": "string",
+ "enum": [
+ "internal",
+ "external"
+ ]
+ },
"UIWidgetFormLayout": {
"type": "string",
"enum": [
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json
index 632d800f47..8e62ba302a 100644
--- a/api-reference/openapi_spec.json
+++ b/api-reference/openapi_spec.json
@@ -26144,6 +26144,13 @@
"payout"
]
},
+ "TriggeredBy": {
+ "type": "string",
+ "enum": [
+ "internal",
+ "external"
+ ]
+ },
"UIWidgetFormLayout": {
"type": "string",
"enum": [
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml
index c159af9724..2b84c50bba 100644
--- a/crates/api_models/Cargo.toml
+++ b/crates/api_models/Cargo.toml
@@ -22,6 +22,7 @@ customer_v2 = ["common_utils/customer_v2"]
payment_methods_v2 = ["common_utils/payment_methods_v2"]
dynamic_routing = []
control_center_theme = ["dep:actix-web", "dep:actix-multipart"]
+revenue_recovery = []
[dependencies]
actix-multipart = { version = "0.6.1", optional = true }
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index faee2e3887..22e845c5e0 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -1511,8 +1511,8 @@ pub struct PaymentAttemptResponse {
pub payment_method_subtype: Option<api_enums::PaymentMethodType>,
/// A unique identifier for a payment provided by the connector
- #[schema(value_type = Option<String>, example = "993672945374576J")]
- pub connector_payment_id: Option<String>,
+ #[schema(value_type = String)]
+ pub connector_payment_id: Option<common_utils::types::ConnectorTransactionId>,
/// Identifier for Payment Method used for the payment attempt
#[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")]
@@ -1522,6 +1522,24 @@ pub struct PaymentAttemptResponse {
pub client_source: Option<String>,
/// Value passed in X-CLIENT-VERSION header during payments confirm request by the client
pub client_version: Option<String>,
+
+ /// Additional data that might be required by hyperswitch, to enable some specific features.
+ pub feature_metadata: Option<PaymentAttemptFeatureMetadata>,
+}
+
+#[cfg(feature = "v2")]
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)]
+pub struct PaymentAttemptFeatureMetadata {
+ /// Revenue recovery metadata that might be required by hyperswitch.
+ pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>,
+}
+
+#[cfg(feature = "v2")]
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)]
+pub struct PaymentAttemptRevenueRecoveryData {
+ /// Flag to find out whether an attempt was created by external or internal system.
+ #[schema(value_type = Option<TriggeredBy>, example = "internal")]
+ pub attempt_triggered_by: common_enums::TriggeredBy,
}
#[derive(
@@ -5563,6 +5581,26 @@ pub struct PaymentsRetrieveResponse {
pub attempts: Option<Vec<PaymentAttemptResponse>>,
}
+#[cfg(feature = "v2")]
+impl PaymentsRetrieveResponse {
+ pub fn find_attempt_in_attempts_list_using_connector_transaction_id(
+ self,
+ connector_transaction_id: &common_utils::types::ConnectorTransactionId,
+ ) -> Option<PaymentAttemptResponse> {
+ self.attempts
+ .as_ref()
+ .and_then(|attempts| {
+ attempts.iter().find(|attempt| {
+ attempt
+ .connector_payment_id
+ .as_ref()
+ .is_some_and(|txn_id| txn_id == connector_transaction_id)
+ })
+ })
+ .cloned()
+ }
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
#[cfg(feature = "v2")]
pub struct PaymentStartRedirectionRequest {
diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs
index ddefea542c..c3e96c47c6 100644
--- a/crates/api_models/src/webhooks.rs
+++ b/crates/api_models/src/webhooks.rs
@@ -57,6 +57,14 @@ pub enum IncomingWebhookEvent {
PayoutExpired,
#[cfg(feature = "payouts")]
PayoutReversed,
+ #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
+ RecoveryPaymentFailure,
+ #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
+ RecoveryPaymentSuccess,
+ #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
+ RecoveryPaymentPending,
+ #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
+ RecoveryInvoiceCancel,
}
pub enum WebhookFlow {
@@ -71,6 +79,8 @@ pub enum WebhookFlow {
Mandate,
ExternalAuthentication,
FraudCheck,
+ #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
+ Recovery,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
@@ -197,6 +207,11 @@ impl From<IncomingWebhookEvent> for WebhookFlow {
| IncomingWebhookEvent::PayoutCreated
| IncomingWebhookEvent::PayoutExpired
| IncomingWebhookEvent::PayoutReversed => Self::Payout,
+ #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
+ IncomingWebhookEvent::RecoveryInvoiceCancel
+ | IncomingWebhookEvent::RecoveryPaymentFailure
+ | IncomingWebhookEvent::RecoveryPaymentPending
+ | IncomingWebhookEvent::RecoveryPaymentSuccess => Self::Recovery,
}
}
}
@@ -236,6 +251,14 @@ pub enum ObjectReferenceId {
ExternalAuthenticationID(AuthenticationIdType),
#[cfg(feature = "payouts")]
PayoutId(PayoutIdType),
+ #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
+ InvoiceId(InvoiceIdType),
+}
+
+#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
+#[derive(Clone)]
+pub enum InvoiceIdType {
+ ConnectorInvoiceId(String),
}
pub struct IncomingWebhookDetails {
@@ -303,3 +326,15 @@ pub struct ConnectorWebhookSecrets {
pub secret: Vec<u8>,
pub additional_secret: Option<masking::Secret<String>>,
}
+
+#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
+impl IncomingWebhookEvent {
+ pub fn is_recovery_transaction_event(&self) -> bool {
+ matches!(
+ self,
+ Self::RecoveryPaymentFailure
+ | Self::RecoveryPaymentSuccess
+ | Self::RecoveryPaymentPending
+ )
+ }
+}
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index c286ae04d5..660474e91e 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -7591,3 +7591,28 @@ pub enum PaymentConnectorTransmission {
/// Payment Connector call succeeded
ConnectorCallSucceeded,
}
+
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Default,
+ Eq,
+ Hash,
+ PartialEq,
+ serde::Deserialize,
+ serde::Serialize,
+ strum::Display,
+ strum::EnumString,
+ ToSchema,
+)]
+#[router_derive::diesel_enum(storage_type = "db_enum")]
+#[strum(serialize_all = "snake_case")]
+#[serde(rename_all = "snake_case")]
+pub enum TriggeredBy {
+ /// Denotes payment attempt is been created by internal system.
+ #[default]
+ Internal,
+ /// Denotes payment attempt is been created by external system.
+ External,
+}
diff --git a/crates/common_utils/src/ext_traits.rs b/crates/common_utils/src/ext_traits.rs
index 945056aafe..6bdeae9b6d 100644
--- a/crates/common_utils/src/ext_traits.rs
+++ b/crates/common_utils/src/ext_traits.rs
@@ -4,6 +4,8 @@
use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface, Secret, Strategy};
use quick_xml::de;
+#[cfg(all(feature = "logs", feature = "async_ext"))]
+use router_env::logger;
use serde::{Deserialize, Serialize};
use crate::{
@@ -295,28 +297,34 @@ impl<T> StringExt<T> for String {
/// Extending functionalities of Wrapper types for idiomatic
#[cfg(feature = "async_ext")]
#[cfg_attr(feature = "async_ext", async_trait::async_trait)]
-pub trait AsyncExt<A, B> {
+pub trait AsyncExt<A> {
/// Output type of the map function
type WrappedSelf<T>;
/// Extending map by allowing functions which are async
- async fn async_map<F, Fut>(self, func: F) -> Self::WrappedSelf<B>
+ async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = B> + Send;
/// Extending the `and_then` by allowing functions which are async
- async fn async_and_then<F, Fut>(self, func: F) -> Self::WrappedSelf<B>
+ async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send;
+
+ /// Extending `unwrap_or_else` to allow async fallback
+ async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A
+ where
+ F: FnOnce() -> Fut + Send,
+ Fut: futures::Future<Output = A> + Send;
}
#[cfg(feature = "async_ext")]
#[cfg_attr(feature = "async_ext", async_trait::async_trait)]
-impl<A: Send, B, E: Send> AsyncExt<A, B> for Result<A, E> {
+impl<A: Send, E: Send + std::fmt::Debug> AsyncExt<A> for Result<A, E> {
type WrappedSelf<T> = Result<T, E>;
- async fn async_and_then<F, Fut>(self, func: F) -> Self::WrappedSelf<B>
+ async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send,
@@ -327,7 +335,7 @@ impl<A: Send, B, E: Send> AsyncExt<A, B> for Result<A, E> {
}
}
- async fn async_map<F, Fut>(self, func: F) -> Self::WrappedSelf<B>
+ async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = B> + Send,
@@ -337,13 +345,28 @@ impl<A: Send, B, E: Send> AsyncExt<A, B> for Result<A, E> {
Err(err) => Err(err),
}
}
+
+ async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A
+ where
+ F: FnOnce() -> Fut + Send,
+ Fut: futures::Future<Output = A> + Send,
+ {
+ match self {
+ Ok(a) => a,
+ Err(_err) => {
+ #[cfg(feature = "logs")]
+ logger::error!("Error: {:?}", _err);
+ func().await
+ }
+ }
+ }
}
#[cfg(feature = "async_ext")]
#[cfg_attr(feature = "async_ext", async_trait::async_trait)]
-impl<A: Send, B> AsyncExt<A, B> for Option<A> {
+impl<A: Send> AsyncExt<A> for Option<A> {
type WrappedSelf<T> = Option<T>;
- async fn async_and_then<F, Fut>(self, func: F) -> Self::WrappedSelf<B>
+ async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send,
@@ -354,7 +377,7 @@ impl<A: Send, B> AsyncExt<A, B> for Option<A> {
}
}
- async fn async_map<F, Fut>(self, func: F) -> Self::WrappedSelf<B>
+ async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = B> + Send,
@@ -364,6 +387,17 @@ impl<A: Send, B> AsyncExt<A, B> for Option<A> {
None => None,
}
}
+
+ async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A
+ where
+ F: FnOnce() -> Fut + Send,
+ Fut: futures::Future<Output = A> + Send,
+ {
+ match self {
+ Some(a) => a,
+ None => func().await,
+ }
+ }
}
/// Extension trait for validating application configuration. This trait provides utilities to
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index 8cf6b604b9..9409be9416 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -101,6 +101,7 @@ pub struct PaymentAttempt {
pub capture_before: Option<PrimitiveDateTime>,
pub card_discovery: Option<storage_enums::CardDiscovery>,
pub charges: Option<common_types::payments::ConnectorChargeResponseData>,
+ pub feature_metadata: Option<PaymentAttemptFeatureMetadata>,
}
#[cfg(feature = "v1")]
@@ -316,6 +317,7 @@ pub struct PaymentAttemptNew {
pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>,
pub capture_before: Option<PrimitiveDateTime>,
pub charges: Option<common_types::payments::ConnectorChargeResponseData>,
+ pub feature_metadata: Option<PaymentAttemptFeatureMetadata>,
}
#[cfg(feature = "v1")]
@@ -835,6 +837,7 @@ pub struct PaymentAttemptUpdateInternal {
// customer_acceptance: Option<pii::SecretSerdeValue>,
// card_network: Option<String>,
pub connector_token_details: Option<ConnectorTokenDetails>,
+ pub feature_metadata: Option<PaymentAttemptFeatureMetadata>,
}
#[cfg(feature = "v1")]
@@ -3525,6 +3528,27 @@ pub enum RedirectForm {
common_utils::impl_to_sql_from_sql_json!(RedirectForm);
+#[cfg(feature = "v2")]
+#[derive(
+ Clone, Debug, serde::Deserialize, serde::Serialize, Eq, PartialEq, diesel::AsExpression,
+)]
+#[diesel(sql_type = diesel::pg::sql_types::Jsonb)]
+pub struct PaymentAttemptFeatureMetadata {
+ pub revenue_recovery: Option<PaymentAttemptRecoveryData>,
+}
+
+#[cfg(feature = "v2")]
+#[derive(
+ Clone, Debug, serde::Deserialize, serde::Serialize, Eq, PartialEq, diesel::AsExpression,
+)]
+#[diesel(sql_type = diesel::pg::sql_types::Jsonb)]
+pub struct PaymentAttemptRecoveryData {
+ pub attempt_triggered_by: common_enums::TriggeredBy,
+}
+
+#[cfg(feature = "v2")]
+common_utils::impl_to_sql_from_sql_json!(PaymentAttemptFeatureMetadata);
+
mod tests {
#[test]
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index c4db38c0ee..69ba37e8df 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -883,6 +883,7 @@ diesel::table! {
capture_before -> Nullable<Timestamp>,
card_discovery -> Nullable<CardDiscovery>,
charges -> Nullable<Jsonb>,
+ feature_metadata -> Nullable<Jsonb>,
}
}
diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml
index ced2151e52..3de5358a2b 100644
--- a/crates/hyperswitch_domain_models/Cargo.toml
+++ b/crates/hyperswitch_domain_models/Cargo.toml
@@ -17,6 +17,7 @@ v2 = ["api_models/v2", "diesel_models/v2", "common_utils/v2"]
v1 = ["api_models/v1", "diesel_models/v1", "common_utils/v1"]
customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2"]
payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2"]
+revenue_recovery= []
[dependencies]
# First party deps
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index 3a1bd933b5..ef2cbe064d 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -20,6 +20,8 @@ pub mod payments;
pub mod payouts;
pub mod refunds;
pub mod relay;
+#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
+pub mod revenue_recovery;
pub mod router_data;
pub mod router_data_v2;
pub mod router_flow_types;
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index dfce21f28b..f512711987 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -20,6 +20,11 @@ use diesel_models::{
PaymentAttemptNew as DieselPaymentAttemptNew,
PaymentAttemptUpdate as DieselPaymentAttemptUpdate,
};
+#[cfg(feature = "v2")]
+use diesel_models::{
+ PaymentAttemptFeatureMetadata as DieselPaymentAttemptFeatureMetadata,
+ PaymentAttemptRecoveryData as DieselPassiveChurnRecoveryData,
+};
use error_stack::ResultExt;
#[cfg(feature = "v2")]
use masking::PeekInterface;
@@ -435,6 +440,8 @@ pub struct PaymentAttempt {
pub card_discovery: Option<common_enums::CardDiscovery>,
/// Split payment data
pub charges: Option<common_types::payments::ConnectorChargeResponseData>,
+ /// Additional data that might be required by hyperswitch, to enable some specific features.
+ pub feature_metadata: Option<PaymentAttemptFeatureMetadata>,
}
impl PaymentAttempt {
@@ -558,6 +565,7 @@ impl PaymentAttempt {
consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH,
)),
}),
+ feature_metadata: None,
id,
card_discovery: None,
})
@@ -1854,6 +1862,7 @@ impl behaviour::Conversion for PaymentAttempt {
connector_token_details,
card_discovery,
charges,
+ feature_metadata,
} = self;
let AttemptAmountDetails {
@@ -1870,6 +1879,7 @@ impl behaviour::Conversion for PaymentAttempt {
.map(ConnectorTransactionId::form_id_and_data)
.map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
.unwrap_or((None, None));
+ let feature_metadata = feature_metadata.as_ref().map(From::from);
Ok(DieselPaymentAttempt {
payment_id,
@@ -1935,6 +1945,7 @@ impl behaviour::Conversion for PaymentAttempt {
extended_authorization_applied: None,
capture_before: None,
charges,
+ feature_metadata,
})
}
@@ -2047,6 +2058,7 @@ impl behaviour::Conversion for PaymentAttempt {
payment_method_billing_address,
connector_token_details: storage_model.connector_token_details,
card_discovery: storage_model.card_discovery,
+ feature_metadata: storage_model.feature_metadata.map(From::from),
})
}
.await
@@ -2102,6 +2114,7 @@ impl behaviour::Conversion for PaymentAttempt {
connector_token_details,
card_discovery,
charges,
+ feature_metadata,
} = self;
let card_network = payment_method_data
@@ -2177,6 +2190,7 @@ impl behaviour::Conversion for PaymentAttempt {
extended_authorization_applied: None,
request_extended_authorization: None,
capture_before: None,
+ feature_metadata: feature_metadata.as_ref().map(From::from),
})
}
}
@@ -2210,6 +2224,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal
amount_to_capture: None,
connector_token_details: None,
authentication_type: Some(authentication_type),
+ feature_metadata: None,
},
PaymentAttemptUpdate::ErrorUpdate {
status,
@@ -2236,6 +2251,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal
amount_to_capture: None,
connector_token_details: None,
authentication_type: None,
+ feature_metadata: None,
},
PaymentAttemptUpdate::ConfirmIntentResponse(confirm_intent_response_update) => {
let ConfirmIntentResponseUpdate {
@@ -2267,6 +2283,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal
amount_to_capture: None,
connector_token_details,
authentication_type: None,
+ feature_metadata: None,
}
}
PaymentAttemptUpdate::SyncUpdate {
@@ -2292,6 +2309,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal
amount_to_capture: None,
connector_token_details: None,
authentication_type: None,
+ feature_metadata: None,
},
PaymentAttemptUpdate::CaptureUpdate {
status,
@@ -2316,6 +2334,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal
connector_metadata: None,
connector_token_details: None,
authentication_type: None,
+ feature_metadata: None,
},
PaymentAttemptUpdate::PreCaptureUpdate {
amount_to_capture,
@@ -2339,7 +2358,44 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal
amount_capturable: None,
connector_token_details: None,
authentication_type: None,
+ feature_metadata: None,
},
}
}
}
+#[cfg(feature = "v2")]
+#[derive(Debug, Clone, serde::Serialize, PartialEq)]
+pub struct PaymentAttemptFeatureMetadata {
+ pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>,
+}
+
+#[cfg(feature = "v2")]
+#[derive(Debug, Clone, serde::Serialize, PartialEq)]
+pub struct PaymentAttemptRevenueRecoveryData {
+ pub attempt_triggered_by: common_enums::TriggeredBy,
+}
+
+#[cfg(feature = "v2")]
+impl From<&PaymentAttemptFeatureMetadata> for DieselPaymentAttemptFeatureMetadata {
+ fn from(item: &PaymentAttemptFeatureMetadata) -> Self {
+ let revenue_recovery =
+ item.revenue_recovery
+ .as_ref()
+ .map(|recovery_data| DieselPassiveChurnRecoveryData {
+ attempt_triggered_by: recovery_data.attempt_triggered_by,
+ });
+ Self { revenue_recovery }
+ }
+}
+
+#[cfg(feature = "v2")]
+impl From<DieselPaymentAttemptFeatureMetadata> for PaymentAttemptFeatureMetadata {
+ fn from(item: DieselPaymentAttemptFeatureMetadata) -> Self {
+ let revenue_recovery =
+ item.revenue_recovery
+ .map(|recovery_data| PaymentAttemptRevenueRecoveryData {
+ attempt_triggered_by: recovery_data.attempt_triggered_by,
+ });
+ Self { revenue_recovery }
+ }
+}
diff --git a/crates/hyperswitch_domain_models/src/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/revenue_recovery.rs
new file mode 100644
index 0000000000..8467189d27
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/revenue_recovery.rs
@@ -0,0 +1,190 @@
+use api_models::webhooks;
+use time::PrimitiveDateTime;
+
+/// Recovery payload is unified struct constructed from billing connectors
+#[derive(Debug)]
+pub struct RevenueRecoveryAttemptData {
+ /// transaction amount against invoice, accepted in minor unit.
+ pub amount: common_utils::types::MinorUnit,
+ /// currency of the transaction
+ pub currency: common_enums::enums::Currency,
+ /// merchant reference id at billing connector. ex: invoice_id
+ pub merchant_reference_id: common_utils::id_type::PaymentReferenceId,
+ /// transaction id reference at payment connector
+ pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>,
+ /// error code sent by billing connector.
+ pub error_code: Option<String>,
+ /// error message sent by billing connector.
+ pub error_message: Option<String>,
+ /// mandate token at payment processor end.
+ pub processor_payment_method_token: Option<String>,
+ /// customer id at payment connector for which mandate is attached.
+ pub connector_customer_id: Option<String>,
+ /// Payment gateway identifier id at billing processor.
+ pub connector_account_reference_id: Option<String>,
+ /// timestamp at which transaction has been created at billing connector
+ pub transaction_created_at: Option<PrimitiveDateTime>,
+ /// transaction status at billing connector equivalent to payment attempt status.
+ pub status: common_enums::enums::AttemptStatus,
+ /// payment method of payment attempt.
+ pub payment_method_type: common_enums::enums::PaymentMethod,
+ /// payment method sub type of the payment attempt.
+ pub payment_method_sub_type: common_enums::enums::PaymentMethodType,
+}
+
+/// This is unified struct for Revenue Recovery Invoice Data and it is constructed from billing connectors
+#[derive(Debug)]
+pub struct RevenueRecoveryInvoiceData {
+ /// invoice amount at billing connector
+ pub amount: common_utils::types::MinorUnit,
+ /// currency of the amount.
+ pub currency: common_enums::enums::Currency,
+ /// merchant reference id at billing connector. ex: invoice_id
+ pub merchant_reference_id: common_utils::id_type::PaymentReferenceId,
+}
+
+/// type of action that needs to taken after consuming recovery payload
+#[derive(Debug)]
+pub enum RecoveryAction {
+ /// Stops the process tracker and update the payment intent.
+ CancelInvoice,
+ /// Records the external transaction against payment intent.
+ ScheduleFailedPayment,
+ /// Records the external payment and stops the internal process tracker.
+ SuccessPaymentExternal,
+ /// Pending payments from billing processor.
+ PendingPayment,
+ /// No action required.
+ NoAction,
+ /// Invalid event has been received.
+ InvalidAction,
+}
+
+pub struct RecoveryPaymentIntent {
+ pub payment_id: common_utils::id_type::GlobalPaymentId,
+ pub status: common_enums::enums::IntentStatus,
+ pub feature_metadata: Option<api_models::payments::FeatureMetadata>,
+}
+
+pub struct RecoveryPaymentAttempt {
+ pub attempt_id: common_utils::id_type::GlobalAttemptId,
+ pub attempt_status: common_enums::AttemptStatus,
+ pub feature_metadata: Option<api_models::payments::PaymentAttemptFeatureMetadata>,
+}
+
+impl RecoveryPaymentAttempt {
+ pub fn get_attempt_triggered_by(self) -> Option<common_enums::TriggeredBy> {
+ self.feature_metadata.and_then(|metadata| {
+ metadata
+ .revenue_recovery
+ .map(|recovery| recovery.attempt_triggered_by)
+ })
+ }
+}
+
+impl RecoveryAction {
+ pub fn get_action(
+ event_type: webhooks::IncomingWebhookEvent,
+ attempt_triggered_by: Option<common_enums::TriggeredBy>,
+ ) -> Self {
+ match event_type {
+ webhooks::IncomingWebhookEvent::PaymentIntentFailure
+ | webhooks::IncomingWebhookEvent::PaymentIntentSuccess
+ | webhooks::IncomingWebhookEvent::PaymentIntentProcessing
+ | webhooks::IncomingWebhookEvent::PaymentIntentPartiallyFunded
+ | webhooks::IncomingWebhookEvent::PaymentIntentCancelled
+ | webhooks::IncomingWebhookEvent::PaymentIntentCancelFailure
+ | webhooks::IncomingWebhookEvent::PaymentIntentAuthorizationSuccess
+ | webhooks::IncomingWebhookEvent::PaymentIntentAuthorizationFailure
+ | webhooks::IncomingWebhookEvent::PaymentIntentCaptureSuccess
+ | webhooks::IncomingWebhookEvent::PaymentIntentCaptureFailure
+ | webhooks::IncomingWebhookEvent::PaymentActionRequired
+ | webhooks::IncomingWebhookEvent::EventNotSupported
+ | webhooks::IncomingWebhookEvent::SourceChargeable
+ | webhooks::IncomingWebhookEvent::SourceTransactionCreated
+ | webhooks::IncomingWebhookEvent::RefundFailure
+ | webhooks::IncomingWebhookEvent::RefundSuccess
+ | webhooks::IncomingWebhookEvent::DisputeOpened
+ | webhooks::IncomingWebhookEvent::DisputeExpired
+ | webhooks::IncomingWebhookEvent::DisputeAccepted
+ | webhooks::IncomingWebhookEvent::DisputeCancelled
+ | webhooks::IncomingWebhookEvent::DisputeChallenged
+ | webhooks::IncomingWebhookEvent::DisputeWon
+ | webhooks::IncomingWebhookEvent::DisputeLost
+ | webhooks::IncomingWebhookEvent::MandateActive
+ | webhooks::IncomingWebhookEvent::MandateRevoked
+ | webhooks::IncomingWebhookEvent::EndpointVerification
+ | webhooks::IncomingWebhookEvent::ExternalAuthenticationARes
+ | webhooks::IncomingWebhookEvent::FrmApproved
+ | webhooks::IncomingWebhookEvent::FrmRejected
+ | webhooks::IncomingWebhookEvent::PayoutSuccess
+ | webhooks::IncomingWebhookEvent::PayoutFailure
+ | webhooks::IncomingWebhookEvent::PayoutProcessing
+ | webhooks::IncomingWebhookEvent::PayoutCancelled
+ | webhooks::IncomingWebhookEvent::PayoutCreated
+ | webhooks::IncomingWebhookEvent::PayoutExpired
+ | webhooks::IncomingWebhookEvent::PayoutReversed => Self::InvalidAction,
+ webhooks::IncomingWebhookEvent::RecoveryPaymentFailure => match attempt_triggered_by {
+ Some(common_enums::TriggeredBy::Internal) => Self::NoAction,
+ Some(common_enums::TriggeredBy::External) | None => Self::ScheduleFailedPayment,
+ },
+ webhooks::IncomingWebhookEvent::RecoveryPaymentSuccess => match attempt_triggered_by {
+ Some(common_enums::TriggeredBy::Internal) => Self::NoAction,
+ Some(common_enums::TriggeredBy::External) | None => Self::SuccessPaymentExternal,
+ },
+ webhooks::IncomingWebhookEvent::RecoveryPaymentPending => Self::PendingPayment,
+ webhooks::IncomingWebhookEvent::RecoveryInvoiceCancel => Self::CancelInvoice,
+ }
+ }
+}
+
+impl From<&RevenueRecoveryInvoiceData> for api_models::payments::AmountDetails {
+ fn from(data: &RevenueRecoveryInvoiceData) -> Self {
+ let amount = api_models::payments::AmountDetailsSetter {
+ order_amount: data.amount.into(),
+ currency: data.currency,
+ shipping_cost: None,
+ order_tax_amount: None,
+ skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip,
+ skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip,
+ surcharge_amount: None,
+ tax_on_surcharge: None,
+ };
+ Self::new(amount)
+ }
+}
+
+impl From<&RevenueRecoveryInvoiceData> for api_models::payments::PaymentsCreateIntentRequest {
+ fn from(data: &RevenueRecoveryInvoiceData) -> Self {
+ let amount_details = api_models::payments::AmountDetails::from(data);
+ Self {
+ amount_details,
+ merchant_reference_id: Some(data.merchant_reference_id.clone()),
+ routing_algorithm_id: None,
+ // Payments in the revenue recovery flow are always recurring transactions,
+ // so capture method will be always automatic.
+ capture_method: Some(common_enums::CaptureMethod::Automatic),
+ authentication_type: Some(common_enums::AuthenticationType::NoThreeDs),
+ billing: None,
+ shipping: None,
+ customer_id: None,
+ customer_present: Some(common_enums::PresenceOfCustomerDuringPayment::Absent),
+ description: None,
+ return_url: None,
+ setup_future_usage: None,
+ apply_mit_exemption: None,
+ statement_descriptor: None,
+ order_details: None,
+ allowed_payment_method_types: None,
+ metadata: None,
+ connector_metadata: None,
+ feature_metadata: None,
+ payment_link_enabled: None,
+ payment_link_config: None,
+ request_incremental_authorization: None,
+ session_expiry: None,
+ frm_metadata: None,
+ request_external_three_ds_authentication: None,
+ }
+ }
+}
diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.toml
index 99a06ff2e3..f0402c45f7 100644
--- a/crates/hyperswitch_interfaces/Cargo.toml
+++ b/crates/hyperswitch_interfaces/Cargo.toml
@@ -10,8 +10,10 @@ license.workspace = true
default = ["dummy_connector", "frm", "payouts"]
dummy_connector = []
v1 = ["hyperswitch_domain_models/v1", "api_models/v1", "common_utils/v1"]
+v2 = []
payouts = ["hyperswitch_domain_models/payouts"]
frm = ["hyperswitch_domain_models/frm"]
+revenue_recovery= []
[dependencies]
actix-web = "4.5.1"
diff --git a/crates/hyperswitch_interfaces/src/webhooks.rs b/crates/hyperswitch_interfaces/src/webhooks.rs
index cc3bd48764..6a243cf09f 100644
--- a/crates/hyperswitch_interfaces/src/webhooks.rs
+++ b/crates/hyperswitch_interfaces/src/webhooks.rs
@@ -275,4 +275,33 @@ pub trait IncomingWebhook: ConnectorCommon + Sync {
> {
Ok(None)
}
+
+ #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
+ /// get revenue recovery invoice details
+ fn get_revenue_recovery_attempt_details(
+ &self,
+ _request: &IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<
+ hyperswitch_domain_models::revenue_recovery::RevenueRecoveryAttemptData,
+ errors::ConnectorError,
+ > {
+ Err(errors::ConnectorError::NotImplemented(
+ "get_revenue_recovery_attempt_details method".to_string(),
+ )
+ .into())
+ }
+ #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
+ /// get revenue recovery transaction details
+ fn get_revenue_recovery_invoice_details(
+ &self,
+ _request: &IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<
+ hyperswitch_domain_models::revenue_recovery::RevenueRecoveryInvoiceData,
+ errors::ConnectorError,
+ > {
+ Err(errors::ConnectorError::NotImplemented(
+ "get_revenue_recovery_invoice_details method".to_string(),
+ )
+ .into())
+ }
}
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index b75d1d2285..1b6f73fb1c 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -281,6 +281,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::enums::PaymentType,
api_models::enums::ScaExemptionType,
api_models::enums::PaymentMethod,
+ api_models::enums::TriggeredBy,
api_models::enums::PaymentMethodType,
api_models::enums::ConnectorType,
api_models::enums::PayoutConnectors,
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 752bd9707f..a4eb67b64f 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -316,6 +316,8 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::AddressDetails,
api_models::payments::BankDebitData,
api_models::payments::AliPayQr,
+ api_models::payments::PaymentAttemptFeatureMetadata,
+ api_models::payments::PaymentAttemptRevenueRecoveryData,
api_models::payments::AliPayRedirection,
api_models::payments::MomoRedirection,
api_models::payments::TouchNGoRedirection,
@@ -477,6 +479,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::PaymentRevenueRecoveryMetadata,
api_models::payments::BillingConnectorPaymentDetails,
api_models::enums::PaymentConnectorTransmission,
+ api_models::enums::TriggeredBy,
api_models::payments::PaymentAttemptResponse,
api_models::payments::PaymentAttemptAmountDetails,
api_models::payments::CaptureResponse,
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index d590797d64..8197670acf 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -33,11 +33,12 @@ payouts = ["api_models/payouts", "common_enums/payouts", "hyperswitch_connectors
payout_retry = ["payouts"]
recon = ["email", "api_models/recon"]
retry = []
-v2 = ["customer_v2", "payment_methods_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2"]
+v2 = ["customer_v2", "payment_methods_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2","hyperswitch_interfaces/v2"]
v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1", "common_utils/v1", "hyperswitch_connectors/v1"]
customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2", "storage_impl/customer_v2"]
payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"]
dynamic_routing = ["external_services/dynamic_routing", "storage_impl/dynamic_routing", "api_models/dynamic_routing"]
+revenue_recovery =["api_models/revenue_recovery","hyperswitch_interfaces/revenue_recovery","hyperswitch_domain_models/revenue_recovery"]
# Partial Auth
# The feature reduces the overhead of the router authenticating the merchant for every request, and trusts on `x-merchant-id` header to be present in the request.
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index 3dbaa99921..d06ffea581 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -445,3 +445,20 @@ pub enum NetworkTokenizationError {
#[error("Failed while calling Network Token Service API")]
ApiError,
}
+
+#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
+#[derive(Debug, thiserror::Error)]
+pub enum RevenueRecoveryError {
+ #[error("Failed to fetch payment intent")]
+ PaymentIntentFetchFailed,
+ #[error("Failed to fetch payment attempt")]
+ PaymentAttemptFetchFailed,
+ #[error("Failed to get revenue recovery invoice webhook")]
+ InvoiceWebhookProcessingFailed,
+ #[error("Failed to get revenue recovery invoice transaction")]
+ TransactionWebhookProcessingFailed,
+ #[error("Failed to create payment intent")]
+ PaymentIntentCreateFailed,
+ #[error("Source verification failed for billing connector")]
+ WebhookAuthenticationFailed,
+}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 74ac9dc0f3..1898dd4066 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1803,7 +1803,7 @@ pub(crate) async fn payments_create_and_confirm_intent(
#[cfg(feature = "v2")]
#[inline]
-fn handle_payments_intent_response<T>(
+pub fn handle_payments_intent_response<T>(
response: hyperswitch_domain_models::api::ApplicationResponse<T>,
) -> CustomResult<T, errors::ApiErrorResponse> {
match response {
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 5c77452b67..661bd73b50 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -1616,7 +1616,7 @@ where
let error = payment_attempt
.error
- .clone()
+ .as_ref()
.map(api_models::payments::ErrorDetails::foreign_from);
let payment_address = self.payment_address;
@@ -1704,6 +1704,7 @@ where
let error = optional_payment_attempt
.and_then(|payment_attempt| payment_attempt.error.clone())
+ .as_ref()
.map(api_models::payments::ErrorDetails::foreign_from);
let attempts = self.attempts.as_ref().map(|attempts| {
attempts
@@ -2811,7 +2812,7 @@ impl ForeignFrom<(storage::PaymentIntent, Option<storage::PaymentAttempt>)>
error: pa
.as_ref()
.and_then(|p| p.error.as_ref())
- .map(|e| api_models::payments::ErrorDetails::foreign_from(e.clone())),
+ .map(api_models::payments::ErrorDetails::foreign_from),
cancellation_reason: pa.as_ref().and_then(|p| p.cancellation_reason.clone()),
order_details: None,
return_url: pi.return_url,
@@ -4245,7 +4246,7 @@ impl ForeignFrom<&hyperswitch_domain_models::payments::payment_attempt::PaymentA
connector: attempt.connector.clone(),
error: attempt
.error
- .clone()
+ .as_ref()
.map(api_models::payments::ErrorDetails::foreign_from),
authentication_type: attempt.authentication_type,
created_at: attempt.created_at,
@@ -4257,10 +4258,16 @@ impl ForeignFrom<&hyperswitch_domain_models::payments::payment_attempt::PaymentA
payment_method_type: attempt.payment_method_type,
connector_reference_id: attempt.connector_response_reference_id.clone(),
payment_method_subtype: attempt.get_payment_method_type(),
- connector_payment_id: attempt.get_connector_payment_id().map(ToString::to_string),
+ connector_payment_id: attempt
+ .get_connector_payment_id()
+ .map(|str| common_utils::types::ConnectorTransactionId::from(str.to_owned())),
payment_method_id: attempt.payment_method_id.clone(),
client_source: attempt.client_source.clone(),
client_version: attempt.client_version.clone(),
+ feature_metadata: attempt
+ .feature_metadata
+ .as_ref()
+ .map(api_models::payments::PaymentAttemptFeatureMetadata::foreign_from),
}
}
}
@@ -4285,29 +4292,39 @@ impl ForeignFrom<&hyperswitch_domain_models::payments::payment_attempt::AttemptA
}
#[cfg(feature = "v2")]
-impl ForeignFrom<hyperswitch_domain_models::payments::payment_attempt::ErrorDetails>
+impl ForeignFrom<&hyperswitch_domain_models::payments::payment_attempt::ErrorDetails>
for api_models::payments::ErrorDetails
{
fn foreign_from(
- amount_details: hyperswitch_domain_models::payments::payment_attempt::ErrorDetails,
+ error_details: &hyperswitch_domain_models::payments::payment_attempt::ErrorDetails,
) -> Self {
- let hyperswitch_domain_models::payments::payment_attempt::ErrorDetails {
- code,
- message,
- reason,
- unified_code,
- unified_message,
- } = amount_details;
-
Self {
- code,
- message: reason.unwrap_or(message),
- unified_code,
- unified_message,
+ code: error_details.code.to_owned(),
+ message: error_details.message.to_owned(),
+ unified_code: error_details.unified_code.clone(),
+ unified_message: error_details.unified_message.clone(),
}
}
}
+#[cfg(feature = "v2")]
+impl
+ ForeignFrom<
+ &hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptFeatureMetadata,
+ > for api_models::payments::PaymentAttemptFeatureMetadata
+{
+ fn foreign_from(
+ feature_metadata: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptFeatureMetadata,
+ ) -> Self {
+ let revenue_recovery = feature_metadata.revenue_recovery.as_ref().map(|recovery| {
+ api_models::payments::PaymentAttemptRevenueRecoveryData {
+ attempt_triggered_by: recovery.attempt_triggered_by,
+ }
+ });
+ Self { revenue_recovery }
+ }
+}
+
#[cfg(feature = "v2")]
impl ForeignFrom<hyperswitch_domain_models::payments::AmountDetails>
for api_models::payments::AmountDetailsResponse
diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs
index 64c5617398..4a9c4106b9 100644
--- a/crates/router/src/core/webhooks.rs
+++ b/crates/router/src/core/webhooks.rs
@@ -4,6 +4,8 @@ mod incoming;
mod incoming_v2;
#[cfg(feature = "v1")]
mod outgoing;
+#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
+mod recovery_incoming;
pub mod types;
pub mod utils;
#[cfg(feature = "olap")]
diff --git a/crates/router/src/core/webhooks/incoming_v2.rs b/crates/router/src/core/webhooks/incoming_v2.rs
index 900a455f99..c564b40583 100644
--- a/crates/router/src/core/webhooks/incoming_v2.rs
+++ b/crates/router/src/core/webhooks/incoming_v2.rs
@@ -15,6 +15,8 @@ use hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails;
use router_env::{instrument, tracing, tracing_actix_web::RequestId};
use super::{types, utils, MERCHANT_ID};
+#[cfg(feature = "revenue_recovery")]
+use crate::core::webhooks::recovery_incoming;
use crate::{
core::{
api_locking,
@@ -349,6 +351,24 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
api::WebhookFlow::Payout => todo!(),
api::WebhookFlow::Subscription => todo!(),
+ #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
+ api::WebhookFlow::Recovery => {
+ Box::pin(recovery_incoming::recovery_incoming_webhook_flow(
+ state.clone(),
+ merchant_account,
+ profile,
+ key_store,
+ webhook_details,
+ source_verified,
+ &connector,
+ &request_details,
+ event_type,
+ req_state,
+ ))
+ .await
+ .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
+ .attach_printable("Failed to process recovery incoming webhook")?
+ }
}
}
}
diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rs
new file mode 100644
index 0000000000..3634acfab9
--- /dev/null
+++ b/crates/router/src/core/webhooks/recovery_incoming.rs
@@ -0,0 +1,307 @@
+use api_models::webhooks;
+use common_utils::ext_traits::AsyncExt;
+use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::revenue_recovery;
+use hyperswitch_interfaces::webhooks as interface_webhooks;
+use router_env::{instrument, tracing};
+
+use crate::{
+ core::{
+ errors::{self, CustomResult},
+ payments::{self, operations},
+ },
+ routes::{app::ReqState, SessionState},
+ services::{self, connector_integration_interface},
+ types::{api, domain},
+};
+
+#[allow(clippy::too_many_arguments)]
+#[instrument(skip_all)]
+#[cfg(feature = "revenue_recovery")]
+pub async fn recovery_incoming_webhook_flow(
+ state: SessionState,
+ merchant_account: domain::MerchantAccount,
+ business_profile: domain::Profile,
+ key_store: domain::MerchantKeyStore,
+ _webhook_details: api::IncomingWebhookDetails,
+ source_verified: bool,
+ connector: &connector_integration_interface::ConnectorEnum,
+ request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
+ event_type: webhooks::IncomingWebhookEvent,
+ req_state: ReqState,
+) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> {
+ // Source verification is necessary for revenue recovery webhooks flow since We don't have payment intent/attempt object created before in our system.
+
+ common_utils::fp_utils::when(!source_verified, || {
+ Err(report!(
+ errors::RevenueRecoveryError::WebhookAuthenticationFailed
+ ))
+ })?;
+
+ let invoice_details = RevenueRecoveryInvoice(
+ interface_webhooks::IncomingWebhook::get_revenue_recovery_invoice_details(
+ connector,
+ request_details,
+ )
+ .change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed)
+ .attach_printable("Failed while getting revenue recovery invoice details")?,
+ );
+ // Fetch the intent using merchant reference id, if not found create new intent.
+ let payment_intent = invoice_details
+ .get_payment_intent(
+ &state,
+ &req_state,
+ &merchant_account,
+ &business_profile,
+ &key_store,
+ )
+ .await
+ .transpose()
+ .async_unwrap_or_else(|| async {
+ invoice_details
+ .create_payment_intent(
+ &state,
+ &req_state,
+ &merchant_account,
+ &business_profile,
+ &key_store,
+ )
+ .await
+ })
+ .await?;
+
+ let payment_attempt = match event_type.is_recovery_transaction_event() {
+ true => {
+ let invoice_transaction_details = RevenueRecoveryAttempt(
+ interface_webhooks::IncomingWebhook::get_revenue_recovery_attempt_details(
+ connector,
+ request_details,
+ )
+ .change_context(errors::RevenueRecoveryError::TransactionWebhookProcessingFailed)?,
+ );
+
+ invoice_transaction_details
+ .get_payment_attempt(
+ &state,
+ &req_state,
+ &merchant_account,
+ &business_profile,
+ &key_store,
+ payment_intent.payment_id.clone(),
+ )
+ .await?
+ }
+ false => None,
+ };
+
+ let attempt_triggered_by = payment_attempt
+ .and_then(revenue_recovery::RecoveryPaymentAttempt::get_attempt_triggered_by);
+
+ let action = revenue_recovery::RecoveryAction::get_action(event_type, attempt_triggered_by);
+
+ match action {
+ revenue_recovery::RecoveryAction::CancelInvoice => todo!(),
+ revenue_recovery::RecoveryAction::ScheduleFailedPayment => {
+ todo!()
+ }
+ revenue_recovery::RecoveryAction::SuccessPaymentExternal => {
+ todo!()
+ }
+ revenue_recovery::RecoveryAction::PendingPayment => {
+ router_env::logger::info!(
+ "Pending transactions are not consumed by the revenue recovery webhooks"
+ );
+ Ok(webhooks::WebhookResponseTracker::NoEffect)
+ }
+ revenue_recovery::RecoveryAction::NoAction => {
+ router_env::logger::info!(
+ "No Recovery action is taken place for recovery event : {:?} and attempt triggered_by : {:?} ", event_type.clone(), attempt_triggered_by
+ );
+ Ok(webhooks::WebhookResponseTracker::NoEffect)
+ }
+ revenue_recovery::RecoveryAction::InvalidAction => {
+ router_env::logger::error!(
+ "Invalid Revenue recovery action state has been received, event : {:?}, triggered_by : {:?}", event_type, attempt_triggered_by
+ );
+ Ok(webhooks::WebhookResponseTracker::NoEffect)
+ }
+ }
+}
+
+pub struct RevenueRecoveryInvoice(revenue_recovery::RevenueRecoveryInvoiceData);
+pub struct RevenueRecoveryAttempt(revenue_recovery::RevenueRecoveryAttemptData);
+
+impl RevenueRecoveryInvoice {
+ async fn get_payment_intent(
+ &self,
+ state: &SessionState,
+ req_state: &ReqState,
+ merchant_account: &domain::MerchantAccount,
+ profile: &domain::Profile,
+ key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Option<revenue_recovery::RecoveryPaymentIntent>, errors::RevenueRecoveryError>
+ {
+ let payment_response = Box::pin(payments::payments_get_intent_using_merchant_reference(
+ state.clone(),
+ merchant_account.clone(),
+ profile.clone(),
+ key_store.clone(),
+ req_state.clone(),
+ &self.0.merchant_reference_id,
+ hyperswitch_domain_models::payments::HeaderPayload::default(),
+ None,
+ ))
+ .await;
+ let response = match payment_response {
+ Ok(services::ApplicationResponse::JsonWithHeaders((payments_response, _))) => {
+ let payment_id = payments_response.id.clone();
+ let status = payments_response.status;
+ let feature_metadata = payments_response.feature_metadata;
+ Ok(Some(revenue_recovery::RecoveryPaymentIntent {
+ payment_id,
+ status,
+ feature_metadata,
+ }))
+ }
+ Err(err)
+ if matches!(
+ err.current_context(),
+ &errors::ApiErrorResponse::PaymentNotFound
+ ) =>
+ {
+ Ok(None)
+ }
+ Ok(_) => Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed)
+ .attach_printable("Unexpected response from payment intent core"),
+ error @ Err(_) => {
+ router_env::logger::error!(?error);
+ Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed)
+ .attach_printable("failed to fetch payment intent recovery webhook flow")
+ }
+ }?;
+ Ok(response)
+ }
+ async fn create_payment_intent(
+ &self,
+ state: &SessionState,
+ req_state: &ReqState,
+ merchant_account: &domain::MerchantAccount,
+ profile: &domain::Profile,
+ key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<revenue_recovery::RecoveryPaymentIntent, errors::RevenueRecoveryError> {
+ let payload = api_models::payments::PaymentsCreateIntentRequest::from(&self.0);
+ let global_payment_id =
+ common_utils::id_type::GlobalPaymentId::generate(&state.conf.cell_information.id);
+
+ let create_intent_response = Box::pin(payments::payments_intent_core::<
+ hyperswitch_domain_models::router_flow_types::payments::PaymentCreateIntent,
+ api_models::payments::PaymentsIntentResponse,
+ _,
+ _,
+ hyperswitch_domain_models::payments::PaymentIntentData<
+ hyperswitch_domain_models::router_flow_types::payments::PaymentCreateIntent,
+ >,
+ >(
+ state.clone(),
+ req_state.clone(),
+ merchant_account.clone(),
+ profile.clone(),
+ key_store.clone(),
+ payments::operations::PaymentIntentCreate,
+ payload,
+ global_payment_id,
+ hyperswitch_domain_models::payments::HeaderPayload::default(),
+ None,
+ ))
+ .await
+ .change_context(errors::RevenueRecoveryError::PaymentIntentCreateFailed)?;
+ let response = payments::handle_payments_intent_response(create_intent_response)
+ .change_context(errors::RevenueRecoveryError::PaymentIntentCreateFailed)?;
+
+ Ok(revenue_recovery::RecoveryPaymentIntent {
+ payment_id: response.id,
+ status: response.status,
+ feature_metadata: response.feature_metadata,
+ })
+ }
+}
+
+impl RevenueRecoveryAttempt {
+ async fn get_payment_attempt(
+ &self,
+ state: &SessionState,
+ req_state: &ReqState,
+ merchant_account: &domain::MerchantAccount,
+ profile: &domain::Profile,
+ key_store: &domain::MerchantKeyStore,
+ payment_id: common_utils::id_type::GlobalPaymentId,
+ ) -> CustomResult<Option<revenue_recovery::RecoveryPaymentAttempt>, errors::RevenueRecoveryError>
+ {
+ let attempt_response = Box::pin(payments::payments_core::<
+ hyperswitch_domain_models::router_flow_types::payments::PSync,
+ api_models::payments::PaymentsRetrieveResponse,
+ _,
+ _,
+ _,
+ hyperswitch_domain_models::payments::PaymentStatusData<
+ hyperswitch_domain_models::router_flow_types::payments::PSync,
+ >,
+ >(
+ state.clone(),
+ req_state.clone(),
+ merchant_account.clone(),
+ profile.clone(),
+ key_store.clone(),
+ payments::operations::PaymentGet,
+ api_models::payments::PaymentsRetrieveRequest {
+ force_sync: false,
+ expand_attempts: true,
+ param: None,
+ },
+ payment_id.clone(),
+ payments::CallConnectorAction::Avoid,
+ hyperswitch_domain_models::payments::HeaderPayload::default(),
+ ))
+ .await;
+ let response = match attempt_response {
+ Ok(services::ApplicationResponse::JsonWithHeaders((payments_response, _))) => {
+ let final_attempt =
+ self.0
+ .connector_transaction_id
+ .as_ref()
+ .and_then(|transaction_id| {
+ payments_response
+ .find_attempt_in_attempts_list_using_connector_transaction_id(
+ transaction_id,
+ )
+ });
+ let payment_attempt =
+ final_attempt.map(|attempt_res| revenue_recovery::RecoveryPaymentAttempt {
+ attempt_id: attempt_res.id.to_owned(),
+ attempt_status: attempt_res.status.to_owned(),
+ feature_metadata: attempt_res.feature_metadata.to_owned(),
+ });
+ Ok(payment_attempt)
+ }
+ Ok(_) => Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed)
+ .attach_printable("Unexpected response from payment intent core"),
+ error @ Err(_) => {
+ router_env::logger::error!(?error);
+ Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed)
+ .attach_printable("failed to fetch payment intent recovery webhook flow")
+ }
+ }?;
+ Ok(response)
+ }
+ async fn record_payment_attempt(
+ &self,
+ _state: &SessionState,
+ _req_state: &ReqState,
+ _merchant_account: &domain::MerchantAccount,
+ _profile: &domain::Profile,
+ _key_store: &domain::MerchantKeyStore,
+ _payment_id: common_utils::id_type::GlobalPaymentId,
+ ) -> CustomResult<revenue_recovery::RecoveryPaymentAttempt, errors::RevenueRecoveryError> {
+ todo!()
+ }
+}
diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs
index b589d4755f..0b50661166 100644
--- a/crates/router/src/routes.rs
+++ b/crates/router/src/routes.rs
@@ -60,6 +60,9 @@ pub mod verify_connector;
pub mod webhook_events;
pub mod webhooks;
+#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
+pub mod recovery_webhooks;
+
pub mod relay;
#[cfg(feature = "dummy_connector")]
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index b8acc66d52..760afc26b0 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -46,6 +46,8 @@ use super::payouts::*;
use super::pm_auth;
#[cfg(feature = "oltp")]
use super::poll;
+#[cfg(all(feature = "v2", feature = "revenue_recovery", feature = "oltp"))]
+use super::recovery_webhooks::*;
#[cfg(feature = "olap")]
use super::routing;
#[cfg(all(feature = "olap", feature = "v1"))]
@@ -1642,6 +1644,16 @@ impl Webhooks {
),
);
+ #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
+ {
+ route = route.service(
+ web::resource("/recovery/{merchant_id}/{profile_id}/{connector_id}").route(
+ web::post()
+ .to(recovery_receive_incoming_webhook::<webhook_type::OutgoingWebhook>),
+ ),
+ );
+ }
+
route
}
}
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index a50a27b9ec..f48a7970fd 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -178,7 +178,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::IncomingRelayWebhookReceive
| Flow::WebhookEventInitialDeliveryAttemptList
| Flow::WebhookEventDeliveryAttemptList
- | Flow::WebhookEventDeliveryRetry => Self::Webhooks,
+ | Flow::WebhookEventDeliveryRetry
+ | Flow::RecoveryIncomingWebhookReceive => Self::Webhooks,
Flow::ApiKeyCreate
| Flow::ApiKeyRetrieve
diff --git a/crates/router/src/routes/recovery_webhooks.rs b/crates/router/src/routes/recovery_webhooks.rs
new file mode 100644
index 0000000000..0c83ba1b39
--- /dev/null
+++ b/crates/router/src/routes/recovery_webhooks.rs
@@ -0,0 +1,53 @@
+use actix_web::{web, HttpRequest, Responder};
+use router_env::{instrument, tracing, Flow};
+
+use super::app::AppState;
+use crate::{
+ core::{
+ api_locking,
+ webhooks::{self, types},
+ },
+ services::{api, authentication as auth},
+};
+
+#[instrument(skip_all, fields(flow = ?Flow::IncomingWebhookReceive))]
+pub async fn recovery_receive_incoming_webhook<W: types::OutgoingWebhookType>(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ body: web::Bytes,
+ path: web::Path<(
+ common_utils::id_type::MerchantId,
+ common_utils::id_type::ProfileId,
+ common_utils::id_type::MerchantConnectorAccountId,
+ )>,
+) -> impl Responder {
+ let flow = Flow::RecoveryIncomingWebhookReceive;
+ let (merchant_id, profile_id, connector_id) = path.into_inner();
+
+ Box::pin(api::server_wrap(
+ flow.clone(),
+ state,
+ &req,
+ (),
+ |state, auth, _, req_state| {
+ webhooks::incoming_webhooks_wrapper::<W>(
+ &flow,
+ state.to_owned(),
+ req_state,
+ &req,
+ auth.merchant_account,
+ auth.profile,
+ auth.key_store,
+ &connector_id,
+ body.clone(),
+ false,
+ )
+ },
+ &auth::MerchantIdAndProfileIdAuth {
+ merchant_id,
+ profile_id,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/services/connector_integration_interface.rs b/crates/router/src/services/connector_integration_interface.rs
index 5903c8e9cc..d9b04f5734 100644
--- a/crates/router/src/services/connector_integration_interface.rs
+++ b/crates/router/src/services/connector_integration_interface.rs
@@ -338,6 +338,34 @@ impl api::IncomingWebhook for ConnectorEnum {
Self::New(connector) => connector.get_network_txn_id(request),
}
}
+
+ #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
+ fn get_revenue_recovery_attempt_details(
+ &self,
+ request: &IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<
+ hyperswitch_domain_models::revenue_recovery::RevenueRecoveryAttemptData,
+ errors::ConnectorError,
+ > {
+ match self {
+ Self::Old(connector) => connector.get_revenue_recovery_attempt_details(request),
+ Self::New(connector) => connector.get_revenue_recovery_attempt_details(request),
+ }
+ }
+
+ #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
+ fn get_revenue_recovery_invoice_details(
+ &self,
+ request: &IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<
+ hyperswitch_domain_models::revenue_recovery::RevenueRecoveryInvoiceData,
+ errors::ConnectorError,
+ > {
+ match self {
+ Self::Old(connector) => connector.get_revenue_recovery_invoice_details(request),
+ Self::New(connector) => connector.get_revenue_recovery_invoice_details(request),
+ }
+ }
}
impl api::ConnectorTransactionId for ConnectorEnum {
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 3eda63bdba..6021ee70d9 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -267,6 +267,8 @@ pub enum Flow {
ToggleBlocklistGuard,
/// Incoming Webhook Receive
IncomingWebhookReceive,
+ /// Recovery incoming webhook receive
+ RecoveryIncomingWebhookReceive,
/// Validate payment method flow
ValidatePaymentMethod,
/// API Key create flow
diff --git a/v2_migrations/2025-01-17-042122_add_feature_metadata_in_payment_attempt/down.sql b/v2_migrations/2025-01-17-042122_add_feature_metadata_in_payment_attempt/down.sql
new file mode 100644
index 0000000000..ec6a51ca79
--- /dev/null
+++ b/v2_migrations/2025-01-17-042122_add_feature_metadata_in_payment_attempt/down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE payment_attempt
+DROP COLUMN IF EXISTS feature_metadata;
\ No newline at end of file
diff --git a/v2_migrations/2025-01-17-042122_add_feature_metadata_in_payment_attempt/up.sql b/v2_migrations/2025-01-17-042122_add_feature_metadata_in_payment_attempt/up.sql
new file mode 100644
index 0000000000..bf06a98f7a
--- /dev/null
+++ b/v2_migrations/2025-01-17-042122_add_feature_metadata_in_payment_attempt/up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE payment_attempt
+ADD COLUMN feature_metadata JSONB;
\ No newline at end of file