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(refunds): add surcharge support for partial refunds (#15155)

Swangi Kumari80ce67cac056
diff --git a/Cargo.lock b/Cargo.lock
index f319f5dcc6..586021c68d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7246,8 +7246,8 @@ version = "0.14.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7"
dependencies = [
- "heck 0.5.0",
- "itertools 0.11.0",
+ "heck 0.4.1",
+ "itertools 0.10.5",
"log",
"multimap",
"petgraph",
@@ -7268,7 +7268,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d"
dependencies = [
"anyhow",
- "itertools 0.11.0",
+ "itertools 0.10.5",
"proc-macro2",
"quote",
"syn 2.0.119",
@@ -7281,7 +7281,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27c6023962132f4b30eb4c172c91ce92d933da334c59c23cddee82358ddafb0b"
dependencies = [
"anyhow",
- "itertools 0.11.0",
+ "itertools 0.10.5",
"proc-macro2",
"quote",
"syn 2.0.119",
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 388dc30983..384e399928 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -3422,6 +3422,10 @@ impl RefundStatus {
pub fn is_success(self) -> bool {
matches!(self, Self::Success)
}
+
+ pub fn is_failure(self) -> bool {
+ matches!(self, Self::Failure | Self::TransactionFailure)
+ }
}
#[derive(
diff --git a/crates/common_types/src/payments.rs b/crates/common_types/src/payments.rs
index 888199d0af..8bdf91050a 100644
--- a/crates/common_types/src/payments.rs
+++ b/crates/common_types/src/payments.rs
@@ -1768,7 +1768,15 @@ pub enum TokenSource {
/// Connector error details shared by surcharge responses, cached quotes, and stored attempts.
#[derive(
- Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize, ToSchema, smithy::SmithyModel,
+ Clone,
+ Debug,
+ Default,
+ PartialEq,
+ Eq,
+ serde::Deserialize,
+ serde::Serialize,
+ ToSchema,
+ smithy::SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct SurchargeErrorDetails {
diff --git a/crates/common_types/src/refunds.rs b/crates/common_types/src/refunds.rs
index bbd2cd59cb..6e6bfb6a3b 100644
--- a/crates/common_types/src/refunds.rs
+++ b/crates/common_types/src/refunds.rs
@@ -2,6 +2,7 @@
#[cfg(feature = "diesel")]
use common_utils::impl_to_sql_from_sql_json;
+use common_utils::types::MinorUnit;
#[cfg(feature = "diesel")]
use diesel::{sql_types::Jsonb, AsExpression, FromSqlRow};
use serde::{Deserialize, Serialize};
@@ -13,6 +14,22 @@ use crate::{
payments::MultiCurrencyProcessingAmountData,
};
+/// InterPayments refund tracking. Only set for a partial surcharge refund.
+#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
+#[cfg_attr(feature = "diesel", derive(FromSqlRow, AsExpression))]
+#[cfg_attr(feature = "diesel", diesel(sql_type = Jsonb))]
+pub struct ExternalSurchargeRefundDetails {
+ /// New InterPayments refund ID returned by Init, used for Complete.
+ pub surcharge_refund_id: String,
+ /// Surcharge fee for this refund, returned by Init.
+ pub refund_surcharge_amount: MinorUnit,
+ /// Whether Complete has succeeded.
+ pub refund_complete_notified: bool,
+}
+
+#[cfg(feature = "diesel")]
+impl_to_sql_from_sql_json!(ExternalSurchargeRefundDetails);
+
#[derive(Default, Debug, ToSchema, Clone, PartialEq, Eq, Deserialize, Serialize, SmithyModel)]
#[cfg_attr(feature = "diesel", derive(FromSqlRow, AsExpression))]
#[cfg_attr(feature = "diesel", diesel(sql_type = Jsonb))]
diff --git a/crates/diesel_models/src/query/refund.rs b/crates/diesel_models/src/query/refund.rs
index 2692acb527..1fc017bfc8 100644
--- a/crates/diesel_models/src/query/refund.rs
+++ b/crates/diesel_models/src/query/refund.rs
@@ -48,7 +48,7 @@ impl Refund {
dsl::refund_id
.eq(self.refund_id.to_owned())
.and(dsl::processor_merchant_id.eq(processor_merchant_id)),
- RefundUpdateInternal::from(refund),
+ RefundUpdateInternal::from(refund).populate_derived_fields(&self),
)
.await
{
@@ -80,7 +80,7 @@ impl Refund {
dsl::refund_id
.eq(self.refund_id.to_owned())
.and(dsl::merchant_id.eq(processor_merchant_id)),
- RefundUpdateInternal::from(refund),
+ RefundUpdateInternal::from(refund).populate_derived_fields(&self),
)
.await
{
diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs
index 15858cba12..60f8e928e4 100644
--- a/crates/diesel_models/src/refund.rs
+++ b/crates/diesel_models/src/refund.rs
@@ -76,6 +76,9 @@ pub struct Refund {
pub refund_surcharge_amount: Option<MinorUnit>,
#[serde(default)]
pub net_refund_amount: Option<MinorUnit>,
+ #[serde(default)]
+ pub external_surcharge_refund_details:
+ Option<common_types::refunds::ExternalSurchargeRefundDetails>,
}
impl Refund {
@@ -111,6 +114,13 @@ impl Refund {
internal_reference_id,
)
}
+
+ /// The surcharge refund tracking stored on this refund, if it has one.
+ pub fn surcharge_refund_details(
+ &self,
+ ) -> Option<common_types::refunds::ExternalSurchargeRefundDetails> {
+ self.external_surcharge_refund_details.clone()
+ }
}
#[cfg(feature = "v2")]
@@ -168,6 +178,9 @@ pub struct Refund {
pub refund_surcharge_amount: Option<MinorUnit>,
#[serde(default)]
pub net_refund_amount: Option<MinorUnit>,
+ #[serde(default)]
+ pub external_surcharge_refund_details:
+ Option<common_types::refunds::ExternalSurchargeRefundDetails>,
pub id: id_type::GlobalRefundId,
#[diesel(deserialize_as = RequiredFromNullable<id_type::RefundReferenceId>)]
pub merchant_reference_id: id_type::RefundReferenceId,
@@ -228,6 +241,9 @@ pub struct RefundNew {
pub refund_surcharge_amount: Option<MinorUnit>,
#[serde(default)]
pub net_refund_amount: Option<MinorUnit>,
+ #[serde(default)]
+ pub external_surcharge_refund_details:
+ Option<common_types::refunds::ExternalSurchargeRefundDetails>,
}
#[cfg(feature = "v2")]
@@ -284,6 +300,9 @@ pub struct RefundNew {
pub refund_surcharge_amount: Option<MinorUnit>,
#[serde(default)]
pub net_refund_amount: Option<MinorUnit>,
+ #[serde(default)]
+ pub external_surcharge_refund_details:
+ Option<common_types::refunds::ExternalSurchargeRefundDetails>,
}
#[cfg(feature = "v1")]
@@ -329,6 +348,11 @@ pub enum RefundUpdate {
refund_error_code: Option<Option<String>>,
updated_by: String,
},
+ /// Persist InterPayments Init/Complete progress through the normal update path.
+ SurchargeUpdate {
+ external_surcharge_refund_details: common_types::refunds::ExternalSurchargeRefundDetails,
+ updated_by: String,
+ },
}
#[cfg(feature = "v2")]
@@ -394,6 +418,10 @@ pub struct RefundUpdateInternal {
unified_message: Option<String>,
issuer_error_code: Option<String>,
issuer_error_message: Option<String>,
+ refund_surcharge_amount: Option<MinorUnit>,
+ net_refund_amount: Option<MinorUnit>,
+ external_surcharge_refund_details:
+ Option<common_types::refunds::ExternalSurchargeRefundDetails>,
}
#[cfg(feature = "v2")]
@@ -436,6 +464,18 @@ impl RefundUpdateInternal {
..source
}
}
+
+ /// Stores the surcharge fee and derives `net_refund_amount` as order + surcharge amount.
+ pub fn populate_derived_fields(self, source: &Refund) -> Self {
+ let mut update_internal = self;
+ let surcharge = update_internal
+ .refund_surcharge_amount
+ .or(source.refund_surcharge_amount);
+ update_internal.refund_surcharge_amount = surcharge;
+ update_internal.net_refund_amount =
+ Some(source.refund_amount + surcharge.unwrap_or_default());
+ update_internal
+ }
}
#[cfg(feature = "v2")]
@@ -488,6 +528,9 @@ impl From<RefundUpdate> for RefundUpdateInternal {
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
+ refund_surcharge_amount: None,
+ net_refund_amount: None,
+ external_surcharge_refund_details: None,
},
RefundUpdate::MetadataAndReasonUpdate {
metadata,
@@ -509,6 +552,9 @@ impl From<RefundUpdate> for RefundUpdateInternal {
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
+ refund_surcharge_amount: None,
+ net_refund_amount: None,
+ external_surcharge_refund_details: None,
},
RefundUpdate::StatusUpdate {
connector_refund_id,
@@ -532,6 +578,9 @@ impl From<RefundUpdate> for RefundUpdateInternal {
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
+ refund_surcharge_amount: None,
+ net_refund_amount: None,
+ external_surcharge_refund_details: None,
},
RefundUpdate::ErrorUpdate {
refund_status,
@@ -560,6 +609,9 @@ impl From<RefundUpdate> for RefundUpdateInternal {
unified_message,
issuer_error_code,
issuer_error_message,
+ refund_surcharge_amount: None,
+ net_refund_amount: None,
+ external_surcharge_refund_details: None,
},
RefundUpdate::ManualUpdate {
connector_refund_id,
@@ -583,6 +635,34 @@ impl From<RefundUpdate> for RefundUpdateInternal {
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
+ refund_surcharge_amount: None,
+ net_refund_amount: None,
+ external_surcharge_refund_details: None,
+ },
+ RefundUpdate::SurchargeUpdate {
+ external_surcharge_refund_details,
+ updated_by,
+ } => Self {
+ refund_status: None,
+ refund_surcharge_amount: Some(
+ external_surcharge_refund_details.refund_surcharge_amount,
+ ),
+ net_refund_amount: None,
+ external_surcharge_refund_details: Some(external_surcharge_refund_details),
+ updated_by,
+ connector_refund_id: None,
+ sent_to_gateway: None,
+ refund_error_message: None,
+ refund_arn: None,
+ metadata: None,
+ refund_reason: None,
+ refund_error_code: None,
+ modified_at: common_utils::date_time::now(),
+ processor_refund_data: None,
+ unified_code: None,
+ unified_message: None,
+ issuer_error_code: None,
+ issuer_error_message: None,
},
}
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 9f43fcf3c2..6f2f0b6ed0 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1715,6 +1715,7 @@ diesel::table! {
feature_metadata -> Nullable<Jsonb>,
refund_surcharge_amount -> Nullable<Int8>,
net_refund_amount -> Nullable<Int8>,
+ external_surcharge_refund_details -> Nullable<Jsonb>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 66c7648d38..6362f95058 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -1621,6 +1621,7 @@ diesel::table! {
feature_metadata -> Nullable<Jsonb>,
refund_surcharge_amount -> Nullable<Int8>,
net_refund_amount -> Nullable<Int8>,
+ external_surcharge_refund_details -> Nullable<Jsonb>,
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rs
index 91e0a60804..2d116045f4 100644
--- a/crates/external_services/src/grpc_client/unified_connector_service.rs
+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs
@@ -1619,6 +1619,60 @@ impl UnifiedConnectorServiceClient {
})
}
+ /// Initiate a surcharge refund using the original surcharge transaction ID.
+ pub async fn surcharge_refund_init(
+ &self,
+ data: payments_grpc::SurchargeServiceSurchargeRefundInitRequest,
+ connector_auth_metadata: ConnectorAuthMetadata,
+ grpc_headers: GrpcHeadersUcs,
+ ) -> UnifiedConnectorServiceResult<
+ tonic::Response<payments_grpc::SurchargeServiceSurchargeRefundInitResponse>,
+ > {
+ let connector_name = connector_auth_metadata.connector_name.clone();
+ let mut request = tonic::Request::new(data);
+ *request.metadata_mut() = build_unified_connector_service_grpc_headers_for_surcharge(
+ connector_auth_metadata,
+ grpc_headers,
+ )?;
+ self.surcharge_service_client
+ .clone()
+ .surcharge_refund_init(request)
+ .await
+ .map_err(|error| {
+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(
+ &error,
+ &connector_name,
+ ))
+ })
+ }
+
+ /// Complete a surcharge refund using the ID returned by Init.
+ pub async fn surcharge_refund_complete(
+ &self,
+ data: payments_grpc::SurchargeServiceSurchargeRefundCompleteRequest,
+ connector_auth_metadata: ConnectorAuthMetadata,
+ grpc_headers: GrpcHeadersUcs,
+ ) -> UnifiedConnectorServiceResult<
+ tonic::Response<payments_grpc::SurchargeServiceSurchargeRefundCompleteResponse>,
+ > {
+ let connector_name = connector_auth_metadata.connector_name.clone();
+ let mut request = tonic::Request::new(data);
+ *request.metadata_mut() = build_unified_connector_service_grpc_headers_for_surcharge(
+ connector_auth_metadata,
+ grpc_headers,
+ )?;
+ self.surcharge_service_client
+ .clone()
+ .surcharge_refund_complete(request)
+ .await
+ .map_err(|error| {
+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(
+ &error,
+ &connector_name,
+ ))
+ })
+ }
+
/// Performs a pre-authorization risk check via the FRM Service.
pub async fn frm_pre_risk_check(
&self,
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index 505102064b..33d6c09c57 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -12825,6 +12825,30 @@ impl<const T: u8>
{
}
+#[cfg(feature = "dummy_connector")]
+impl<const T: u8> api::SurchargeRefundInit for connectors::DummyConnector<T> {}
+#[cfg(feature = "dummy_connector")]
+impl<const T: u8>
+ ConnectorIntegration<
+ hyperswitch_domain_models::router_flow_types::payments::SurchargeRefundInit,
+ hyperswitch_domain_models::router_request_types::PaymentsSurchargeRefundInitData,
+ hyperswitch_domain_models::router_response_types::SurchargeRefundInitResponseData,
+ > for connectors::DummyConnector<T>
+{
+}
+
+#[cfg(feature = "dummy_connector")]
+impl<const T: u8> api::SurchargeRefundComplete for connectors::DummyConnector<T> {}
+#[cfg(feature = "dummy_connector")]
+impl<const T: u8>
+ ConnectorIntegration<
+ hyperswitch_domain_models::router_flow_types::payments::SurchargeRefundComplete,
+ hyperswitch_domain_models::router_request_types::PaymentsSurchargeRefundCompleteData,
+ hyperswitch_domain_models::router_response_types::SurchargeRefundCompleteResponseData,
+ > for connectors::DummyConnector<T>
+{
+}
+
#[cfg(feature = "dummy_connector")]
impl<const T: u8> SurchargeRefund for connectors::DummyConnector<T> {}
#[cfg(feature = "dummy_connector")]
diff --git a/crates/hyperswitch_domain_models/src/refunds.rs b/crates/hyperswitch_domain_models/src/refunds.rs
index d1cd822132..80e3716981 100644
--- a/crates/hyperswitch_domain_models/src/refunds.rs
+++ b/crates/hyperswitch_domain_models/src/refunds.rs
@@ -2,7 +2,6 @@ use common_utils::types::MinorUnit;
#[cfg(feature = "v2")]
use crate::business_profile::Profile;
-#[cfg(feature = "v1")]
use crate::errors;
/// Amounts that make up a refund. Older refunds have no surcharge component.
@@ -254,3 +253,27 @@ impl From<(api_models::refunds::RefundListRequest, Profile)> for RefundListConst
}
}
}
+
+pub fn validate_surcharge_order_amount(
+ original: i64,
+ remaining: i64,
+ requested: i64,
+) -> Result<(), error_stack::Report<errors::api_error_response::ApiErrorResponse>> {
+ if requested > original {
+ return Err(error_stack::Report::new(
+ errors::api_error_response::ApiErrorResponse::PreconditionFailed {
+ message: "Requested refund amount is greater than the original order amount."
+ .to_string(),
+ },
+ ));
+ }
+ if requested > remaining {
+ return Err(error_stack::Report::new(
+ errors::api_error_response::ApiErrorResponse::PreconditionFailed {
+ message: "Requested refund amount exceeds the remaining refundable order amount."
+ .to_string(),
+ },
+ ));
+ }
+ Ok(())
+}
diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
index 79884d2959..9b636f8477 100644
--- a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
+++ b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
@@ -77,6 +77,14 @@ pub struct CompleteSurcharge;
#[derive(Debug, Clone)]
pub struct CompleteRefundSurchrge;
+/// Initialize a surcharge refund before submitting the processor refund.
+#[derive(Debug, Clone)]
+pub struct SurchargeRefundInit;
+
+/// Complete the initialized surcharge refund after processor success.
+#[derive(Debug, Clone)]
+pub struct SurchargeRefundComplete;
+
#[derive(Debug, Clone)]
pub struct SdkSessionUpdate;
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index 12109f878f..e0d6854fca 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -1882,6 +1882,20 @@ pub struct PaymentsCompleteSurchargeData {
pub amount: Option<MinorUnit>,
}
+#[derive(Clone, Debug, Serialize)]
+pub struct PaymentsSurchargeRefundInitData {
+ pub refund_id: String,
+ pub original_surcharge_id: String,
+ pub order_amount: MinorUnit,
+ pub currency: common_enums::Currency,
+}
+
+#[derive(Clone, Debug, Serialize)]
+pub struct PaymentsSurchargeRefundCompleteData {
+ pub refund_id: String,
+ pub connector_surcharge_refund_id: String,
+}
+
#[derive(Debug, Clone)]
pub struct PaymentsCompleteRefundSurchrgeData {
/// transaction ID from surcharge connectors
diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs
index 1c33774db8..c691486005 100644
--- a/crates/hyperswitch_domain_models/src/router_response_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_response_types.rs
@@ -169,6 +169,18 @@ pub struct CompleteSurchargeResponseData {
pub connector_surcharge_id: String,
}
+/// Validated Init result: the surcharge fee owed for this refund.
+#[derive(Debug, Clone, Serialize)]
+pub struct SurchargeRefundInitResponseData {
+ pub refund_surcharge_amount: MinorUnit,
+ pub original_transaction_fee: Option<MinorUnit>,
+ pub previously_refunded_transaction_fees: Option<MinorUnit>,
+}
+
+/// Acknowledgement that Complete succeeded; validated against the request, nothing to carry.
+#[derive(Debug, Clone, Serialize)]
+pub struct SurchargeRefundCompleteResponseData;
+
/// Response data for refunding surcharge
#[derive(Debug, Clone)]
pub struct CompleteRefundSurchrgeResponseData {
diff --git a/crates/hyperswitch_interfaces/src/api/payments.rs b/crates/hyperswitch_interfaces/src/api/payments.rs
index aa16055fb2..dcf6ffb3ac 100644
--- a/crates/hyperswitch_interfaces/src/api/payments.rs
+++ b/crates/hyperswitch_interfaces/src/api/payments.rs
@@ -8,7 +8,9 @@ use hyperswitch_domain_models::{
ExtendAuthorization, GenerateQr, IncrementalAuthorization, PSync, PaymentMethodToken,
PostCaptureVoid, PostCaptureVoidSync, PostProcessing, PostSessionTokens,
PreAuthorizeVoid, PushNotification, Reject, SdkSessionUpdate, Session,
- SettlementSplitCreate, SetupMandate, UpdateMetadata, Void,
+ SettlementSplitCreate, SetupMandate,
+ SurchargeRefundComplete as SurchargeRefundCompleteFlow,
+ SurchargeRefundInit as SurchargeRefundInitFlow, UpdateMetadata, Void,
},
Authenticate, CreateOrder, ExternalVaultProxy, GiftCardBalanceCheck, PostAuthenticate,
PreAuthenticate, UpdatePostConfirm,
@@ -23,14 +25,15 @@ use hyperswitch_domain_models::{
PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData,
PaymentsPostAuthenticateData, PaymentsPostProcessingData, PaymentsPostSessionTokensData,
PaymentsPreAuthenticateData, PaymentsPreAuthorizeCancelData, PaymentsRejectData,
- PaymentsSessionData, PaymentsSurchargeCalculationData, PaymentsSyncData,
- PaymentsTaxCalculationData, PaymentsUpdateMetadataData, PaymentsUpdatePostConfirmData,
- PushNotificationRequestData, SdkPaymentsSessionUpdateData, SettlementSplitRequestData,
- SetupMandateRequestData,
+ PaymentsSessionData, PaymentsSurchargeCalculationData, PaymentsSurchargeRefundCompleteData,
+ PaymentsSurchargeRefundInitData, PaymentsSyncData, PaymentsTaxCalculationData,
+ PaymentsUpdateMetadataData, PaymentsUpdatePostConfirmData, PushNotificationRequestData,
+ SdkPaymentsSessionUpdateData, SettlementSplitRequestData, SetupMandateRequestData,
},
router_response_types::{
CompleteRefundSurchrgeResponseData, CompleteSurchargeResponseData,
GiftCardBalanceCheckResponseData, PaymentsResponseData, SurchargeCalculationResponseData,
+ SurchargeRefundCompleteResponseData, SurchargeRefundInitResponseData,
TaxCalculationResponseData,
},
};
@@ -204,6 +207,26 @@ pub trait SurchargeComplete:
{
}
+/// Initializes an external surcharge refund and returns its fee and new refund ID.
+pub trait SurchargeRefundInit:
+ api::ConnectorIntegration<
+ SurchargeRefundInitFlow,
+ PaymentsSurchargeRefundInitData,
+ SurchargeRefundInitResponseData,
+>
+{
+}
+
+/// Completes an external surcharge refund after the processor refund succeeds.
+pub trait SurchargeRefundComplete:
+ api::ConnectorIntegration<
+ SurchargeRefundCompleteFlow,
+ PaymentsSurchargeRefundCompleteData,
+ SurchargeRefundCompleteResponseData,
+>
+{
+}
+
/// trait SurchargeRefund
pub trait SurchargeRefund:
api::ConnectorIntegration<
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 1407c2e03a..51a1460ff0 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -1,3 +1,5 @@
+pub mod surcharge;
+
#[cfg(feature = "olap")]
use std::collections::HashMap;
@@ -1748,12 +1750,15 @@ pub async fn validate_and_create_refund(
),
})?;
- let refund_amount_details = RefundAmountDetails::from(refund_amount);
let total_amount_captured = payment_intent
.amount_captured
.unwrap_or(payment_attempt.get_total_amount());
- validator::validate_refund_amount(total_amount_captured, &all_refunds, refund_amount_details)
- .change_context(errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount)?;
+ validator::validate_refund_amount(
+ total_amount_captured,
+ &all_refunds,
+ RefundAmountDetails::from(refund_amount),
+ )
+ .change_context(errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount)?;
validator::validate_maximum_refund_against_payment_attempt(
&all_refunds,
@@ -1761,6 +1766,30 @@ pub async fn validate_and_create_refund(
)
.change_context(errors::ApiErrorResponse::MaximumRefundCount)?;
+ // Surcharge refund: (1) validate the requested order amount, (2) initiate — Init to get the fee.
+ // The fee/tracking is set on the new refund row below so it carries the correct net amount.
+ // `None` is a plain or full refund (legacy path).
+ let surcharge_context = surcharge::validate_partial_refund(
+ payment_attempt,
+ payment_intent,
+ req.amount,
+ &all_refunds,
+ )?;
+ let surcharge_details = match &surcharge_context {
+ Some(context) => Some(
+ surcharge::init_surcharge_refund(state, platform, payment_attempt, &refund_id, context)
+ .await?,
+ ),
+ None => None,
+ };
+ let refund_amount_details = match (&surcharge_context, &surcharge_details) {
+ (Some(context), Some(details)) => RefundAmountDetails::new(
+ context.order_amount(),
+ Some(details.refund_surcharge_amount),
+ ),
+ _ => RefundAmountDetails::from(refund_amount),
+ };
+
let connector = payment_attempt
.connector
.clone()
@@ -1809,6 +1838,8 @@ pub async fn validate_and_create_refund(
refund_amount,
refund_surcharge_amount,
net_refund_amount: Some(net_refund_amount),
+ // For a partial surcharge refund, Init already succeeded, so the row carries its tracking.
+ external_surcharge_refund_details: surcharge_details.clone(),
currency,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
diff --git a/crates/router/src/core/refunds/surcharge.rs b/crates/router/src/core/refunds/surcharge.rs
new file mode 100644
index 0000000000..0d96439bc3
--- /dev/null
+++ b/crates/router/src/core/refunds/surcharge.rs
@@ -0,0 +1,472 @@
+//! InterPayments surcharge refund orchestration.
+//!
+//! Partial refunds run the two-call Init/Complete protocol; a whole-order refund keeps the legacy
+//! single call. The refund-create flow runs two steps, and the webhook runs the third:
+//!
+//! - [`validate_partial_refund`] (create, step 1): validate the requested order amount against the
+//! remaining balance.
+//! - [`init_surcharge_refund`] (create, step 2): calculate the surcharge fee via Init; the caller
+//! stores it on the new refund row (so the row carries the correct net amount for execution).
+//! - [`complete_from_webhook`] (off the refund's outgoing webhook): call Complete and record it.
+
+use common_types::refunds::ExternalSurchargeRefundDetails;
+use common_utils::types::MinorUnit;
+use diesel_models::refund::{Refund, RefundUpdate};
+use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ router_request_types::{PaymentsSurchargeRefundCompleteData, PaymentsSurchargeRefundInitData},
+ router_response_types::{SurchargeRefundCompleteResponseData, SurchargeRefundInitResponseData},
+};
+use router_env::logger;
+
+use crate::{
+ core::{
+ errors::{self, RouterResult},
+ payments::helpers,
+ unified_connector_service as ucs,
+ },
+ routes::SessionState,
+ types::{domain, storage, transformers::ForeignTryFrom},
+};
+
+// ------------------------------------------------------------------------------------------------
+// validate — the balances a requested amount is checked against.
+// ------------------------------------------------------------------------------------------------
+
+/// Error for an overflow in the surcharge balance arithmetic (should never happen for real amounts).
+fn arithmetic_overflow() -> error_stack::Report<errors::ApiErrorResponse> {
+ error_stack::Report::new(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Arithmetic overflow while computing surcharge refund balances")
+}
+
+/// How much order amount and surcharge fee remain refundable, derived from the original attempt
+/// and the stored amounts on previous refunds. No I/O.
+#[derive(Clone, Copy, Debug)]
+struct SurchargeRefundBalances {
+ /// Order amount of the original payment, excluding the surcharge fee.
+ original_order_amount: i64,
+ /// Order amount still refundable after previous refunds.
+ remaining_order_amount: i64,
+ /// Surcharge fee of the original payment.
+ original_surcharge_amount: i64,
+ /// Surcharge fee still refundable after previous refunds.
+ remaining_surcharge_amount: i64,
+}
+
+impl SurchargeRefundBalances {
+ /// Pure calculation: derives the balances from the originally-charged surcharge amount and the
+ /// stored amounts on previous (non-failed) refunds. The caller (`validate_partial_refund`) has
+ /// already verified that a usable surcharge applies, so there is nothing to validate here.
+ fn from_previous_refunds(
+ attempt: &storage::PaymentAttempt,
+ original_surcharge_amount: MinorUnit,
+ previous_refunds: &[Refund],
+ ) -> RouterResult<Self> {
+ let original_surcharge_amount = original_surcharge_amount.get_amount_as_i64();
+ let original_order_amount = attempt
+ .get_total_amount()
+ .get_amount_as_i64()
+ .checked_sub(original_surcharge_amount)
+ .ok_or_else(arithmetic_overflow)?;
+
+ let mut refunded_order_amount: i64 = 0;
+ let mut refunded_surcharge_amount: i64 = 0;
+ for refund in previous_refunds
+ .iter()
+ .filter(|refund| !refund.refund_status.is_failure())
+ {
+ refunded_order_amount = refunded_order_amount
+ .checked_add(refund.refund_amount.get_amount_as_i64())
+ .ok_or_else(arithmetic_overflow)?;
+ refunded_surcharge_amount = refunded_surcharge_amount
+ .checked_add(
+ refund
+ .refund_surcharge_amount
+ .unwrap_or_default()
+ .get_amount_as_i64(),
+ )
+ .ok_or_else(arithmetic_overflow)?;
+ }
+
+ Ok(Self {
+ original_order_amount,
+ remaining_order_amount: original_order_amount
+ .checked_sub(refunded_order_amount)
+ .ok_or_else(arithmetic_overflow)?,
+ original_surcharge_amount,
+ remaining_surcharge_amount: original_surcharge_amount
+ .checked_sub(refunded_surcharge_amount)
+ .ok_or_else(arithmetic_overflow)?,
+ })
+ }
+
+ /// A whole-order refund (the entire order amount, with no prior non-failed refund) keeps the
+ /// legacy single-call path rather than the partial Init/Complete protocol.
+ fn is_whole_order_refund(
+ &self,
+ requested: Option<MinorUnit>,
+ previous_refunds: &[Refund],
+ ) -> bool {
+ previous_refunds
+ .iter()
+ .all(|refund| refund.refund_status.is_failure())
+ && requested
+ .is_none_or(|amount| amount.get_amount_as_i64() == self.original_order_amount)
+ }
+
+ /// Create-flow check of the requested order amount against the remaining order balance. The
+ /// captured-funds check is left to the generic `validate_refund_amount`.
+ fn validate_requested_order_amount(
+ &self,
+ requested_order_amount: MinorUnit,
+ ) -> RouterResult<()> {
+ hyperswitch_domain_models::refunds::validate_surcharge_order_amount(
+ self.original_order_amount,
+ self.remaining_order_amount,
+ requested_order_amount.get_amount_as_i64(),
+ )
+ }
+
+ /// Checks the Init-reported surcharge fee against the remaining surcharge balance and guards
+ /// against an InterPayments inconsistency. Runs after Init (the fee only exists then), not in
+ /// the create flow.
+ fn validate_init_surcharge_fee(
+ &self,
+ response: &SurchargeRefundInitResponseData,
+ ) -> RouterResult<()> {
+ let refund_surcharge_fee = response.refund_surcharge_amount;
+ if refund_surcharge_fee < MinorUnit::zero()
+ || refund_surcharge_fee.get_amount_as_i64() > self.remaining_surcharge_amount
+ {
+ return Err(error_stack::Report::new(
+ errors::ApiErrorResponse::PreconditionFailed {
+ message: "Surcharge refund exceeds remaining surcharge amount".to_string(),
+ },
+ ));
+ }
+ // Init echoes the original surcharge InterPayments recorded. If it disagrees with what we
+ // charged, our records are out of sync — reject and flag for reconciliation.
+ let original_fee_mismatch = response
+ .original_transaction_fee
+ .is_some_and(|amount| amount.get_amount_as_i64() != self.original_surcharge_amount);
+ // This refund's fee plus everything InterPayments already refunded must not exceed the
+ // original fee (checked add avoids overflow on the running total).
+ let refunded_fee_exceeded = match response.previously_refunded_transaction_fees {
+ Some(previously_refunded) => {
+ refund_surcharge_fee
+ .get_amount_as_i64()
+ .checked_add(previously_refunded.get_amount_as_i64())
+ .ok_or_else(arithmetic_overflow)?
+ > self.original_surcharge_amount
+ }
+ None => false,
+ };
+ if original_fee_mismatch || refunded_fee_exceeded {
+ return Err(error_stack::Report::new(
+ errors::ApiErrorResponse::PreconditionFailed {
+ message:
+ "InterPayments surcharge balance is inconsistent; reconciliation required"
+ .to_string(),
+ },
+ ));
+ }
+ Ok(())
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+// Create — two steps the refund-create flow runs: `validate_partial_refund`, then
+// `init_surcharge_refund`.
+// ------------------------------------------------------------------------------------------------
+
+/// A validated partial surcharge refund: the order-only amount to refund, plus the balances the
+/// surcharge fee is later checked against. Produced by [`validate_partial_refund`], consumed by
+/// [`init_surcharge_refund`].
+pub struct SurchargeRefundContext {
+ order_amount: MinorUnit,
+ balances: SurchargeRefundBalances,
+}
+
+impl SurchargeRefundContext {
+ /// The order-only amount this refund will refund (what goes on the refund row).
+ pub fn order_amount(&self) -> MinorUnit {
+ self.order_amount
+ }
+}
+
+/// Step 1 (validate): for a partial surcharge refund, validate the requested order amount against
+/// the remaining order balance. Returns the validated context for [`init_surcharge_refund`];
+/// `None` for a plain or whole-order refund, which takes the legacy path.
+pub fn validate_partial_refund(
+ attempt: &storage::PaymentAttempt,
+ intent: &storage::PaymentIntent,
+ requested_amount: Option<MinorUnit>,
+ previous_refunds: &[Refund],
+) -> RouterResult<Option<SurchargeRefundContext>> {
+ // The usable surcharge charged on the original payment (same condition as `has_surcharge`).
+ let usable_surcharge = attempt
+ .external_surcharge_details
+ .as_ref()
+ .filter(|details| details.usable_connector_id().is_some());
+
+ match usable_surcharge {
+ // No usable surcharge: a plain refund (legacy path), unless one was actually charged and its
+ // details are now lost — then reconciliation is required.
+ None => {
+ let surcharge_was_calculated = intent.external_surcharge_applicable == Some(true)
+ && attempt
+ .net_amount
+ .get_surcharge_amount()
+ .is_some_and(|surcharge| surcharge > MinorUnit::zero());
+ if surcharge_was_calculated {
+ Err(error_stack::Report::new(
+ errors::ApiErrorResponse::PreconditionFailed {
+ message:
+ "Missing original external surcharge details; reconciliation required"
+ .to_string(),
+ },
+ ))
+ } else {
+ Ok(None)
+ }
+ }
+ // The charged surcharge on the attempt must match the stored breakdown.
+ Some(details)
+ if attempt.net_amount.get_surcharge_amount()
+ != Some(details.external_surcharge_amount) =>
+ {
+ Err(error_stack::Report::new(
+ errors::ApiErrorResponse::PreconditionFailed {
+ message: "Charged surcharge breakdown mismatch; reconciliation required"
+ .to_string(),
+ },
+ ))
+ }
+ Some(details) => {
+ let balances = SurchargeRefundBalances::from_previous_refunds(
+ attempt,
+ details.external_surcharge_amount,
+ previous_refunds,
+ )?;
+ // A whole-order refund keeps the legacy single-call path; only partial refunds use
+ // Init/Complete.
+ if balances.is_whole_order_refund(requested_amount, previous_refunds) {
+ Ok(None)
+ } else {
+ let order_amount = requested_amount
+ .unwrap_or_else(|| MinorUnit::new(balances.remaining_order_amount));
+ balances.validate_requested_order_amount(order_amount)?;
+ Ok(Some(SurchargeRefundContext {
+ order_amount,
+ balances,
+ }))
+ }
+ }
+ }
+}
+
+/// Step 2 (initiate/calculate): call InterPayments Init for the validated order amount, validate the
+/// returned fee, and return the surcharge tracking to store on the refund row. Runs before the row
+/// is inserted, so any error simply fails the create (nothing is persisted).
+pub async fn init_surcharge_refund(
+ state: &SessionState,
+ platform: &domain::Platform,
+ attempt: &storage::PaymentAttempt,
+ refund_id: &str,
+ context: &SurchargeRefundContext,
+) -> RouterResult<ExternalSurchargeRefundDetails> {
+ let currency = attempt.currency.ok_or_else(|| {
+ error_stack::Report::new(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Missing currency on payment attempt")
+ })?;
+ let profile_id = &attempt.profile_id;
+ let mca = resolve_interpayments_account(state, platform, profile_id).await?;
+ let original_surcharge_id = attempt
+ .external_surcharge_details
+ .as_ref()
+ .and_then(|details| details.usable_connector_id())
+ .ok_or_else(|| {
+ error_stack::Report::new(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Missing original surcharge ID on payment attempt")
+ })?
+ .to_owned();
+
+ let response = ucs::call_unified_connector_service_for_surcharge_refund_init(
+ state,
+ platform.get_processor(),
+ mca,
+ profile_id,
+ PaymentsSurchargeRefundInitData {
+ refund_id: refund_id.to_owned(),
+ original_surcharge_id,
+ order_amount: context.order_amount,
+ currency,
+ },
+ )
+ .await
+ .attach_printable("SurchargeRefundInit call failed")?;
+
+ let data = SurchargeRefundInitResponseData::foreign_try_from((&response, refund_id, currency))
+ .map_err(|message| {
+ error_stack::Report::new(errors::ApiErrorResponse::PreconditionFailed {
+ message: message.to_string(),
+ })
+ })?;
+
+ context.balances.validate_init_surcharge_fee(&data)?;
+
+ let surcharge_refund_id = response
+ .connector_surcharge_refund_id
+ .clone()
+ .filter(|id| !id.trim().is_empty())
+ .ok_or_else(|| {
+ error_stack::Report::new(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "SurchargeRefundInit succeeded but returned no surcharge refund ID",
+ )
+ })?;
+
+ Ok(ExternalSurchargeRefundDetails {
+ surcharge_refund_id,
+ refund_surcharge_amount: data.refund_surcharge_amount,
+ refund_complete_notified: false,
+ })
+}
+
+/// Drives `SurchargeRefundComplete` from the refund's outgoing webhook delivery.
+///
+/// `None` when the refund is not a partial surcharge refund (no Init ran) — caller takes the
+/// ordinary notify path. Otherwise calls Complete and returns a `NotifyConnectorResponseData` that
+/// plugs into the generic notify success/retry handling. A failure reschedules the webhook, never
+/// the refund: the money is already refunded.
+#[cfg(all(feature = "oltp", feature = "v1"))]
+pub async fn complete_from_webhook(
+ state: &SessionState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ key_store: &domain::MerchantKeyStore,
+ profile_id: &common_utils::id_type::ProfileId,
+ surcharge_account: helpers::MerchantConnectorAccountType,
+ refund_id: &str,
+) -> error_stack::Result<
+ Option<hyperswitch_domain_models::router_response_types::NotifyConnectorResponseData>,
+ errors::ApiClientError,
+> {
+ let acknowledged =
+ hyperswitch_domain_models::router_response_types::NotifyConnectorResponseData {
+ status_code: 200,
+ error_code: None,
+ error_message: None,
+ };
+
+ let storage_scheme = state
+ .store
+ .find_merchant_account_by_merchant_id(merchant_id, key_store)
+ .await
+ .map(|account| account.storage_scheme)
+ .unwrap_or_default();
+
+ let refund = state
+ .store
+ .find_refund_by_processor_merchant_id_refund_id(merchant_id, refund_id, storage_scheme)
+ .await
+ .change_context(errors::ApiClientError::UnexpectedServerResponse)
+ .attach_printable("Failed to fetch refund for SurchargeRefundComplete")?;
+
+ // Not a partial surcharge refund (no Init ran): let the caller take the ordinary notify path.
+ let Some(details) = refund.surcharge_refund_details() else {
+ return Ok(None);
+ };
+ // Already completed: the gate that keeps Complete to exactly one successful call per refund.
+ if details.refund_complete_notified {
+ return Ok(Some(acknowledged));
+ }
+
+ let response = ucs::call_unified_connector_service_for_surcharge_refund_complete(
+ state,
+ merchant_id,
+ surcharge_account,
+ profile_id,
+ PaymentsSurchargeRefundCompleteData {
+ refund_id: refund.refund_id.clone(),
+ connector_surcharge_refund_id: details.surcharge_refund_id.clone(),
+ },
+ )
+ .await
+ .change_context(errors::ApiClientError::UnexpectedServerResponse)
+ .attach_printable("SurchargeRefundComplete call failed")?;
+
+ SurchargeRefundCompleteResponseData::foreign_try_from((
+ &response,
+ refund.refund_id.as_str(),
+ details.surcharge_refund_id.as_str(),
+ ))
+ .map_err(|message| {
+ error_stack::Report::new(errors::ApiClientError::UnexpectedServerResponse)
+ .attach_printable(message.to_string())
+ })?;
+
+ // Record the acknowledgement so a webhook retry can't re-call Complete. A persist failure is
+ // only logged, since the connector has already acknowledged.
+ let completed = ExternalSurchargeRefundDetails {
+ refund_complete_notified: true,
+ ..details
+ };
+ if let Err(persist_error) = state
+ .store
+ .update_refund(
+ refund.clone(),
+ RefundUpdate::SurchargeUpdate {
+ external_surcharge_refund_details: completed,
+ updated_by: storage_scheme.to_string(),
+ },
+ storage_scheme,
+ )
+ .await
+ {
+ logger::error!(
+ ?persist_error,
+ refund_id = %refund.refund_id,
+ "SurchargeRefundComplete acknowledged but failed to persist refund_complete_notified"
+ );
+ }
+
+ Ok(Some(acknowledged))
+}
+
+// ------------------------------------------------------------------------------------------------
+// Shared — connector resolution used by initiate and complete.
+// ------------------------------------------------------------------------------------------------
+
+/// Resolves the surcharge connector account configured on the profile (the InterPayments MCA).
+async fn resolve_interpayments_account(
+ state: &SessionState,
+ platform: &domain::Platform,
+ profile_id: &common_utils::id_type::ProfileId,
+) -> RouterResult<helpers::MerchantConnectorAccountType> {
+ let processor = platform.get_processor();
+ let business_profile = state
+ .store
+ .find_business_profile_by_profile_id(processor.get_key_store(), profile_id)
+ .await
+ .change_context(errors::ApiErrorResponse::ProfileNotFound {
+ id: profile_id.get_string_repr().to_owned(),
+ })?;
+ let account_id = business_profile
+ .surcharge_connector_details
+ .as_ref()
+ .and_then(|details| details.surcharge_connector_id.as_ref())
+ .ok_or_else(|| {
+ error_stack::Report::new(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Surcharge connector is not configured on the profile".to_string(),
+ })
+ })?;
+ helpers::get_merchant_connector_account(
+ state,
+ processor,
+ None,
+ profile_id,
+ "interpayments",
+ Some(account_id),
+ )
+ .await
+}
diff --git a/crates/router/src/core/refunds_v2.rs b/crates/router/src/core/refunds_v2.rs
index b79db20b20..f40b7e004d 100644
--- a/crates/router/src/core/refunds_v2.rs
+++ b/crates/router/src/core/refunds_v2.rs
@@ -1280,6 +1280,7 @@ pub async fn validate_and_create_refund(
feature_metadata: refund_feature_metadata,
refund_surcharge_amount: None,
net_refund_amount: None,
+ external_surcharge_refund_details: None,
description: req.reason.clone(),
attempt_id: payment_attempt.id.clone(),
refund_reason: req.reason,
diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs
index 0c329bbd30..60e395b89b 100644
--- a/crates/router/src/core/unified_connector_service.rs
+++ b/crates/router/src/core/unified_connector_service.rs
@@ -5456,3 +5456,75 @@ pub async fn call_unified_connector_service_for_notify_connector(
Ok(notify_connector_response_data)
}
+
+#[cfg(feature = "v1")]
+#[instrument(skip_all)]
+pub async fn call_unified_connector_service_for_surcharge_refund_init(
+ state: &SessionState,
+ processor: &Processor,
+ account: MerchantConnectorAccountType,
+ profile_id: &id_type::ProfileId,
+ data: hyperswitch_domain_models::router_request_types::PaymentsSurchargeRefundInitData,
+) -> RouterResult<payments_grpc::SurchargeServiceSurchargeRefundInitResponse> {
+ let auth = build_unified_connector_service_auth_metadata(
+ account,
+ processor.get_account().get_id(),
+ "interpayments".to_owned(),
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ let headers = state
+ .get_grpc_headers_ucs(ExecutionMode::Primary)
+ .payment_method(None)
+ .payment_method_type(None)
+ .lineage_ids(LineageIds::new(
+ processor.get_account().get_id().clone(),
+ profile_id.clone(),
+ ))
+ .external_vault_proxy_metadata(None)
+ .merchant_reference_id(None)
+ .resource_id(None)
+ .build();
+ let request =
+ payments_grpc::SurchargeServiceSurchargeRefundInitRequest::foreign_try_from(&data)
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ get_ucs_client(state)?
+ .surcharge_refund_init(request, auth, headers)
+ .await
+ .map(|response| response.into_inner())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("SurchargeRefundInit outcome is unknown; reconcile before retrying")
+}
+
+#[cfg(feature = "v1")]
+#[instrument(skip_all)]
+pub async fn call_unified_connector_service_for_surcharge_refund_complete(
+ state: &SessionState,
+ merchant_id: &id_type::MerchantId,
+ account: MerchantConnectorAccountType,
+ profile_id: &id_type::ProfileId,
+ data: hyperswitch_domain_models::router_request_types::PaymentsSurchargeRefundCompleteData,
+) -> RouterResult<payments_grpc::SurchargeServiceSurchargeRefundCompleteResponse> {
+ let auth = build_unified_connector_service_auth_metadata(
+ account,
+ merchant_id,
+ "interpayments".to_owned(),
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ let headers = state
+ .get_grpc_headers_ucs(ExecutionMode::Primary)
+ .payment_method(None)
+ .payment_method_type(None)
+ .lineage_ids(LineageIds::new(merchant_id.clone(), profile_id.clone()))
+ .external_vault_proxy_metadata(None)
+ .merchant_reference_id(None)
+ .resource_id(None)
+ .build();
+ let request =
+ payments_grpc::SurchargeServiceSurchargeRefundCompleteRequest::foreign_from(&data);
+ get_ucs_client(state)?
+ .surcharge_refund_complete(request, auth, headers)
+ .await
+ .map(|response| response.into_inner())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("SurchargeRefundComplete outcome is unknown; reconcile before retrying")
+}
diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs
index a93e389fa8..07631f2142 100644
--- a/crates/router/src/core/unified_connector_service/transformers.rs
+++ b/crates/router/src/core/unified_connector_service/transformers.rs
@@ -37,12 +37,14 @@ use hyperswitch_domain_models::{
self, fraud_check::FraudCheckCheckoutData, AuthenticationData,
ExternalVaultProxyPaymentsData, PaymentsAuthorizeData, PaymentsCancelData,
PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData,
- PaymentsPreAuthorizeCancelData, PaymentsSessionData, PaymentsSyncData, RefundsData,
- SetupMandateRequestData, SyncRequestType,
+ PaymentsPreAuthorizeCancelData, PaymentsSessionData, PaymentsSurchargeRefundCompleteData,
+ PaymentsSurchargeRefundInitData, PaymentsSyncData, RefundsData, SetupMandateRequestData,
+ SyncRequestType,
},
router_response_types::{
fraud_check::FraudCheckResponseData, NotifyConnectorResponseData, PaymentsResponseData,
PayoutsResponseData, RedirectForm, RefundsResponseData,
+ SurchargeRefundCompleteResponseData, SurchargeRefundInitResponseData,
},
ApiModelToDieselModelConvertor,
};
@@ -12100,5 +12102,132 @@ impl
}
}
+impl transformers::ForeignTryFrom<&PaymentsSurchargeRefundInitData>
+ for payments_grpc::SurchargeServiceSurchargeRefundInitRequest
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+ fn foreign_try_from(data: &PaymentsSurchargeRefundInitData) -> Result<Self, Self::Error> {
+ Ok(Self {
+ merchant_surcharge_refund_id: Some(data.refund_id.clone()),
+ connector_surcharge_id: data.original_surcharge_id.clone(),
+ amount: Some(payments_grpc::Money {
+ minor_amount: data.order_amount.get_amount_as_i64(),
+ currency:
+ <payments_grpc::Currency as transformers::ForeignTryFrom<_>>::foreign_try_from(
+ data.currency,
+ )?
+ .into(),
+ }),
+ })
+ }
+}
+
+impl ForeignFrom<&PaymentsSurchargeRefundCompleteData>
+ for payments_grpc::SurchargeServiceSurchargeRefundCompleteRequest
+{
+ fn foreign_from(data: &PaymentsSurchargeRefundCompleteData) -> Self {
+ Self {
+ merchant_surcharge_refund_id: Some(data.refund_id.clone()),
+ connector_surcharge_refund_id: data.connector_surcharge_refund_id.clone(),
+ }
+ }
+}
+
+impl
+ transformers::ForeignTryFrom<(
+ &payments_grpc::SurchargeServiceSurchargeRefundInitResponse,
+ &str,
+ common_enums::Currency,
+ )> for SurchargeRefundInitResponseData
+{
+ type Error = &'static str;
+ fn foreign_try_from(
+ (response, reference, payment_currency): (
+ &payments_grpc::SurchargeServiceSurchargeRefundInitResponse,
+ &str,
+ common_enums::Currency,
+ ),
+ ) -> Result<Self, Self::Error> {
+ if response.error.is_some() || !(200..300).contains(&response.status_code) {
+ return Err("Surcharge Init returned a connector error");
+ }
+ if response.merchant_surcharge_refund_id.as_deref() != Some(reference) {
+ return Err("Surcharge Init reference mismatch");
+ }
+ if response
+ .connector_surcharge_refund_id
+ .as_ref()
+ .is_none_or(|id| id.trim().is_empty())
+ {
+ return Err("Surcharge Init is missing the new refund ID");
+ }
+ let currency: i32 =
+ <payments_grpc::Currency as transformers::ForeignTryFrom<_>>::foreign_try_from(
+ payment_currency,
+ )
+ .map_err(|_| "Unknown currency")?
+ .into();
+ let fee = response
+ .refund_amount
+ .as_ref()
+ .ok_or("Surcharge Init is missing refund_amount")?;
+ for money in [
+ Some(fee),
+ response.original_transaction_fee.as_ref(),
+ response.previously_refunded_transaction_fees.as_ref(),
+ ]
+ .into_iter()
+ .flatten()
+ {
+ if money.currency != currency || money.minor_amount < 0 {
+ return Err("Invalid surcharge fee or currency");
+ }
+ }
+ Ok(Self {
+ refund_surcharge_amount: MinorUnit::new(fee.minor_amount),
+ original_transaction_fee: response
+ .original_transaction_fee
+ .as_ref()
+ .map(|m| MinorUnit::new(m.minor_amount)),
+ previously_refunded_transaction_fees: response
+ .previously_refunded_transaction_fees
+ .as_ref()
+ .map(|m| MinorUnit::new(m.minor_amount)),
+ })
+ }
+}
+
+impl
+ transformers::ForeignTryFrom<(
+ &payments_grpc::SurchargeServiceSurchargeRefundCompleteResponse,
+ &str,
+ &str,
+ )> for SurchargeRefundCompleteResponseData
+{
+ type Error = &'static str;
+ fn foreign_try_from(
+ (response, reference, refund_id): (
+ &payments_grpc::SurchargeServiceSurchargeRefundCompleteResponse,
+ &str,
+ &str,
+ ),
+ ) -> Result<Self, Self::Error> {
+ if response.error.is_some() || !(200..300).contains(&response.status_code) {
+ return Err("Surcharge Complete returned a connector error");
+ }
+ if reference.is_empty()
+ || response.merchant_surcharge_refund_id.as_deref() != Some(reference)
+ {
+ return Err("Surcharge Complete reference mismatch");
+ }
+ if refund_id.trim().is_empty()
+ || response.connector_surcharge_refund_id.as_deref() != Some(refund_id)
+ {
+ return Err("Surcharge Complete refund ID mismatch");
+ }
+ Ok(Self)
+ }
+}
+
#[cfg(test)]
mod tests;
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index 0a64661084..9fb5869c62 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -30,6 +30,7 @@ use hyperswitch_domain_models::{
MerchantConnectorAccount, MerchantConnectorAccountWithoutEncrypted,
},
payment_address::PaymentAddress,
+ refunds::RefundAmountDetails,
router_data::ErrorResponse,
router_data_v2::flow_common_types::VaultConnectorFlowData,
router_request_types,
@@ -576,8 +577,10 @@ pub async fn construct_refund_router_data<'a, F>(
.map(api_models::payments::FeatureMetadata::foreign_from),
feature_metadata: refund.feature_metadata.clone(),
connector_transaction_id: refund.get_connector_transaction_id().clone(),
- refund_amount: refund.refund_amount.get_amount_as_i64(),
- minor_refund_amount: refund.refund_amount,
+ refund_amount: RefundAmountDetails::from(refund)
+ .get_net_refund_amount()
+ .get_amount_as_i64(),
+ minor_refund_amount: RefundAmountDetails::from(refund).get_net_refund_amount(),
currency,
payment_amount: payment_amount.get_amount_as_i64(),
minor_payment_amount: payment_amount,
@@ -812,8 +815,10 @@ pub async fn construct_refund_router_data<'a, F>(
.attach_printable("Failed to parse payment feature metadata")?,
feature_metadata: refund.feature_metadata.clone(),
connector_transaction_id: refund.get_connector_transaction_id().clone(),
- refund_amount: refund.refund_amount.get_amount_as_i64(),
- minor_refund_amount: refund.refund_amount,
+ refund_amount: RefundAmountDetails::from(refund)
+ .get_net_refund_amount()
+ .get_amount_as_i64(),
+ minor_refund_amount: RefundAmountDetails::from(refund).get_net_refund_amount(),
currency,
payment_amount: payment_amount.get_amount_as_i64(),
minor_payment_amount: payment_amount,
diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rs
index 811b54faea..728198bfb5 100644
--- a/crates/router/src/core/webhooks/outgoing.rs
+++ b/crates/router/src/core/webhooks/outgoing.rs
@@ -690,26 +690,50 @@ async fn trigger_webhook_to_connector(
let connector_name = mca.connector_name.clone();
- let (notify_request, connector_auth_metadata, notify_event_type) =
- crate::core::unified_connector_service::build_notify_connector_request(
- &event,
- &provider_merchant_id,
- MerchantConnectorAccountType::DbVal(Box::new(mca)),
- connector_name,
- notify_feature_data,
- )
- .change_context(errors::WebhooksFlowError::WebhookRequestConstructionFailed)?;
-
- let response = crate::core::unified_connector_service::call_unified_connector_service_for_notify_connector(
+ // Partial surcharge refunds finalise via SurchargeRefundComplete; everything else takes the
+ // generic notify (`complete_from_webhook` returns `None`). Both yield NotifyConnectorResponseData
+ // so the handling below is shared — a failed Complete only reschedules the webhook, not the refund.
+ let surcharge_complete = if event.event_type == enums::EventType::SurchargeRefundSucceeded {
+ crate::core::refunds::surcharge::complete_from_webhook(
&state,
- &event,
- connector_auth_metadata,
- notify_request,
- notify_event_type,
&provider_merchant_id,
+ &merchant_key_store,
business_profile.get_id(),
+ MerchantConnectorAccountType::DbVal(Box::new(mca.clone())),
+ &event.primary_object_id,
)
- .await;
+ .await
+ .transpose()
+ } else {
+ None
+ };
+
+ let response = match surcharge_complete {
+ Some(result) => result,
+ // Original-payment surcharge, or a full refund, send the legacy single notify.
+ None => {
+ let (notify_request, connector_auth_metadata, notify_event_type) =
+ crate::core::unified_connector_service::build_notify_connector_request(
+ &event,
+ &provider_merchant_id,
+ MerchantConnectorAccountType::DbVal(Box::new(mca)),
+ connector_name,
+ notify_feature_data,
+ )
+ .change_context(errors::WebhooksFlowError::WebhookRequestConstructionFailed)?;
+
+ crate::core::unified_connector_service::call_unified_connector_service_for_notify_connector(
+ &state,
+ &event,
+ connector_auth_metadata,
+ notify_request,
+ notify_event_type,
+ &provider_merchant_id,
+ business_profile.get_id(),
+ )
+ .await
+ }
+ };
metrics::WEBHOOK_OUTGOING_COUNT.add(
1,
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index 0cf77148f1..9e42aa9cf6 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -686,6 +686,9 @@ mod storage {
refund_amount: new.refund_amount,
refund_surcharge_amount: new.refund_surcharge_amount,
net_refund_amount: new.net_refund_amount,
+ external_surcharge_refund_details: new
+ .external_surcharge_refund_details
+ .clone(),
refund_status: new.refund_status,
sent_to_gateway: new.sent_to_gateway,
refund_error_message: None,
@@ -913,7 +916,7 @@ mod storage {
let conn = connection::pg_connection_write(self).await?;
// Stagger release fallback: first try processor_merchant_id, if not found fallback to merchant_id
// For old records processor_merchant_id is NULL, so we use merchant_id (which has the same value)
- let result = this.clone().update(&conn, refund.clone()).await;
+ let result = Box::pin(this.clone().update(&conn, refund.clone())).await;
match result {
Ok(refund) => Ok(refund),
@@ -922,7 +925,7 @@ mod storage {
error.current_context(),
diesel_models::errors::DatabaseError::NotFound
) {
- this.update_by_merchant_id(&conn, refund)
+ Box::pin(this.update_by_merchant_id(&conn, refund))
.await
.map_err(|error| report!(errors::StorageError::from(error)))
} else {
@@ -1457,6 +1460,7 @@ impl RefundInterface for MockDb {
refund_amount: new.refund_amount,
refund_surcharge_amount: new.refund_surcharge_amount,
net_refund_amount: new.net_refund_amount,
+ external_surcharge_refund_details: new.external_surcharge_refund_details.clone(),
refund_status: new.refund_status,
sent_to_gateway: new.sent_to_gateway,
refund_error_message: None,
@@ -1515,6 +1519,7 @@ impl RefundInterface for MockDb {
refund_amount: new.refund_amount,
refund_surcharge_amount: new.refund_surcharge_amount,
net_refund_amount: new.net_refund_amount,
+ external_surcharge_refund_details: new.external_surcharge_refund_details.clone(),
refund_status: new.refund_status,
sent_to_gateway: new.sent_to_gateway,
refund_error_message: None,
diff --git a/crates/router/src/services/kafka/refund.rs b/crates/router/src/services/kafka/refund.rs
index 42c66646cf..4b36aa697e 100644
--- a/crates/router/src/services/kafka/refund.rs
+++ b/crates/router/src/services/kafka/refund.rs
@@ -168,6 +168,7 @@ impl<'a> KafkaRefund<'a> {
feature_metadata: _,
refund_surcharge_amount: _,
net_refund_amount: _,
+ external_surcharge_refund_details: _,
} = refund;
Self {
diff --git a/crates/router/src/services/kafka/refund_event.rs b/crates/router/src/services/kafka/refund_event.rs
index dc2e769568..6dc786e8b6 100644
--- a/crates/router/src/services/kafka/refund_event.rs
+++ b/crates/router/src/services/kafka/refund_event.rs
@@ -170,6 +170,7 @@ impl<'a> KafkaRefundEvent<'a> {
feature_metadata: _,
refund_surcharge_amount: _,
net_refund_amount: _,
+ external_surcharge_refund_details: _,
} = refund;
Self {
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 66eb0c589b..dfbb35c00e 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -44,7 +44,8 @@ use hyperswitch_domain_models::router_flow_types::{
CreateConnectorCustomer, CreateOrder, ExtendAuthorization, ExternalVaultProxy, GenerateQr,
IncrementalAuthorization, InitPayment, PSync, PostCaptureVoid, PostCaptureVoidSync,
PostProcessing, PostSessionTokens, PreAuthorizeVoid, PushNotification, Reject,
- SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, UpdatePostConfirm, Void,
+ SdkSessionUpdate, Session, SetupMandate, SurchargeRefundComplete, SurchargeRefundInit,
+ UpdateMetadata, UpdatePostConfirm, Void,
},
refunds::{Execute, RSync},
webhooks::VerifyWebhookSource,
@@ -88,12 +89,12 @@ pub use hyperswitch_domain_models::{
PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData,
PaymentsPostAuthenticateData, PaymentsPostProcessingData, PaymentsPostSessionTokensData,
PaymentsPreAuthenticateData, PaymentsPreAuthorizeCancelData, PaymentsRejectData,
- PaymentsSessionData, PaymentsSurchargeCalculationData, PaymentsSyncData,
- PaymentsTaxCalculationData, PaymentsUpdateMetadataData, PaymentsUpdatePostConfirmData,
- PushNotificationRequestData, RefundsData, ResponseId, RetrieveFileRequestData,
- SdkPaymentsSessionUpdateData, SetupMandateRequestData, SplitRefundsRequest,
- SubmitEvidenceRequestData, SyncRequestType, UploadFileRequestData, VaultRequestData,
- VerifyWebhookSourceRequestData,
+ PaymentsSessionData, PaymentsSurchargeCalculationData, PaymentsSurchargeRefundCompleteData,
+ PaymentsSurchargeRefundInitData, PaymentsSyncData, PaymentsTaxCalculationData,
+ PaymentsUpdateMetadataData, PaymentsUpdatePostConfirmData, PushNotificationRequestData,
+ RefundsData, ResponseId, RetrieveFileRequestData, SdkPaymentsSessionUpdateData,
+ SetupMandateRequestData, SplitRefundsRequest, SubmitEvidenceRequestData, SyncRequestType,
+ UploadFileRequestData, VaultRequestData, VerifyWebhookSourceRequestData,
},
router_response_types::{
merchant_connector_webhook_management::{
@@ -107,7 +108,8 @@ pub use hyperswitch_domain_models::{
CompleteSurchargeResponseData, DefendDisputeResponse, DisputeSyncResponse,
FetchDisputesResponse, MandateReference, MandateRevokeResponseData, PaymentsResponseData,
PreprocessingResponseId, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse,
- SurchargeCalculationResponseData, TaxCalculationResponseData, UploadFileResponse,
+ SurchargeCalculationResponseData, SurchargeRefundCompleteResponseData,
+ SurchargeRefundInitResponseData, TaxCalculationResponseData, UploadFileResponse,
VaultResponseData, VerifyWebhookSourceResponseData, VerifyWebhookStatus,
},
};
@@ -182,6 +184,16 @@ pub type SurchargeCalculationRouterData = RouterData<
>;
pub type CompleteSurchargeRouterData =
RouterData<CompleteSurcharge, PaymentsCompleteSurchargeData, CompleteSurchargeResponseData>;
+pub type SurchargeRefundInitRouterData = RouterData<
+ SurchargeRefundInit,
+ PaymentsSurchargeRefundInitData,
+ SurchargeRefundInitResponseData,
+>;
+pub type SurchargeRefundCompleteRouterData = RouterData<
+ SurchargeRefundComplete,
+ PaymentsSurchargeRefundCompleteData,
+ SurchargeRefundCompleteResponseData,
+>;
pub type CompleteRefundSurchrgeRouterData = RouterData<
CompleteRefundSurchrge,
PaymentsCompleteRefundSurchrgeData,
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index a5ac0b5360..3c55b850d2 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -46,7 +46,8 @@ pub use hyperswitch_domain_models::router_flow_types::payments::{
IncrementalAuthorization, InitPayment, PSync, PaymentCreateIntent, PaymentGetIntent,
PaymentMethodToken, PaymentUpdateIntent, PostCaptureVoid, PostCaptureVoidSync, PostProcessing,
PostSessionTokens, PreAuthorizeVoid, PushNotification, RecordAttempt, Reject, SdkSessionUpdate,
- Session, SetupMandate, UpdateMetadata, UpdatePostConfirm, Void,
+ Session, SetupMandate, SurchargeRefundComplete as SurchargeRefundCompleteFlow,
+ SurchargeRefundInit as SurchargeRefundInitFlow, UpdateMetadata, UpdatePostConfirm, Void,
};
pub use hyperswitch_interfaces::api::payments::{
ConnectorCustomer, MandateSetup, Payment, PaymentApprove, PaymentAuthorize,
@@ -55,7 +56,8 @@ pub use hyperswitch_interfaces::api::payments::{
PaymentSession, PaymentSessionUpdate, PaymentSync, PaymentToken, PaymentUpdate,
PaymentUpdateMetadata, PaymentVoid, PaymentsCompleteAuthorize, PaymentsCreateOrder,
PaymentsGenerateQr, PaymentsPostProcessing, PaymentsPushNotification, SurchargeCalculation,
- SurchargeComplete, SurchargeRefund, TaxCalculation,
+ SurchargeComplete, SurchargeRefund, SurchargeRefundComplete, SurchargeRefundInit,
+ TaxCalculation,
};
pub use mandates::MandateTransactionType;
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index 2551bd7cde..17ae51a467 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -1387,7 +1387,9 @@ pub async fn trigger_refund_outgoing_webhook(
let refund_response: api_models::refunds::RefundResponse = refund.clone().foreign_into();
let refund_id = refund_response.refund_id.clone();
let cloned_state = state.clone();
- let cloned_payment_attempt = payment_attempt.clone();
+ let webhook_resource_data = Some(WebhookResourceData::Refund {
+ payment_attempt: payment_attempt.clone(),
+ });
let primary_object_created_at = refund_response.created_at;
if let Some(outgoing_event_type) = event_type {
let created_by = refund
@@ -1405,9 +1407,6 @@ pub async fn trigger_refund_outgoing_webhook(
let cloned_platform = platform.clone();
tokio::spawn(
async move {
- let webhook_resource_data = WebhookResourceData::Refund {
- payment_attempt: cloned_payment_attempt,
- };
Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook(
cloned_state,
cloned_platform,
@@ -1418,7 +1417,7 @@ pub async fn trigger_refund_outgoing_webhook(
webhooks::OutgoingWebhookContent::RefundDetails(Box::new(refund_response)),
primary_object_created_at,
webhook_recipient,
- Some(webhook_resource_data),
+ webhook_resource_data,
business_profile,
))
.await
diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs
index ffeb56456d..06668dbaa2 100644
--- a/crates/router/src/utils/user/sample_data.rs
+++ b/crates/router/src/utils/user/sample_data.rs
@@ -454,6 +454,7 @@ pub async fn generate_sample_data(
refund_amount: MinorUnit::new(amount * 100),
refund_surcharge_amount: None,
net_refund_amount: Some(MinorUnit::new(amount * 100)),
+ external_surcharge_refund_details: None,
refund_status: common_enums::RefundStatus::Success,
sent_to_gateway: true,
refund_type: diesel_models::enums::RefundType::InstantRefund,
diff --git a/migrations/2026-11-03-000001_surcharge_refund_lifecycle/down.sql b/migrations/2026-11-03-000001_surcharge_refund_lifecycle/down.sql
new file mode 100644
index 0000000000..9f5c21507f
--- /dev/null
+++ b/migrations/2026-11-03-000001_surcharge_refund_lifecycle/down.sql
@@ -0,0 +1 @@
+ALTER TABLE refund DROP COLUMN IF EXISTS external_surcharge_refund_details;
diff --git a/migrations/2026-11-03-000001_surcharge_refund_lifecycle/up.sql b/migrations/2026-11-03-000001_surcharge_refund_lifecycle/up.sql
new file mode 100644
index 0000000000..fb53c4bd6b
--- /dev/null
+++ b/migrations/2026-11-03-000001_surcharge_refund_lifecycle/up.sql
@@ -0,0 +1 @@
+ALTER TABLE refund ADD COLUMN IF NOT EXISTS external_surcharge_refund_details JSONB;