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): send the next retry to the merchant by webhook (#15210)

CHALLA NISHANTH BABUaaf0b435093f
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index 2916889ce0..e2506be8c2 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -32254,8 +32254,7 @@
"transaction_created_at",
"connector_customer_id",
"billing_started_at",
- "connector_transaction_id",
- "payment_method_data"
+ "connector_transaction_id"
],
"properties": {
"amount_details": {
@@ -32288,6 +32287,18 @@
"example": "mca_1234567890",
"nullable": true
},
+ "merchant_reference_billing_connector_id": {
+ "type": "string",
+ "description": "The merchant's own identifier for the billing connector account of the invoice. Accepted, and not used yet.",
+ "example": "billing_account_main",
+ "nullable": true
+ },
+ "merchant_reference_payment_connector_id": {
+ "type": "string",
+ "description": "The merchant's own identifier for the payment connector account on which the transaction was processed. Accepted, and not used yet.",
+ "example": "payment_account_us",
+ "nullable": true
+ },
"connector": {
"allOf": [
{
@@ -32377,7 +32388,12 @@
"example": "993672945374576J"
},
"payment_method_data": {
- "$ref": "#/components/schemas/CustomRecoveryPaymentMethodData"
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CustomRecoveryPaymentMethodData"
+ }
+ ],
+ "nullable": true
},
"enable_partial_authorization": {
"type": "boolean",
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index efa6eb14e9..c4d6766b8a 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -14660,8 +14660,8 @@ pub struct PaymentsAttemptRecordRequest {
pub transaction_created_at: Option<PrimitiveDateTime>,
/// payment method token at payment processor end.
- #[schema(value_type = String, example = "1234567890")]
- pub processor_payment_method_token: String,
+ #[schema(value_type = Option<String>, example = "1234567890")]
+ pub processor_payment_method_token: Option<String>,
/// customer id at payment connector for which mandate is attached.
#[schema(value_type = String, example = "cust_12345")]
@@ -14726,6 +14726,14 @@ pub struct RecoveryPaymentsCreate {
#[schema(value_type = Option<String>, example = "mca_1234567890")]
pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
+ /// The merchant's own identifier for the billing connector account of the invoice. Accepted, and not used yet.
+ #[schema(value_type = Option<String>, example = "billing_account_main")]
+ pub merchant_reference_billing_connector_id: Option<String>,
+
+ /// The merchant's own identifier for the payment connector account on which the transaction was processed. Accepted, and not used yet.
+ #[schema(value_type = Option<String>, example = "payment_account_us")]
+ pub merchant_reference_payment_connector_id: Option<String>,
+
/// Payment processor on which the transaction was processed. Required when the `revenue_recovery_trigger_model` of the profile is `external_triggers`, and ignored when it is `internal_triggers`, where the processor comes from `payment_merchant_connector_id`.
#[schema(value_type = Option<RecoveryConnector>, example = "stripe")]
pub connector: Option<common_payments_types::RecoveryConnector>,
@@ -14782,8 +14790,9 @@ pub struct RecoveryPaymentsCreate {
#[schema(value_type = String, example = "993672945374576J")]
pub connector_transaction_id: String,
- /// Payment method token and card details at the payment processor's end.
- pub payment_method_data: CustomRecoveryPaymentMethodData,
+ /// Payment method token and card details at the payment processor's end. Required unless the
+ /// customer is present and the payment is on session.
+ pub payment_method_data: Option<CustomRecoveryPaymentMethodData>,
/// Allow partial authorization for this payment
#[schema(value_type = Option<bool>, default = false)]
diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs
index b55f4ebeee..13a6f8bfd4 100644
--- a/crates/diesel_models/src/process_tracker.rs
+++ b/crates/diesel_models/src/process_tracker.rs
@@ -336,4 +336,12 @@ pub mod business_status {
/// A reported transaction's attempt is recorded, but its invoice does not show every attempt
/// recorded on it, so the recovery request is not decided and the invoice needs a manual check
pub const RECOVERY_REQUEST_INVOICE_OUT_OF_SYNC: &str = "RECOVERY_REQUEST_INVOICE_OUT_OF_SYNC";
+
+ /// A reported transaction was recorded and decided, but the merchant was not told: outgoing
+ /// webhooks are off, or the profile has no webhook URL
+ pub const RECOVERY_REQUEST_WEBHOOK_DISABLED: &str = "RECOVERY_REQUEST_WEBHOOK_DISABLED";
+
+ /// A reported transaction could not be recorded: its job failed for good, ran out of retries,
+ /// or waited too long for its invoice, or it has no card and its invoice is new
+ pub const RECOVERY_REQUEST_RECORDING_FAILED: &str = "RECOVERY_REQUEST_RECORDING_FAILED";
}
diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs
index 15cf096126..56c6984449 100644
--- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs
@@ -911,7 +911,7 @@ impl TryFrom<ChargebeeWebhookBody> for revenue_recovery::RevenueRecoveryAttemptD
connector_transaction_id,
error_code,
error_message,
- processor_payment_method_token: connector_mandate_details.mandate_id,
+ processor_payment_method_token: Some(connector_mandate_details.mandate_id),
connector_customer_id: connector_mandate_details.customer_id,
connector_account_reference_id,
transaction_created_at,
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index 5af73913ad..0014f4bfc1 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -1381,7 +1381,7 @@ impl PaymentIntent {
connector_transaction_id: None, // No connector id
error_code: None,
error_message: None,
- processor_payment_method_token: payment_processor_token.to_string(),
+ processor_payment_method_token: Some(payment_processor_token.to_string()),
connector_customer_id: revenue_recovery_metadata
.billing_connector_payment_details
.connector_customer_id,
@@ -1655,7 +1655,7 @@ where
#[derive(Clone)]
pub struct RevenueRecoveryData {
pub connector_details: common_types::payments::RecoveryConnectorDetails,
- pub processor_payment_method_token: String,
+ pub processor_payment_method_token: Option<String>,
pub connector_customer_id: String,
pub retry_count: Option<u16>,
pub invoice_next_billing_time: Option<PrimitiveDateTime>,
@@ -1752,13 +1752,45 @@ where
),
);
+ let is_merchant_initiated = self
+ .payment_attempt
+ .feature_metadata
+ .as_ref()
+ .and_then(|feature_metadata| feature_metadata.revenue_recovery.as_ref())
+ .is_none_or(|recovery_data| {
+ revenue_recovery::is_merchant_initiated(
+ recovery_data.customer_present,
+ recovery_data.setup_future_usage,
+ )
+ });
+ // A merchant-initiated transaction the merchant reported makes its card the invoice's. A
+ // customer-initiated one keeps the invoice's card and its last error code, and counts as a
+ // retry only on that card.
+ let kept_invoice_card = revenue_recovery.as_ref().filter(|_| {
+ !is_merchant_initiated
+ && matches!(
+ connector_details,
+ common_types::payments::RecoveryConnectorDetails::ReportedByMerchant { .. }
+ )
+ });
+ let counts_as_retry = kept_invoice_card.is_none_or(|data| {
+ self.revenue_recovery_data
+ .processor_payment_method_token
+ .as_ref()
+ == Some(
+ &data
+ .billing_connector_payment_details
+ .payment_processor_token,
+ )
+ });
+
let payment_revenue_recovery_metadata =
Some(diesel_models::types::PaymentRevenueRecoveryMetadata {
- // Update retry count by one.
- total_retry_count: revenue_recovery.as_ref().map_or(
- self.revenue_recovery_data.retry_count.unwrap_or(1),
- |data| (data.total_retry_count + 1),
- ),
+ total_retry_count: match revenue_recovery.as_ref() {
+ None => self.revenue_recovery_data.retry_count.unwrap_or(1),
+ Some(data) if counts_as_retry => data.total_retry_count + 1,
+ Some(data) => data.total_retry_count,
+ },
// Since this is an external system call, marking this payment_connector_transmission to ConnectorCallSucceeded.
payment_connector_transmission:
common_enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,
@@ -1766,17 +1798,27 @@ where
active_attempt_payment_connector_id: connector_details
.get_payment_connector_id()
.cloned(),
- billing_connector_payment_details:
- diesel_models::types::BillingConnectorPaymentDetails {
+ billing_connector_payment_details: kept_invoice_card.map_or_else(
+ || diesel_models::types::BillingConnectorPaymentDetails {
payment_processor_token: self
.revenue_recovery_data
.processor_payment_method_token
- .clone(),
+ .clone()
+ .or_else(|| {
+ revenue_recovery.as_ref().map(|data| {
+ data.billing_connector_payment_details
+ .payment_processor_token
+ .clone()
+ })
+ })
+ .unwrap_or_default(),
connector_customer_id: self
.revenue_recovery_data
.connector_customer_id
.clone(),
},
+ |data| data.billing_connector_payment_details.clone(),
+ ),
payment_method_type: self.payment_attempt.payment_method_type,
payment_method_subtype: self
.payment_attempt
@@ -1798,7 +1840,10 @@ where
.as_ref()
.and_then(|data| data.invoice_billing_started_at_time)
.or(self.revenue_recovery_data.invoice_billing_started_at_time),
- billing_connector_payment_method_details,
+ billing_connector_payment_method_details: kept_invoice_card
+ .map_or(billing_connector_payment_method_details, |data| {
+ data.billing_connector_payment_method_details.clone()
+ }),
first_payment_attempt_network_advice_code: first_network_advice_code,
first_payment_attempt_network_decline_code: first_network_decline_code,
first_payment_attempt_pg_error_code: first_pg_error_code,
@@ -1808,7 +1853,13 @@ where
external_trigger_state: revenue_recovery
.as_ref()
.and_then(|data| data.external_trigger_state.clone()),
- last_failure_code: self.revenue_recovery_data.standardised_error_code,
+ last_failure_code: if counts_as_retry {
+ self.revenue_recovery_data.standardised_error_code
+ } else {
+ revenue_recovery
+ .as_ref()
+ .and_then(|data| data.last_failure_code)
+ },
});
Ok(Some(FeatureMetadata {
multi_currency_processing: payment_intent_feature_metadata
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 74feb1bf5b..7778ae0a9a 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -1374,7 +1374,7 @@ impl PaymentAttempt {
feature_metadata: Some(feature_metadata),
id,
connector_token_details: Some(diesel_models::ConnectorTokenDetails {
- connector_mandate_id: Some(request.processor_payment_method_token.clone()),
+ connector_mandate_id: request.processor_payment_method_token.clone(),
connector_token_request_reference_id: None,
}),
card_discovery: None,
diff --git a/crates/hyperswitch_domain_models/src/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/revenue_recovery.rs
index 09a7c80a73..5f7f1c7ac4 100644
--- a/crates/hyperswitch_domain_models/src/revenue_recovery.rs
+++ b/crates/hyperswitch_domain_models/src/revenue_recovery.rs
@@ -16,6 +16,19 @@ use crate::{
ApiModelToDieselModelConvertor,
};
+/// Only a transaction made off session with the customer absent is merchant initiated. One that
+/// leaves either out gets the defaults the invoice is created with.
+pub fn is_merchant_initiated(
+ customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>,
+ setup_future_usage: Option<common_enums::FutureUsage>,
+) -> bool {
+ customer_present.unwrap_or(common_enums::PresenceOfCustomerDuringPayment::Absent)
+ == common_enums::PresenceOfCustomerDuringPayment::Absent
+ && setup_future_usage
+ .unwrap_or(common_enums::FutureUsage::OffSession)
+ .is_off_session()
+}
+
/// Recovery payload is unified struct constructed from billing connectors
#[derive(Debug)]
pub struct RevenueRecoveryAttemptData {
@@ -34,8 +47,8 @@ pub struct RevenueRecoveryAttemptData {
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: String,
+ /// mandate token at payment processor end, absent for a transaction reported without its card.
+ pub processor_payment_method_token: Option<String>,
/// customer id at payment connector for which mandate is attached.
pub connector_customer_id: String,
/// Payment gateway identifier id at billing processor.
@@ -243,9 +256,11 @@ impl
.clone(),
error_code: billing_connector_payment_details.error_code.clone(),
error_message: billing_connector_payment_details.error_message.clone(),
- processor_payment_method_token: billing_connector_payment_details
- .processor_payment_method_token
- .clone(),
+ processor_payment_method_token: Some(
+ billing_connector_payment_details
+ .processor_payment_method_token
+ .clone(),
+ ),
connector_customer_id: billing_connector_payment_details
.connector_customer_id
.clone(),
diff --git a/crates/router/src/core/revenue_recovery/api.rs b/crates/router/src/core/revenue_recovery/api.rs
index fdfcb6c292..9ef2e818b7 100644
--- a/crates/router/src/core/revenue_recovery/api.rs
+++ b/crates/router/src/core/revenue_recovery/api.rs
@@ -316,6 +316,7 @@ pub async fn custom_revenue_recovery_core(
) -> RouterResponse<payments_api::RecoveryPaymentsCreateResponse> {
validate_recovery_amounts(&request)?;
validate_customer_information(&request)?;
+ validate_payment_method_data(&request)?;
let response = match RecoveryTrigger::from_profile_settings(
profile.revenue_recovery_trigger_model,
@@ -475,7 +476,8 @@ async fn record_transaction_and_schedule_retries(
Ok(updated_recovery_intent)
}
-/// Finds or creates the invoice of the transaction.
+/// Finds or creates the invoice of the transaction, refusing a transaction without its card that
+/// would start one.
pub(super) async fn get_or_create_invoice(
state: &SessionState,
req_state: &ReqState,
@@ -483,6 +485,32 @@ pub(super) async fn get_or_create_invoice(
profile: &domain::Profile,
request: &api_models::payments::RecoveryPaymentsCreate,
) -> RouterResult<hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent> {
+ find_or_create_invoice(state, req_state, platform, profile, request)
+ .await?
+ .ok_or_else(|| report!(card_needed_for_a_new_invoice()))
+}
+
+/// Finds or creates the invoice of the transaction. A transaction without its card cannot start
+/// an invoice, so there is none for it when Hyperswitch does not have the invoice yet.
+pub(super) async fn find_or_create_invoice(
+ state: &SessionState,
+ req_state: &ReqState,
+ platform: &Platform,
+ profile: &domain::Profile,
+ request: &api_models::payments::RecoveryPaymentsCreate,
+) -> RouterResult<Option<hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent>> {
+ if request.payment_method_data.is_none() {
+ return recovery_incoming::RevenueRecoveryInvoice::find_custom_recovery_intent(
+ request.clone(),
+ state,
+ req_state,
+ platform,
+ profile,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to read the invoice of the recovery request");
+ }
recovery_incoming::RevenueRecoveryInvoice::get_or_create_custom_recovery_intent(
request.clone(),
state,
@@ -491,6 +519,7 @@ pub(super) async fn get_or_create_invoice(
profile,
)
.await
+ .map(Some)
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: format!(
"Failed to load recovery intent for merchant reference id : {:?}",
@@ -594,6 +623,30 @@ pub async fn cancel_revenue_recovery_core(
))
}
+/// The card can be left out only when the customer is present and pays on session, as the merchant
+/// may then have none to send.
+fn validate_payment_method_data(
+ request: &api_models::payments::RecoveryPaymentsCreate,
+) -> RouterResult<()> {
+ let is_customer_present_on_session = request.customer_present
+ == Some(common_enums::PresenceOfCustomerDuringPayment::Present)
+ && request.setup_future_usage == Some(common_enums::FutureUsage::OnSession);
+ if request.payment_method_data.is_none() && !is_customer_present_on_session {
+ return Err(report!(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "payment_method_data".into(),
+ }));
+ }
+ Ok(())
+}
+
+/// A transaction reported without its card cannot start an invoice, which keeps the card to retry.
+pub(super) fn card_needed_for_a_new_invoice() -> errors::ApiErrorResponse {
+ errors::ApiErrorResponse::InvalidRequestData {
+ message: "payment_method_data is required for the first transaction of an invoice"
+ .to_string(),
+ }
+}
+
fn validate_customer_information(
request: &api_models::payments::RecoveryPaymentsCreate,
) -> RouterResult<()> {
diff --git a/crates/router/src/core/revenue_recovery/external_triggers.rs b/crates/router/src/core/revenue_recovery/external_triggers.rs
index 36029a1bfd..fdb2d13358 100644
--- a/crates/router/src/core/revenue_recovery/external_triggers.rs
+++ b/crates/router/src/core/revenue_recovery/external_triggers.rs
@@ -43,7 +43,7 @@ use crate::{
payment_attempt_record::PaymentAttemptRecord, ValidateStatusForOperation,
},
},
- webhooks::recovery_incoming::RevenueRecoveryAttempt,
+ webhooks::{self, recovery_incoming::RevenueRecoveryAttempt},
},
routes::{lock_utils, metrics, SessionState},
types::{
@@ -178,6 +178,9 @@ async fn decide_recovery_request_retry(
/// A charged card is healthy again, so its retry history starts over, as it does for the retries
/// Hyperswitch makes.
async fn reset_card_history_after_a_charge(state: &SessionState, request: &RecoveryPaymentsCreate) {
+ let Some(payment_method_data) = request.payment_method_data.as_ref() else {
+ return;
+ };
match request.transaction_status {
RecoveryTransactionStatus::Failure => {}
RecoveryTransactionStatus::Charged | RecoveryTransactionStatus::PartialCharged => {
@@ -188,8 +191,7 @@ async fn reset_card_history_after_a_charge(state: &SessionState, request: &Recov
&None,
&None,
Some(
- request
- .payment_method_data
+ payment_method_data
.primary_processor_payment_method_token
.peek()
.as_str(),
@@ -573,6 +575,8 @@ enum RecoveryRequestOutcome {
LimitsExhausted(RecoveryNoRetryReason),
/// Recorded, and no retry follows, for a reason that needs no webhook.
NoWebhook(RecoveryNoRetryReason),
+ /// Recorded and decided, with the next retry's reason, but the profile takes no webhooks.
+ WebhookDisabled(Option<RecoveryNoRetryReason>),
/// Made with the customer, so only recorded.
CustomerInitiated,
/// A newer recovery request of the invoice was applied first, so only recorded.
@@ -581,6 +585,9 @@ enum RecoveryRequestOutcome {
Duplicate,
/// The invoice is closed, so nothing is recorded.
InvoiceClosed,
+ /// The transaction has no card and Hyperswitch has no invoice for it yet, so nothing is
+ /// recorded: a new invoice needs the card to retry.
+ CardMissing,
/// The invoice does not show every attempt recorded on it, so nothing is decided.
InvoiceOutOfSync,
}
@@ -603,15 +610,33 @@ impl RecoveryRequestOutcome {
}
}
+ /// The webhook that tells the merchant the decision, for a decision that has one.
+ fn webhook_event(self) -> Option<common_enums::EventType> {
+ match self {
+ Self::RetryScheduled => Some(common_enums::EventType::RecoveryRetryScheduled),
+ Self::LimitsExhausted(_) => Some(common_enums::EventType::RecoveryLimitsExhausted),
+ Self::NoWebhook(_)
+ | Self::WebhookDisabled(_)
+ | Self::CustomerInitiated
+ | Self::Stale
+ | Self::Duplicate
+ | Self::InvoiceClosed
+ | Self::CardMissing
+ | Self::InvoiceOutOfSync => None,
+ }
+ }
+
fn name(self) -> &'static str {
match self {
Self::RetryScheduled => "retry_scheduled",
Self::LimitsExhausted(_) => "limits_exhausted",
Self::NoWebhook(_) => "no_webhook",
+ Self::WebhookDisabled(_) => "webhook_disabled",
Self::CustomerInitiated => "customer_initiated",
Self::Stale => "stale",
Self::Duplicate => "duplicate",
Self::InvoiceClosed => "invoice_closed",
+ Self::CardMissing => "card_missing",
Self::InvoiceOutOfSync => "invoice_out_of_sync",
}
}
@@ -619,11 +644,13 @@ impl RecoveryRequestOutcome {
fn reason(self) -> Option<RecoveryNoRetryReason> {
match self {
Self::LimitsExhausted(reason) | Self::NoWebhook(reason) => Some(reason),
+ Self::WebhookDisabled(reason) => reason,
Self::RetryScheduled
| Self::CustomerInitiated
| Self::Stale
| Self::Duplicate
| Self::InvoiceClosed
+ | Self::CardMissing
| Self::InvoiceOutOfSync => None,
}
}
@@ -633,10 +660,12 @@ impl RecoveryRequestOutcome {
Self::RetryScheduled => business_status::RECOVERY_REQUEST_RETRY_SCHEDULED,
Self::LimitsExhausted(_) => business_status::RECOVERY_REQUEST_LIMITS_EXHAUSTED,
Self::NoWebhook(_) => business_status::RECOVERY_REQUEST_NO_WEBHOOK,
+ Self::WebhookDisabled(_) => business_status::RECOVERY_REQUEST_WEBHOOK_DISABLED,
Self::CustomerInitiated => business_status::RECOVERY_REQUEST_CUSTOMER_INITIATED,
Self::Stale => business_status::RECOVERY_REQUEST_STALE,
Self::Duplicate => business_status::RECOVERY_REQUEST_DUPLICATE,
Self::InvoiceClosed => business_status::RECOVERY_REQUEST_INVOICE_CLOSED,
+ Self::CardMissing => business_status::RECOVERY_REQUEST_RECORDING_FAILED,
Self::InvoiceOutOfSync => business_status::RECOVERY_REQUEST_INVOICE_OUT_OF_SYNC,
}
}
@@ -828,10 +857,10 @@ async fn decrypt_recovery_request(
Ok(decrypted.into_inner().expose())
}
-/// Records a transaction the merchant reported and decides the next retry of its invoice. Called by
-/// the recovery request workflow: every outcome finishes the job here, apart from a wait for the
-/// invoice's lock, which puts the job back in the queue, and only a temporary error is returned, for
-/// the workflow to run the recovery request again.
+/// Records a transaction the merchant reported, decides the next retry of its invoice and tells the
+/// merchant by webhook. Called by the recovery request workflow: every outcome finishes the job here,
+/// apart from a wait for the invoice's lock, which puts the job back in the queue, and only a
+/// temporary error is returned, for the workflow to run the recovery request again.
#[instrument(
skip_all,
fields(
@@ -977,8 +1006,8 @@ async fn load_recovery_request_context(
Ok((platform, profile))
}
-/// Records the reported transaction and decides the next retry, under the invoice's lock. An error
-/// is temporary, and the recovery request runs again.
+/// Records the reported transaction, decides the next retry and tells the merchant, under the
+/// invoice's lock. An error is temporary, and the recovery request runs again.
async fn apply_recovery_request(
state: &SessionState,
tracking_data: &pcr::RecoveryRequestTrackingData,
@@ -988,9 +1017,12 @@ async fn apply_recovery_request(
retry_config: &RevenueRecoveryConfig,
) -> Result<RecoveryRequestOutcome, sch_errors::ProcessTrackerError> {
let req_state = state.get_req_state();
- let invoice = api::get_or_create_invoice(state, &req_state, platform, profile, request)
+ let Some(invoice) = api::find_or_create_invoice(state, &req_state, platform, profile, request)
.await
- .map_err(|error| recovery_request_step_failed("invoice", error))?;
+ .map_err(|error| recovery_request_step_failed("invoice", error))?
+ else {
+ return Ok(RecoveryRequestOutcome::CardMissing);
+ };
tracing::Span::current().record("payment_id", invoice.payment_id.get_string_repr());
let previous_recovery_metadata = invoice
@@ -1020,16 +1052,23 @@ async fn apply_recovery_request(
if let Some(saved_state) = previous_trigger_state.as_ref().filter(|trigger_state| {
trigger_state.last_recovery_request_id.as_deref() == Some(recovery_request_id)
}) {
- return Ok(RecoveryRequestOutcome::from_next_retry(
- &get_next_retry_for_intent_status(invoice.status, saved_state.next_retry),
- ));
+ return Box::pin(send_next_retry(
+ state,
+ platform,
+ profile,
+ tracking_data,
+ &invoice.payment_id,
+ get_next_retry_for_intent_status(invoice.status, saved_state.next_retry),
+ true,
+ ))
+ .await;
}
let recorded_on_invoice = previous_recovery_metadata
.map(|recovery_metadata| usize::from(recovery_metadata.total_retry_count));
- if recorded_on_invoice != Some(attempts.total) {
+ if recorded_on_invoice != Some(attempts.counted_as_retries) {
logger::error!(
?recorded_on_invoice,
- attempts = ?attempts.total,
+ attempts_counted_as_retries = ?attempts.counted_as_retries,
"The invoice does not show every attempt recorded on it"
);
return Ok(RecoveryRequestOutcome::InvoiceOutOfSync);
@@ -1064,7 +1103,10 @@ async fn apply_recovery_request(
reset_card_history_after_a_charge(state, request).await;
- if !is_merchant_initiated(request) {
+ if !hyperswitch_domain_models::revenue_recovery::is_merchant_initiated(
+ request.customer_present,
+ request.setup_future_usage,
+ ) {
return Ok(RecoveryRequestOutcome::CustomerInitiated);
}
if let Some(last_transaction_created_at) = previous_trigger_state
@@ -1083,13 +1125,17 @@ async fn apply_recovery_request(
}
let is_existing_invoice = attempts.earlier > 0;
- let is_same_card = attempts.previous_card.as_ref()
- == Some(
- request
- .payment_method_data
- .primary_processor_payment_method_token
- .peek(),
- );
+ let is_same_card = request
+ .payment_method_data
+ .as_ref()
+ .is_some_and(|payment_method_data| {
+ attempts.previous_retry_card.as_ref()
+ == Some(
+ payment_method_data
+ .primary_processor_payment_method_token
+ .peek(),
+ )
+ });
let payment_intent = read_invoice(state, platform, profile, &invoice.payment_id)
.await
.map_err(|error| recovery_request_step_failed("invoice", error))?;
@@ -1129,20 +1175,116 @@ async fn apply_recovery_request(
reason = ?next_retry.reason,
"Next retry of the invoice decided"
);
- Ok(RecoveryRequestOutcome::from_next_retry(&next_retry))
+ Box::pin(send_next_retry(
+ state,
+ platform,
+ profile,
+ tracking_data,
+ &invoice.payment_id,
+ next_retry,
+ false,
+ ))
+ .await
}
-/// Only a transaction made off session with the customer absent is merchant initiated. A request
-/// that leaves either out gets the defaults the invoice is created with.
-fn is_merchant_initiated(request: &RecoveryPaymentsCreate) -> bool {
- request
- .customer_present
- .unwrap_or(common_enums::PresenceOfCustomerDuringPayment::Absent)
- == common_enums::PresenceOfCustomerDuringPayment::Absent
- && request
- .setup_future_usage
- .unwrap_or(common_enums::FutureUsage::OffSession)
- .is_off_session()
+/// Tells the merchant the next retry of the invoice by webhook, for a decision that has one, and
+/// returns how the recovery request ends. The webhook's event is keyed by the recovery request. A
+/// later run answering from the decision an earlier run saved (`is_saved_decision`) sends it only
+/// if that run did not.
+async fn send_next_retry(
+ state: &SessionState,
+ platform: &Platform,
+ profile: &domain::Profile,
+ tracking_data: &pcr::RecoveryRequestTrackingData,
+ payment_id: &id_type::GlobalPaymentId,
+ next_retry: RecoveryNextRetry,
+ is_saved_decision: bool,
+) -> Result<RecoveryRequestOutcome, sch_errors::ProcessTrackerError> {
+ let outcome = RecoveryRequestOutcome::from_next_retry(&next_retry);
+ let Some(event_type) = outcome.webhook_event() else {
+ return Ok(outcome);
+ };
+ let webhook_recipient =
+ webhooks::utils::resolve_webhook_recipient_from_created_by(state, platform, profile, None)
+ .await
+ .map_err(|error| recovery_request_step_failed("webhook", error))?;
+ let idempotent_event_id = webhooks::utils::get_idempotent_event_id(
+ &tracking_data.recovery_request_id,
+ event_type,
+ common_enums::WebhookDeliveryAttempt::InitialAttempt,
+ )
+ .map_err(|error| recovery_request_step_failed("webhook", error))?;
+ let webhook_url = webhook_recipient
+ .profile
+ .get_webhook_url_from_profile()
+ .change_context(errors::WebhooksFlowError::MerchantWebhookUrlNotConfigured);
+ if webhooks::utils::is_outgoing_webhook_disabled(
+ state,
+ &webhook_url,
+ &webhook_recipient.profile,
+ &idempotent_event_id,
+ ) {
+ return Ok(RecoveryRequestOutcome::WebhookDisabled(next_retry.reason));
+ }
+ if is_saved_decision
+ && is_webhook_queued(state, platform, &webhook_recipient, &idempotent_event_id).await?
+ {
+ logger::info!(
+ %event_type,
+ %idempotent_event_id,
+ "Recovery webhook already queued by an earlier run of the recovery request"
+ );
+ return Ok(outcome);
+ }
+
+ Box::pin(webhooks::create_event_and_trigger_outgoing_webhook(
+ state.clone(),
+ platform.clone(),
+ event_type,
+ common_enums::EventClass::RevenueRecovery,
+ tracking_data.recovery_request_id.clone(),
+ common_enums::EventObjectType::RecoveryRetryDetails,
+ api_models::webhooks::OutgoingWebhookContent::RecoveryRetryDetails(Box::new(
+ api_models::payments::RecoveryRetryWebhookDetails {
+ id: payment_id.clone(),
+ merchant_reference_id: tracking_data.merchant_reference_id.clone(),
+ next_retry,
+ },
+ )),
+ tracking_data.received_at,
+ webhook_recipient,
+ ))
+ .await
+ .map_err(|error| recovery_request_step_failed("webhook", error))?;
+ metrics::REVENUE_RECOVERY_REQUEST_TIME_TO_WEBHOOK.record(
+ (common_utils::date_time::now() - tracking_data.received_at).as_seconds_f64(),
+ router_env::metric_attributes!(("outcome", outcome.name())),
+ );
+ logger::info!(%event_type, %idempotent_event_id, "Recovery webhook queued");
+ Ok(outcome)
+}
+
+/// Whether an earlier run of the recovery request already queued its webhook, which it stored as
+/// an event.
+async fn is_webhook_queued(
+ state: &SessionState,
+ platform: &Platform,
+ webhook_recipient: &webhooks::utils::WebhookRecipientContext,
+ idempotent_event_id: &str,
+) -> Result<bool, sch_errors::ProcessTrackerError> {
+ match state
+ .store
+ .find_event_by_merchant_id_idempotent_event_id(
+ platform.get_provider().get_account().get_id(),
+ idempotent_event_id,
+ &webhook_recipient.key_store,
+ )
+ .await
+ {
+ Ok(_) => Ok(true),
+ Err(error) if error.current_context().is_db_not_found() => Ok(false),
+ Err(error) => Err(recovery_request_step_failed("webhook", error)),
+ }
}
/// The invoice as it is now, read through the get intent operation.
@@ -1203,7 +1345,10 @@ async fn wait_for_invoice_lock(
state
.store
.as_scheduler()
- .finish_process_with_business_status(process.clone(), business_status::RETRIES_EXCEEDED)
+ .finish_process_with_business_status(
+ process.clone(),
+ business_status::RECOVERY_REQUEST_RECORDING_FAILED,
+ )
.await?;
record_recovery_request_outcome("retries_exceeded", None);
Ok(())
@@ -1224,12 +1369,18 @@ async fn finish_recovery_request(
match outcome {
RecoveryRequestOutcome::Stale
| RecoveryRequestOutcome::Duplicate
- | RecoveryRequestOutcome::InvoiceClosed => {
+ | RecoveryRequestOutcome::InvoiceClosed
+ | RecoveryRequestOutcome::CardMissing => {
logger::warn!(
outcome = outcome.name(),
"Recovery request ended without a decision"
)
}
+ RecoveryRequestOutcome::WebhookDisabled(reason) => logger::warn!(
+ ?reason,
+ "Recovery request decided, but the merchant is not told: outgoing webhooks are off or \
+ the profile has no webhook URL"
+ ),
RecoveryRequestOutcome::InvoiceOutOfSync => logger::error!(
outcome = outcome.name(),
"Recovery request not decided, as its invoice does not show every attempt recorded on \
@@ -1265,7 +1416,10 @@ pub(crate) async fn finish_failed_recovery_request(
state
.store
.as_scheduler()
- .finish_process_with_business_status(process.clone(), business_status::FAILURE)
+ .finish_process_with_business_status(
+ process.clone(),
+ business_status::RECOVERY_REQUEST_RECORDING_FAILED,
+ )
.await?;
record_recovery_request_outcome("failed", None);
Ok(())
@@ -1311,7 +1465,10 @@ pub(crate) async fn retry_recovery_request(
state
.store
.as_scheduler()
- .finish_process_with_business_status(process, business_status::RETRIES_EXCEEDED)
+ .finish_process_with_business_status(
+ process,
+ business_status::RECOVERY_REQUEST_RECORDING_FAILED,
+ )
.await
.change_context(sch_errors::ProcessTrackerError::ProcessUpdateFailed)?;
record_recovery_request_outcome("retries_exceeded", None);
diff --git a/crates/router/src/core/revenue_recovery/transformers.rs b/crates/router/src/core/revenue_recovery/transformers.rs
index e96f4d8be8..0e1f1da611 100644
--- a/crates/router/src/core/revenue_recovery/transformers.rs
+++ b/crates/router/src/core/revenue_recovery/transformers.rs
@@ -89,11 +89,14 @@ impl ForeignFrom<&api_models::payments::RecoveryPaymentsCreate>
)),
error_code: data.error.as_ref().map(|error| error.code.clone()),
error_message: data.error.as_ref().map(|error| error.message.clone()),
- processor_payment_method_token: data
- .payment_method_data
- .primary_processor_payment_method_token
- .peek()
- .to_string(),
+ processor_payment_method_token: data.payment_method_data.as_ref().map(
+ |payment_method_data| {
+ payment_method_data
+ .primary_processor_payment_method_token
+ .peek()
+ .to_string()
+ },
+ ),
connector_customer_id: data.connector_customer_id.peek().to_string(),
// Only the billing connector webhooks look up an account through this reference.
connector_account_reference_id: String::new(),
@@ -117,7 +120,11 @@ impl ForeignFrom<&api_models::payments::RecoveryPaymentsCreate>
retry_count: None,
invoice_next_billing_time: None,
invoice_billing_started_at_time: Some(data.billing_started_at),
- card_info: data.payment_method_data.payment_method_metadata.clone(),
+ card_info: data
+ .payment_method_data
+ .as_ref()
+ .map(|payment_method_data| payment_method_data.payment_method_metadata.clone())
+ .unwrap_or_default(),
charge_id: None,
}
}
diff --git a/crates/router/src/core/revenue_recovery/trigger_model.rs b/crates/router/src/core/revenue_recovery/trigger_model.rs
index 2f32b7a1ce..5fdaba03a1 100644
--- a/crates/router/src/core/revenue_recovery/trigger_model.rs
+++ b/crates/router/src/core/revenue_recovery/trigger_model.rs
@@ -49,12 +49,25 @@ impl RecoveryTrigger {
let connector = request.connector.get_required_value("connector")?;
// Profiles are refused without it, this holds for one saved before that check.
- retry_config.ok_or_else(|| {
+ let retry_config = retry_config.ok_or_else(|| {
report!(errors::ApiErrorResponse::PreconditionFailed {
message: "The `revenue_recovery_config` of the profile is required when its `revenue_recovery_trigger_model` is `external_triggers`".to_owned(),
})
})?;
+ // The invoice's grace window ends its grace period after billing started, so a
+ // billing start too late for that end to be a date is wrong.
+ request
+ .billing_started_at
+ .checked_add(time::Duration::days(i64::from(
+ retry_config.grace_period_days,
+ )))
+ .ok_or_else(|| {
+ report!(errors::ApiErrorResponse::InvalidRequestData {
+ message: "`billing_started_at` is wrong: the invoice's grace period would end after the latest date supported".to_owned(),
+ })
+ })?;
+
Ok(Self::External { connector })
}
}
diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rs
index c38ea593cc..80f9ecfef8 100644
--- a/crates/router/src/core/webhooks/recovery_incoming.rs
+++ b/crates/router/src/core/webhooks/recovery_incoming.rs
@@ -311,14 +311,52 @@ pub struct RecoveryRequestAttempts {
pub recorded: Option<revenue_recovery::RecoveryPaymentAttempt>,
/// How many attempts were recorded on the invoice before the transaction's.
pub earlier: usize,
- /// The processor token of the card of the last attempt recorded before the transaction's.
- pub previous_card: Option<String>,
- /// How many attempts the invoice has.
- pub total: usize,
+ /// The card of the last merchant-initiated attempt recorded before the transaction's: the card
+ /// the invoice's last decision, and its error code, were for.
+ pub previous_retry_card: Option<String>,
+ /// How many of the invoice's attempts count as retries.
+ pub counted_as_retries: usize,
}
#[derive(Debug)]
pub struct RevenueRecoveryAttempt(revenue_recovery::RevenueRecoveryAttemptData);
+/// Whether the merchant initiated an attempt, by what it was recorded with.
+#[cfg(feature = "v2")]
+fn is_merchant_initiated_attempt(attempt: &api_payments::PaymentAttemptResponse) -> bool {
+ attempt
+ .feature_metadata
+ .as_ref()
+ .and_then(|feature_metadata| feature_metadata.revenue_recovery.as_ref())
+ .is_none_or(|recovery_data| {
+ revenue_recovery::is_merchant_initiated(
+ recovery_data.customer_present,
+ recovery_data.setup_future_usage,
+ )
+ })
+}
+
+/// How many of an invoice's attempts count as retries, replayed in the order they were made: every
+/// merchant-initiated one, and a customer-initiated one on the invoice's card at the time. The first
+/// attempt's card is the invoice's until a merchant-initiated attempt brings its own.
+#[cfg(feature = "v2")]
+fn count_retries(attempts: &[api_payments::PaymentAttemptResponse]) -> usize {
+ let mut attempts: Vec<&api_payments::PaymentAttemptResponse> = attempts.iter().collect();
+ attempts.sort_by_key(|attempt| attempt.created_at);
+ let mut invoice_card: Option<&String> = None;
+ let mut retries = 0;
+ for attempt in attempts {
+ let card = attempt.payment_token.as_ref();
+ let is_merchant_initiated = is_merchant_initiated_attempt(attempt);
+ if is_merchant_initiated || invoice_card.is_none() || card == invoice_card {
+ retries += 1;
+ }
+ if card.is_some() && (is_merchant_initiated || invoice_card.is_none()) {
+ invoice_card = card;
+ }
+ }
+ retries
+}
+
impl RevenueRecoveryInvoice {
pub async fn get_or_create_custom_recovery_intent(
data: api_models::payments::RecoveryPaymentsCreate,
@@ -342,6 +380,22 @@ impl RevenueRecoveryInvoice {
.await
}
+ /// The invoice of a transaction the merchant reported, when Hyperswitch already has it.
+ pub async fn find_custom_recovery_intent(
+ data: api_models::payments::RecoveryPaymentsCreate,
+ state: &SessionState,
+ req_state: &ReqState,
+ platform: &domain::Platform,
+ profile: &domain::Profile,
+ ) -> CustomResult<Option<revenue_recovery::RecoveryPaymentIntent>, errors::RevenueRecoveryError>
+ {
+ Self(revenue_recovery::RevenueRecoveryInvoiceData::foreign_from(
+ data,
+ ))
+ .get_payment_intent(state, req_state, platform, profile)
+ .await
+ }
+
/// Fills in partial authorization from the billing connector account when the invoice
/// itself does not carry a value.
fn with_default_partial_authorization(mut self, default: bool) -> Self {
@@ -557,10 +611,12 @@ impl RevenueRecoveryAttempt {
recorded_at.is_none_or(|recorded_at| attempt.created_at < recorded_at)
})
.collect();
- let previous_card = earlier
+ let previous_retry_card = earlier
.iter()
+ .filter(|attempt| is_merchant_initiated_attempt(attempt))
.max_by_key(|attempt| attempt.created_at)
.and_then(|attempt| attempt.payment_token.clone());
+ let counted_as_retries = count_retries(&attempts.payment_attempt_list);
let recorded = match listed {
Some(attempt) => Some(recovery_attempt.to_recovery_attempt(state, attempt).await),
None => None,
@@ -568,8 +624,8 @@ impl RevenueRecoveryAttempt {
Ok(RecoveryRequestAttempts {
recorded,
earlier: earlier.len(),
- previous_card,
- total: attempts.payment_attempt_list.len(),
+ previous_retry_card,
+ counted_as_retries,
})
}
@@ -924,7 +980,23 @@ impl RevenueRecoveryAttempt {
}
}?;
- if recovery_attempt.attempt_status.is_terminal_status() {
+ // The invoice's last error code is for its card, so a transaction the merchant reported on
+ // another card is not counted against it.
+ let invoice_card = payment_intent
+ .feature_metadata
+ .as_ref()
+ .and_then(|feature_metadata| feature_metadata.revenue_recovery.as_ref())
+ .map(|recovery_metadata| {
+ &recovery_metadata
+ .billing_connector_payment_details
+ .payment_processor_token
+ });
+ let is_on_invoice_card = !matches!(
+ connector_details,
+ common_types::payments::RecoveryConnectorDetails::ReportedByMerchant { .. }
+ ) || invoice_card
+ .is_none_or(|card| self.0.processor_payment_method_token.as_ref() == Some(card));
+ if recovery_attempt.attempt_status.is_terminal_status() && is_on_invoice_card {
retry_stats::RetryOutcomeEvent::from_retry_outcome(
recovery_attempt.created_at,
payment_intent
@@ -1047,7 +1119,10 @@ impl RevenueRecoveryAttempt {
.clone(),
payment_method_type: revenue_recovery_attempt_data.payment_method_type,
payment_method_subtype: revenue_recovery_attempt_data.payment_method_sub_type,
- payment_method_data: Some(payment_method_data),
+ payment_method_data: revenue_recovery_attempt_data
+ .processor_payment_method_token
+ .is_some()
+ .then_some(payment_method_data),
metadata: None,
feature_metadata: Some(feature_metadata),
transaction_created_at: revenue_recovery_attempt_data.transaction_created_at,
@@ -1187,6 +1262,12 @@ impl RevenueRecoveryAttempt {
payment_connector: common_enums::connector_enums::Connector,
) -> CustomResult<(), errors::RevenueRecoveryError> {
let revenue_recovery_attempt_data = &self.0;
+ let Some(payment_processor_token) = revenue_recovery_attempt_data
+ .processor_payment_method_token
+ .clone()
+ else {
+ return Ok(());
+ };
let error_code = revenue_recovery_attempt_data.error_code.clone();
let error_message = revenue_recovery_attempt_data.error_message.clone();
@@ -1233,9 +1314,7 @@ impl RevenueRecoveryAttempt {
is_hard_decline: Some(is_hard_decline),
modified_at: Some(recovery_attempt.created_at),
payment_processor_token_details: PaymentProcessorTokenDetails {
- payment_processor_token: revenue_recovery_attempt_data
- .processor_payment_method_token
- .clone(),
+ payment_processor_token,
expiry_month: revenue_recovery_attempt_data
.card_info
.card_exp_month
diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs
index 7c2de5bdb3..1249cc2f19 100644
--- a/crates/router/src/routes/metrics.rs
+++ b/crates/router/src/routes/metrics.rs
@@ -397,8 +397,9 @@ counter_metric!(
GLOBAL_METER,
name: "revenue_recovery.recovery_request.outcome",
description: "Recovery requests by how their workflow ended (retry_scheduled, \
- limits_exhausted, no_webhook, customer_initiated, stale, duplicate, \
- invoice_closed, retries_exceeded, failed), with the next retry `reason`",
+ limits_exhausted, no_webhook, webhook_disabled, customer_initiated, stale, \
+ duplicate, invoice_closed, card_missing, retries_exceeded, failed), with \
+ the next retry `reason`",
unit: "1",
);
counter_metric!(
@@ -420,6 +421,17 @@ histogram_metric_f64!(
1.0, 5.0, 15.0, 30.0, 60.0, 120.0, 300.0, 600.0, 900.0, 1800.0, 3600.0
],
);
+histogram_metric_f64!(
+ REVENUE_RECOVERY_REQUEST_TIME_TO_WEBHOOK,
+ GLOBAL_METER,
+ name: "revenue_recovery.recovery_request.time_to_webhook",
+ description: "Seconds from the API accepting a recovery request to the webhook with its next \
+ retry being queued, once per request, by `outcome`",
+ unit: "s",
+ boundaries: vec![
+ 1.0, 5.0, 15.0, 30.0, 60.0, 120.0, 300.0, 600.0, 900.0, 1800.0, 3600.0
+ ],
+);
// Analytics reports generated by the process tracker
counter_metric!(
diff --git a/crates/router/src/workflows/recovery_request.rs b/crates/router/src/workflows/recovery_request.rs
index 3fe90a0fad..19fb0b1669 100644
--- a/crates/router/src/workflows/recovery_request.rs
+++ b/crates/router/src/workflows/recovery_request.rs
@@ -1,5 +1,6 @@
//! The recovery request workflow, which records a transaction the merchant reported on a profile
-//! whose retries it triggers, and decides the next retry of its invoice.
+//! whose retries it triggers, decides the next retry of its invoice, and tells the merchant by
+//! webhook.
use common_utils::errors::CustomResult;
#[cfg(feature = "v2")]