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(core): support for post refund void (#13610)
Swangi Kumarieef9c66e18c6
diff --git a/crates/analytics/src/api_event/events.rs b/crates/analytics/src/api_event/events.rsindex 90705e0e07..4634605585 100644--- a/crates/analytics/src/api_event/events.rs+++ b/crates/analytics/src/api_event/events.rs@@ -54,6 +54,7 @@ whereFlow::PaymentsUpdate,Flow::RefundsCreate,Flow::RefundsUpdate,+ Flow::RefundsReverse,Flow::DisputesEvidenceSubmit,Flow::AttachDisputeEvidence,Flow::RetrieveDisputeEvidence,@@ -81,6 +82,7 @@ where&[Flow::RefundsCreate,Flow::RefundsUpdate,+ Flow::RefundsReverse,Flow::IncomingWebhookReceive,],)diff --git a/crates/api_models/src/events/refund.rs b/crates/api_models/src/events/refund.rsindex 7a50af6928..3a20b1ce85 100644--- a/crates/api_models/src/events/refund.rs+++ b/crates/api_models/src/events/refund.rs@@ -6,7 +6,8 @@ use crate::refunds::{};#[cfg(feature = "v1")]use crate::refunds::{- RefundManualUpdateRequest, RefundRequest, RefundUpdateRequest, RefundsRetrieveRequest,+ RefundManualUpdateRequest, RefundRequest, RefundReverseRequest, RefundUpdateRequest,+ RefundsRetrieveRequest,};#[cfg(feature = "v1")]@@ -72,6 +73,16 @@ impl ApiEventMetric for RefundUpdateRequest {}}+#[cfg(feature = "v1")]+impl ApiEventMetric for RefundReverseRequest {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::Refund {+ payment_id: None,+ refund_id: self.refund_id.clone(),+ })+ }+}+#[cfg(feature = "v1")]impl ApiEventMetric for RefundManualUpdateRequest {fn get_api_event_type(&self) -> Option<ApiEventsType> {diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rsindex 8697512a47..9e9072baba 100644--- a/crates/api_models/src/refunds.rs+++ b/crates/api_models/src/refunds.rs@@ -214,6 +214,20 @@ pub struct RefundUpdateRequest {pub metadata: Option<pii::SecretSerdeValue>,}+#[cfg(feature = "v1")]+#[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize, SmithyModel)]+#[serde(deny_unknown_fields)]+#[smithy(namespace = "com.hyperswitch.smithy.types")]+pub struct RefundReverseRequest {+ #[serde(skip)]+ pub refund_id: String,++ /// Reason for reversing or voiding the refund at the connector before settlement.+ #[schema(max_length = 255, example = "POST_AUTH_USER_DECLINE")]+ #[smithy(value_type = "Option<String>")]+ pub cancellation_reason: Option<String>,+}+#[cfg(feature = "v2")]#[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)]#[serde(deny_unknown_fields)]diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 738c11b36c..ea04c0529b 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -2995,6 +2995,15 @@ impl ExecutionPath {Self::UnifiedConnectorService => false,}}++ /// Returns the execution mode corresponding to this execution path.+ pub fn get_execution_mode(&self) -> ExecutionMode {+ match self {+ Self::UnifiedConnectorService => ExecutionMode::Primary,+ Self::ShadowUnifiedConnectorService => ExecutionMode::Shadow,+ Self::Direct => ExecutionMode::NotApplicable,+ }+ }}#[derive(diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rsindex e98d21ec0f..cb7f3e75a5 100644--- a/crates/external_services/src/grpc_client/unified_connector_service.rs+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs@@ -1158,6 +1158,40 @@ impl UnifiedConnectorServiceClient {})}+ /// Voids or reverses a refund before connector settlement.+ pub async fn refund_void_post_refund(+ &self,+ request_data: payments_grpc::RefundServiceVoidPostRefundRequest,+ connector_auth_metadata: ConnectorAuthMetadata,+ grpc_headers: GrpcHeadersUcs,+ ) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::RefundResponse>> {+ let mut request = tonic::Request::new(request_data);++ let connector_name = connector_auth_metadata.connector_name.clone();+ let metadata =+ build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;+ *request.metadata_mut() = metadata;++ self.refund_service_client+ .clone()+ .void_post_refund(request)+ .await+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ })+ .inspect_err(|error| {+ logger::error!(+ grpc_error=?error,+ method="refund_void_post_refund",+ connector_name=?connector_name,+ "UCS refund void post-refund gRPC call failed"+ )+ })+ }+/// Performs Payout Createpub async fn payout_create(&self,diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rsindex 33d85c15f8..86d83e8efd 100644--- a/crates/hyperswitch_connectors/src/default_implementations.rs+++ b/crates/hyperswitch_connectors/src/default_implementations.rs@@ -12803,3 +12803,202 @@ default_imp_for_pre_authorize_void!(connectors::AbsaSanlam,connectors::Trustly);++macro_rules! default_imp_for_refund_void_post_refund {+ ($($path:ident::$connector:ident),*) => {+ $(+ impl hyperswitch_interfaces::api::refunds::RefundVoidPostRefund for $path::$connector {}++ impl ConnectorIntegration<+ hyperswitch_domain_models::router_flow_types::refunds::VoidPostRefund,+ hyperswitch_domain_models::router_request_types::RefundsData,+ hyperswitch_domain_models::router_response_types::RefundsResponseData,+ > for $path::$connector+ {+ fn build_request(+ &self,+ _req: &hyperswitch_domain_models::types::RefundsRouterData<+ hyperswitch_domain_models::router_flow_types::refunds::VoidPostRefund,+ >,+ _connectors: &hyperswitch_interfaces::configs::Connectors,+ ) -> CustomResult<+ Option<common_utils::request::Request>,+ hyperswitch_interfaces::errors::ConnectorError,+ > {+ Err(hyperswitch_interfaces::errors::ConnectorError::NotImplemented(+ "Void post-refund not implemented for this connector".to_string(),+ )+ .into())+ }+ }+ )*+ };+}++default_imp_for_refund_void_post_refund!(+ 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::Bitpay,+ connectors::Blackhawknetwork,+ connectors::Bluesnap,+ connectors::Boku,+ connectors::Braintree,+ connectors::Breadpay,+ connectors::Calida,+ connectors::Cashtocode,+ connectors::Celero,+ connectors::Chargebee,+ connectors::Checkbook,+ connectors::Checkout,+ connectors::Citigate,+ 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::Helcim,+ connectors::Hipay,+ connectors::Hyperpg,+ 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::Mifinity,+ connectors::Mollie,+ connectors::Moneris,+ connectors::Mpgs,+ connectors::Multisafepay,+ connectors::Netcetera,+ connectors::Nexinets,+ connectors::Nexixpay,+ connectors::Nmi,+ connectors::Nomupay,+ connectors::Noon,+ connectors::Nordea,+ connectors::Novalnet,+ connectors::Nuvei,+ connectors::Opayo,+ connectors::Opennode,+ connectors::Paybox,+ connectors::Payconex,+ connectors::Payeezy,+ connectors::Payjustnow,+ connectors::Payjustnowinstore,+ connectors::Payload,+ connectors::Payme,+ connectors::Payone,+ connectors::Paypal,+ connectors::Paysafe,+ connectors::Paystack,+ connectors::Paytm,+ connectors::Payu,+ connectors::Peachpayments,+ connectors::Phonepe,+ connectors::Placetopay,+ connectors::Plaid,+ connectors::Powertranz,+ connectors::Prophetpay,+ connectors::Rapyd,+ connectors::Razorpay,+ connectors::Redsys,+ connectors::Revolv3,+ connectors::Riskified,+ connectors::Santander,+ connectors::Shift4,+ connectors::Sift,+ connectors::Signifyd,+ connectors::Silverflow,+ connectors::Square,+ connectors::Stax,+ connectors::Stripe,+ 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::TsysTransit,+ connectors::UnifiedAuthenticationService,+ connectors::Vgs,+ connectors::Volt,+ connectors::Wellsfargo,+ connectors::Wellsfargopayout,+ connectors::Wise,+ connectors::Worldline,+ connectors::Worldpay,+ connectors::Worldpaymodular,+ connectors::Worldpayraft,+ connectors::Worldpayvantiv,+ connectors::Worldpayxml,+ connectors::Xendit,+ connectors::Zen,+ connectors::Zift,+ connectors::Zsl+);++#[cfg(feature = "dummy_connector")]+impl<const T: u8> api::refunds::RefundVoidPostRefund for connectors::DummyConnector<T> {}++#[cfg(feature = "dummy_connector")]+impl<const T: u8>+ ConnectorIntegration<+ hyperswitch_domain_models::router_flow_types::refunds::VoidPostRefund,+ hyperswitch_domain_models::router_request_types::RefundsData,+ hyperswitch_domain_models::router_response_types::RefundsResponseData,+ > for connectors::DummyConnector<T>+{+}diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rsindex ac3b4d70c3..399ac94e49 100644--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs@@ -29,7 +29,7 @@ use hyperswitch_domain_models::{PreProcessing, PushNotification, Reject, SdkSessionUpdate, Session,SettlementSplitCreate, SetupMandate, UpdateMetadata, UpdatePostConfirm, Void,},- refunds::{Execute, RSync},+ refunds::{Execute, RSync, VoidPostRefund},revenue_recovery::{BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, DisputeRecordBack,InvoiceRecordBack,@@ -138,7 +138,7 @@ use hyperswitch_interfaces::{PaymentsPushNotificationV2, PaymentsSettlementSplitCreate, SurchargeCalculationV2,TaxCalculationV2,},- refunds_v2::{RefundExecuteV2, RefundSyncV2, RefundV2},+ refunds_v2::{RefundExecuteV2, RefundSyncV2, RefundV2, RefundVoidPostRefundV2},revenue_recovery_v2::{BillingConnectorInvoiceSyncIntegrationV2, BillingConnectorPaymentsSyncIntegrationV2,RevenueRecoveryDisputeRecordBackV2, RevenueRecoveryRecordBackV2, RevenueRecoveryV2,@@ -543,12 +543,20 @@ macro_rules! default_imp_for_new_connector_integration_refund {impl RefundV2 for $path::$connector{}impl RefundExecuteV2 for $path::$connector{}impl RefundSyncV2 for $path::$connector{}+ impl RefundVoidPostRefundV2 for $path::$connector{}implConnectorIntegrationV2<Execute, RefundFlowData, RefundsData, RefundsResponseData>for $path::$connector{}implConnectorIntegrationV2<RSync, RefundFlowData, RefundsData, RefundsResponseData>for $path::$connector{}+ impl+ ConnectorIntegrationV2<+ VoidPostRefund,+ RefundFlowData,+ RefundsData,+ RefundsResponseData,+ > for $path::$connector{})*};}diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/refunds.rs b/crates/hyperswitch_domain_models/src/router_flow_types/refunds.rsindex eea6c7d0bb..1f9207d704 100644--- a/crates/hyperswitch_domain_models/src/router_flow_types/refunds.rs+++ b/crates/hyperswitch_domain_models/src/router_flow_types/refunds.rs@@ -2,3 +2,5 @@pub struct Execute;#[derive(Debug, Clone)]pub struct RSync;+#[derive(Debug, Clone)]+pub struct VoidPostRefund;diff --git a/crates/hyperswitch_interfaces/src/api/refunds.rs b/crates/hyperswitch_interfaces/src/api/refunds.rsindex f09c0d1aea..073d851cfd 100644--- a/crates/hyperswitch_interfaces/src/api/refunds.rs+++ b/crates/hyperswitch_interfaces/src/api/refunds.rs@@ -1,7 +1,7 @@//! Refunds interfaceuse hyperswitch_domain_models::{- router_flow_types::{Execute, RSync},+ router_flow_types::{Execute, RSync, VoidPostRefund},router_request_types::RefundsData,router_response_types::RefundsResponseData,};@@ -17,5 +17,11 @@ pub trait RefundExecute:/// trait RefundSyncpub trait RefundSync: api::ConnectorIntegration<RSync, RefundsData, RefundsResponseData> {}+/// trait RefundVoidPostRefund+pub trait RefundVoidPostRefund:+ api::ConnectorIntegration<VoidPostRefund, RefundsData, RefundsResponseData>+{+}+/// trait Refund-pub trait Refund: ConnectorCommon + RefundExecute + RefundSync {}+pub trait Refund: ConnectorCommon + RefundExecute + RefundSync + RefundVoidPostRefund {}diff --git a/crates/hyperswitch_interfaces/src/api/refunds_v2.rs b/crates/hyperswitch_interfaces/src/api/refunds_v2.rsindex 7812c3e283..ca9a9f9285 100644--- a/crates/hyperswitch_interfaces/src/api/refunds_v2.rs+++ b/crates/hyperswitch_interfaces/src/api/refunds_v2.rs@@ -2,7 +2,7 @@use hyperswitch_domain_models::{router_data_v2::flow_common_types::RefundFlowData,- router_flow_types::refunds::{Execute, RSync},+ router_flow_types::refunds::{Execute, RSync, VoidPostRefund},router_request_types::RefundsData,router_response_types::RefundsResponseData,};@@ -21,5 +21,14 @@ pub trait RefundSyncV2:{}+/// trait RefundVoidPostRefundV2+pub trait RefundVoidPostRefundV2:+ ConnectorIntegrationV2<VoidPostRefund, RefundFlowData, RefundsData, RefundsResponseData>+{+}+/// trait RefundV2-pub trait RefundV2: ConnectorCommon + RefundExecuteV2 + RefundSyncV2 {}+pub trait RefundV2:+ ConnectorCommon + RefundExecuteV2 + RefundSyncV2 + RefundVoidPostRefundV2+{+}diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rsindex bfe11ffa1c..b69a032fa3 100644--- a/crates/router/src/core/refunds.rs+++ b/crates/router/src/core/refunds.rs@@ -6,7 +6,8 @@ use api_models::admin::MerchantConnectorInfo;use api_models::enums as api_enums;use common_enums::ExecutionMode;use common_utils::{- ext_traits::AsyncExt,+ ext_traits::{AsyncExt, Encode, ValueExt},+ pii,types::{ConnectorTransactionId, MinorUnit},};use diesel_models::{process_tracker::business_status, refund as diesel_refund};@@ -19,6 +20,7 @@ use hyperswitch_interfaces::{consts as interfaces_consts,integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject},};+use hyperswitch_masking::ExposeInterface;use router_env::{instrument, tracing, tracing::Instrument};use scheduler::{errors as sch_errors, utils as process_tracker_utils};#[cfg(feature = "olap")]@@ -52,6 +54,316 @@ use crate::{utils::{self, OptionExt},};+#[derive(Debug, serde::Serialize)]+struct VoidPostRefundStateMetadata {+ status: common_enums::RefundStatus,+ connector_refund_id: String,+}++struct RefundReverseResponse {+ state_metadata: Option<pii::SecretSerdeValue>,+ raw_connector_response: Option<hyperswitch_masking::Secret<String>>,+ connector_refund_id: String,+ status: common_enums::RefundStatus,+ error_details: Option<ErrorResponse>,+}++impl From<unified_connector_service::RefundReverseUcsResponse> for RefundReverseResponse {+ fn from(response: unified_connector_service::RefundReverseUcsResponse) -> Self {+ Self {+ state_metadata: response.state_metadata,+ raw_connector_response: response.raw_connector_response,+ connector_refund_id: response.connector_refund_id,+ status: response.status,+ error_details: response.error,+ }+ }+}++fn build_void_post_refund_metadata(+ existing_metadata: Option<pii::SecretSerdeValue>,+ reverse_response: &RefundReverseResponse,+) -> RouterResult<pii::SecretSerdeValue> {+ let mut metadata: serde_json::Value = existing_metadata+ .map(ExposeInterface::expose)+ .map(|metadata| metadata.parse_value("refund metadata"))+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse refund metadata as a JSON object")?+ .unwrap_or_else(|| serde_json::Value::Object(Default::default()));++ let state_metadata = reverse_response+ .state_metadata+ .clone()+ .map(ExposeInterface::expose)+ .map(Ok)+ .unwrap_or_else(|| {+ VoidPostRefundStateMetadata {+ status: reverse_response.status,+ connector_refund_id: reverse_response.connector_refund_id.clone(),+ }+ .encode_to_value()+ })+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to encode void post-refund state metadata")?;++ metadata+ .as_object_mut()+ .ok_or_else(|| report!(errors::ApiErrorResponse::InternalServerError))+ .attach_printable("Refund metadata is not a JSON object")?+ .insert("state_metadata".to_string(), state_metadata);++ Ok(pii::SecretSerdeValue::new(metadata))+}++#[cfg(feature = "v1")]+pub async fn refund_reverse_core(+ state: SessionState,+ platform: domain::Platform,+ req: refunds::RefundReverseRequest,+) -> RouterResponse<api_models::refunds::RefundResponse> {+ let db = state.store.as_ref();+ let processor = platform.get_processor();+ let processor_account = processor.get_account();+ let storage_scheme = processor_account.storage_scheme;+ let processor_merchant_id = processor_account.get_id();++ let refund = db+ .find_refund_by_processor_merchant_id_refund_id(+ processor_merchant_id,+ &req.refund_id,+ storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;++ utils::when(refund.refund_status != enums::RefundStatus::Success, || {+ Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState {+ current_flow: "refund_reverse".into(),+ field_name: "refund_status".into(),+ current_value: refund.refund_status.to_string(),+ states: "success".to_string(),+ })+ .attach_printable("refund reverse is only supported for successful refunds"))+ })?;++ let payment_intent = db+ .find_payment_intent_by_payment_id_processor_merchant_id(+ &refund.payment_id,+ processor_merchant_id,+ processor.get_key_store(),+ storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;++ let payment_attempt = db+ .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_processor_merchant_id(+ &refund.payment_id,+ processor_merchant_id,+ storage_scheme,+ processor.get_key_store(),+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::SuccessfulPaymentNotFound)?;++ let connector_id = refund.connector.to_string();+ let connector = api::ConnectorData::get_connector_by_name(+ &state.conf.connectors,+ &connector_id,+ api::GetToken::Connector,+ payment_attempt.merchant_connector_id.clone(),+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to get the connector")?;++ let profile_id = payment_intent+ .profile_id+ .as_ref()+ .get_required_value("profile_id")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("profile_id is not set in payment_intent")?;++ let merchant_connector_account = helpers::get_merchant_connector_account(+ &state,+ processor,+ None,+ profile_id,+ &connector_id,+ payment_attempt.merchant_connector_id.as_ref(),+ )+ .await?;++ let currency = payment_attempt.currency.get_required_value("currency")?;+ let mut router_data = core_utils::construct_refund_router_data::<api::VoidPostRefund>(+ &state,+ &connector_id,+ processor,+ (payment_attempt.get_total_amount(), currency),+ &payment_intent,+ &payment_attempt,+ &refund,+ None,+ &merchant_connector_account,+ )+ .await?;+ router_data.request.reason = req.cancellation_reason.clone();++ let (execution_path, updated_state) =+ unified_connector_service::should_call_unified_connector_service(+ &state,+ processor,+ &router_data,+ None,+ payments::CallConnectorAction::Trigger,+ None,+ common_enums::TransactionType::Payment,+ )+ .await?;++ let execution_mode = execution_path.get_execution_mode();+ let lineage_ids = LineageIds::new(payment_intent.merchant_id.clone(), profile_id.clone());+ let gateway_context = gateway_context::RouterGatewayContext {+ creds_identifier: None,+ processor: processor.clone(),+ header_payload: HeaderPayload::default(),+ lineage_ids,+ merchant_connector_account: merchant_connector_account.clone(),+ execution_path,+ execution_mode,+ };+ let add_access_token_result = Box::pin(access_token::add_access_token(+ &state,+ &connector,+ &router_data,+ None,+ &gateway_context,+ None,+ ))+ .await?;+ access_token::update_router_data_with_access_token_result(+ &add_access_token_result,+ &mut router_data,+ &payments::CallConnectorAction::Trigger,+ );+ utils::when(+ add_access_token_result.connector_supports_access_token+ && router_data.access_token.is_none(),+ || {+ Err(report!(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("access token required for refund reverse but not available"))+ },+ )?;++ let reverse_response = match execution_path {+ common_enums::ExecutionPath::UnifiedConnectorService => {+ unified_connector_service::call_unified_connector_service_for_refund_void_post_refund(+ &updated_state,+ processor,+ router_data,+ ExecutionMode::Primary,+ merchant_connector_account,+ )+ .await+ .attach_printable(format!(+ "UCS refund reverse failed for connector: {connector_id}, refund_id: {}",+ refund.refund_id+ ))?+ .into()+ }+ common_enums::ExecutionPath::Direct+ | common_enums::ExecutionPath::ShadowUnifiedConnectorService => {+ Box::pin(execute_refund_void_post_refund_via_direct(+ &state,+ &connector,+ router_data,+ ))+ .await?+ }+ };+ let metadata = build_void_post_refund_metadata(refund.metadata.clone(), &reverse_response)?;+ let raw_connector_response = reverse_response.raw_connector_response.clone();+ let response = db+ .update_refund(+ refund,+ diesel_refund::RefundUpdate::MetadataAndReasonUpdate {+ metadata: Some(metadata),+ reason: req.cancellation_reason,+ updated_by: storage_scheme.to_string(),+ },+ storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable_lazy(|| {+ format!(+ "Unable to update refund reverse metadata with refund_id: {}",+ req.refund_id+ )+ })?;++ if let Some(error) = reverse_response.error_details {+ return Err(report!(errors::ApiErrorResponse::ExternalConnectorError {+ code: error.code,+ message: error.message,+ connector: connector_id,+ status_code: error.status_code,+ reason: error.reason,+ }));+ }++ Ok(services::ApplicationResponse::Json(+ (response, raw_connector_response).foreign_into(),+ ))+}++async fn execute_refund_void_post_refund_via_direct(+ state: &SessionState,+ connector: &api::ConnectorData,+ router_data: types::RefundsRouterData<api::VoidPostRefund>,+) -> RouterResult<RefundReverseResponse> {+ let connector_integration: services::BoxedRefundConnectorIntegrationInterface<+ api::VoidPostRefund,+ types::RefundsData,+ types::RefundsResponseData,+ > = connector.connector.get_connector_integration();++ let router_data = services::execute_connector_processing_step(+ state,+ connector_integration,+ &router_data,+ payments::CallConnectorAction::Trigger,+ None,+ None,+ )+ .await+ .to_refund_failed_response()?;++ let raw_connector_response = router_data.raw_connector_response.clone();+ let fallback_connector_refund_id = router_data+ .request+ .connector_refund_id+ .clone()+ .unwrap_or_default();++ Ok(match router_data.response {+ Ok(response) => RefundReverseResponse {+ state_metadata: None,+ raw_connector_response,+ connector_refund_id: response.connector_refund_id,+ status: response.refund_status,+ error_details: None,+ },+ Err(error) => RefundReverseResponse {+ state_metadata: None,+ raw_connector_response,+ connector_refund_id: fallback_connector_refund_id,+ status: common_enums::RefundStatus::Failure,+ error_details: Some(error),+ },+ })+}+// ********************************************** REFUND EXECUTE **********************************************#[instrument(skip_all)]diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex 5d5298b8dc..3b59eeccfa 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -10,7 +10,7 @@ use common_enums::{use common_utils::{consts::BASE64_ENGINE,errors::{CustomResult, ErrorSwitch},- ext_traits::ValueExt,+ ext_traits::{StringExt, ValueExt},id_type,request::Method,ucs_types,@@ -73,6 +73,15 @@ pub mod connector_config;pub mod kill_switch;pub mod transformers;+#[derive(Default)]+pub struct RefundReverseUcsResponse {+ pub state_metadata: Option<common_utils::pii::SecretSerdeValue>,+ pub raw_connector_response: Option<Secret<String>>,+ pub connector_refund_id: String,+ pub status: common_enums::RefundStatus,+ pub error: Option<ErrorResponse>,+}+fn parse_grpc_enum<T>(value: i32) -> Result<T, error_stack::Report<UnifiedConnectorServiceError>>whereT: TryFrom<i32>,@@ -823,6 +832,15 @@ type UnifiedConnectorServiceResult = CustomResult<type UnifiedConnectorServiceRefundResult =CustomResult<(Result<RefundsResponseData, ErrorResponse>, u16), UnifiedConnectorServiceError>;+type UnifiedConnectorServiceRefundVoidPostRefundResult = CustomResult<+ (+ RefundReverseUcsResponse,+ Result<RefundsResponseData, ErrorResponse>,+ u16,+ ),+ UnifiedConnectorServiceError,+>;+type UnifiedConnectorServiceCreateOrderResult = CustomResult<(Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>,@@ -3285,6 +3303,44 @@ pub fn handle_unified_connector_service_response_for_refund_get(Ok((router_data_response, status_code))}+pub fn handle_unified_connector_service_response_for_refund_void_post_refund(+ response: payments_grpc::RefundResponse,+) -> UnifiedConnectorServiceRefundVoidPostRefundResult {+ let status_code = transformers::convert_connector_service_status_code(response.status_code)?;+ let router_data_response = Result::<RefundsResponseData, ErrorResponse>::foreign_try_from((+ response.clone(),+ common_enums::RefundStatus::Success,+ ))?;+ let status = common_enums::RefundStatus::foreign_try_from((+ response.status(),+ common_enums::RefundStatus::Success,+ ))?;+ let state_metadata = response+ .state_metadata+ .map(|state_metadata| {+ state_metadata+ .expose()+ .parse_struct("UCS refund reverse state metadata")+ .map(common_utils::pii::SecretSerdeValue::new)+ })+ .transpose()+ .change_context(UnifiedConnectorServiceError::ResponseDeserializationFailed)+ .attach_printable("Failed to deserialize UCS refund reverse state metadata")?;+ let error = router_data_response.as_ref().err().cloned();++ Ok((+ RefundReverseUcsResponse {+ state_metadata,+ raw_connector_response: response.raw_connector_response,+ connector_refund_id: response.connector_refund_id,+ status,+ error,+ },+ router_data_response,+ status_code,+ ))+}+pub fn handle_unified_connector_service_response_for_payment_cancel(response: payments_grpc::PaymentServiceVoidResponse,prev_status: AttemptStatus,@@ -4312,6 +4368,87 @@ pub async fn call_unified_connector_service_for_refund_sync(.map(|(router_data, _flow_response)| router_data)}+/// Execute a post-refund void using RefundService.VoidPostRefund.+#[instrument(skip_all)]+pub async fn call_unified_connector_service_for_refund_void_post_refund(+ state: &SessionState,+ processor: &Processor,+ router_data: RouterData<refunds::VoidPostRefund, RefundsData, RefundsResponseData>,+ execution_mode: ExecutionMode,+ #[cfg(feature = "v1")] merchant_connector_account: MerchantConnectorAccountType,+ #[cfg(feature = "v2")] merchant_connector_account: MerchantConnectorAccountTypeDetails,+) -> RouterResult<RefundReverseUcsResponse> {+ let ucs_client = get_ucs_client(state)?;+ let connector_auth_metadata = build_unified_connector_service_auth_metadata(+ merchant_connector_account,+ processor.get_account().get_id(),+ router_data.connector.clone(),+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to build UCS auth metadata for refund reverse")?;+ let grpc_request =+ payments_grpc::RefundServiceVoidPostRefundRequest::foreign_try_from(&router_data)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to transform router data to UCS refund reverse request")?;++ let merchant_id = processor.get_account().get_id().clone();+ let profile_id = id_type::ProfileId::from_str(merchant_id.get_string_repr())+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to convert merchant_id to profile_id for UCS refund reverse")?;+ let lineage_ids = LineageIds::new(merchant_id, profile_id);+ let merchant_reference_id =+ id_type::PaymentReferenceId::from_str(router_data.payment_id.as_str())+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to convert payment_id to UCS reference id")+ .map(ucs_types::UcsReferenceId::Payment)+ .map(Some)?;+ let resource_id = router_data+ .refund_id+ .as_ref()+ .map(|refund_id| {+ id_type::RefundReferenceId::try_from(Cow::Owned(refund_id.to_string()))+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to convert refund_id to UCS resource id")+ })+ .transpose()?+ .map(ucs_types::UcsResourceId::Refund);+ let grpc_header_builder = state+ .get_grpc_headers_ucs(execution_mode)+ .lineage_ids(lineage_ids)+ .external_vault_proxy_metadata(None)+ .merchant_reference_id(merchant_reference_id)+ .resource_id(resource_id);++ Box::pin(ucs_logging_wrapper_granular(+ router_data,+ state,+ grpc_request,+ grpc_header_builder,+ execution_mode,+ |mut router_data, grpc_request, grpc_headers| async move {+ let grpc_response = ucs_client+ .refund_void_post_refund(grpc_request, connector_auth_metadata, grpc_headers)+ .await+ .attach_printable("UCS refund reverse execution failed")?+ .into_inner();+ let (reverse_response, router_data_response, status_code) =+ handle_unified_connector_service_response_for_refund_void_post_refund(+ grpc_response.clone(),+ )+ .attach_printable("Failed to transform UCS refund reverse response")?;++ router_data.connector_http_status_code = Some(status_code);+ router_data.response = router_data_response;++ Ok((router_data, reverse_response, grpc_response))+ },+ ))+ .await+ .map(|(_router_data, reverse_response)| reverse_response)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("UCS refund reverse execution failed")+}+/// Execute a surcharge calculation call via UCS SurchargeService.Calculate.////// This is a lightweight helper — it does not go through the full RouterDatadiff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rsindex dfc10d24a2..6666bd8cee 100644--- a/crates/router/src/core/unified_connector_service/transformers.rs+++ b/crates/router/src/core/unified_connector_service/transformers.rs@@ -25,7 +25,7 @@ use hyperswitch_domain_models::{router_data::{AccessToken, ErrorResponse, L2L3Data, RouterData},router_flow_types::{payments::{Authorize, Capture, PSync, PreAuthorizeVoid, SetupMandate},- refunds::{Execute, RSync},+ refunds::{Execute, RSync, VoidPostRefund},unified_authentication_service as uas_flows, ExternalVaultProxy, IncrementalAuthorization,Session,},@@ -7802,6 +7802,68 @@ impl transformers::ForeignTryFrom<&RouterData<RSync, RefundsData, RefundsRespons}}+impl transformers::ForeignTryFrom<&RouterData<VoidPostRefund, RefundsData, RefundsResponseData>>+ for payments_grpc::RefundServiceVoidPostRefundRequest+{+ type Error = error_stack::Report<UnifiedConnectorServiceError>;++ fn foreign_try_from(+ router_data: &RouterData<VoidPostRefund, RefundsData, RefundsResponseData>,+ ) -> Result<Self, Self::Error> {+ let state = router_data+ .access_token+ .as_ref()+ .map(ConnectorState::foreign_from);+ let payment_method_type = router_data+ .payment_method_type+ .map(payments_grpc::PaymentMethodType::foreign_try_from)+ .transpose()?+ .map(Into::into);++ Ok(Self {+ merchant_refund_id: Some(router_data.connector_request_reference_id.clone()),+ connector_refund_id: router_data.request.connector_refund_id.clone().ok_or(+ UnifiedConnectorServiceError::RequestEncodingFailedWithReason(+ "Missing connector_refund_id for refund reverse operation".to_string(),+ ),+ )?,+ cancellation_reason: router_data.request.reason.clone(),+ browser_info: router_data+ .request+ .browser_info+ .clone()+ .map(payments_grpc::BrowserInformation::foreign_try_from)+ .transpose()+ .map_err(|_| {+ UnifiedConnectorServiceError::RequestEncodingFailedWithReason(+ "Failed to convert browser info".to_string(),+ )+ })?,+ refund_metadata: router_data+ .request+ .refund_connector_metadata+ .as_ref()+ .map(serde_json::to_string)+ .transpose()+ .change_context(UnifiedConnectorServiceError::RequestEncodingFailed)?+ .map(Into::into),+ state,+ test_mode: router_data.test_mode,+ payment_method_type,+ connector_feature_data: router_data+ .request+ .connector_metadata+ .as_ref()+ .map(serde_json::to_string)+ .transpose()+ .change_context(UnifiedConnectorServiceError::RequestEncodingFailed)?+ .map(Into::into),+ merchant_request_id: None,+ connector_order_id: Some(router_data.request.connector_transaction_id.clone()),+ })+ }+}+/// Transform UCS RefundResponse into Result<RefundsResponseData, ErrorResponse>./// prev_status is the refund status prior to the UCS call; it is used as a fallback when UCS/// returns Unspecified (i.e. an unknown connector refund status) so the DB state is not corrupted.diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex e04d59bc1c..98dad56122 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -1591,7 +1591,8 @@ impl Refunds {web::resource("/{id}").route(web::get().to(refunds_retrieve)).route(web::post().to(refunds_update)),- );+ )+ .service(web::resource("/{id}/reverse").route(web::post().to(refunds_reverse)));}route}diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rsindex 75f9b6dbef..0aa7356dc6 100644--- a/crates/router/src/routes/lock_utils.rs+++ b/crates/router/src/routes/lock_utils.rs@@ -221,6 +221,7 @@ impl From<Flow> for ApiIdentifier {| Flow::RefundsRetrieve| Flow::RefundsRetrieveForceSync| Flow::RefundsUpdate+ | Flow::RefundsReverse| Flow::RefundsList| Flow::RefundsFilters| Flow::RefundsAggregatediff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rsindex 091857f46b..74d8958f79 100644--- a/crates/router/src/routes/refunds.rs+++ b/crates/router/src/routes/refunds.rs@@ -373,6 +373,38 @@ pub async fn refunds_update(.await}+#[cfg(feature = "v1")]+/// Refunds - Reverse+///+/// Reverse or void a successful refund before connector settlement.+#[instrument(skip_all, fields(flow = ?Flow::RefundsReverse))]+pub async fn refunds_reverse(+ state: web::Data<AppState>,+ req: HttpRequest,+ json_payload: web::Json<refunds::RefundReverseRequest>,+ path: web::Path<String>,+) -> HttpResponse {+ let flow = Flow::RefundsReverse;+ let mut refund_reverse_request = json_payload.into_inner();+ refund_reverse_request.refund_id = path.into_inner();++ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ refund_reverse_request,+ |state, auth: auth::AuthenticationData, request, _| {+ refund_reverse_core(state, auth.platform, request)+ },+ &auth::HeaderAuth(auth::ApiKeyAuth {+ allow_connected_scope_operation: true,+ allow_platform_self_operation: false,+ }),+ api_locking::LockAction::NotApplicable,+ ))+ .await+}+#[cfg(feature = "v2")]#[instrument(skip_all, fields(flow = ?Flow::RefundsUpdate))]pub async fn refunds_metadata_update(diff --git a/crates/router/src/types/api/refunds.rs b/crates/router/src/types/api/refunds.rsindex be2058b691..f40bdb7473 100644--- a/crates/router/src/types/api/refunds.rs+++ b/crates/router/src/types/api/refunds.rs@@ -1,12 +1,12 @@-#[cfg(feature = "v1")]-pub use api_models::refunds::RefundRequest;pub use api_models::refunds::{RefundListRequest, RefundListResponse, RefundResponse, RefundStatus, RefundType,RefundUpdateRequest, RefundsRetrieveBody, RefundsRetrieveRequest,};#[cfg(feature = "v2")]pub use api_models::refunds::{RefundMetadataUpdateRequest, RefundsCreateRequest};-pub use hyperswitch_domain_models::router_flow_types::refunds::{Execute, RSync};+#[cfg(feature = "v1")]+pub use api_models::refunds::{RefundRequest, RefundReverseRequest};+pub use hyperswitch_domain_models::router_flow_types::refunds::{Execute, RSync, VoidPostRefund};pub use hyperswitch_interfaces::api::refunds::{Refund, RefundExecute, RefundSync};use crate::types::{storage::enums as storage_enums, transformers::ForeignFrom};diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rsindex bbeed2c8c1..86553e1f79 100644--- a/crates/router_env/src/logger/types.rs+++ b/crates/router_env/src/logger/types.rs@@ -263,6 +263,8 @@ pub enum Flow {RefundsRetrieveForceSync,/// Refunds update flow.RefundsUpdate,+ /// Refunds reverse flow.+ RefundsReverse,/// Refunds list flow.RefundsList,/// Refunds filters flow