Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(revenue_recovery): add DisputeRecordBack flow and implement it for Chargebee (#13919)
CHALLA NISHANTH BABUd8a07c8d30ef
diff --git a/config/config.example.toml b/config/config.example.tomlindex 988753fce0..50f032bac1 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -1482,6 +1482,9 @@ base_url = "http://127.0.0.1:8080" #Base URL[billing_connectors_invoice_sync]billing_connectors_which_requires_invoice_sync_call = "recurly" # List of billing connectors which has invoice sync api call+[billing_connectors_dispute_record_back]+billing_connectors_which_requires_dispute_record_back_call = "chargebee" # List of billing connectors which support the dispute record back api call+[revenue_recovery]monitoring_threshold_in_seconds = 60 # 60 secs , threshold for monitoring the retry systemretry_algorithm_type = "cascading" # type of retry algorithmdiff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.tomlindex 378ad74fc0..e612a6e572 100644--- a/config/deployments/integration_test.toml+++ b/config/deployments/integration_test.toml@@ -1037,6 +1037,9 @@ billing_connectors_which_require_payment_sync = "stripebilling, recurly"[billing_connectors_invoice_sync]billing_connectors_which_requires_invoice_sync_call = "recurly"+[billing_connectors_dispute_record_back]+billing_connectors_which_requires_dispute_record_back_call = "chargebee"+[authentication_providers]click_to_pay = {connector_list = "adyen, cybersource, trustpay"}diff --git a/config/deployments/production.toml b/config/deployments/production.tomlindex 2679178c6d..22c9ab0c8a 100644--- a/config/deployments/production.toml+++ b/config/deployments/production.toml@@ -1048,6 +1048,9 @@ billing_connectors_which_require_payment_sync = "stripebilling, recurly"[billing_connectors_invoice_sync]billing_connectors_which_requires_invoice_sync_call = "recurly"+[billing_connectors_dispute_record_back]+billing_connectors_which_requires_dispute_record_back_call = "chargebee"+[authentication_providers]click_to_pay = {connector_list = "adyen, cybersource, trustpay"}diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.tomlindex afb38143b9..e3f35ff9eb 100644--- a/config/deployments/sandbox.toml+++ b/config/deployments/sandbox.toml@@ -1056,6 +1056,9 @@ billing_connectors_which_require_payment_sync = "stripebilling, recurly"[billing_connectors_invoice_sync]billing_connectors_which_requires_invoice_sync_call = "recurly"+[billing_connectors_dispute_record_back]+billing_connectors_which_requires_dispute_record_back_call = "chargebee"+[authentication_providers]click_to_pay = {connector_list = "adyen, cybersource, trustpay"}diff --git a/config/development.toml b/config/development.tomlindex 40ac9a9ec5..de53d02f62 100644--- a/config/development.toml+++ b/config/development.toml@@ -1262,6 +1262,9 @@ billing_connectors_which_require_payment_sync = "stripebilling, recurly"[billing_connectors_invoice_sync]billing_connectors_which_requires_invoice_sync_call = "recurly"+[billing_connectors_dispute_record_back]+billing_connectors_which_requires_dispute_record_back_call = "chargebee"+[zero_mandates.supported_payment_methods]bank_debit.ach = { connector_list = "gocardless,adyen,payload" }bank_debit.becs = { connector_list = "gocardless,adyen" }diff --git a/config/docker_compose.toml b/config/docker_compose.tomlindex e94e9817f8..690fdba633 100644--- a/config/docker_compose.toml+++ b/config/docker_compose.toml@@ -498,6 +498,9 @@ billing_connectors_which_require_payment_sync = "stripebilling, recurly"[billing_connectors_invoice_sync]billing_connectors_which_requires_invoice_sync_call = "recurly"+[billing_connectors_dispute_record_back]+billing_connectors_which_requires_dispute_record_back_call = "chargebee"+[scheduler]stream = "SCHEDULER_STREAM"diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rsindex ed2267c582..1bf2a92e5d 100644--- a/crates/diesel_models/src/payment_attempt.rs+++ b/crates/diesel_models/src/payment_attempt.rs@@ -4665,6 +4665,9 @@ pub struct PaymentAttemptRecoveryData {pub attempt_triggered_by: common_enums::TriggeredBy,// stripe specific field used to identify duplicate attempts.pub charge_id: Option<String>,+ /// Transaction id returned by the billing connector when the payment was recorded+ /// back to it. Used to issue an offline refund if a dispute is later lost.+ pub billing_connector_transaction_id: Option<String>,}#[cfg(feature = "v2")]common_utils::impl_to_sql_from_sql_json!(PaymentAttemptFeatureMetadata);diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee.rs b/crates/hyperswitch_connectors/src/connectors/chargebee.rsindex b6a9efc1b1..2d68a74b24 100644--- a/crates/hyperswitch_connectors/src/connectors/chargebee.rs+++ b/crates/hyperswitch_connectors/src/connectors/chargebee.rs@@ -23,7 +23,7 @@ use hyperswitch_domain_models::{access_token_auth::AccessTokenAuth,payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},refunds::{Execute, RSync},- revenue_recovery::InvoiceRecordBack,+ revenue_recovery::{DisputeRecordBack, InvoiceRecordBack},subscriptions::{GetSubscriptionEstimate, GetSubscriptionItemPrices, GetSubscriptionItems,SubscriptionCancel, SubscriptionCreate, SubscriptionPause, SubscriptionResume,@@ -31,7 +31,7 @@ use hyperswitch_domain_models::{CreateConnectorCustomer,},router_request_types::{- revenue_recovery::InvoiceRecordBackRequest,+ revenue_recovery::{DisputeRecordBackRequest, InvoiceRecordBackRequest},subscriptions::{GetSubscriptionEstimateRequest, GetSubscriptionItemPricesRequest,GetSubscriptionItemsRequest, SubscriptionCancelRequest, SubscriptionCreateRequest,@@ -42,7 +42,7 @@ use hyperswitch_domain_models::{PaymentsSyncData, RefundsData, SetupMandateRequestData,},router_response_types::{- revenue_recovery::InvoiceRecordBackResponse,+ revenue_recovery::{DisputeRecordBackResponse, InvoiceRecordBackResponse},subscriptions::{GetSubscriptionEstimateResponse, GetSubscriptionItemPricesResponse,GetSubscriptionItemsResponse, SubscriptionCancelResponse, SubscriptionCreateResponse,@@ -51,12 +51,12 @@ use hyperswitch_domain_models::{ConnectorInfo, PaymentsResponseData, RefundsResponseData,},types::{- ConnectorCustomerRouterData, GetSubscriptionEstimateRouterData,- GetSubscriptionItemsRouterData, GetSubscriptionPlanPricesRouterData,- InvoiceRecordBackRouterData, PaymentsAuthorizeRouterData, PaymentsCaptureRouterData,- PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,- SubscriptionCancelRouterData, SubscriptionCreateRouterData, SubscriptionPauseRouterData,- SubscriptionResumeRouterData,+ ConnectorCustomerRouterData, DisputeRecordBackRouterData,+ GetSubscriptionEstimateRouterData, GetSubscriptionItemsRouterData,+ GetSubscriptionPlanPricesRouterData, InvoiceRecordBackRouterData,+ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,+ RefundSyncRouterData, RefundsRouterData, SubscriptionCancelRouterData,+ SubscriptionCreateRouterData, SubscriptionPauseRouterData, SubscriptionResumeRouterData,},};use hyperswitch_interfaces::{@@ -115,6 +115,8 @@ impl api::subscriptions::Subscriptions for Chargebee {}#[cfg(all(feature = "v2", feature = "revenue_recovery"))]impl api::revenue_recovery::RevenueRecoveryRecordBack for Chargebee {}+#[cfg(all(feature = "v2", feature = "revenue_recovery"))]+impl api::revenue_recovery::RevenueRecoveryDisputeRecordBack for Chargebee {}fn build_chargebee_url<Flow, Request, Response>(connector: &Chargebee,@@ -501,6 +503,16 @@ fn build_connector_customer_request_body(Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))}+fn build_dispute_record_back_request_body(+ _connector: &Chargebee,+ req: &DisputeRecordBackRouterData,+) -> CustomResult<RequestContent, errors::ConnectorError> {+ // The dispute amount is already in minor units, which is what Chargebee wants, so+ // there is nothing to convert.+ let connector_req = chargebee::ChargebeeRecordRefundRequest::try_from(req)?;+ Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))+}+fn build_invoice_record_back_request_body(connector: &Chargebee,req: &InvoiceRecordBackRouterData,@@ -573,6 +585,18 @@ impl_chargebee_integration!(request_body: build_invoice_record_back_request_body);+impl_chargebee_integration!(+ flow: DisputeRecordBack,+ flow_type: types::DisputeRecordBackType,+ request: DisputeRecordBackRequest,+ response: DisputeRecordBackResponse,+ router_data: DisputeRecordBackRouterData,+ connector_response: chargebee::ChargebeeRecordRefundResponse,+ url_path: |req| Some(format!("v2/invoices/{}/record_refund", req.request.merchant_reference_id.get_string_repr())),+ method: Method::Post,+ request_body: build_dispute_record_back_request_body+);+fn get_chargebee_subscription_items_query_params(req: &GetSubscriptionItemsRouterData,) -> CustomResult<String, errors::ConnectorError> {diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rsindex d397ad149d..ff57f53428 100644--- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs@@ -19,7 +19,7 @@ use hyperswitch_domain_models::{router_flow_types::refunds::{Execute, RSync},router_request_types::{subscriptions::SubscriptionAutoCollection, ResponseId},router_response_types::{- revenue_recovery::InvoiceRecordBackResponse,+ revenue_recovery::{DisputeRecordBackResponse, InvoiceRecordBackResponse},subscriptions::{self, GetSubscriptionEstimateResponse, GetSubscriptionItemPricesResponse,GetSubscriptionItemsResponse, SubscriptionCancelResponse, SubscriptionCreateResponse,@@ -29,9 +29,9 @@ use hyperswitch_domain_models::{ConnectorCustomerResponseData, PaymentsResponseData, RefundsResponseData,},types::{- GetSubscriptionEstimateRouterData, InvoiceRecordBackRouterData,- PaymentsAuthorizeRouterData, RefundsRouterData, SubscriptionCancelRouterData,- SubscriptionPauseRouterData, SubscriptionResumeRouterData,+ DisputeRecordBackRouterData, GetSubscriptionEstimateRouterData,+ InvoiceRecordBackRouterData, PaymentsAuthorizeRouterData, RefundsRouterData,+ SubscriptionCancelRouterData, SubscriptionPauseRouterData, SubscriptionResumeRouterData,},};use hyperswitch_interfaces::errors;@@ -1203,8 +1203,86 @@ impl TryFrom<enums::AttemptStatus> for ChargebeeRecordStatus {#[derive(Debug, Deserialize, Serialize, Clone)]pub struct ChargebeeRecordbackResponse {pub invoice: ChargebeeRecordbackInvoice,+ /// Chargebee creates a transaction for the recorded payment and returns it alongside+ /// the invoice. Its id is the only handle `record_refund` accepts.+ pub transaction: Option<ChargebeeRecordbackTransaction>,}+#[derive(Debug, Deserialize, Serialize, Clone)]+pub struct ChargebeeRecordbackTransaction {+ pub id: String,+}++/// Body for `POST v2/transactions/{id}/record_refund`.+///+/// Unlike `record_payment`, whose parameters Chargebee documents nested under+/// `transaction[...]`, `record_refund` takes them flat.+#[derive(Debug, Serialize, Clone)]+pub struct ChargebeeRecordRefundRequest {+ #[serde(rename = "transaction[amount]")]+ pub amount: MinorUnit,+ #[serde(rename = "transaction[payment_method]")]+ pub payment_method: ChargebeeRefundPaymentMethod,+ /// Chargebee expects a UTC unix timestamp in seconds.+ #[serde(rename = "transaction[date]")]+ pub date: i64,+ /// The payment transaction this refund reverses, so the Chargebee record points back+ /// at it. Chargebee caps this at 100 characters.+ #[serde(+ rename = "transaction[reference_number]",+ skip_serializing_if = "Option::is_none"+ )]+ pub reference_number: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub comment: Option<String>,+}++#[derive(Debug, Serialize, Clone, Copy)]+#[serde(rename_all = "snake_case")]+pub enum ChargebeeRefundPaymentMethod {+ /// A lost dispute is literally a chargeback, so Chargebee's own reporting attributes+ /// the refund correctly rather than lumping it under "other".+ Chargeback,+}++impl TryFrom<&DisputeRecordBackRouterData> for ChargebeeRecordRefundRequest {+ type Error = error_stack::Report<errors::ConnectorError>;+ fn try_from(item: &DisputeRecordBackRouterData) -> Result<Self, Self::Error> {+ let req = &item.request;+ Ok(Self {+ // Already in minor units, which is what Chargebee wants; no conversion needed.+ amount: req.amount,+ payment_method: ChargebeeRefundPaymentMethod::Chargeback,+ date: req.refund_date.assume_utc().unix_timestamp(),+ reference_number: Some(req.billing_connector_transaction_id.clone()),+ comment: req.comment.clone(),+ })+ }+}++#[derive(Debug, Deserialize, Serialize, Clone)]+pub struct ChargebeeRecordRefundResponse {+ pub transaction: ChargebeeRefundTransaction,+}++#[derive(Debug, Deserialize, Serialize, Clone)]+pub struct ChargebeeRefundTransaction {+ pub id: String,+}++convert_connector_response_to_domain_response!(+ ChargebeeRecordRefundResponse,+ DisputeRecordBackResponse,+ |item: ResponseRouterData<_, ChargebeeRecordRefundResponse, _, _>| {+ Ok(Self {+ response: Ok(DisputeRecordBackResponse {+ connector_refund_id: item.response.transaction.id,+ }),+ ..item.data+ })+ }+);+#[derive(Debug, Deserialize, Serialize, Clone)]pub struct ChargebeeRecordbackInvoice {pub id: common_utils::id_type::PaymentReferenceId,@@ -1215,9 +1293,11 @@ convert_connector_response_to_domain_response!(InvoiceRecordBackResponse,|item: ResponseRouterData<_, ChargebeeRecordbackResponse, _, _>| {let merchant_reference_id = item.response.invoice.id;+ let connector_transaction_id = item.response.transaction.map(|txn| txn.id);Ok(Self {response: Ok(InvoiceRecordBackResponse {merchant_reference_id,+ connector_transaction_id,}),..item.data})diff --git a/crates/hyperswitch_connectors/src/connectors/recurly.rs b/crates/hyperswitch_connectors/src/connectors/recurly.rsindex 3eb4692869..089b43390a 100644--- a/crates/hyperswitch_connectors/src/connectors/recurly.rs+++ b/crates/hyperswitch_connectors/src/connectors/recurly.rs@@ -280,6 +280,19 @@ impl#[cfg(all(feature = "v2", feature = "revenue_recovery"))]impl api::revenue_recovery_v2::RevenueRecoveryRecordBackV2 for Recurly {}+// Recurly does not support recording a dispute back; it takes the unimplemented default.+#[cfg(all(feature = "v2", feature = "revenue_recovery"))]+impl api::revenue_recovery_v2::RevenueRecoveryDisputeRecordBackV2 for Recurly {}+#[cfg(all(feature = "v2", feature = "revenue_recovery"))]+impl+ ConnectorIntegrationV2<+ recovery_router_flows::DisputeRecordBack,+ recovery_flow_common_types::DisputeRecordBackData,+ recovery_request_types::DisputeRecordBackRequest,+ recovery_response_types::DisputeRecordBackResponse,+ > for Recurly+{+}#[cfg(all(feature = "v2", feature = "revenue_recovery"))]impl api::revenue_recovery_v2::BillingConnectorPaymentsSyncIntegrationV2 for Recurly {}#[cfg(all(feature = "v2", feature = "revenue_recovery"))]diff --git a/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs b/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rsindex d7598d641f..fbc3dbb77e 100644--- a/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs@@ -341,6 +341,8 @@ implOk(Self {response: Ok(recovery_response_types::InvoiceRecordBackResponse {merchant_reference_id,+ // Recurly's record-back does not return a usable transaction id.+ connector_transaction_id: None,}),..item.data})diff --git a/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rsindex c96ff9ac6c..b80cd6f41d 100644--- a/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs@@ -659,6 +659,8 @@ impl.change_context(errors::ConnectorError::MissingRequiredField {field_name: "invoice_id in the response",})?,+ // Stripe Billing's record-back does not return a usable transaction id.+ connector_transaction_id: None,}),..item.data})diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rsindex 13fc3d345b..33d85c15f8 100644--- a/crates/hyperswitch_connectors/src/default_implementations.rs+++ b/crates/hyperswitch_connectors/src/default_implementations.rs@@ -120,6 +120,12 @@ use hyperswitch_domain_models::{router_request_types::PayoutsData,router_response_types::PayoutsResponseData,};+#[cfg(all(feature = "v2", feature = "revenue_recovery"))]+use hyperswitch_domain_models::{+ router_flow_types::DisputeRecordBack,+ router_request_types::revenue_recovery::DisputeRecordBackRequest,+ router_response_types::revenue_recovery::DisputeRecordBackResponse,+};#[cfg(feature = "frm")]use hyperswitch_interfaces::api::fraud_check::{FraudCheck, FraudCheckCheckout, FraudCheckFulfillment, FraudCheckRecordReturn, FraudCheckSale,@@ -135,6 +141,7 @@ use hyperswitch_interfaces::api::revenue_recovery as recovery_traits;#[cfg(all(feature = "v2", feature = "revenue_recovery"))]use hyperswitch_interfaces::api::revenue_recovery::{BillingConnectorInvoiceSyncIntegration, BillingConnectorPaymentsSyncIntegration,+ RevenueRecoveryDisputeRecordBack,};#[cfg(feature = "dummy_connector")]use hyperswitch_interfaces::api::ConnectorVerifyWebhookSource;@@ -8876,6 +8883,181 @@ macro_rules! default_imp_for_revenue_recovery {};}+/// Every connector in the `default_imp_for_revenue_recovery!` list needs a+/// `RevenueRecoveryDisputeRecordBack` impl, because `RevenueRecovery` requires it as a+/// supertrait. Chargebee is the sole exception — it has a real implementation — so this+/// list is the umbrella list minus Chargebee.+#[cfg(all(feature = "v2", feature = "revenue_recovery"))]+macro_rules! default_imp_for_revenue_recovery_dispute_record_back {+ ($($path:ident::$connector:ident),*) => {+ $( impl RevenueRecoveryDisputeRecordBack for $path::$connector {}+ impl+ ConnectorIntegration<+ DisputeRecordBack,+ DisputeRecordBackRequest,+ DisputeRecordBackResponse,+ > for $path::$connector+ {}+ )*+ };+}++#[cfg(all(feature = "v2", feature = "revenue_recovery"))]+default_imp_for_revenue_recovery_dispute_record_back!(+ connectors::Vgs,+ connectors::AbsaSanlam,+ connectors::Aci,+ connectors::Adyen,+ connectors::Adyenplatform,+ connectors::Affirm,+ connectors::Airwallex,+ connectors::Amazonpay,+ connectors::Archipel,+ connectors::Authipay,+ connectors::Authorizedotnet,+ connectors::Bambora,+ connectors::Bamboraapac,+ connectors::Bankofamerica,+ connectors::Barclaycard,+ connectors::Billwerk,+ connectors::Bluesnap,+ connectors::Bitpay,+ connectors::Blackhawknetwork,+ connectors::Calida,+ connectors::Braintree,+ connectors::Boku,+ connectors::Breadpay,+ connectors::Cashtocode,+ connectors::Celero,+ connectors::Checkbook,+ connectors::Checkout,+ connectors::Coinbase,+ connectors::Coingate,+ connectors::Cryptopay,+ connectors::CtpMastercard,+ connectors::Custombilling,+ connectors::Cybersource,+ connectors::Cybersourcedecisionmanager,+ connectors::Datatrans,+ connectors::Deutschebank,+ connectors::Digitalvirgo,+ connectors::Dlocal,+ connectors::Dwolla,+ connectors::Ebanx,+ connectors::Elavon,+ connectors::Envoy,+ connectors::Facilitapay,+ connectors::Finix,+ connectors::Fiserv,+ connectors::Fiservcommercehub,+ connectors::Fiservemea,+ connectors::Fiuu,+ connectors::Flexiti,+ connectors::Forte,+ connectors::Getnet,+ connectors::Gigadat,+ connectors::Givepayments,+ connectors::Globalpay,+ connectors::Globepay,+ connectors::Gocardless,+ connectors::GotymeSanlam,+ connectors::Gpayments,+ connectors::Hipay,+ connectors::Hyperpg,+ connectors::Helcim,+ connectors::HyperswitchVault,+ connectors::Hyperwallet,+ connectors::Iatapay,+ connectors::Ilixium,+ connectors::Imerchantsolutions,+ connectors::Inespay,+ connectors::Interpayments,+ connectors::Itaubank,+ connectors::Jpmorgan,+ connectors::Juspaythreedsserver,+ connectors::Katapult,+ connectors::Klarna,+ connectors::Loonio,+ connectors::Netcetera,+ connectors::Nmi,+ connectors::Nomupay,+ connectors::Noon,+ connectors::Nordea,+ connectors::Novalnet,+ connectors::Nexinets,+ connectors::Nexixpay,+ connectors::Payconex,+ connectors::Citigate,+ connectors::Nuvei,+ connectors::Opayo,+ connectors::Opennode,+ connectors::Payeezy,+ connectors::Payjustnow,+ connectors::Payjustnowinstore,+ connectors::Payload,+ connectors::Paystack,+ connectors::Paytm,+ connectors::Payu,+ connectors::Peachpayments,+ connectors::Phonepe,+ connectors::Paypal,+ connectors::Paysafe,+ connectors::Powertranz,+ connectors::Prophetpay,+ connectors::Mifinity,+ connectors::Mollie,+ connectors::Moneris,+ connectors::Mpgs,+ connectors::Multisafepay,+ connectors::Paybox,+ connectors::Payme,+ connectors::Payone,+ connectors::Placetopay,+ connectors::Plaid,+ connectors::Rapyd,+ connectors::Razorpay,+ connectors::Recurly,+ connectors::Redsys,+ connectors::Revolv3,+ connectors::TsysTransit,+ connectors::Riskified,+ connectors::Santander,+ connectors::Shift4,+ connectors::Sift,+ connectors::Silverflow,+ connectors::Signifyd,+ connectors::Stax,+ connectors::Stripe,+ connectors::Square,+ connectors::Stripebilling,+ connectors::Taxjar,+ connectors::Tesouro,+ connectors::Threedsecureio,+ connectors::Thunes,+ connectors::Tokenex,+ connectors::Tokenio,+ connectors::Truelayer,+ connectors::Trustly,+ connectors::Trustpay,+ connectors::Trustpayments,+ connectors::Tsys,+ connectors::UnifiedAuthenticationService,+ connectors::Wise,+ connectors::Worldline,+ connectors::Worldpay,+ connectors::Worldpaymodular,+ connectors::Worldpayvantiv,+ connectors::Worldpayraft,+ connectors::Worldpayxml,+ connectors::Wellsfargo,+ connectors::Wellsfargopayout,+ connectors::Volt,+ connectors::Xendit,+ connectors::Zift,+ connectors::Zen,+ connectors::Zsl+);+default_imp_for_revenue_recovery!(connectors::Vgs,connectors::AbsaSanlam,@@ -11928,6 +12110,16 @@ impl<const T: u8> api::revenue_recovery::RevenueRecoveryRecordBack}#[cfg(all(feature = "v2", feature = "revenue_recovery"))]#[cfg(feature = "dummy_connector")]+impl<const T: u8> RevenueRecoveryDisputeRecordBack for connectors::DummyConnector<T> {}+#[cfg(all(feature = "v2", feature = "revenue_recovery"))]+#[cfg(feature = "dummy_connector")]+impl<const T: u8>+ ConnectorIntegration<DisputeRecordBack, DisputeRecordBackRequest, DisputeRecordBackResponse>+ for connectors::DummyConnector<T>+{+}+#[cfg(all(feature = "v2", feature = "revenue_recovery"))]+#[cfg(feature = "dummy_connector")]impl<const T: u8>ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse>for connectors::DummyConnector<T>diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rsindex 30355e355a..ac3b4d70c3 100644--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs@@ -3,9 +3,9 @@ use hyperswitch_domain_models::{router_data_v2::{flow_common_types::{BillingConnectorInvoiceSyncFlowData, BillingConnectorPaymentsSyncFlowData,- ConnectorWebhookConfigurationFlowData, DisputesFlowData, GiftCardBalanceCheckFlowData,- InvoiceRecordBackData, MandateRevokeFlowData, PaymentFlowData, RefundFlowData,- WebhookSourceVerifyData,+ ConnectorWebhookConfigurationFlowData, DisputeRecordBackData, DisputesFlowData,+ GiftCardBalanceCheckFlowData, InvoiceRecordBackData, MandateRevokeFlowData,+ PaymentFlowData, RefundFlowData, WebhookSourceVerifyData,},AccessTokenFlowData, AuthenticationTokenFlowData, ExternalAuthenticationFlowData,FilesFlowData, VaultConnectorFlowData,@@ -31,7 +31,8 @@ use hyperswitch_domain_models::{},refunds::{Execute, RSync},revenue_recovery::{- BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, InvoiceRecordBack,+ BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, DisputeRecordBack,+ InvoiceRecordBack,},unified_authentication_service::{Authenticate, PostAuthenticate, PreAuthenticate},webhooks::VerifyWebhookSource,@@ -45,7 +46,7 @@ use hyperswitch_domain_models::{},revenue_recovery::{BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest,- InvoiceRecordBackRequest,+ DisputeRecordBackRequest, InvoiceRecordBackRequest,},AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AccessTokenRequestData,AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData,@@ -71,7 +72,7 @@ use hyperswitch_domain_models::{},revenue_recovery::{BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse,- InvoiceRecordBackResponse,+ DisputeRecordBackResponse, InvoiceRecordBackResponse,},AcceptDisputeResponse, AuthenticationResponseData, CompleteRefundSurchrgeResponseData,CompleteSurchargeResponseData, DefendDisputeResponse, DisputeSyncResponse,@@ -140,7 +141,7 @@ use hyperswitch_interfaces::{refunds_v2::{RefundExecuteV2, RefundSyncV2, RefundV2},revenue_recovery_v2::{BillingConnectorInvoiceSyncIntegrationV2, BillingConnectorPaymentsSyncIntegrationV2,- RevenueRecoveryRecordBackV2, RevenueRecoveryV2,+ RevenueRecoveryDisputeRecordBackV2, RevenueRecoveryRecordBackV2, RevenueRecoveryV2,},vault_v2::{ExternalVaultCreateV2, ExternalVaultDeleteV2, ExternalVaultInsertV2,@@ -4968,6 +4969,7 @@ macro_rules! default_imp_for_new_connector_integration_revenue_recovery {$( impl RevenueRecoveryV2 for $path::$connector {}impl BillingConnectorPaymentsSyncIntegrationV2 for $path::$connector {}impl RevenueRecoveryRecordBackV2 for $path::$connector {}+ impl RevenueRecoveryDisputeRecordBackV2 for $path::$connector {}impl BillingConnectorInvoiceSyncIntegrationV2 for $path::$connector {}implConnectorIntegrationV2<@@ -4977,6 +4979,14 @@ macro_rules! default_imp_for_new_connector_integration_revenue_recovery {InvoiceRecordBackResponse,> for $path::$connector{}+ impl+ ConnectorIntegrationV2<+ DisputeRecordBack,+ DisputeRecordBackData,+ DisputeRecordBackRequest,+ DisputeRecordBackResponse,+ > for $path::$connector+ {}implConnectorIntegrationV2<BillingConnectorPaymentsSync,diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rsindex 37e35ab37d..37758e3cbe 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs@@ -1233,6 +1233,9 @@ impl PaymentAttempt {.as_ref().and_then(|data| data.charge_id.clone())}),+ // Populated later, when the payment is recorded back to the+ // billing connector.+ billing_connector_transaction_id: None,}}),};@@ -2939,6 +2942,12 @@ pub enum PaymentAttemptUpdate {amount_to_capture: Option<MinorUnit>,updated_by: String,},+ /// Update the attempt's feature metadata after recording the payment back to the+ /// billing connector. Touches nothing else.+ RecordBackUpdate {+ feature_metadata: Option<PaymentAttemptFeatureMetadata>,+ updated_by: String,+ },/// Update the payment after attempting capture with the connectorCaptureUpdate {status: storage_enums::AttemptStatus,@@ -3565,6 +3574,40 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternalamount_captured: None,payment_method_data: None,},+ PaymentAttemptUpdate::RecordBackUpdate {+ feature_metadata,+ updated_by,+ } => Self {+ feature_metadata: feature_metadata.as_ref().map(From::from),+ updated_by,+ modified_at: common_utils::date_time::now(),+ amount_to_capture: None,+ payment_method_id: None,+ error_message: None,+ browser_info: None,+ error_code: None,+ error_reason: None,+ merchant_connector_id: None,+ unified_code: None,+ unified_message: None,+ connector_payment_id: None,+ connector_payment_data: None,+ connector: None,+ redirection_data: None,+ status: None,+ connector_metadata: None,+ amount_capturable: None,+ connector_token_details: None,+ authentication_type: None,+ network_advice_code: None,+ network_decline_code: None,+ network_error_message: None,+ connector_request_reference_id: None,+ connector_response_reference_id: None,+ cancellation_reason: None,+ amount_captured: None,+ payment_method_data: None,+ },PaymentAttemptUpdate::PreCaptureUpdate {amount_to_capture,updated_by,@@ -3688,6 +3731,8 @@ pub struct PaymentAttemptRevenueRecoveryData {pub attempt_triggered_by: common_enums::TriggeredBy,// stripe specific field used to identify duplicate attempts.pub charge_id: Option<String>,+ /// Transaction id returned by the billing connector at record-back time.+ pub billing_connector_transaction_id: Option<String>,}#[cfg(feature = "v2")]@@ -3699,6 +3744,9 @@ impl From<&PaymentAttemptFeatureMetadata> for DieselPaymentAttemptFeatureMetadat.map(|recovery_data| DieselPassiveChurnRecoveryData {attempt_triggered_by: recovery_data.attempt_triggered_by,charge_id: recovery_data.charge_id.clone(),+ billing_connector_transaction_id: recovery_data+ .billing_connector_transaction_id+ .clone(),});Self { revenue_recovery }}@@ -3712,6 +3760,8 @@ impl From<DieselPaymentAttemptFeatureMetadata> for PaymentAttemptFeatureMetadata.map(|recovery_data| PaymentAttemptRevenueRecoveryData {attempt_triggered_by: recovery_data.attempt_triggered_by,charge_id: recovery_data.charge_id,+ billing_connector_transaction_id: recovery_data+ .billing_connector_transaction_id,});Self { revenue_recovery }}diff --git a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rsindex 0e0bbbcf45..4e24388ad1 100644--- a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs+++ b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs@@ -154,6 +154,11 @@ pub struct InvoiceRecordBackData {pub connector_meta_data: Option<pii::SecretSerdeValue>,}+#[derive(Debug, Clone)]+pub struct DisputeRecordBackData {+ pub connector_meta_data: Option<pii::SecretSerdeValue>,+}+#[derive(Debug, Clone)]pub struct SubscriptionCustomerData {pub connector_meta_data: Option<pii::SecretSerdeValue>,diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/router_flow_types/revenue_recovery.rsindex da496656c6..09ad7efcaa 100644--- a/crates/hyperswitch_domain_models/src/router_flow_types/revenue_recovery.rs+++ b/crates/hyperswitch_domain_models/src/router_flow_types/revenue_recovery.rs@@ -3,5 +3,9 @@ pub struct BillingConnectorPaymentsSync;#[derive(Debug, Clone)]pub struct InvoiceRecordBack;+/// Record a lost dispute back to the billing connector as an offline refund.+#[derive(Debug, Clone)]+pub struct DisputeRecordBack;+#[derive(Debug, Clone)]pub struct BillingConnectorInvoiceSync;diff --git a/crates/hyperswitch_domain_models/src/router_request_types/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/router_request_types/revenue_recovery.rsindex 197de0b0fb..0e3690d8a2 100644--- a/crates/hyperswitch_domain_models/src/router_request_types/revenue_recovery.rs+++ b/crates/hyperswitch_domain_models/src/router_request_types/revenue_recovery.rs@@ -21,6 +21,24 @@ pub struct InvoiceRecordBackRequest {pub connector_params: connector_endpoints::ConnectorParams,}+#[derive(Debug, Clone)]+pub struct DisputeRecordBackRequest {+ /// Invoice the disputed payment was recorded against. The refund is recorded on the+ /// invoice rather than on the payment transaction: the transaction-level endpoint can+ /// only refund a payment's unapplied balance, which is zero once it has paid an invoice.+ pub merchant_reference_id: common_utils::id_type::PaymentReferenceId,+ /// Transaction id at the billing connector, captured at record-back time. Sent as the+ /// refund's reference number so the record points back at the payment it reverses.+ pub billing_connector_transaction_id: String,+ /// The disputed amount, in minor units.+ pub amount: common_utils::types::MinorUnit,+ /// When the refund occurred.+ pub refund_date: time::PrimitiveDateTime,+ /// Free-text note stored against the billing connector's record.+ pub comment: Option<String>,+ pub connector_params: connector_endpoints::ConnectorParams,+}+#[derive(Debug, Clone)]pub struct BillingConnectorInvoiceSyncRequest {/// Invoice iddiff --git a/crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rsindex dabdf981e3..7249c72ce8 100644--- a/crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs+++ b/crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs@@ -37,6 +37,15 @@ pub struct BillingConnectorPaymentsSyncResponse {#[derive(Debug, Clone)]pub struct InvoiceRecordBackResponse {pub merchant_reference_id: common_utils::id_type::PaymentReferenceId,+ /// Transaction id at the billing connector for the payment just recorded.+ /// `None` for connectors that do not return one.+ pub connector_transaction_id: Option<String>,+}++#[derive(Debug, Clone)]+pub struct DisputeRecordBackResponse {+ /// Id of the refund transaction created at the billing connector.+ pub connector_refund_id: String,}#[derive(Debug, Clone)]diff --git a/crates/hyperswitch_domain_models/src/types.rs b/crates/hyperswitch_domain_models/src/types.rsindex 99846dd205..410ee493eb 100644--- a/crates/hyperswitch_domain_models/src/types.rs+++ b/crates/hyperswitch_domain_models/src/types.rs@@ -8,7 +8,7 @@ use crate::{merchant_connector_webhook_management::{ConnectorWebhookGenerateSecret, ConnectorWebhookRegister,},- revenue_recovery::InvoiceRecordBack,+ revenue_recovery::{DisputeRecordBack, InvoiceRecordBack},subscriptions::{GetSubscriptionEstimate, GetSubscriptionItemPrices, GetSubscriptionItems,SubscriptionCancel, SubscriptionCreate, SubscriptionPause, SubscriptionResume,@@ -30,7 +30,7 @@ use crate::{},revenue_recovery::{BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest,- InvoiceRecordBackRequest,+ DisputeRecordBackRequest, InvoiceRecordBackRequest,},subscriptions::{GetSubscriptionEstimateRequest, GetSubscriptionItemPricesRequest,@@ -63,7 +63,7 @@ use crate::{},revenue_recovery::{BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse,- InvoiceRecordBackResponse,+ DisputeRecordBackResponse, InvoiceRecordBackResponse,},subscriptions::{GetSubscriptionEstimateResponse, GetSubscriptionItemPricesResponse,@@ -191,6 +191,9 @@ pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>;pub type InvoiceRecordBackRouterData =RouterData<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse>;+pub type DisputeRecordBackRouterData =+ RouterData<DisputeRecordBack, DisputeRecordBackRequest, DisputeRecordBackResponse>;+pub type GetSubscriptionItemsRouterData =RouterData<GetSubscriptionItems, GetSubscriptionItemsRequest, GetSubscriptionItemsResponse>;@@ -245,6 +248,13 @@ pub type InvoiceRecordBackRouterDataV2 = RouterDataV2<InvoiceRecordBackResponse,>;+pub type DisputeRecordBackRouterDataV2 = RouterDataV2<+ DisputeRecordBack,+ router_data_v2::flow_common_types::DisputeRecordBackData,+ DisputeRecordBackRequest,+ DisputeRecordBackResponse,+>;+pub type GetSubscriptionPlanPricesRouterData = RouterData<GetSubscriptionItemPrices,GetSubscriptionItemPricesRequest,diff --git a/crates/hyperswitch_interfaces/src/api/revenue_recovery.rs b/crates/hyperswitch_interfaces/src/api/revenue_recovery.rsindex 998c1888e6..0657c6ec94 100644--- a/crates/hyperswitch_interfaces/src/api/revenue_recovery.rs+++ b/crates/hyperswitch_interfaces/src/api/revenue_recovery.rs@@ -2,15 +2,16 @@use hyperswitch_domain_models::{router_flow_types::{- BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, InvoiceRecordBack,+ BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, DisputeRecordBack,+ InvoiceRecordBack,},router_request_types::revenue_recovery::{BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest,- InvoiceRecordBackRequest,+ DisputeRecordBackRequest, InvoiceRecordBackRequest,},router_response_types::revenue_recovery::{BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse,- InvoiceRecordBackResponse,+ DisputeRecordBackResponse, InvoiceRecordBackResponse,},};@@ -24,6 +25,7 @@ pub trait RevenueRecovery:ConnectorCommon+ BillingConnectorPaymentsSyncIntegration+ RevenueRecoveryRecordBack+ + RevenueRecoveryDisputeRecordBack+ BillingConnectorInvoiceSyncIntegration{}@@ -44,6 +46,12 @@ pub trait RevenueRecoveryRecordBack:{}+/// trait RevenueRecoveryDisputeRecordBack+pub trait RevenueRecoveryDisputeRecordBack:+ ConnectorIntegration<DisputeRecordBack, DisputeRecordBackRequest, DisputeRecordBackResponse>+{+}+/// trait BillingConnectorInvoiceSyncIntegrationpub trait BillingConnectorInvoiceSyncIntegration:ConnectorIntegration<diff --git a/crates/hyperswitch_interfaces/src/api/revenue_recovery_v2.rs b/crates/hyperswitch_interfaces/src/api/revenue_recovery_v2.rsindex 08efb664f9..ff73cb9d14 100644--- a/crates/hyperswitch_interfaces/src/api/revenue_recovery_v2.rs+++ b/crates/hyperswitch_interfaces/src/api/revenue_recovery_v2.rs@@ -3,18 +3,19 @@use hyperswitch_domain_models::{router_data_v2::flow_common_types::{BillingConnectorInvoiceSyncFlowData, BillingConnectorPaymentsSyncFlowData,- InvoiceRecordBackData,+ DisputeRecordBackData, InvoiceRecordBackData,},router_flow_types::{- BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, InvoiceRecordBack,+ BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, DisputeRecordBack,+ InvoiceRecordBack,},router_request_types::revenue_recovery::{BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest,- InvoiceRecordBackRequest,+ DisputeRecordBackRequest, InvoiceRecordBackRequest,},router_response_types::revenue_recovery::{BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse,- InvoiceRecordBackResponse,+ DisputeRecordBackResponse, InvoiceRecordBackResponse,},};@@ -25,6 +26,7 @@ use crate::connector_integration_v2::ConnectorIntegrationV2;pub trait RevenueRecoveryV2:BillingConnectorPaymentsSyncIntegrationV2+ RevenueRecoveryRecordBackV2+ + RevenueRecoveryDisputeRecordBackV2+ BillingConnectorInvoiceSyncIntegrationV2{}@@ -55,6 +57,17 @@ pub trait RevenueRecoveryRecordBackV2:{}+/// trait RevenueRecoveryDisputeRecordBackV2+pub trait RevenueRecoveryDisputeRecordBackV2:+ ConnectorIntegrationV2<+ DisputeRecordBack,+ DisputeRecordBackData,+ DisputeRecordBackRequest,+ DisputeRecordBackResponse,+>+{+}+/// trait BillingConnectorInvoiceSyncIntegrationV2pub trait BillingConnectorInvoiceSyncIntegrationV2:ConnectorIntegrationV2<diff --git a/crates/hyperswitch_interfaces/src/conversion_impls.rs b/crates/hyperswitch_interfaces/src/conversion_impls.rsindex fc62059a90..5d98b0d2d0 100644--- a/crates/hyperswitch_interfaces/src/conversion_impls.rs+++ b/crates/hyperswitch_interfaces/src/conversion_impls.rs@@ -13,12 +13,13 @@ use hyperswitch_domain_models::{flow_common_types::{AccessTokenFlowData, AuthenticationTokenFlowData, BillingConnectorInvoiceSyncFlowData,BillingConnectorPaymentsSyncFlowData, ConnectorWebhookConfigurationFlowData,- DisputesFlowData, ExternalAuthenticationFlowData, ExternalVaultProxyFlowData,- FilesFlowData, GetSubscriptionEstimateData, GetSubscriptionItemPricesData,- GetSubscriptionItemsData, GiftCardBalanceCheckFlowData, InvoiceRecordBackData,- MandateRevokeFlowData, PaymentFlowData, RefundFlowData, SubscriptionCancelData,- SubscriptionCreateData, SubscriptionCustomerData, SubscriptionPauseData,- SubscriptionResumeData, UasFlowData, VaultConnectorFlowData, WebhookSourceVerifyData,+ DisputeRecordBackData, DisputesFlowData, ExternalAuthenticationFlowData,+ ExternalVaultProxyFlowData, FilesFlowData, GetSubscriptionEstimateData,+ GetSubscriptionItemPricesData, GetSubscriptionItemsData, GiftCardBalanceCheckFlowData,+ InvoiceRecordBackData, MandateRevokeFlowData, PaymentFlowData, RefundFlowData,+ SubscriptionCancelData, SubscriptionCreateData, SubscriptionCustomerData,+ SubscriptionPauseData, SubscriptionResumeData, UasFlowData, VaultConnectorFlowData,+ WebhookSourceVerifyData,},RouterDataV2,},@@ -946,6 +947,7 @@ default_router_data_conversion!(GetSubscriptionEstimateData);default_router_data_conversion!(SubscriptionResumeData);default_router_data_conversion!(SubscriptionPauseData);default_router_data_conversion!(SubscriptionCancelData);+default_router_data_conversion!(DisputeRecordBackData);impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for UasFlowData {fn from_old_router_data(diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rsindex f954f4e515..45158d5d4b 100644--- a/crates/hyperswitch_interfaces/src/types.rs+++ b/crates/hyperswitch_interfaces/src/types.rs@@ -20,7 +20,7 @@ use hyperswitch_domain_models::{Session, SettlementSplitCreate, SetupMandate, UpdateMetadata, UpdatePostConfirm, Void,},refunds::{Execute, RSync},- revenue_recovery::{BillingConnectorPaymentsSync, InvoiceRecordBack},+ revenue_recovery::{BillingConnectorPaymentsSync, DisputeRecordBack, InvoiceRecordBack},subscriptions::{GetSubscriptionEstimate, GetSubscriptionItemPrices, GetSubscriptionItems,SubscriptionCancel, SubscriptionCreate, SubscriptionPause, SubscriptionResume,@@ -42,7 +42,7 @@ use hyperswitch_domain_models::{},revenue_recovery::{BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest,- InvoiceRecordBackRequest,+ DisputeRecordBackRequest, InvoiceRecordBackRequest,},subscriptions::{GetSubscriptionEstimateRequest, GetSubscriptionItemPricesRequest,@@ -77,7 +77,7 @@ use hyperswitch_domain_models::{},revenue_recovery::{BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse,- InvoiceRecordBackResponse,+ DisputeRecordBackResponse, InvoiceRecordBackResponse,},subscriptions::{GetSubscriptionEstimateResponse, GetSubscriptionItemPricesResponse,@@ -415,6 +415,13 @@ pub type UasProcessWebhookType = dyn ConnectorIntegration<UasAuthenticationResponseData,>;+/// Type alias for `ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse>`+pub type DisputeRecordBackType = dyn ConnectorIntegration<+ DisputeRecordBack,+ DisputeRecordBackRequest,+ DisputeRecordBackResponse,+>;+/// Type alias for `ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse>`pub type InvoiceRecordBackType = dyn ConnectorIntegration<InvoiceRecordBack,@@ -443,6 +450,14 @@ pub type BillingConnectorInvoiceSyncType = dyn ConnectorIntegration<BillingConnectorInvoiceSyncResponse,>;+/// Type alias for `ConnectorIntegrationV2<InvoiceRecordBack, InvoiceRecordBackData, InvoiceRecordBackRequest, InvoiceRecordBackResponse>`+pub type DisputeRecordBackTypeV2 = dyn ConnectorIntegrationV2<+ DisputeRecordBack,+ flow_common_types::DisputeRecordBackData,+ DisputeRecordBackRequest,+ DisputeRecordBackResponse,+>;+/// Type alias for `ConnectorIntegrationV2<InvoiceRecordBack, InvoiceRecordBackData, InvoiceRecordBackRequest, InvoiceRecordBackResponse>`pub type InvoiceRecordBackTypeV2 = dyn ConnectorIntegrationV2<InvoiceRecordBack,diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rsindex 9f1b06963b..aa885b7b31 100644--- a/crates/router/src/configs/secrets_transformers.rs+++ b/crates/router/src/configs/secrets_transformers.rs@@ -733,6 +733,7 @@ pub(crate) async fn fetch_raw_secrets(webhook_source_verification_call: conf.webhook_source_verification_call,billing_connectors_payment_sync: conf.billing_connectors_payment_sync,billing_connectors_invoice_sync: conf.billing_connectors_invoice_sync,+ billing_connectors_dispute_record_back: conf.billing_connectors_dispute_record_back,payment_method_auth,connector_request_reference_id_config: conf.connector_request_reference_id_config,#[cfg(feature = "payouts")]diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex c02b2cbd4a..1f319e9c25 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -139,6 +139,7 @@ pub struct Settings<S: SecretState> {pub webhook_source_verification_call: WebhookSourceVerificationCall,pub billing_connectors_payment_sync: BillingConnectorPaymentsSyncCall,pub billing_connectors_invoice_sync: BillingConnectorInvoiceSyncCall,+ pub billing_connectors_dispute_record_back: BillingConnectorDisputeRecordBackCall,pub payment_method_auth: SecretStateContainer<PaymentMethodAuth, S>,pub connector_request_reference_id_config: ConnectorRequestReferenceIdConfig,#[cfg(feature = "payouts")]@@ -1317,6 +1318,12 @@ pub struct BillingConnectorInvoiceSyncCall {pub billing_connectors_which_requires_invoice_sync_call: HashSet<enums::Connector>,}+#[derive(Debug, Deserialize, Clone, Default)]+pub struct BillingConnectorDisputeRecordBackCall {+ #[serde(deserialize_with = "deserialize_hashset")]+ pub billing_connectors_which_requires_dispute_record_back_call: HashSet<enums::Connector>,+}+#[derive(Debug, Deserialize, Clone, Default)]pub struct ApplePayDecryptConfig {pub apple_pay_ppc: Secret<String>,diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rsindex b12daa582f..9554f4aacf 100644--- a/crates/router/src/core/revenue_recovery/types.rs+++ b/crates/router/src/core/revenue_recovery/types.rs@@ -228,7 +228,7 @@ impl RevenueRecoveryPaymentIntentStatus {state,&payment_attempt,payment_intent,- &revenue_recovery_payment_data.billing_mca,+ revenue_recovery_payment_data,).await.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)@@ -928,7 +928,7 @@ impl Action {state,payment_attempt,payment_intent,- &revenue_recovery_payment_data.billing_mca,+ revenue_recovery_payment_data,).await.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)@@ -1236,7 +1236,7 @@ impl Action {state,payment_attempt,payment_intent,- &revenue_recovery_payment_data.billing_mca,+ revenue_recovery_payment_data,).await.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)@@ -1548,10 +1548,11 @@ async fn record_back_to_billing_connector(state: &SessionState,payment_attempt: &PaymentAttempt,payment_intent: &PaymentIntent,- billing_mca: &merchant_connector_account::MerchantConnectorAccount,+ revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,) -> RecoveryResult<()> {logger::info!("Entering record_back_to_billing_connector");+ let billing_mca = &revenue_recovery_payment_data.billing_mca;let connector_name = billing_mca.connector_name.to_string();let connector_data = api_types::ConnectorData::get_connector_by_name(&state.conf.connectors,@@ -1587,7 +1588,7 @@ async fn record_back_to_billing_connector(.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed).attach_printable("Failed while handling response of record back to billing connector")?;- match response.response {+ let record_back_response = match response.response {Ok(response) => Ok(response),error @ Err(_) => {router_env::logger::error!(?error);@@ -1595,9 +1596,73 @@ async fn record_back_to_billing_connector(.attach_printable("Failed while recording back to billing connector")}}?;++ persist_billing_connector_transaction_id(+ state,+ payment_attempt,+ revenue_recovery_payment_data,+ record_back_response.connector_transaction_id.as_deref(),+ )+ .await;+Ok(())}+/// Merge the billing connector's transaction id into the attempt's feature metadata.+///+/// Failure is logged, never propagated: the payment succeeded and the billing connector+/// recorded it. Losing the id degrades a future dispute refund; it does not invalidate+/// anything that already happened.+async fn persist_billing_connector_transaction_id(+ state: &SessionState,+ payment_attempt: &PaymentAttempt,+ revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,+ connector_transaction_id: Option<&str>,+) {+ let Some(connector_transaction_id) = connector_transaction_id else {+ return;+ };++ // Merge rather than replace: attempt_triggered_by and charge_id must survive.+ let Some(mut feature_metadata) = payment_attempt.feature_metadata.clone() else {+ logger::warn!(+ "No feature metadata on the attempt; cannot store the billing connector transaction id"+ );+ return;+ };+ let Some(revenue_recovery) = feature_metadata.revenue_recovery.as_mut() else {+ logger::warn!(+ "No revenue recovery metadata on the attempt; cannot store the billing connector transaction id"+ );+ return;+ };+ revenue_recovery.billing_connector_transaction_id = Some(connector_transaction_id.to_string());++ let storage_scheme = revenue_recovery_payment_data+ .merchant_account+ .storage_scheme;+ let update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::RecordBackUpdate {+ feature_metadata: Some(feature_metadata),+ updated_by: storage_scheme.to_string(),+ };++ if let Err(error) = state+ .store+ .update_payment_attempt(+ &revenue_recovery_payment_data.key_store,+ payment_attempt.clone(),+ update,+ storage_scheme,+ )+ .await+ {+ logger::error!(+ ?error,+ "Failed to persist the billing connector transaction id on the payment attempt"+ );+ }+}+pub fn construct_invoice_record_back_router_data(state: &SessionState,billing_mca: &merchant_connector_account::MerchantConnectorAccount,diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rsindex 6d1f7438d7..b941338806 100644--- a/crates/router/src/services/api.rs+++ b/crates/router/src/services/api.rs@@ -99,6 +99,8 @@ pub type BoxedFilesConnectorIntegrationInterface<T, Req, Resp> =BoxedConnectorIntegrationInterface<T, common_types::FilesFlowData, Req, Resp>;pub type BoxedRevenueRecoveryRecordBackInterface<T, Req, Res> =BoxedConnectorIntegrationInterface<T, common_types::InvoiceRecordBackData, Req, Res>;+pub type BoxedRevenueRecoveryDisputeRecordBackInterface<T, Req, Res> =+ BoxedConnectorIntegrationInterface<T, common_types::DisputeRecordBackData, Req, Res>;pub type BoxedGetSubscriptionPlansInterface<T, Req, Res> =BoxedConnectorIntegrationInterface<T, common_types::GetSubscriptionItemsData, Req, Res>;pub type BoxedGetSubscriptionPlanPricesInterface<T, Req, Res> =diff --git a/loadtest/config/development.toml b/loadtest/config/development.tomlindex 42d9a37222..c6212fa878 100644--- a/loadtest/config/development.toml+++ b/loadtest/config/development.toml@@ -966,6 +966,9 @@ billing_connectors_which_require_payment_sync = "stripebilling, recurly"[billing_connectors_invoice_sync]billing_connectors_which_requires_invoice_sync_call = "recurly"+[billing_connectors_dispute_record_back]+billing_connectors_which_requires_dispute_record_back_call = "chargebee"+[chat]enabled = falsehyperswitch_ai_host = "http://0.0.0.0:8000"