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(core): Added Refund flow support for Hyperswitch <> UCS Integration (#9862)

gopikrishna0004bb60d04c159
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 301f94704e..fd39db5c3b 100644
--- a/crates/external_services/src/grpc_client/unified_connector_service.rs
+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs
@@ -13,8 +13,9 @@ use tonic::{
};
use unified_connector_service_client::payments::{
self as payments_grpc, payment_service_client::PaymentServiceClient,
- PaymentServiceAuthorizeResponse, PaymentServiceTransformRequest,
- PaymentServiceTransformResponse,
+ refund_service_client::RefundServiceClient, PaymentServiceAuthorizeResponse,
+ PaymentServiceRefundRequest, PaymentServiceTransformRequest, PaymentServiceTransformResponse,
+ RefundResponse, RefundServiceGetRequest,
};
use crate::{
@@ -30,6 +31,8 @@ pub type UnifiedConnectorServiceResult<T> = CustomResult<T, UnifiedConnectorServ
pub struct UnifiedConnectorServiceClient {
/// The Unified Connector Service Client
pub client: PaymentServiceClient<tonic::transport::Channel>,
+ /// The Refund Service Client
+ pub refund_client: RefundServiceClient<tonic::transport::Channel>,
}
/// Contains the Unified Connector Service Client config
@@ -110,22 +113,31 @@ impl UnifiedConnectorServiceClient {
}
};
- let connect_result = timeout(
+ let payment_client_result = timeout(
Duration::from_secs(unified_connector_service_client_config.connection_timeout),
- PaymentServiceClient::connect(uri),
+ PaymentServiceClient::connect(uri.clone()),
)
.await;
- match connect_result {
- Ok(Ok(client)) => {
+ let refund_client_result = timeout(
+ Duration::from_secs(unified_connector_service_client_config.connection_timeout),
+ RefundServiceClient::connect(uri),
+ )
+ .await;
+
+ match (payment_client_result, refund_client_result) {
+ (Ok(Ok(client)), Ok(Ok(refund_client))) => {
logger::info!("Successfully connected to Unified Connector Service");
- Some(Self { client })
+ Some(Self {
+ client,
+ refund_client,
+ })
}
- Ok(Err(err)) => {
+ (Ok(Err(err)), _) | (_, Ok(Err(err))) => {
logger::error!(error = ?err, "Failed to connect to Unified Connector Service");
None
}
- Err(err) => {
+ (Err(err), _) | (_, Err(err)) => {
logger::error!(error = ?err, "Connection to Unified Connector Service timed out");
None
}
@@ -379,6 +391,64 @@ impl UnifiedConnectorServiceClient {
)
})
}
+
+ /// Performs Payment Refund through PaymentService.Refund
+ pub async fn payment_refund(
+ &self,
+ payment_refund_request: PaymentServiceRefundRequest,
+ connector_auth_metadata: ConnectorAuthMetadata,
+ grpc_headers: GrpcHeadersUcs,
+ ) -> UnifiedConnectorServiceResult<tonic::Response<RefundResponse>> {
+ let mut request = tonic::Request::new(payment_refund_request);
+
+ 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.client
+ .clone()
+ .refund(request)
+ .await
+ .change_context(UnifiedConnectorServiceError::PaymentRefundFailure)
+ .inspect_err(|error| {
+ logger::error!(
+ grpc_error=?error,
+ method="payment_refund",
+ connector_name=?connector_name,
+ "UCS payment refund gRPC call failed"
+ )
+ })
+ }
+
+ /// Performs Refund Sync through RefundService.Get
+ pub async fn refund_sync(
+ &self,
+ refund_sync_request: RefundServiceGetRequest,
+ connector_auth_metadata: ConnectorAuthMetadata,
+ grpc_headers: GrpcHeadersUcs,
+ ) -> UnifiedConnectorServiceResult<tonic::Response<RefundResponse>> {
+ let mut request = tonic::Request::new(refund_sync_request);
+
+ 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_client
+ .clone()
+ .get(request)
+ .await
+ .change_context(UnifiedConnectorServiceError::RefundSyncFailure)
+ .inspect_err(|error| {
+ logger::error!(
+ grpc_error=?error,
+ method="refund_sync",
+ connector_name=?connector_name,
+ "UCS refund sync gRPC call failed"
+ )
+ })
+ }
}
/// Build the gRPC Headers for Unified Connector Service Request
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index fdfcee54c7..f89c22d7b7 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -1068,7 +1068,7 @@ pub struct AuthenticationData {
pub authentication_type: Option<common_enums::DecoupledAuthenticationType>,
}
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, serde::Serialize)]
pub struct RefundsData {
pub refund_id: String,
pub connector_transaction_id: String,
@@ -1101,7 +1101,7 @@ pub struct RefundsData {
pub additional_payment_method_data: Option<AdditionalPaymentData>,
}
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct RefundIntegrityObject {
/// refund currency
pub currency: storage_enums::Currency,
@@ -1109,14 +1109,14 @@ pub struct RefundIntegrityObject {
pub refund_amount: MinorUnit,
}
-#[derive(Debug, serde::Deserialize, Clone)]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub enum SplitRefundsRequest {
StripeSplitRefund(StripeSplitRefund),
AdyenSplitRefund(common_types::domain::AdyenSplitData),
XenditSplitRefund(common_types::domain::XenditSplitSubMerchantData),
}
-#[derive(Debug, serde::Deserialize, Clone)]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct StripeSplitRefund {
pub charge_id: String,
pub transfer_account_id: String,
diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs
index 8268bf85a9..c5d396a62a 100644
--- a/crates/hyperswitch_domain_models/src/router_response_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_response_types.rs
@@ -18,7 +18,7 @@ use crate::{
vault::PaymentMethodVaultingData,
};
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, serde::Serialize)]
pub struct RefundsResponseData {
pub connector_refund_id: String,
pub refund_status: common_enums::RefundStatus,
diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
index 4b0fce8fba..678328f9d8 100644
--- a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
@@ -102,6 +102,14 @@ pub enum UnifiedConnectorServiceError {
#[error("Failed to perform Repeat Payment from gRPC Server")]
PaymentRepeatEverythingFailure,
+ /// Failed to perform Payment Refund from gRPC Server
+ #[error("Failed to perform Payment Refund from gRPC Server")]
+ PaymentRefundFailure,
+
+ /// Failed to perform Refund Sync from gRPC Server
+ #[error("Failed to perform Refund Sync from gRPC Server")]
+ RefundSyncFailure,
+
/// Failed to transform incoming webhook from gRPC Server
#[error("Failed to transform incoming webhook from gRPC Server")]
WebhookTransformFailure,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index afdeca19ba..fbf0935c32 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -81,9 +81,7 @@ use crate::core::{
should_add_task_to_process_tracker, OperationSessionGetters, OperationSessionSetters,
TokenizationAction,
},
- unified_connector_service::{
- send_comparison_data, update_gateway_system_in_feature_metadata, ComparisonData,
- },
+ unified_connector_service::update_gateway_system_in_feature_metadata,
utils as core_utils,
};
#[cfg(feature = "v1")]
@@ -126,7 +124,8 @@ use crate::{
use crate::{core::admin as core_admin, headers, types::ConnectorAuthType};
#[cfg(feature = "v1")]
use crate::{
- core::payment_methods::cards::create_encrypted_data, types::storage::CustomerUpdate::Update,
+ core::{payment_methods::cards::create_encrypted_data, unified_connector_service},
+ types::storage::CustomerUpdate::Update,
};
#[instrument(skip_all)]
@@ -8672,7 +8671,7 @@ where
.map_err(|e| router_env::logger::debug!("Shadow UCS call failed: {:?}", e));
// Compare results
- match serialize_router_data_and_send_to_comparison_service(
+ match unified_connector_service::serialize_router_data_and_send_to_comparison_service(
&state,
direct_router_data,
unified_connector_service_router_data,
@@ -8689,43 +8688,3 @@ where
}
}
}
-
-#[cfg(feature = "v1")]
-pub async fn serialize_router_data_and_send_to_comparison_service<F, RouterDReq>(
- state: &SessionState,
- hyperswitch_router_data: RouterData<F, RouterDReq, PaymentsResponseData>,
- unified_connector_service_router_data: RouterData<F, RouterDReq, PaymentsResponseData>,
-) -> RouterResult<()>
-where
- F: Send + Clone + Sync + 'static,
- RouterDReq: Send + Sync + Clone + 'static + Serialize,
-{
- router_env::logger::info!("Simulating UCS call for shadow mode comparison");
- let hyperswitch_data = match serde_json::to_value(hyperswitch_router_data) {
- Ok(data) => masking::Secret::new(data),
- Err(_) => {
- router_env::logger::debug!("Failed to serialize HS router data");
- return Ok(());
- }
- };
-
- let unified_connector_service_data =
- match serde_json::to_value(unified_connector_service_router_data) {
- Ok(data) => masking::Secret::new(data),
- Err(_) => {
- router_env::logger::debug!("Failed to serialize UCS router data");
- return Ok(());
- }
- };
-
- let comparison_data = ComparisonData {
- hyperswitch_data,
- unified_connector_service_data,
- };
- let _ = send_comparison_data(state, comparison_data)
- .await
- .map_err(|e| {
- router_env::logger::debug!("Failed to send comparison data: {:?}", e);
- });
- Ok(())
-}
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 37e04ec4f4..72348017fd 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -3,6 +3,7 @@ use std::collections::HashMap;
#[cfg(feature = "olap")]
use api_models::admin::MerchantConnectorInfo;
+use common_enums::ExecutionMode;
use common_utils::{
ext_traits::{AsyncExt, StringExt},
types::{ConnectorTransactionId, MinorUnit},
@@ -24,8 +25,9 @@ use crate::{
consts,
core::{
errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt},
- payments::{self, access_token, helpers},
+ payments::{self, access_token, helpers, helpers::MerchantConnectorAccountType},
refunds::transformers::SplitRefundInput,
+ unified_connector_service,
utils::{
self as core_utils, refunds_transformers as transformers,
refunds_validator as validator,
@@ -171,6 +173,25 @@ pub async fn trigger_refund_to_gateway(
validator::validate_for_valid_refunds(payment_attempt, connector.connector_name)?;
+ // Fetch merchant connector account
+ 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,
+ merchant_context.get_merchant_account().get_id(),
+ creds_identifier.as_deref(),
+ merchant_context.get_merchant_key_store(),
+ profile_id,
+ &routed_through,
+ payment_attempt.merchant_connector_id.as_ref(),
+ )
+ .await?;
+
let mut router_data = core_utils::construct_refund_router_data(
state,
&routed_through,
@@ -179,11 +200,12 @@ pub async fn trigger_refund_to_gateway(
payment_intent,
payment_attempt,
refund,
- creds_identifier.clone(),
split_refunds,
+ &merchant_connector_account,
)
.await?;
+ // Add access token for both UCS and direct connector paths
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
@@ -200,90 +222,69 @@ pub async fn trigger_refund_to_gateway(
&payments::CallConnectorAction::Trigger,
);
+ // Common access token handling for all flows
let router_data_res = if !(add_access_token_result.connector_supports_access_token
&& router_data.access_token.is_none())
{
- let connector_integration: services::BoxedRefundConnectorIntegrationInterface<
- api::Execute,
- types::RefundsData,
- types::RefundsResponseData,
- > = connector.connector.get_connector_integration();
- let router_data_res = services::execute_connector_processing_step(
- state,
- connector_integration,
- &router_data,
- payments::CallConnectorAction::Trigger,
- None,
- None,
- )
- .await;
- let option_refund_error_update =
- router_data_res
- .as_ref()
- .err()
- .and_then(|error| match error.current_context() {
- errors::ConnectorError::NotImplemented(message) => {
- Some(diesel_refund::RefundUpdate::ErrorUpdate {
- refund_status: Some(enums::RefundStatus::Failure),
- refund_error_message: Some(
- errors::ConnectorError::NotImplemented(message.to_owned())
- .to_string(),
- ),
- refund_error_code: Some("NOT_IMPLEMENTED".to_string()),
- updated_by: storage_scheme.to_string(),
- connector_refund_id: None,
- processor_refund_data: None,
- unified_code: None,
- unified_message: None,
- issuer_error_code: None,
- issuer_error_message: None,
- })
- }
- errors::ConnectorError::NotSupported { message, connector } => {
- Some(diesel_refund::RefundUpdate::ErrorUpdate {
- refund_status: Some(enums::RefundStatus::Failure),
- refund_error_message: Some(format!(
- "{message} is not supported by {connector}"
- )),
- refund_error_code: Some("NOT_SUPPORTED".to_string()),
- updated_by: storage_scheme.to_string(),
- connector_refund_id: None,
- processor_refund_data: None,
- unified_code: None,
- unified_message: None,
- issuer_error_code: None,
- issuer_error_message: None,
- })
- }
- _ => None,
- });
- // Update the refund status as failure if connector_error is NotImplemented
- if let Some(refund_error_update) = option_refund_error_update {
- state
- .store
- .update_refund(
- refund.to_owned(),
- refund_error_update,
- merchant_context.get_merchant_account().storage_scheme,
+ // Access token available or not needed - proceed with execution
+
+ // Check which gateway system to use for refunds
+ let (execution_path, _session_state) =
+ unified_connector_service::should_call_unified_connector_service(
+ state,
+ merchant_context,
+ &router_data,
+ None::<&payments::PaymentData<api::Execute>>, // No payment data for refunds
+ payments::CallConnectorAction::Trigger,
+ )
+ .await?;
+
+ router_env::logger::info!(
+ refund_id = refund.refund_id,
+ execution_path = ?execution_path,
+ "Executing refund via {execution_path:?}"
+ );
+
+ // Execute refund based on gateway system decision
+ match execution_path {
+ common_enums::ExecutionPath::UnifiedConnectorService => {
+ unified_connector_service::call_unified_connector_service_for_refund_execute(
+ state,
+ merchant_context,
+ router_data.clone(),
+ ExecutionMode::Primary,
+ merchant_connector_account,
)
.await
- .to_not_found_response(errors::ApiErrorResponse::InternalServerError)
- .attach_printable_lazy(|| {
- format!(
- "Failed while updating refund: refund_id: {}",
- refund.refund_id
- )
- })?;
+ .attach_printable(format!(
+ "UCS refund execution failed for connector: {}, refund_id: {}",
+ connector.connector_name, router_data.request.refund_id
+ ))?
+ }
+ common_enums::ExecutionPath::Direct => {
+ Box::pin(execute_refund_execute_via_direct(
+ state,
+ &connector,
+ merchant_context,
+ refund,
+ router_data,
+ ))
+ .await?
+ }
+ common_enums::ExecutionPath::ShadowUnifiedConnectorService => {
+ Box::pin(execute_refund_execute_via_direct_with_ucs_shadow(
+ state,
+ &connector,
+ merchant_context,
+ refund,
+ router_data,
+ merchant_connector_account.clone(),
+ ))
+ .await?
+ }
}
- let mut refund_router_data_res = router_data_res.to_refund_failed_response()?;
- // Initiating Integrity check
- let integrity_result = check_refund_integrity(
- &refund_router_data_res.request,
- &refund_router_data_res.response,
- );
- refund_router_data_res.integrity_check = integrity_result;
- refund_router_data_res
} else {
+ // Access token needed but not available - return error router_data
router_data
};
@@ -429,6 +430,176 @@ pub async fn trigger_refund_to_gateway(
Ok(response)
}
+// ============================================================================
+// REFUND EXECUTION FUNCTIONS
+// ============================================================================
+
+/// Execute refund via Direct connector
+async fn execute_refund_execute_via_direct(
+ state: &SessionState,
+ connector: &api::ConnectorData,
+ merchant_context: &domain::MerchantContext,
+ refund: &diesel_refund::Refund,
+ router_data: types::RefundExecuteRouterData,
+) -> RouterResult<types::RefundExecuteRouterData> {
+ let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
+
+ let connector_integration: services::BoxedRefundConnectorIntegrationInterface<
+ api::Execute,
+ types::RefundsData,
+ types::RefundsResponseData,
+ > = connector.connector.get_connector_integration();
+
+ let router_data_res = services::execute_connector_processing_step(
+ state,
+ connector_integration,
+ &router_data,
+ payments::CallConnectorAction::Trigger,
+ None,
+ None,
+ )
+ .await;
+
+ // Handle specific connector errors and update refund status if needed
+ let option_refund_error_update =
+ router_data_res
+ .as_ref()
+ .err()
+ .and_then(|error| match error.current_context() {
+ errors::ConnectorError::NotImplemented(message) => {
+ Some(diesel_refund::RefundUpdate::ErrorUpdate {
+ refund_status: Some(enums::RefundStatus::Failure),
+ refund_error_message: Some(
+ errors::ConnectorError::NotImplemented(message.to_owned()).to_string(),
+ ),
+ refund_error_code: Some("NOT_IMPLEMENTED".to_string()),
+ updated_by: storage_scheme.to_string(),
+ connector_refund_id: None,
+ processor_refund_data: None,
+ unified_code: None,
+ unified_message: None,
+ issuer_error_code: None,
+ issuer_error_message: None,
+ })
+ }
+ errors::ConnectorError::NotSupported { message, connector } => {
+ Some(diesel_refund::RefundUpdate::ErrorUpdate {
+ refund_status: Some(enums::RefundStatus::Failure),
+ refund_error_message: Some(format!(
+ "{message} is not supported by {connector}"
+ )),
+ refund_error_code: Some("NOT_SUPPORTED".to_string()),
+ updated_by: storage_scheme.to_string(),
+ connector_refund_id: None,
+ processor_refund_data: None,
+ unified_code: None,
+ unified_message: None,
+ issuer_error_code: None,
+ issuer_error_message: None,
+ })
+ }
+ _ => None,
+ });
+
+ // Update the refund status as failure if connector_error is NotImplemented or NotSupported
+ if let Some(refund_error_update) = option_refund_error_update {
+ state
+ .store
+ .update_refund(refund.to_owned(), refund_error_update, storage_scheme)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable_lazy(|| {
+ format!(
+ "Failed while updating refund: refund_id: {}",
+ refund.refund_id
+ )
+ })?;
+ }
+
+ let mut refund_router_data_res = router_data_res.to_refund_failed_response()?;
+
+ // Perform integrity check
+ let integrity_result = check_refund_integrity(
+ &refund_router_data_res.request,
+ &refund_router_data_res.response,
+ );
+ refund_router_data_res.integrity_check = integrity_result;
+
+ Ok(refund_router_data_res)
+}
+
+/// Execute refund via Direct connector with UCS shadow comparison
+async fn execute_refund_execute_via_direct_with_ucs_shadow(
+ state: &SessionState,
+ connector: &api::ConnectorData,
+ merchant_context: &domain::MerchantContext,
+ refund: &diesel_refund::Refund,
+ router_data: types::RefundExecuteRouterData,
+ merchant_connector_account: MerchantConnectorAccountType,
+) -> RouterResult<types::RefundExecuteRouterData> {
+ // Execute Direct connector (PRIMARY)
+ let direct_result = Box::pin(execute_refund_execute_via_direct(
+ state,
+ connector,
+ merchant_context,
+ refund,
+ router_data.clone(),
+ ))
+ .await;
+
+ // Execute UCS in parallel (SHADOW - for comparison only)
+ let ucs_router_data = router_data.clone();
+ let ucs_merchant_context = merchant_context.clone();
+ let ucs_state = state.clone();
+
+ // Clone direct result for comparison (if successful)
+ let direct_router_data_for_comparison = direct_result.as_ref().ok().cloned();
+
+ tokio::spawn(async move {
+ let ucs_result =
+ unified_connector_service::call_unified_connector_service_for_refund_execute(
+ &ucs_state,
+ &ucs_merchant_context,
+ ucs_router_data,
+ ExecutionMode::Shadow,
+ merchant_connector_account,
+ )
+ .await;
+
+ match (ucs_result, direct_router_data_for_comparison) {
+ (Ok(ucs_router_data), Some(direct_router_data)) => {
+ unified_connector_service::serialize_router_data_and_send_to_comparison_service(
+ &ucs_state,
+ direct_router_data,
+ ucs_router_data,
+ )
+ .await
+ .inspect_err(|e| {
+ router_env::logger::debug!(
+ "Shadow UCS refund execute comparison failed: {:?}",
+ e
+ );
+ })
+ .ok();
+ }
+ (Err(e), _) => {
+ router_env::logger::debug!(
+ "Skipping refund execute comparison - UCS shadow execute failed: {:?}",
+ e
+ );
+ }
+ (_, None) => {
+ router_env::logger::debug!(
+ "Skipping refund execute comparison - direct execute failed"
+ );
+ }
+ }
+ });
+
+ // Return PRIMARY result (Direct connector response)
+ direct_result
+}
+
pub fn check_refund_integrity<T, Request>(
request: &Request,
refund_response_data: &Result<types::RefundsResponseData, ErrorResponse>,
@@ -604,6 +775,25 @@ pub async fn sync_refund_with_gateway(
let currency = payment_attempt.currency.get_required_value("currency")?;
+ // Fetch merchant connector account
+ 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,
+ merchant_context.get_merchant_account().get_id(),
+ creds_identifier.as_deref(),
+ merchant_context.get_merchant_key_store(),
+ profile_id,
+ &connector_id,
+ payment_attempt.merchant_connector_id.as_ref(),
+ )
+ .await?;
+
let mut router_data = core_utils::construct_refund_router_data::<api::RSync>(
state,
&connector_id,
@@ -612,11 +802,12 @@ pub async fn sync_refund_with_gateway(
payment_intent,
payment_attempt,
refund,
- creds_identifier.clone(),
split_refunds,
+ &merchant_connector_account,
)
.await?;
+ // Add access token for both UCS and direct connector paths
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
@@ -633,35 +824,66 @@ pub async fn sync_refund_with_gateway(
&payments::CallConnectorAction::Trigger,
);
+ // Common access token handling for all flows
let router_data_res = if !(add_access_token_result.connector_supports_access_token
&& router_data.access_token.is_none())
{
- let connector_integration: services::BoxedRefundConnectorIntegrationInterface<
- api::RSync,
- types::RefundsData,
- types::RefundsResponseData,
- > = connector.connector.get_connector_integration();
- let mut refund_sync_router_data = services::execute_connector_processing_step(
- state,
- connector_integration,
- &router_data,
- payments::CallConnectorAction::Trigger,
- None,
- None,
- )
- .await
- .to_refund_failed_response()?;
+ // Access token available or not needed - proceed with execution
- // Initiating connector integrity checks
- let integrity_result = check_refund_integrity(
- &refund_sync_router_data.request,
- &refund_sync_router_data.response,
- );
+ // Check which gateway system to use for refund sync
+ let (execution_path, _session_state) =
+ unified_connector_service::should_call_unified_connector_service(
+ state,
+ merchant_context,
+ &router_data,
+ None::<&payments::PaymentData<api::RSync>>, // No payment data for refunds
+ payments::CallConnectorAction::Trigger,
+ )
+ .await?;
- refund_sync_router_data.integrity_check = integrity_result;
+ router_env::logger::info!(
+ refund_id = router_data.request.refund_id,
+ execution_path = ?execution_path,
+ "Executing refund sync via {execution_path:?}"
+ );
- refund_sync_router_data
+ // Execute refund sync based on gateway system decision
+ match execution_path {
+ common_enums::ExecutionPath::UnifiedConnectorService => {
+ unified_connector_service::call_unified_connector_service_for_refund_sync(
+ state,
+ merchant_context,
+ router_data.clone(),
+ ExecutionMode::Primary,
+ merchant_connector_account,
+ )
+ .await
+ .attach_printable(format!(
+ "UCS refund sync failed for connector: {}, refund_id: {}",
+ connector.connector_name, router_data.request.refund_id
+ ))?
+ }
+ common_enums::ExecutionPath::Direct => {
+ Box::pin(execute_refund_sync_via_direct(
+ state,
+ &connector,
+ router_data,
+ ))
+ .await?
+ }
+ common_enums::ExecutionPath::ShadowUnifiedConnectorService => {
+ Box::pin(execute_refund_sync_via_direct_with_ucs_shadow(
+ state,
+ &connector,
+ merchant_context,
+ router_data,
+ merchant_connector_account,
+ ))
+ .await?
+ }
+ }
} else {
+ // Access token needed but not available - return error router_data
router_data
};
@@ -763,6 +985,109 @@ pub async fn sync_refund_with_gateway(
Ok(response)
}
+// ============================================================================
+// REFUND SYNC EXECUTION FUNCTIONS
+// ============================================================================
+
+/// Execute refund sync via Direct connector
+async fn execute_refund_sync_via_direct(
+ state: &SessionState,
+ connector: &api::ConnectorData,
+ router_data: types::RefundSyncRouterData,
+) -> RouterResult<types::RefundSyncRouterData> {
+ let connector_integration: services::BoxedRefundConnectorIntegrationInterface<
+ api::RSync,
+ types::RefundsData,
+ types::RefundsResponseData,
+ > = connector.connector.get_connector_integration();
+
+ let router_data_res = services::execute_connector_processing_step(
+ state,
+ connector_integration,
+ &router_data,
+ payments::CallConnectorAction::Trigger,
+ None,
+ None,
+ )
+ .await;
+
+ let mut refund_router_data_res = router_data_res.to_refund_failed_response()?;
+
+ // Perform integrity check
+ let integrity_result = check_refund_integrity(
+ &refund_router_data_res.request,
+ &refund_router_data_res.response,
+ );
+ refund_router_data_res.integrity_check = integrity_result;
+
+ router_env::logger::info!(
+ connector = connector.connector_name.to_string(),
+ refund_id = refund_router_data_res.request.refund_id,
+ "Direct refund sync completed successfully"
+ );
+
+ Ok(refund_router_data_res)
+}
+
+/// Execute refund sync via Direct connector with UCS shadow comparison
+async fn execute_refund_sync_via_direct_with_ucs_shadow(
+ state: &SessionState,
+ connector: &api::ConnectorData,
+ merchant_context: &domain::MerchantContext,
+ router_data: types::RefundSyncRouterData,
+ merchant_connector_account: MerchantConnectorAccountType,
+) -> RouterResult<types::RefundSyncRouterData> {
+ // Execute Direct connector (PRIMARY)
+ let direct_result = Box::pin(execute_refund_sync_via_direct(
+ state,
+ connector,
+ router_data.clone(),
+ ))
+ .await;
+
+ // Execute UCS in shadow mode for comparison
+ let state = state.clone();
+ let merchant_context = merchant_context.clone();
+ let merchant_connector_account = merchant_connector_account.clone();
+ let direct_router_data_for_comparison = direct_result.as_ref().ok().cloned();
+
+ tokio::spawn(async move {
+ let ucs_result = unified_connector_service::call_unified_connector_service_for_refund_sync(
+ &state,
+ &merchant_context,
+ router_data,
+ ExecutionMode::Shadow,
+ merchant_connector_account,
+ )
+ .await;
+
+ match (ucs_result, direct_router_data_for_comparison) {
+ (Ok(ucs_router_data), Some(direct_router_data)) => {
+ unified_connector_service::serialize_router_data_and_send_to_comparison_service(
+ &state,
+ direct_router_data,
+ ucs_router_data,
+ )
+ .await
+ .inspect_err(|e| {
+ router_env::logger::debug!("Shadow UCS sync comparison failed: {:?}", e);
+ })
+ .ok();
+ }
+ (Err(_), _) => {
+ router_env::logger::debug!(
+ "Skipping refund sync comparison - UCS shadow sync failed"
+ );
+ }
+ (_, None) => {
+ router_env::logger::debug!("Skipping refund sync comparison - direct sync failed");
+ }
+ }
+ });
+
+ direct_result
+}
+
// ********************************************** REFUND UPDATE **********************************************
pub async fn refund_update_core(
diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs
index 3aa77c591a..96182d41e2 100644
--- a/crates/router/src/core/unified_connector_service.rs
+++ b/crates/router/src/core/unified_connector_service.rs
@@ -14,6 +14,7 @@ use common_utils::{
consts::X_FLOW_NAME,
errors::CustomResult,
ext_traits::ValueExt,
+ id_type,
request::{Method, RequestBuilder, RequestContent},
};
use diesel_models::types::FeatureMetadata;
@@ -33,7 +34,9 @@ use hyperswitch_domain_models::merchant_connector_account::{
use hyperswitch_domain_models::{
merchant_context::MerchantContext,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
- router_response_types::PaymentsResponseData,
+ router_flow_types::refunds,
+ router_request_types::RefundsData,
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
};
use masking::{ExposeInterface, PeekInterface, Secret};
use router_env::{instrument, logger, tracing};
@@ -81,6 +84,10 @@ type UnifiedConnectorServiceResult = CustomResult<
UnifiedConnectorServiceError,
>;
+/// Type alias for return type used by unified connector service refund response handlers
+type UnifiedConnectorServiceRefundResult =
+ CustomResult<(Result<RefundsResponseData, ErrorResponse>, u16), UnifiedConnectorServiceError>;
+
/// Gets the rollout percentage for a given config key
async fn get_rollout_percentage(state: &SessionState, config_key: &str) -> Option<f64> {
let db = state.store.as_ref();
@@ -163,15 +170,16 @@ async fn determine_connector_integration_type(
}
}
-pub async fn should_call_unified_connector_service<F: Clone, T, D>(
+pub async fn should_call_unified_connector_service<F: Clone, T, R, D>(
state: &SessionState,
merchant_context: &MerchantContext,
- router_data: &RouterData<F, T, PaymentsResponseData>,
+ router_data: &RouterData<F, T, R>,
payment_data: Option<&D>,
call_connector_action: CallConnectorAction,
) -> RouterResult<(ExecutionPath, SessionState)>
where
D: OperationSessionGetters<F>,
+ R: Send + Sync + Clone,
{
// Extract context information
let merchant_id = merchant_context
@@ -182,22 +190,18 @@ where
let connector_name = &router_data.connector;
let connector_enum = Connector::from_str(connector_name)
.change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)
- .attach_printable_lazy(|| format!("Failed to parse connector name: {}", connector_name))?;
+ .attach_printable_lazy(|| format!("Failed to parse connector name: {connector_name}"))?;
- let payment_method = router_data.payment_method.to_string();
let flow_name = get_flow_name::<F>()?;
// Check UCS availability using idiomatic helper
let ucs_availability = check_ucs_availability(state).await;
- // Build rollout keys
- let rollout_key = format!(
- "{}_{}_{}_{}_{}",
- consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX,
+ let (rollout_key, shadow_rollout_key) = build_rollout_keys(
merchant_id,
connector_name,
- payment_method,
- flow_name
+ &flow_name,
+ router_data.payment_method,
);
// Determine connector integration type
@@ -206,7 +210,6 @@ where
// Extract previous gateway from payment data
let previous_gateway = payment_data.and_then(extract_gateway_system_from_payment_intent);
- let shadow_rollout_key = format!("{}_shadow", rollout_key);
// Check both rollout keys to determine priority based on shadow percentage
let rollout_result = should_execute_based_on_rollout(state, &rollout_key).await?;
@@ -237,7 +240,7 @@ where
};
// Single decision point using pattern matching
- let (_gateway_system, execution_path) = if ucs_availability == UcsAvailability::Disabled {
+ let (gateway_system, execution_path) = if ucs_availability == UcsAvailability::Disabled {
match call_connector_action {
CallConnectorAction::UCSConsumeResponse(_)
| CallConnectorAction::UCSHandleResponse(_) => {
@@ -281,7 +284,14 @@ where
}
};
- router_env::logger::info!( "Payment gateway decision: execution_path={:?} - merchant_id={}, connector={}, payment_method={}, flow={}", execution_path, merchant_id, connector_name, payment_method, flow_name );
+ router_env::logger::info!(
+ "Payment gateway decision: gateway={:?}, execution_path={:?} - merchant_id={}, connector={}, flow={}",
+ gateway_system,
+ execution_path,
+ merchant_id,
+ connector_name,
+ flow_name
+ );
// Handle proxy configuration for Shadow UCS flows
let session_state = match execution_path {
@@ -448,6 +458,42 @@ fn decide_execution_path(
}
}
+/// Build rollout keys based on flow type - include payment method for payments, skip for refunds
+fn build_rollout_keys(
+ merchant_id: &str,
+ connector_name: &str,
+ flow_name: &str,
+ payment_method: common_enums::PaymentMethod,
+) -> (String, String) {
+ // Detect if this is a refund flow based on flow name
+ let is_refund_flow = matches!(flow_name, "Execute" | "RSync");
+
+ let rollout_key = if is_refund_flow {
+ // Refund flows: UCS_merchant_connector_flow (e.g., UCS_merchant123_stripe_Execute)
+ format!(
+ "{}_{}_{}_{}",
+ consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX,
+ merchant_id,
+ connector_name,
+ flow_name
+ )
+ } else {
+ // Payment flows: UCS_merchant_connector_paymentmethod_flow (e.g., UCS_merchant123_stripe_card_Authorize)
+ let payment_method_str = payment_method.to_string();
+ format!(
+ "{}_{}_{}_{}_{}",
+ consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX,
+ merchant_id,
+ connector_name,
+ payment_method_str,
+ flow_name
+ )
+ };
+
+ let shadow_rollout_key = format!("{rollout_key}_shadow");
+ (rollout_key, shadow_rollout_key)
+}
+
/// Extracts the gateway system from the payment intent's feature metadata
/// Returns None if metadata is missing, corrupted, or doesn't contain gateway_system
fn extract_gateway_system_from_payment_intent<F: Clone, D>(
@@ -715,6 +761,23 @@ pub fn build_unified_connector_service_payment_method_for_external_proxy(
}
}
}
+
+/// Gets the UCS client from session state
+fn get_ucs_client(
+ state: &SessionState,
+) -> RouterResult<
+ &external_services::grpc_client::unified_connector_service::UnifiedConnectorServiceClient,
+> {
+ state
+ .grpc_client
+ .unified_connector_service_client
+ .as_ref()
+ .ok_or_else(|| {
+ error_stack::report!(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("UCS client is not available")
+ })
+}
+
pub fn build_unified_connector_service_auth_metadata(
#[cfg(feature = "v1")] merchant_connector_account: MerchantConnectorAccountType,
#[cfg(feature = "v2")] merchant_connector_account: MerchantConnectorAccountTypeDetails,
@@ -972,6 +1035,28 @@ pub fn extract_connector_response_from_ucs(
})
}
+pub fn handle_unified_connector_service_response_for_refund_execute(
+ response: payments_grpc::RefundResponse,
+) -> UnifiedConnectorServiceRefundResult {
+ let status_code = transformers::convert_connector_service_status_code(response.status_code)?;
+
+ let router_data_response: Result<RefundsResponseData, ErrorResponse> =
+ Result::<RefundsResponseData, ErrorResponse>::foreign_try_from(response)?;
+
+ Ok((router_data_response, status_code))
+}
+
+pub fn handle_unified_connector_service_response_for_refund_sync(
+ response: payments_grpc::RefundResponse,
+) -> UnifiedConnectorServiceRefundResult {
+ let status_code = transformers::convert_connector_service_status_code(response.status_code)?;
+
+ let router_data_response =
+ Result::<RefundsResponseData, ErrorResponse>::foreign_try_from(response)?;
+
+ Ok((router_data_response, status_code))
+}
+
pub fn handle_unified_connector_service_response_for_payment_cancel(
response: payments_grpc::PaymentServiceVoidResponse,
) -> UnifiedConnectorServiceResult {
@@ -1269,7 +1354,12 @@ where
// Emit event
state.event_handler.log_event(&connector_event);
- router_result
+ // Set external latency on router data
+ router_result.map(|mut router_data| {
+ router_data.external_latency =
+ Some(router_data.external_latency.unwrap_or(0) + external_latency);
+ router_data
+ })
}
#[derive(serde::Serialize)]
@@ -1278,6 +1368,48 @@ pub struct ComparisonData {
pub unified_connector_service_data: Secret<serde_json::Value>,
}
+/// Generic function to serialize router data and send comparison to external service
+/// Works for both payments and refunds
+#[cfg(feature = "v1")]
+pub async fn serialize_router_data_and_send_to_comparison_service<F, RouterDReq, RouterDResp>(
+ state: &SessionState,
+ hyperswitch_router_data: RouterData<F, RouterDReq, RouterDResp>,
+ unified_connector_service_router_data: RouterData<F, RouterDReq, RouterDResp>,
+) -> RouterResult<()>
+where
+ F: Send + Clone + Sync + 'static,
+ RouterDReq: Send + Sync + Clone + 'static + serde::Serialize,
+ RouterDResp: Send + Sync + Clone + 'static + serde::Serialize,
+{
+ logger::info!("Simulating UCS call for shadow mode comparison");
+
+ let [hyperswitch_data, unified_connector_service_data] = [
+ (hyperswitch_router_data, "hyperswitch"),
+ (unified_connector_service_router_data, "ucs"),
+ ]
+ .map(|(data, source)| {
+ serde_json::to_value(data)
+ .map(Secret::new)
+ .unwrap_or_else(|e| {
+ Secret::new(serde_json::json!({
+ "error": e.to_string(),
+ "source": source
+ }))
+ })
+ });
+
+ let comparison_data = ComparisonData {
+ hyperswitch_data,
+ unified_connector_service_data,
+ };
+ let _ = send_comparison_data(state, comparison_data)
+ .await
+ .map_err(|e| {
+ logger::debug!("Failed to send comparison data: {:?}", e);
+ });
+ Ok(())
+}
+
/// Sends router data comparison to external service
pub async fn send_comparison_data(
state: &SessionState,
@@ -1313,3 +1445,148 @@ pub async fn send_comparison_data(
Ok(())
}
+
+// ============================================================================
+// REFUND UCS FUNCTIONS
+// ============================================================================
+
+/// Execute UCS refund request using PaymentService.Refund gRPC method
+#[instrument(skip_all)]
+pub async fn call_unified_connector_service_for_refund_execute(
+ state: &SessionState,
+ merchant_context: &MerchantContext,
+ router_data: RouterData<refunds::Execute, RefundsData, RefundsResponseData>,
+ execution_mode: ExecutionMode,
+ #[cfg(feature = "v1")] merchant_connector_account: MerchantConnectorAccountType,
+ #[cfg(feature = "v2")] merchant_connector_account: MerchantConnectorAccountTypeDetails,
+) -> RouterResult<RouterData<refunds::Execute, RefundsData, RefundsResponseData>> {
+ // Get UCS client
+ let ucs_client = get_ucs_client(state)?;
+
+ // Build auth metadata using standard UCS function
+ let connector_auth_metadata =
+ build_unified_connector_service_auth_metadata(merchant_connector_account, merchant_context)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to build UCS auth metadata for refund execute")?;
+
+ // Transform router data to UCS refund request
+ let ucs_refund_request =
+ payments_grpc::PaymentServiceRefundRequest::foreign_try_from(&router_data)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to transform router data to UCS refund request")?;
+
+ // Build gRPC headers
+ // Use merchant_id as profile_id fallback since RouterData doesn't have profile_id field
+ let merchant_id = merchant_context.get_merchant_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")?;
+ let lineage_ids = LineageIds::new(merchant_id, profile_id);
+ let grpc_header_builder = state
+ .get_grpc_headers_ucs(execution_mode)
+ .lineage_ids(lineage_ids)
+ .external_vault_proxy_metadata(None)
+ .merchant_reference_id(None);
+
+ // Make UCS refund call with logging wrapper
+ Box::pin(ucs_logging_wrapper(
+ router_data,
+ state,
+ ucs_refund_request,
+ grpc_header_builder,
+ |router_data, grpc_request, grpc_headers| async move {
+ // Call UCS payment_refund method
+ let response = ucs_client
+ .payment_refund(grpc_request, connector_auth_metadata, grpc_headers)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("UCS refund execution failed")?;
+
+ let grpc_response = response.into_inner();
+
+ // Transform UCS response back to RouterData
+ let (refund_response_data, status_code) =
+ handle_unified_connector_service_response_for_refund_execute(grpc_response.clone())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to transform UCS refund response")?;
+
+ let mut updated_router_data = router_data;
+ updated_router_data.response = refund_response_data;
+ updated_router_data.connector_http_status_code = Some(status_code);
+
+ Ok((updated_router_data, grpc_response))
+ },
+ ))
+ .await
+}
+
+/// Execute UCS refund sync request using RefundService.Get gRPC method
+#[instrument(skip_all)]
+pub async fn call_unified_connector_service_for_refund_sync(
+ state: &SessionState,
+ merchant_context: &MerchantContext,
+ router_data: RouterData<refunds::RSync, RefundsData, RefundsResponseData>,
+ execution_mode: ExecutionMode,
+ #[cfg(feature = "v1")] merchant_connector_account: MerchantConnectorAccountType,
+ #[cfg(feature = "v2")] merchant_connector_account: MerchantConnectorAccountTypeDetails,
+) -> RouterResult<RouterData<refunds::RSync, RefundsData, RefundsResponseData>> {
+ // Get UCS client
+ let ucs_client = get_ucs_client(state)?;
+
+ // Build auth metadata using standard UCS function
+ let connector_auth_metadata =
+ build_unified_connector_service_auth_metadata(merchant_connector_account, merchant_context)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to build UCS auth metadata for refund sync")?;
+
+ // Transform router data to UCS refund sync request
+ let ucs_refund_sync_request =
+ payments_grpc::RefundServiceGetRequest::foreign_try_from(&router_data)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to transform router data to UCS refund sync request")?;
+
+ // Build gRPC headers
+ // Use merchant_id as profile_id fallback since RouterData doesn't have profile_id field
+ let merchant_id = merchant_context.get_merchant_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")?;
+ let lineage_ids = LineageIds::new(merchant_id, profile_id);
+
+ let grpc_header_builder = state
+ .get_grpc_headers_ucs(execution_mode)
+ .lineage_ids(lineage_ids)
+ .external_vault_proxy_metadata(None)
+ .merchant_reference_id(None);
+
+ // Make UCS refund sync call with logging wrapper
+ Box::pin(ucs_logging_wrapper(
+ router_data,
+ state,
+ ucs_refund_sync_request,
+ grpc_header_builder,
+ |router_data, grpc_request, grpc_headers| async move {
+ // Call UCS refund_sync method
+ let response = ucs_client
+ .refund_sync(grpc_request, connector_auth_metadata, grpc_headers)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("UCS refund sync execution failed")?;
+
+ let grpc_response = response.into_inner();
+
+ // Transform UCS response back to RouterData
+ let (refund_response_data, status_code) =
+ handle_unified_connector_service_response_for_refund_sync(grpc_response.clone())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to transform UCS refund sync response")?;
+
+ let mut updated_router_data = router_data;
+ updated_router_data.response = refund_response_data;
+ updated_router_data.connector_http_status_code = Some(status_code);
+
+ Ok((updated_router_data, grpc_response))
+ },
+ ))
+ .await
+}
diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs
index 3be51f7bce..db15bef26d 100644
--- a/crates/router/src/core/unified_connector_service/transformers.rs
+++ b/crates/router/src/core/unified_connector_service/transformers.rs
@@ -1,6 +1,6 @@
use std::collections::HashMap;
-use common_enums::{AttemptStatus, AuthenticationType};
+use common_enums::{AttemptStatus, AuthenticationType, RefundStatus};
use common_utils::{ext_traits::Encode, request::Method};
use diesel_models::enums as storage_enums;
use error_stack::ResultExt;
@@ -9,13 +9,15 @@ use hyperswitch_domain_models::{
router_data::{ErrorResponse, RouterData},
router_flow_types::{
payments::{Authorize, Capture, PSync, SetupMandate},
+ refunds::{Execute, RSync},
unified_authentication_service as uas_flows, ExternalVaultProxy,
},
router_request_types::{
self, AuthenticationData, ExternalVaultProxyPaymentsData, PaymentsAuthorizeData,
- PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData, SetupMandateRequestData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData, RefundsData,
+ SetupMandateRequestData,
},
- router_response_types::{PaymentsResponseData, RedirectForm},
+ router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
};
pub use hyperswitch_interfaces::{
helpers::ForeignTryFrom,
@@ -1709,6 +1711,232 @@ pub fn build_webhook_transform_request(
})
}
+// ============================================================================
+// REFUND TRANSFORMERS
+// ============================================================================
+
+/// Transform RouterData for Execute refund into UCS PaymentServiceRefundRequest
+impl transformers::ForeignTryFrom<&RouterData<Execute, RefundsData, RefundsResponseData>>
+ for payments_grpc::PaymentServiceRefundRequest
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ router_data: &RouterData<Execute, RefundsData, RefundsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ let currency = payments_grpc::Currency::foreign_try_from(router_data.request.currency)?;
+
+ let transaction_id = Identifier {
+ id_type: Some(payments_grpc::identifier::IdType::Id(
+ router_data.request.connector_transaction_id.clone(),
+ )),
+ };
+
+ let request_ref_id = Some(Identifier {
+ id_type: Some(payments_grpc::identifier::IdType::Id(
+ router_data.connector_request_reference_id.clone(),
+ )),
+ });
+
+ // Convert connector_metadata to gRPC format
+ let metadata = router_data
+ .request
+ .connector_metadata
+ .as_ref()
+ .map(|metadata| {
+ metadata
+ .as_object()
+ .map(|obj| {
+ obj.iter()
+ .map(|(k, v)| (k.clone(), v.to_string()))
+ .collect()
+ })
+ .unwrap_or_default()
+ })
+ .unwrap_or_default();
+
+ // Convert refund_connector_metadata to gRPC format
+ let refund_metadata = router_data
+ .request
+ .refund_connector_metadata
+ .as_ref()
+ .map(|metadata| {
+ metadata
+ .clone()
+ .expose()
+ .as_object()
+ .map(|obj| {
+ obj.iter()
+ .map(|(k, v)| (k.clone(), v.to_string()))
+ .collect()
+ })
+ .unwrap_or_default()
+ })
+ .unwrap_or_default();
+
+ Ok(Self {
+ request_ref_id,
+ refund_id: router_data.request.refund_id.clone(),
+ transaction_id: Some(transaction_id),
+ payment_amount: router_data.request.payment_amount,
+ currency: currency.into(),
+ minor_payment_amount: router_data.request.minor_payment_amount.get_amount_as_i64(),
+ refund_amount: router_data.request.refund_amount,
+ minor_refund_amount: router_data.request.minor_refund_amount.get_amount_as_i64(),
+ reason: router_data.request.reason.clone(),
+ webhook_url: router_data.request.webhook_url.clone(),
+ merchant_account_id: router_data
+ .request
+ .merchant_account_id
+ .as_ref()
+ .map(|id| id.clone().expose().clone()),
+ capture_method: router_data
+ .request
+ .capture_method
+ .map(payments_grpc::CaptureMethod::foreign_try_from)
+ .transpose()
+ .map_err(|_| {
+ UnifiedConnectorServiceError::RequestEncodingFailedWithReason(
+ "Failed to convert capture method".to_string(),
+ )
+ })?
+ .map(i32::from),
+ metadata,
+ refund_metadata,
+ 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(),
+ )
+ })?,
+ access_token: router_data
+ .access_token
+ .as_ref()
+ .map(|token| token.token.clone().expose()),
+ })
+ }
+}
+
+/// Transform RouterData for RSync refund into UCS RefundServiceGetRequest
+impl transformers::ForeignTryFrom<&RouterData<RSync, RefundsData, RefundsResponseData>>
+ for payments_grpc::RefundServiceGetRequest
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ router_data: &RouterData<RSync, RefundsData, RefundsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ let transaction_id = Identifier {
+ id_type: Some(payments_grpc::identifier::IdType::Id(
+ router_data.request.connector_transaction_id.clone(),
+ )),
+ };
+
+ let request_ref_id = Some(Identifier {
+ id_type: Some(payments_grpc::identifier::IdType::Id(
+ router_data.connector_request_reference_id.clone(),
+ )),
+ });
+
+ Ok(Self {
+ request_ref_id,
+ transaction_id: Some(transaction_id),
+ refund_id: router_data.request.connector_refund_id.clone().ok_or(
+ UnifiedConnectorServiceError::RequestEncodingFailedWithReason(
+ "Missing connector_refund_id for refund sync operation".to_string(),
+ ),
+ )?,
+ refund_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(),
+ )
+ })?,
+ access_token: router_data
+ .access_token
+ .as_ref()
+ .map(|token| token.token.clone().expose()),
+ refund_metadata: router_data
+ .request
+ .refund_connector_metadata
+ .as_ref()
+ .map(|metadata| {
+ metadata
+ .clone()
+ .expose()
+ .as_object()
+ .map(|obj| {
+ obj.iter()
+ .map(|(k, v)| (k.clone(), v.to_string()))
+ .collect()
+ })
+ .unwrap_or_default()
+ })
+ .unwrap_or_default(),
+ })
+ }
+}
+
+/// Transform UCS RefundResponse into Result<RefundsResponseData, ErrorResponse>
+impl transformers::ForeignTryFrom<payments_grpc::RefundResponse>
+ for Result<RefundsResponseData, ErrorResponse>
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(response: payments_grpc::RefundResponse) -> Result<Self, Self::Error> {
+ let connector_response_reference_id =
+ response.response_ref_id.as_ref().and_then(|identifier| {
+ identifier
+ .id_type
+ .clone()
+ .and_then(|id_type| match id_type {
+ payments_grpc::identifier::IdType::Id(id) => Some(id),
+ payments_grpc::identifier::IdType::EncodedData(encoded_data) => {
+ Some(encoded_data)
+ }
+ payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None,
+ })
+ });
+
+ let status_code = convert_connector_service_status_code(response.status_code)?;
+
+ let response = if response.error_code.is_some() {
+ Err(ErrorResponse {
+ code: response.error_code().to_owned(),
+ message: response.error_message().to_owned(),
+ reason: Some(response.error_message().to_owned()),
+ status_code,
+ attempt_status: None,
+ connector_transaction_id: connector_response_reference_id,
+ network_decline_code: None,
+ network_advice_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ })
+ } else {
+ let refund_status = RefundStatus::foreign_try_from(response.status())?;
+
+ Ok(RefundsResponseData {
+ connector_refund_id: response.refund_id,
+ refund_status,
+ })
+ };
+
+ Ok(response)
+ }
+}
+
impl transformers::ForeignTryFrom<&RouterData<api::Void, PaymentsCancelData, PaymentsResponseData>>
for payments_grpc::PaymentServiceVoidRequest
{
@@ -1766,6 +1994,21 @@ impl transformers::ForeignTryFrom<&RouterData<api::Void, PaymentsCancelData, Pay
}
}
+impl transformers::ForeignTryFrom<payments_grpc::RefundStatus> for RefundStatus {
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(grpc_status: payments_grpc::RefundStatus) -> Result<Self, Self::Error> {
+ match grpc_status {
+ payments_grpc::RefundStatus::Unspecified => Ok(Self::Pending),
+ payments_grpc::RefundStatus::RefundFailure => Ok(Self::Failure),
+ payments_grpc::RefundStatus::RefundManualReview => Ok(Self::ManualReview),
+ payments_grpc::RefundStatus::RefundPending => Ok(Self::Pending),
+ payments_grpc::RefundStatus::RefundSuccess => Ok(Self::Success),
+ payments_grpc::RefundStatus::RefundTransactionFailure => Ok(Self::TransactionFailure),
+ }
+ }
+}
+
impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceVoidResponse>
for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>
{
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index 729881a831..aaff70cb30 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -423,27 +423,9 @@ pub async fn construct_refund_router_data<'a, F>(
payment_intent: &'a storage::PaymentIntent,
payment_attempt: &storage::PaymentAttempt,
refund: &'a diesel_refund::Refund,
- creds_identifier: Option<String>,
split_refunds: Option<router_request_types::SplitRefundsRequest>,
+ merchant_connector_account: &helpers::MerchantConnectorAccountType,
) -> RouterResult<types::RefundsRouterData<F>> {
- 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,
- merchant_context.get_merchant_account().get_id(),
- creds_identifier.as_deref(),
- merchant_context.get_merchant_key_store(),
- profile_id,
- connector_id,
- payment_attempt.merchant_connector_id.as_ref(),
- )
- .await?;
-
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")