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

refactor: Consolidate payment gateway routing with unified execution path (#10710)

Hrithikesh88cd005ae8f9
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index f40e2bd8ef..b73f26b4b6 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -28,6 +28,7 @@ use external_services::grpc_client;
#[cfg(feature = "v2")]
pub mod payment_methods;
+#[cfg(feature = "v2")]
use std::future;
#[cfg(feature = "olap")]
@@ -114,11 +115,6 @@ use crate::core::debit_routing;
use crate::core::fraud_check as frm_core;
#[cfg(feature = "v2")]
use crate::core::payment_methods::vault;
-#[cfg(feature = "v1")]
-use crate::core::payments::helpers::{
- process_through_direct, process_through_direct_with_shadow_unified_connector_service,
- process_through_ucs,
-};
#[cfg(feature = "v2")]
use crate::core::revenue_recovery::get_workflow_entries;
#[cfg(feature = "v2")]
@@ -4492,7 +4488,7 @@ pub async fn decide_unified_connector_service_call<'a, F, RouterDReq, ApiRequest
is_retry_payment: bool,
all_keys_required: Option<bool>,
merchant_connector_account: helpers::MerchantConnectorAccountType,
- mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
+ router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
tokenization_action: TokenizationAction,
) -> RouterResult<(
RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
@@ -4524,162 +4520,54 @@ where
)
.await?;
- let ucs_flow = if matches!(
- execution_path,
- ExecutionPath::UnifiedConnectorService | ExecutionPath::ShadowUnifiedConnectorService
- ) {
- let cached_access_token = access_token::get_cached_access_token_for_ucs(
- state,
- &connector,
- platform,
- router_data.payment_method,
- payment_data.get_creds_identifier(),
- )
- .await?;
+ let lineage_ids = grpc_client::LineageIds::new(
+ business_profile.merchant_id.clone(),
+ business_profile.get_id().clone(),
+ );
- // Set cached access token in router_data if available
- if let Some(access_token) = cached_access_token {
- router_data.access_token = Some(access_token);
- }
- true
- } else {
- false
+ let execution_mode = match execution_path {
+ ExecutionPath::UnifiedConnectorService => ExecutionMode::Primary,
+ ExecutionPath::ShadowUnifiedConnectorService => ExecutionMode::Shadow,
+ // ExecutionMode is irrelevant for Direct path in this context
+ ExecutionPath::Direct => ExecutionMode::NotApplicable,
};
- let is_ucs_granular_flow =
- gateway::GRANULAR_GATEWAY_SUPPORTED_FLOWS.contains(&std::any::type_name::<F>());
-
- if is_ucs_granular_flow && ucs_flow {
- logger::info!("Current flow is UCS Granular flow");
- let lineage_ids = grpc_client::LineageIds::new(
- business_profile.merchant_id.clone(),
- business_profile.get_id().clone(),
- );
-
- let execution_mode = match execution_path {
- ExecutionPath::UnifiedConnectorService => ExecutionMode::Primary,
- ExecutionPath::ShadowUnifiedConnectorService => ExecutionMode::Shadow,
- // ExecutionMode is irrelevant for Direct path in this context
- ExecutionPath::Direct => ExecutionMode::NotApplicable,
- };
-
- let gateway_context = gateway_context::RouterGatewayContext {
- creds_identifier: payment_data.get_creds_identifier().map(|id| id.to_string()),
- platform: platform.clone(),
- header_payload: header_payload.clone(),
- lineage_ids,
- merchant_connector_account: merchant_connector_account.clone(),
- execution_path,
- execution_mode,
- };
- // Update feature metadata to track Direct routing usage for stickiness
- update_gateway_system_in_feature_metadata(
- payment_data,
- gateway_context.get_gateway_system(),
- )?;
- call_connector_service(
- &updated_state,
- req_state,
- platform,
- connector,
- operation,
- payment_data,
- customer,
- call_connector_action,
- validate_result,
- schedule_time,
- header_payload,
- frm_suggestion,
- business_profile,
- is_retry_payment,
- all_keys_required,
- merchant_connector_account,
- router_data,
- tokenization_action,
- gateway_context,
- )
- .await
- } else {
- record_time_taken_with(|| async {
- match execution_path {
- // Process through UCS when system is UCS and not handling response or if it is a UCS webhook action
- ExecutionPath::UnifiedConnectorService => {
- process_through_ucs(
- &updated_state,
- req_state,
- platform,
- operation,
- payment_data,
- customer,
- call_connector_action,
- validate_result,
- schedule_time,
- header_payload,
- frm_suggestion,
- business_profile,
- merchant_connector_account,
- &connector,
- router_data,
- )
- .await
- }
-
- // Process through Direct with Shadow UCS
- ExecutionPath::ShadowUnifiedConnectorService => {
- process_through_direct_with_shadow_unified_connector_service(
- &updated_state,
- req_state,
- platform,
- connector,
- operation,
- payment_data,
- customer,
- call_connector_action,
- shadow_ucs_call_connector_action,
- validate_result,
- schedule_time,
- header_payload,
- frm_suggestion,
- business_profile,
- is_retry_payment,
- all_keys_required,
- merchant_connector_account,
- router_data,
- tokenization_action,
- )
- .await
- }
-
- // Process through Direct gateway
- ExecutionPath::Direct => {
- process_through_direct(
- state,
- req_state,
- platform,
- connector,
- operation,
- payment_data,
- customer,
- call_connector_action,
- validate_result,
- schedule_time,
- header_payload,
- frm_suggestion,
- business_profile,
- is_retry_payment,
- all_keys_required,
- merchant_connector_account,
- router_data,
- tokenization_action,
- )
- .await
- }
- }
- })
- .await
- }
+ let gateway_context = gateway_context::RouterGatewayContext {
+ creds_identifier: payment_data.get_creds_identifier().map(|id| id.to_string()),
+ platform: platform.clone(),
+ header_payload: header_payload.clone(),
+ lineage_ids,
+ merchant_connector_account: merchant_connector_account.clone(),
+ execution_path,
+ execution_mode,
+ };
+ // Update feature metadata to track Direct routing usage for stickiness
+ update_gateway_system_in_feature_metadata(payment_data, gateway_context.get_gateway_system())?;
+ call_connector_service(
+ &updated_state,
+ req_state,
+ platform,
+ connector,
+ operation,
+ payment_data,
+ customer,
+ call_connector_action,
+ validate_result,
+ schedule_time,
+ header_payload,
+ frm_suggestion,
+ business_profile,
+ is_retry_payment,
+ all_keys_required,
+ merchant_connector_account,
+ router_data,
+ tokenization_action,
+ gateway_context,
+ )
+ .await
}
+#[cfg(feature = "v2")]
async fn record_time_taken_with<F, Fut, R>(f: F) -> RouterResult<R>
where
F: FnOnce() -> Fut,
@@ -4716,6 +4604,7 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>(
mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
updated_customer: Option<storage::CustomerUpdate>,
tokenization_action: TokenizationAction,
+ gateway_context: gateway_context::RouterGatewayContext,
) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
where
F: Send + Clone + Sync,
@@ -4730,13 +4619,6 @@ where
+ Send
+ Sync,
{
- let gateway_context = gateway_context::RouterGatewayContext::direct(
- platform.clone(),
- merchant_connector_account_type_details,
- business_profile.merchant_id.clone(),
- business_profile.get_id().clone(),
- payment_data.get_creds_identifier().map(|id| id.to_string()),
- );
let add_access_token_result = router_data
.add_access_token(
state,
@@ -5291,7 +5173,7 @@ where
// Extract previous gateway from payment data
let previous_gateway = extract_gateway_system_from_payment_intent(payment_data);
- let (execution, updated_state) = should_call_unified_connector_service(
+ let (execution_path, updated_state) = should_call_unified_connector_service(
state,
platform,
&router_data,
@@ -5300,127 +5182,50 @@ where
None,
)
.await?;
- if matches!(execution, ExecutionPath::UnifiedConnectorService) {
- router_env::logger::info!(
- "Executing payment through UCS gateway system - payment_id={}, attempt_id={}",
- payment_data.get_payment_intent().id.get_string_repr(),
- payment_data.get_payment_attempt().id.get_string_repr()
- );
- if should_add_task_to_process_tracker(payment_data) {
- operation
- .to_domain()?
- .add_task_to_process_tracker(
- state,
- payment_data.get_payment_attempt(),
- false,
- schedule_time,
- )
- .await
- .map_err(|error| logger::error!(process_tracker_error=?error))
- .ok();
- }
-
- (_, *payment_data) = operation
- .to_update_tracker()?
- .update_trackers(
- state,
- req_state,
- payment_data.clone(),
- customer.clone(),
- platform.get_processor().get_account().storage_scheme,
- None,
- platform.get_processor().get_key_store(),
- frm_suggestion,
- header_payload.clone(),
- )
- .await?;
- let lineage_ids = grpc_client::LineageIds::new(
- business_profile.merchant_id.clone(),
- business_profile.get_id().clone(),
- );
-
- // Extract merchant_order_reference_id from payment data for UCS audit trail
- let merchant_order_reference_id = payment_data.get_payment_intent().merchant_reference_id
- .clone()
- .map(|id| id.get_string_repr().to_string());
- let creds_identifier = payment_data.get_creds_identifier().map(str::to_owned);
-
- // Check for cached access token in Redis (no generation for UCS flows)
- let cached_access_token = access_token::get_cached_access_token_for_ucs(
- state,
- &connector,
- platform,
- router_data.payment_method,
- payment_data.get_creds_identifier(),
- )
- .await?;
-
- // Set cached access token in router_data if available
- if let Some(access_token) = cached_access_token {
- router_data.access_token = Some(access_token);
- }
-
- router_data
- .call_unified_connector_service(
- state,
- &header_payload,
- lineage_ids,
- merchant_connector_account_type_details.clone(),
- platform,
- &connector,
- ExecutionMode::Primary, //UCS is called in primary mode
- merchant_order_reference_id,
- call_connector_action,
- creds_identifier
- )
- .await?;
-
- Ok(router_data)
- } else {
- if matches!(execution, ExecutionPath::ShadowUnifiedConnectorService) {
- router_env::logger::info!(
- "Shadow UCS mode not implemented in v2, processing through direct path - payment_id={}, attempt_id={}",
- payment_data.get_payment_intent().id.get_string_repr(),
- payment_data.get_payment_attempt().id.get_string_repr()
- );
- } else {
- router_env::logger::info!(
- "Processing payment through Direct gateway system - payment_id={}, attempt_id={}",
- payment_data.get_payment_intent().id.get_string_repr(),
- payment_data.get_payment_attempt().id.get_string_repr()
- );
- }
-
+ let lineage_ids = grpc_client::LineageIds::new(
+ business_profile.merchant_id.clone(),
+ business_profile.get_id().clone(),
+ );
- let session_state = if matches!(execution, ExecutionPath::ShadowUnifiedConnectorService) {
- &updated_state
- } else {
- state
- };
+ let execution_mode = match execution_path {
+ ExecutionPath::UnifiedConnectorService => ExecutionMode::Primary,
+ ExecutionPath::ShadowUnifiedConnectorService => ExecutionMode::Shadow,
+ // ExecutionMode is irrelevant for Direct path in this context
+ ExecutionPath::Direct => ExecutionMode::NotApplicable,
+ };
- call_connector_service(
- session_state,
- req_state,
- platform,
- connector,
- operation,
- payment_data,
- customer,
- call_connector_action,
- schedule_time,
- header_payload,
- frm_suggestion,
- business_profile,
- is_retry_payment,
- should_retry_with_pan,
- return_raw_connector_response,
- merchant_connector_account_type_details,
- router_data,
- updated_customer,
- tokenization_action,
- )
- .await
- }
+ let gateway_context = gateway_context::RouterGatewayContext {
+ creds_identifier: payment_data.get_creds_identifier().map(|id| id.to_string()),
+ platform: platform.clone(),
+ header_payload: header_payload.clone(),
+ lineage_ids,
+ merchant_connector_account: merchant_connector_account_type_details.clone(),
+ execution_path,
+ execution_mode,
+ };
+ call_connector_service(
+ &updated_state,
+ req_state,
+ platform,
+ connector,
+ operation,
+ payment_data,
+ customer,
+ call_connector_action,
+ schedule_time,
+ header_payload,
+ frm_suggestion,
+ business_profile,
+ is_retry_payment,
+ should_retry_with_pan,
+ return_raw_connector_response,
+ merchant_connector_account_type_details,
+ router_data,
+ updated_customer,
+ tokenization_action,
+ gateway_context,
+ )
+ .await
})
.await
}
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index 982090dc34..9922309f8b 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -17,8 +17,9 @@ pub mod setup_mandate_flow;
pub mod update_metadata_flow;
use async_trait::async_trait;
-use common_enums::{self, ExecutionMode};
+use common_enums;
use common_types::payments::CustomerAcceptance;
+#[cfg(feature = "v2")]
use external_services::grpc_client;
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
use hyperswitch_domain_models::router_flow_types::{
@@ -255,28 +256,7 @@ pub trait Feature<F, T> {
) {
}
- async fn call_preprocessing_through_unified_connector_service<'a>(
- self,
- _state: &SessionState,
- _header_payload: &domain_payments::HeaderPayload,
- _lineage_ids: &grpc_client::LineageIds,
- #[cfg(feature = "v1")] _merchant_connector_account: helpers::MerchantConnectorAccountType,
- #[cfg(feature = "v2")]
- _merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
- _platform: &domain::Platform,
- _connector_data: &api::ConnectorData,
- _unified_connector_service_execution_mode: ExecutionMode,
- _merchant_order_reference_id: Option<String>,
- ) -> RouterResult<(Self, bool)>
- where
- F: Clone,
- Self: Sized,
- dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>,
- {
- // Default behaviour is to do nothing and continue further
- Ok((self, true))
- }
-
+ #[cfg(feature = "v2")]
async fn call_unified_connector_service<'a>(
&mut self,
_state: &SessionState,
@@ -287,7 +267,7 @@ pub trait Feature<F, T> {
_merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
_platform: &domain::Platform,
_connector_data: &api::ConnectorData,
- _unified_connector_service_execution_mode: ExecutionMode,
+ _unified_connector_service_execution_mode: common_enums::ExecutionMode,
_merchant_order_reference_id: Option<String>,
_call_connector_action: common_enums::CallConnectorAction,
_creds_identifier: Option<String>,
@@ -309,7 +289,7 @@ pub trait Feature<F, T> {
_merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
_external_vault_merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
_platform: &domain::Platform,
- _unified_connector_service_execution_mode: ExecutionMode,
+ _unified_connector_service_execution_mode: common_enums::ExecutionMode,
_merchant_order_reference_id: Option<String>,
) -> RouterResult<()>
where
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index 1fbe3dd8b0..046c683c65 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -3,7 +3,9 @@ use std::str::FromStr;
use async_trait::async_trait;
use common_enums as enums;
use common_types::payments as common_payments_types;
-use common_utils::{errors, id_type, types::MinorUnit, ucs_types};
+#[cfg(feature = "v2")]
+use common_utils::types::MinorUnit;
+use common_utils::{errors, id_type, ucs_types};
use error_stack::ResultExt;
use external_services::grpc_client;
#[cfg(feature = "v2")]
@@ -23,6 +25,13 @@ use unified_connector_service_masking::ExposeInterface as UcsMaskingExposeInterf
// use router_env::tracing::Instrument;
use super::{ConstructFlowSpecificData, Feature};
+#[cfg(feature = "v2")]
+use crate::core::unified_connector_service::{
+ get_access_token_from_ucs_response,
+ handle_unified_connector_service_response_for_payment_authorize,
+ handle_unified_connector_service_response_for_payment_repeat, set_access_token_for_ucs,
+ ucs_logging_wrapper,
+};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
@@ -32,11 +41,7 @@ use crate::{
helpers, session_token, tokenization, transformers, PaymentData,
},
unified_connector_service::{
- self, build_unified_connector_service_auth_metadata,
- get_access_token_from_ucs_response,
- handle_unified_connector_service_response_for_payment_authorize,
- handle_unified_connector_service_response_for_payment_repeat, set_access_token_for_ucs,
- ucs_logging_wrapper, ucs_logging_wrapper_granular,
+ self, build_unified_connector_service_auth_metadata, ucs_logging_wrapper_granular,
},
},
logger,
@@ -584,6 +589,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
}
}
+ #[cfg(feature = "v2")]
async fn call_unified_connector_service<'a>(
&mut self,
state: &SessionState,
@@ -969,6 +975,7 @@ async fn process_capture_flow(
Ok(router_data)
}
+#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
async fn call_unified_connector_service_authorize(
router_data: &mut types::RouterData<
@@ -1303,6 +1310,7 @@ pub async fn call_unified_connector_service_pre_authenticate(
.change_context(interface_errors::ConnectorError::ResponseHandlingFailed)
}
+#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
async fn call_unified_connector_service_repeat_payment(
router_data: &mut types::RouterData<
diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs
index 6c6a86f43c..4e1939e726 100644
--- a/crates/router/src/core/payments/flows/cancel_flow.rs
+++ b/crates/router/src/core/payments/flows/cancel_flow.rs
@@ -1,26 +1,14 @@
-use std::str::FromStr;
-
use async_trait::async_trait;
-use common_utils::{id_type, ucs_types};
-use error_stack::ResultExt;
-use external_services::grpc_client;
-use hyperswitch_domain_models::payments as domain_payments;
-use router_env::logger;
-use unified_connector_service_client::payments as payments_grpc;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
- errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult},
+ errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
- unified_connector_service::{
- build_unified_connector_service_auth_metadata,
- handle_unified_connector_service_response_for_payment_cancel, ucs_logging_wrapper,
- },
},
routes::{metrics, SessionState},
services,
- types::{self, api, domain, transformers::ForeignTryFrom},
+ types::{self, api, domain},
};
#[cfg(feature = "v1")]
#[async_trait]
@@ -167,96 +155,4 @@ impl Feature<api::Void, types::PaymentsCancelData>
Ok((request, true))
}
-
- async fn call_unified_connector_service<'a>(
- &mut self,
- state: &SessionState,
- header_payload: &domain_payments::HeaderPayload,
- lineage_ids: grpc_client::LineageIds,
- #[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
- #[cfg(feature = "v2")]
- merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
- platform: &domain::Platform,
- _connector_data: &api::ConnectorData,
- unified_connector_service_execution_mode: common_enums::ExecutionMode,
- merchant_order_reference_id: Option<String>,
- _call_connector_action: common_enums::CallConnectorAction,
- _creds_identifier: Option<String>,
- ) -> RouterResult<()> {
- let client = state
- .grpc_client
- .unified_connector_service_client
- .clone()
- .ok_or(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to fetch Unified Connector Service client")?;
-
- let payment_void_request =
- payments_grpc::PaymentServiceVoidRequest::foreign_try_from(&*self)
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to construct Payment Void Request")?;
-
- let connector_auth_metadata = build_unified_connector_service_auth_metadata(
- merchant_connector_account,
- platform,
- self.connector.clone(),
- )
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to construct request metadata")?;
-
- let merchant_reference_id = header_payload
- .x_reference_id
- .clone()
- .or(merchant_order_reference_id)
- .map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
- .transpose()
- .inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
- .ok()
- .flatten()
- .map(ucs_types::UcsReferenceId::Payment);
-
- let header_payload = state
- .get_grpc_headers_ucs(unified_connector_service_execution_mode)
- .external_vault_proxy_metadata(None)
- .merchant_reference_id(merchant_reference_id)
- .lineage_ids(lineage_ids);
-
- let (updated_router_data, _) = Box::pin(ucs_logging_wrapper(
- self.clone(),
- state,
- payment_void_request,
- header_payload,
- |mut router_data, payment_void_request, grpc_headers| async move {
- let response = Box::pin(client.payment_cancel(
- payment_void_request,
- connector_auth_metadata,
- grpc_headers,
- ))
- .await
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to Cancel payment")?;
-
- let payment_void_response = response.into_inner();
-
- let (router_data_response, status_code) =
- handle_unified_connector_service_response_for_payment_cancel(
- payment_void_response.clone(),
- )
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to deserialize UCS response")?;
-
- let router_data_response = router_data_response.map(|(response, status)| {
- router_data.status = status;
- response
- });
- router_data.response = router_data_response;
- router_data.connector_http_status_code = Some(status_code);
-
- Ok((router_data, (), payment_void_response))
- },
- ))
- .await?;
-
- *self = updated_router_data;
- Ok(())
- }
}
diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs
index 418fb7b5db..af7e0a235a 100644
--- a/crates/router/src/core/payments/flows/capture_flow.rs
+++ b/crates/router/src/core/payments/flows/capture_flow.rs
@@ -1,27 +1,14 @@
-use std::str::FromStr;
-
use async_trait::async_trait;
-use common_utils::{id_type, types::MinorUnit, ucs_types};
-use error_stack::ResultExt;
-use external_services::grpc_client;
-use hyperswitch_domain_models::{
- errors::api_error_response::ApiErrorResponse, payments as domain_payments,
-};
-use unified_connector_service_client::payments as payments_grpc;
use super::ConstructFlowSpecificData;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, Feature, PaymentData},
- unified_connector_service::{
- build_unified_connector_service_auth_metadata,
- handle_unified_connector_service_response_for_payment_capture, ucs_logging_wrapper,
- },
},
routes::SessionState,
- services::{self, logger},
- types::{self, api, domain, transformers::ForeignTryFrom},
+ services,
+ types::{self, api, domain},
};
#[cfg(feature = "v1")]
@@ -176,98 +163,4 @@ impl Feature<api::Capture, types::PaymentsCaptureData>
Ok((request, true))
}
-
- async fn call_unified_connector_service<'a>(
- &mut self,
- state: &SessionState,
- header_payload: &domain_payments::HeaderPayload,
- lineage_ids: grpc_client::LineageIds,
- #[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
- #[cfg(feature = "v2")]
- merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
- platform: &domain::Platform,
- _connector_data: &api::ConnectorData,
- unified_connector_service_execution_mode: common_enums::ExecutionMode,
- merchant_order_reference_id: Option<String>,
- _call_connector_action: common_enums::CallConnectorAction,
- _creds_identifier: Option<String>,
- ) -> RouterResult<()> {
- let client = state
- .grpc_client
- .unified_connector_service_client
- .clone()
- .ok_or(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to fetch Unified Connector Service client")?;
-
- let payment_capture_request =
- payments_grpc::PaymentServiceCaptureRequest::foreign_try_from(&*self)
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to construct Payment Capture Request")?;
-
- let connector_auth_metadata = build_unified_connector_service_auth_metadata(
- merchant_connector_account,
- platform,
- self.connector.clone(),
- )
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to construct request metadata")?;
- let merchant_reference_id = header_payload
- .x_reference_id
- .clone()
- .or(merchant_order_reference_id)
- .map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
- .transpose()
- .inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
- .ok()
- .flatten()
- .map(ucs_types::UcsReferenceId::Payment);
- let header_payload = state
- .get_grpc_headers_ucs(unified_connector_service_execution_mode)
- .external_vault_proxy_metadata(None)
- .merchant_reference_id(merchant_reference_id)
- .lineage_ids(lineage_ids);
- let (updated_router_data, _) = Box::pin(ucs_logging_wrapper(
- self.clone(),
- state,
- payment_capture_request,
- header_payload,
- |mut router_data, payment_capture_request, grpc_headers| async move {
- let response = Box::pin(client.payment_capture(
- payment_capture_request,
- connector_auth_metadata,
- grpc_headers,
- ))
- .await
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to capture payment")?;
-
- let payment_capture_response = response.into_inner();
-
- let (router_data_response, status_code) =
- handle_unified_connector_service_response_for_payment_capture(
- payment_capture_response.clone(),
- )
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to deserialize UCS response")?;
-
- let router_data_response = router_data_response.map(|(response, status)| {
- router_data.status = status;
- response
- });
- router_data.response = router_data_response;
- router_data.amount_captured = payment_capture_response.captured_amount;
- router_data.minor_amount_captured = payment_capture_response
- .minor_captured_amount
- .map(MinorUnit::new);
- router_data.connector_http_status_code = Some(status_code);
-
- Ok((router_data, (), payment_capture_response))
- },
- ))
- .await?;
-
- // Copy back the updated data
- *self = updated_router_data;
- Ok(())
- }
}
diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rs
index 8f0e7f3d4e..09aff48b73 100644
--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs
@@ -404,199 +404,6 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>
Ok((self, true))
}
}
-
- async fn call_preprocessing_through_unified_connector_service<'a>(
- self,
- state: &SessionState,
- header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
- lineage_ids: &grpc_client::LineageIds,
- #[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
- #[cfg(feature = "v2")]
- merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
- platform: &domain::Platform,
- connector_data: &api::ConnectorData,
- unified_connector_service_execution_mode: common_enums::ExecutionMode,
- merchant_order_reference_id: Option<String>,
- ) -> RouterResult<(Self, bool)> {
- let current_flow = api_interface::CurrentFlowInfo::CompleteAuthorize {
- request_data: &self.request,
- payment_method: Some(self.payment_method),
- };
- let optional_preprocessing_flow = connector_data
- .connector
- .get_preprocessing_flow_if_needed(current_flow);
- match optional_preprocessing_flow {
- Some(preprocessing_flow) => {
- let updated_router_data =
- Box::pin(handle_preprocessing_through_unified_connector_service(
- self,
- state,
- header_payload,
- lineage_ids.clone(),
- merchant_connector_account.clone(),
- platform,
- connector_data,
- unified_connector_service_execution_mode,
- merchant_order_reference_id.clone(),
- preprocessing_flow,
- ))
- .await?;
- // check if redirection is not present in the response and attempt status is not AuthenticationFailed
- // if condition does not satisfy, then we don't need to proceed further
- let should_continue = (matches!(
- updated_router_data.response,
- Ok(types::PaymentsResponseData::TransactionResponse {
- ref redirection_data,
- ..
- }) if redirection_data.is_none()
- ) && updated_router_data.status
- != common_enums::AttemptStatus::AuthenticationFailed);
- Ok((updated_router_data, should_continue))
- }
- None => Ok((self, true)),
- }
- }
-
- async fn call_unified_connector_service<'a>(
- &mut self,
- state: &SessionState,
- header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
- lineage_ids: grpc_client::LineageIds,
- #[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
- #[cfg(feature = "v2")]
- merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
- platform: &domain::Platform,
- connector_data: &api::ConnectorData,
- unified_connector_service_execution_mode: common_enums::ExecutionMode,
- merchant_order_reference_id: Option<String>,
- _call_connector_action: common_enums::CallConnectorAction,
- _creds_identifier: Option<String>,
- ) -> RouterResult<()> {
- // Call UCS for Complete Authorize flow
- Box::pin(call_unified_connector_service_complete_authorize(
- self,
- state,
- header_payload,
- lineage_ids,
- merchant_connector_account,
- platform,
- connector_data.connector_name,
- unified_connector_service_execution_mode,
- merchant_order_reference_id,
- ))
- .await
- }
-}
-
-#[allow(clippy::too_many_arguments)]
-async fn handle_preprocessing_through_unified_connector_service(
- router_data: types::RouterData<
- api::CompleteAuthorize,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
- >,
- state: &SessionState,
- header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
- lineage_ids: grpc_client::LineageIds,
- #[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
- #[cfg(feature = "v2")] merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
- platform: &domain::Platform,
- connector_data: &api::ConnectorData,
- unified_connector_service_execution_mode: common_enums::ExecutionMode,
- merchant_order_reference_id: Option<String>,
- preprocessing_flow_name: api_interface::PreProcessingFlowName,
-) -> RouterResult<
- types::RouterData<
- api::CompleteAuthorize,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
- >,
-> {
- match preprocessing_flow_name {
- api_interface::PreProcessingFlowName::Authenticate => {
- // Convert CompleteAuthorize to Authenticate for UCS call
- let mut complete_authorize_request_data = router_data.request.clone();
- let authenticate_request_data =
- types::PaymentsAuthenticateData::try_from(router_data.request.to_owned())?;
- let authenticate_response_data: Result<
- types::PaymentsResponseData,
- types::ErrorResponse,
- > = Err(types::ErrorResponse::default());
- let authenticate_router_data =
- helpers::router_data_type_conversion::<_, api::Authenticate, _, _, _, _>(
- router_data.clone(),
- authenticate_request_data,
- authenticate_response_data,
- );
-
- // Call UCS for Authenticate flow and store authentication result for next step
- let (authenticate_router_data, authentication_data) =
- call_unified_connector_service_authenticate(
- &authenticate_router_data,
- state,
- header_payload,
- lineage_ids,
- merchant_connector_account,
- platform,
- connector_data.connector_name,
- unified_connector_service_execution_mode,
- merchant_order_reference_id,
- )
- .await
- .to_payment_failed_response()?;
- complete_authorize_request_data.authentication_data = authentication_data;
- // Convert back to CompleteAuthorize router data while preserving preprocessing response data
- let authenticate_response = authenticate_router_data.response.clone();
- let complete_authorize_router_data =
- helpers::router_data_type_conversion::<_, api::CompleteAuthorize, _, _, _, _>(
- authenticate_router_data,
- complete_authorize_request_data,
- authenticate_response,
- );
- Ok(complete_authorize_router_data)
- }
- api_interface::PreProcessingFlowName::PostAuthenticate => {
- // Convert CompleteAuthorize to PostAuthenticate for UCS call
- let mut complete_authorize_request_data = router_data.request.clone();
- let post_authenticate_request_data =
- types::PaymentsPostAuthenticateData::try_from(router_data.request.to_owned())?;
- let post_authenticate_response_data: Result<
- types::PaymentsResponseData,
- types::ErrorResponse,
- > = Err(types::ErrorResponse::default());
- let post_authenticate_router_data =
- helpers::router_data_type_conversion::<_, api::PostAuthenticate, _, _, _, _>(
- router_data.clone(),
- post_authenticate_request_data,
- post_authenticate_response_data,
- );
-
- // Call UCS for PostAuthenticate flow and store authentication result for next step
- let (post_authenticate_router_data, authentication_data) =
- call_unified_connector_service_post_authenticate(
- &post_authenticate_router_data,
- state,
- header_payload,
- lineage_ids,
- merchant_connector_account,
- platform,
- unified_connector_service_execution_mode,
- merchant_order_reference_id,
- )
- .await
- .to_payment_failed_response()?;
- complete_authorize_request_data.authentication_data = authentication_data;
- // Convert back to CompleteAuthorize router data while preserving preprocessing response data
- let post_authenticate_response = post_authenticate_router_data.response.clone();
- let complete_authorize_router_data =
- helpers::router_data_type_conversion::<_, api::CompleteAuthorize, _, _, _, _>(
- post_authenticate_router_data,
- complete_authorize_request_data,
- post_authenticate_response,
- );
- Ok(complete_authorize_router_data)
- }
- }
}
fn transform_redirection_response_for_authenticate_flow(
@@ -1026,121 +833,6 @@ impl<F>
}
}
-#[allow(clippy::too_many_arguments)]
-async fn call_unified_connector_service_complete_authorize(
- router_data: &mut types::RouterData<
- api::CompleteAuthorize,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
- >,
- state: &SessionState,
- header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
- lineage_ids: grpc_client::LineageIds,
- #[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
- #[cfg(feature = "v2")] merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
- platform: &domain::Platform,
- _connector: connector_enums::Connector,
- unified_connector_service_execution_mode: common_enums::ExecutionMode,
- merchant_order_reference_id: Option<String>,
-) -> RouterResult<()> {
- let client = state
- .grpc_client
- .unified_connector_service_client
- .clone()
- .ok_or(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to fetch Unified Connector Service client")?;
-
- let payment_authorize_request =
- payments_grpc::PaymentServiceAuthorizeRequest::foreign_try_from(&(*router_data))
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to construct Payment Complete Authorize Request")?;
-
- let connector_auth_metadata = ucs_core::build_unified_connector_service_auth_metadata(
- merchant_connector_account,
- platform,
- router_data.connector.clone(),
- )
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to construct request metadata")?;
-
- let merchant_reference_id = header_payload
- .x_reference_id
- .clone()
- .or(merchant_order_reference_id)
- .map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
- .transpose()
- .inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
- .ok()
- .flatten()
- .map(ucs_types::UcsReferenceId::Payment);
-
- let headers_builder = state
- .get_grpc_headers_ucs(unified_connector_service_execution_mode)
- .external_vault_proxy_metadata(None)
- .merchant_reference_id(merchant_reference_id)
- .lineage_ids(lineage_ids);
-
- let (updated_router_data, _) = Box::pin(ucs_core::ucs_logging_wrapper(
- router_data.clone(),
- state,
- payment_authorize_request,
- headers_builder,
- |mut router_data, payment_authorize_request, grpc_headers| async move {
- let response = Box::pin(client.payment_authorize(
- payment_authorize_request,
- connector_auth_metadata,
- grpc_headers,
- ))
- .await
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to complete authorize payment")?;
-
- let payment_authorize_response = response.into_inner();
-
- let ucs_authorize_response =
- ucs_core::handle_unified_connector_service_response_for_payment_authorize(
- payment_authorize_response.clone(),
- )
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to deserialize UCS response")?;
-
- let router_data_response =
- ucs_authorize_response
- .router_data_response
- .map(|(response, status)| {
- router_data.status = status;
- response
- });
- router_data.response = router_data_response;
- router_data.raw_connector_response = payment_authorize_response
- .raw_connector_response
- .clone()
- .map(|raw_connector_response| raw_connector_response.expose().into());
- router_data.connector_http_status_code = Some(ucs_authorize_response.status_code);
-
- // Populate connector_customer_id if present
- ucs_authorize_response
- .connector_customer_id
- .map(|connector_customer_id| {
- router_data.connector_customer = Some(connector_customer_id);
- });
-
- ucs_authorize_response
- .connector_response
- .map(|customer_response| {
- router_data.connector_response = Some(customer_response);
- });
-
- Ok((router_data, (), payment_authorize_response))
- },
- ))
- .await?;
-
- // Copy back the updated data
- *router_data = updated_router_data;
- Ok(())
-}
-
#[allow(clippy::too_many_arguments)]
async fn process_capture_flow(
mut router_data: types::RouterData<
diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs
index aa84c430fd..cf3266e1d2 100644
--- a/crates/router/src/core/payments/flows/psync_flow.rs
+++ b/crates/router/src/core/payments/flows/psync_flow.rs
@@ -1,20 +1,9 @@
-use std::{collections::HashMap, str::FromStr};
+use std::collections::HashMap;
use async_trait::async_trait;
-use common_enums::{self, enums};
-use common_utils::{id_type, types::MinorUnit, ucs_types};
-use error_stack::ResultExt;
-use external_services::grpc_client;
+use common_enums;
use hyperswitch_domain_models::payments as domain_payments;
-use hyperswitch_interfaces::{
- api::gateway,
- unified_connector_service::{
- get_payments_response_from_ucs_webhook_content,
- handle_unified_connector_service_response_for_payment_get,
- },
-};
-use unified_connector_service_client::payments as payments_grpc;
-use unified_connector_service_masking::ExposeInterface;
+use hyperswitch_interfaces::api::gateway;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
@@ -22,14 +11,10 @@ use crate::{
core::{
errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
- unified_connector_service::{
- build_unified_connector_service_auth_metadata, extract_connector_response_from_ucs,
- get_access_token_from_ucs_response, set_access_token_for_ucs, ucs_logging_wrapper,
- },
},
routes::SessionState,
services::{self, api::ConnectorValidation, logger},
- types::{self, api, domain, transformers::ForeignTryFrom},
+ types::{self, api, domain},
};
#[cfg(feature = "v1")]
@@ -236,229 +221,6 @@ impl Feature<api::PSync, types::PaymentsSyncData>
Ok((request, true))
}
-
- async fn call_unified_connector_service<'a>(
- &mut self,
- state: &SessionState,
- header_payload: &domain_payments::HeaderPayload,
- lineage_ids: grpc_client::LineageIds,
- #[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
- #[cfg(feature = "v2")]
- merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
- platform: &domain::Platform,
- _connector_data: &api::ConnectorData,
- unified_connector_service_execution_mode: enums::ExecutionMode,
- merchant_order_reference_id: Option<String>,
- call_connector_action: common_enums::CallConnectorAction,
- creds_identifier: Option<String>,
- ) -> RouterResult<()> {
- match call_connector_action {
- common_enums::CallConnectorAction::UCSConsumeResponse(transform_data_bytes) => {
- let webhook_content: payments_grpc::WebhookResponseContent =
- serde_json::from_slice(&transform_data_bytes)
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to deserialize UCS webhook transform data")?;
-
- let payment_get_response =
- get_payments_response_from_ucs_webhook_content(webhook_content)
- .change_context(ApiErrorResponse::WebhookProcessingFailure)
- .attach_printable(
- "Failed to construct payments response from UCS webhook content",
- )?;
-
- let (router_data_response, status_code) =
- handle_unified_connector_service_response_for_payment_get(
- payment_get_response.clone(),
- )
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to deserialize UCS response")?;
-
- let router_data_response = router_data_response.map(|(response, status)| {
- self.status = status;
- response
- });
-
- let connector_response = extract_connector_response_from_ucs(
- payment_get_response.connector_response.as_ref(),
- );
-
- self.response = router_data_response;
- self.amount_captured = payment_get_response.captured_amount;
- self.minor_amount_captured = payment_get_response
- .minor_captured_amount
- .map(MinorUnit::new);
- self.raw_connector_response = payment_get_response
- .raw_connector_response
- .clone()
- .map(|raw_connector_response| raw_connector_response.expose().into());
- self.connector_http_status_code = Some(status_code);
-
- connector_response.map(|customer_response| {
- self.connector_response = Some(customer_response);
- });
- }
- common_enums::CallConnectorAction::UCSHandleResponse(_)
- | common_enums::CallConnectorAction::Trigger => {
- let connector_name = self.connector.clone();
- let connector_enum =
- common_enums::connector_enums::Connector::from_str(&connector_name)
- .change_context(ApiErrorResponse::IncorrectConnectorNameGiven)?;
-
- let is_ucs_psync_disabled = state
- .conf
- .grpc_client
- .unified_connector_service
- .as_ref()
- .is_some_and(|config| {
- config
- .ucs_psync_disabled_connectors
- .contains(&connector_enum)
- });
-
- if is_ucs_psync_disabled {
- logger::info!(
- "UCS PSync call disabled for connector: {}, skipping UCS call",
- connector_name
- );
- return Ok(());
- }
- let client = state
- .grpc_client
- .unified_connector_service_client
- .clone()
- .ok_or(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to fetch Unified Connector Service client")?;
-
- let payment_get_request =
- payments_grpc::PaymentServiceGetRequest::foreign_try_from((
- &*self,
- call_connector_action,
- ))
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to construct Payment Get Request")?;
-
- let merchant_connector_id = merchant_connector_account.get_mca_id();
-
- let connector_auth_metadata = build_unified_connector_service_auth_metadata(
- merchant_connector_account,
- platform,
- self.connector.clone(),
- )
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to construct request metadata")?;
- let merchant_reference_id = header_payload
- .x_reference_id
- .clone()
- .or(merchant_order_reference_id)
- .map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
- .transpose()
- .inspect_err(
- |err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"),
- )
- .ok()
- .flatten()
- .map(ucs_types::UcsReferenceId::Payment);
- let header_payload = state
- .get_grpc_headers_ucs(unified_connector_service_execution_mode)
- .external_vault_proxy_metadata(None)
- .merchant_reference_id(merchant_reference_id)
- .lineage_ids(lineage_ids);
- let connector_name = self.connector.clone();
- let (updated_router_data, _) = Box::pin(ucs_logging_wrapper(
- self.clone(),
- state,
- payment_get_request,
- header_payload,
- |mut router_data, payment_get_request, grpc_headers| async move {
- let response = client
- .payment_get(payment_get_request, connector_auth_metadata, grpc_headers)
- .await
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to get payment")?;
-
- let payment_get_response = response.into_inner();
-
- let (router_data_response, status_code) =
- handle_unified_connector_service_response_for_payment_get(
- payment_get_response.clone(),
- )
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to deserialize UCS response")?;
-
- // Extract and store access token if present
- if let Some(access_token) = get_access_token_from_ucs_response(
- state,
- platform,
- &connector_name,
- merchant_connector_id.as_ref(),
- creds_identifier.clone(),
- payment_get_response.state.as_ref(),
- )
- .await
- {
- if let Err(error) = set_access_token_for_ucs(
- state,
- platform,
- &connector_name,
- access_token,
- merchant_connector_id.as_ref(),
- creds_identifier,
- )
- .await
- {
- logger::error!(
- ?error,
- "Failed to store UCS access token from psync response"
- );
- } else {
- logger::debug!(
- "Successfully stored access token from UCS psync response"
- );
- }
- }
-
- let router_data_response =
- router_data_response.map(|(response, status)| {
- router_data.status = status;
- response
- });
- router_data.response = router_data_response;
- router_data.amount_captured = payment_get_response.captured_amount;
- router_data.minor_amount_captured = payment_get_response
- .minor_captured_amount
- .map(MinorUnit::new);
- router_data.raw_connector_response = payment_get_response
- .raw_connector_response
- .clone()
- .map(|raw_connector_response| raw_connector_response.expose().into());
- router_data.connector_http_status_code = Some(status_code);
-
- let connector_response = extract_connector_response_from_ucs(
- payment_get_response.connector_response.as_ref(),
- );
-
- connector_response.map(|customer_response| {
- router_data.connector_response = Some(customer_response);
- });
-
- Ok((router_data, (), payment_get_response))
- },
- ))
- .await?;
-
- // Copy back the updated data
- *self = updated_router_data;
- }
- common_enums::CallConnectorAction::HandleResponse(_)
- | common_enums::CallConnectorAction::Avoid
- | common_enums::CallConnectorAction::StatusUpdate { .. } => {
- Err(ApiErrorResponse::InternalServerError).attach_printable(
- "Invalid CallConnectorAction for payment sync via UCS Gateway system",
- )?
- }
- }
- Ok(())
- }
}
#[async_trait]
diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
index d64ecc3e25..d9468d10e2 100644
--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs
+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
@@ -1,34 +1,23 @@
-use std::str::FromStr;
-
use async_trait::async_trait;
-use common_enums::{self, enums};
+use common_enums;
use common_types::payments as common_payments_types;
-use common_utils::{id_type, ucs_types};
-use error_stack::ResultExt;
-use external_services::grpc_client;
use hyperswitch_domain_models::payments as domain_payments;
use hyperswitch_interfaces::api::{gateway, ConnectorSpecifications};
use router_env::logger;
-use unified_connector_service_client::payments as payments_grpc;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
- errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult},
+ errors::{ConnectorErrorExt, RouterResult},
mandate,
payments::{
self, access_token, customers, gateway::context as gateway_context, helpers,
session_token, tokenization, transformers, PaymentData,
},
- unified_connector_service::{
- build_unified_connector_service_auth_metadata, get_access_token_from_ucs_response,
- handle_unified_connector_service_response_for_payment_register,
- set_access_token_for_ucs, ucs_logging_wrapper,
- },
},
routes::SessionState,
services,
- types::{self, api, domain, transformers::ForeignTryFrom},
+ types::{self, api, domain},
};
#[cfg(feature = "v1")]
@@ -266,139 +255,6 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup
) -> RouterResult<Self> {
setup_mandate_preprocessing_steps(state, &self, true, connector).await
}
-
- async fn call_unified_connector_service<'a>(
- &mut self,
- state: &SessionState,
- header_payload: &domain_payments::HeaderPayload,
- lineage_ids: grpc_client::LineageIds,
- #[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
- #[cfg(feature = "v2")]
- merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
- platform: &domain::Platform,
- _connector_data: &api::ConnectorData,
- unified_connector_service_execution_mode: enums::ExecutionMode,
- merchant_order_reference_id: Option<String>,
- _call_connector_action: common_enums::CallConnectorAction,
- creds_identifier: Option<String>,
- ) -> RouterResult<()> {
- let client = state
- .grpc_client
- .unified_connector_service_client
- .clone()
- .ok_or(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to fetch Unified Connector Service client")?;
-
- let payment_register_request =
- payments_grpc::PaymentServiceRegisterRequest::foreign_try_from(&*self)
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to construct Payment Setup Mandate Request")?;
-
- let merchant_connector_id = merchant_connector_account.get_mca_id();
-
- let connector_auth_metadata = build_unified_connector_service_auth_metadata(
- merchant_connector_account,
- platform,
- self.connector.clone(),
- )
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to construct request metadata")?;
- let merchant_reference_id = header_payload
- .x_reference_id
- .clone()
- .or(merchant_order_reference_id)
- .map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
- .transpose()
- .inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
- .ok()
- .flatten()
- .map(ucs_types::UcsReferenceId::Payment);
- let header_payload = state
- .get_grpc_headers_ucs(unified_connector_service_execution_mode)
- .external_vault_proxy_metadata(None)
- .merchant_reference_id(merchant_reference_id)
- .lineage_ids(lineage_ids);
- let connector_name = self.connector.clone();
- let (updated_router_data, _) = Box::pin(ucs_logging_wrapper(
- self.clone(),
- state,
- payment_register_request,
- header_payload,
- |mut router_data, payment_register_request, grpc_headers| async move {
- let response = Box::pin(client.payment_setup_mandate(
- payment_register_request,
- connector_auth_metadata,
- grpc_headers,
- ))
- .await
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to Setup Mandate payment")?;
-
- let payment_register_response = response.into_inner();
-
- let ucs_data = handle_unified_connector_service_response_for_payment_register(
- payment_register_response.clone(),
- )
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to deserialize UCS response")?;
-
- // Extract and store access token if present
- if let Some(access_token) = get_access_token_from_ucs_response(
- state,
- platform,
- &router_data.connector,
- merchant_connector_id.as_ref(),
- creds_identifier.clone(),
- payment_register_response.state.as_ref(),
- )
- .await
- {
- if let Err(error) = set_access_token_for_ucs(
- state,
- platform,
- &connector_name,
- access_token,
- merchant_connector_id.as_ref(),
- creds_identifier,
- )
- .await
- {
- logger::error!(
- ?error,
- "Failed to store UCS access token from setup mandate response"
- );
- } else {
- logger::debug!(
- "Successfully stored access token from UCS setup mandate response"
- );
- }
- }
- let router_data_response =
- ucs_data.router_data_response.map(|(response, status)| {
- router_data.status = status;
- response
- });
- router_data.response = router_data_response;
- router_data.connector_http_status_code = Some(ucs_data.status_code);
-
- // Populate connector_customer_id if present
- ucs_data.connector_customer_id.map(|connector_customer_id| {
- router_data.connector_customer = Some(connector_customer_id);
- });
-
- ucs_data.connector_response.map(|connector_response| {
- router_data.connector_response = Some(connector_response);
- });
-
- Ok((router_data, (), payment_register_response))
- },
- ))
- .await?;
-
- // Copy back the updated data
- *self = updated_router_data;
- Ok(())
- }
}
impl mandate::MandateBehaviour for types::SetupMandateRequestData {
diff --git a/crates/router/src/core/payments/gateway.rs b/crates/router/src/core/payments/gateway.rs
index b649f8826a..57cd4eca05 100644
--- a/crates/router/src/core/payments/gateway.rs
+++ b/crates/router/src/core/payments/gateway.rs
@@ -1,6 +1,8 @@
pub mod access_token_gateway;
pub mod authenticate_gateway;
pub mod authorize_gateway;
+pub mod cancel_gateway;
+pub mod capture_gateway;
pub mod complete_authorize_gateway;
pub mod context;
pub mod create_customer_gateway;
diff --git a/crates/router/src/core/payments/gateway/cancel_gateway.rs b/crates/router/src/core/payments/gateway/cancel_gateway.rs
new file mode 100644
index 0000000000..524b67e877
--- /dev/null
+++ b/crates/router/src/core/payments/gateway/cancel_gateway.rs
@@ -0,0 +1,177 @@
+use std::str::FromStr;
+
+use async_trait::async_trait;
+use common_enums::{CallConnectorAction, ExecutionPath};
+use common_utils::{errors::CustomResult, id_type, request::Request, ucs_types};
+use error_stack::ResultExt;
+use hyperswitch_domain_models::{router_data::RouterData, router_flow_types as domain};
+use hyperswitch_interfaces::{
+ api::gateway as payment_gateway,
+ connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
+ errors::ConnectorError,
+};
+use unified_connector_service_client::payments as payments_grpc;
+
+use crate::{
+ core::{payments::gateway::context::RouterGatewayContext, unified_connector_service},
+ routes::SessionState,
+ services::logger,
+ types::{self, transformers::ForeignTryFrom},
+};
+
+// =============================================================================
+// PaymentGateway Implementation for domain::Void
+// =============================================================================
+
+/// Implementation of PaymentGateway for api::Void flow
+#[async_trait]
+impl<RCD>
+ payment_gateway::PaymentGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PaymentsCancelData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ > for domain::Void
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PaymentsCancelData, types::PaymentsResponseData>,
+{
+ async fn execute(
+ self: Box<Self>,
+ state: &SessionState,
+ _connector_integration: BoxedConnectorIntegrationInterface<
+ Self,
+ RCD,
+ types::PaymentsCancelData,
+ types::PaymentsResponseData,
+ >,
+ router_data: &RouterData<Self, types::PaymentsCancelData, types::PaymentsResponseData>,
+ _call_connector_action: CallConnectorAction,
+ _connector_request: Option<Request>,
+ _return_raw_connector_response: Option<bool>,
+ context: RouterGatewayContext,
+ ) -> CustomResult<
+ RouterData<Self, types::PaymentsCancelData, types::PaymentsResponseData>,
+ ConnectorError,
+ > {
+ let merchant_connector_account = context.merchant_connector_account;
+ let platform = &context.platform;
+ let lineage_ids = context.lineage_ids;
+ let header_payload = context.header_payload;
+ let unified_connector_service_execution_mode = context.execution_mode;
+ let merchant_order_reference_id = header_payload.x_reference_id.clone();
+ let client = state
+ .grpc_client
+ .unified_connector_service_client
+ .clone()
+ .ok_or(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to fetch Unified Connector Service client")?;
+
+ let payment_void_request =
+ payments_grpc::PaymentServiceVoidRequest::foreign_try_from(router_data)
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct Payment Void Request")?;
+
+ let connector_auth_metadata =
+ unified_connector_service::build_unified_connector_service_auth_metadata(
+ merchant_connector_account,
+ platform,
+ router_data.connector.clone(),
+ )
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct request metadata")?;
+
+ let merchant_reference_id = header_payload
+ .x_reference_id
+ .clone()
+ .or(merchant_order_reference_id)
+ .map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
+ .transpose()
+ .inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
+ .ok()
+ .flatten()
+ .map(ucs_types::UcsReferenceId::Payment);
+
+ let header_payload = state
+ .get_grpc_headers_ucs(unified_connector_service_execution_mode)
+ .external_vault_proxy_metadata(None)
+ .merchant_reference_id(merchant_reference_id)
+ .lineage_ids(lineage_ids);
+
+ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
+ router_data.clone(),
+ state,
+ payment_void_request,
+ header_payload,
+ |mut router_data, payment_void_request, grpc_headers| async move {
+ let response = client
+ .payment_cancel(payment_void_request, connector_auth_metadata, grpc_headers)
+ .await
+ .attach_printable("Failed to Cancel payment")?;
+
+ let payment_void_response = response.into_inner();
+
+ let (router_data_response, status_code) =
+ unified_connector_service::handle_unified_connector_service_response_for_payment_cancel(
+ payment_void_response.clone(),
+ )
+ .attach_printable("Failed to deserialize UCS response")?;
+
+ let router_data_response = router_data_response.map(|(response, status)| {
+ router_data.status = status;
+ response
+ });
+ router_data.response = router_data_response;
+ router_data.connector_http_status_code = Some(status_code);
+
+ Ok((router_data, (), payment_void_response))
+ },
+ ))
+ .await
+ .map(|(router_data, _)| router_data)
+ .change_context(ConnectorError::ResponseHandlingFailed)
+ }
+}
+
+/// Implementation of FlowGateway for api::PSync
+///
+/// This allows the flow to provide its specific gateway based on execution path
+impl<RCD>
+ payment_gateway::FlowGateway<
+ SessionState,
+ RCD,
+ types::PaymentsCancelData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ > for domain::Void
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PaymentsCancelData, types::PaymentsResponseData>,
+{
+ fn get_gateway(
+ execution_path: ExecutionPath,
+ ) -> Box<
+ dyn payment_gateway::PaymentGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PaymentsCancelData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ >,
+ > {
+ match execution_path {
+ ExecutionPath::Direct => Box::new(payment_gateway::DirectGateway),
+ ExecutionPath::UnifiedConnectorService
+ | ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),
+ }
+ }
+}
diff --git a/crates/router/src/core/payments/gateway/capture_gateway.rs b/crates/router/src/core/payments/gateway/capture_gateway.rs
new file mode 100644
index 0000000000..4c0ec80b23
--- /dev/null
+++ b/crates/router/src/core/payments/gateway/capture_gateway.rs
@@ -0,0 +1,182 @@
+use std::str::FromStr;
+
+use async_trait::async_trait;
+use common_enums::{CallConnectorAction, ExecutionPath};
+use common_utils::{errors::CustomResult, id_type, request::Request, ucs_types};
+use error_stack::ResultExt;
+use hyperswitch_domain_models::{router_data::RouterData, router_flow_types as domain};
+use hyperswitch_interfaces::{
+ api::gateway as payment_gateway,
+ connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
+ errors::ConnectorError,
+};
+use unified_connector_service_client::payments as payments_grpc;
+
+use crate::{
+ core::{payments::gateway::context::RouterGatewayContext, unified_connector_service},
+ routes::SessionState,
+ services::logger,
+ types::{self, transformers::ForeignTryFrom, MinorUnit},
+};
+
+// =============================================================================
+// PaymentGateway Implementation for domain::Capture
+// =============================================================================
+
+/// Implementation of PaymentGateway for api::Capture flow
+#[async_trait]
+impl<RCD>
+ payment_gateway::PaymentGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PaymentsCaptureData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ > for domain::Capture
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PaymentsCaptureData, types::PaymentsResponseData>,
+{
+ async fn execute(
+ self: Box<Self>,
+ state: &SessionState,
+ _connector_integration: BoxedConnectorIntegrationInterface<
+ Self,
+ RCD,
+ types::PaymentsCaptureData,
+ types::PaymentsResponseData,
+ >,
+ router_data: &RouterData<Self, types::PaymentsCaptureData, types::PaymentsResponseData>,
+ _call_connector_action: CallConnectorAction,
+ _connector_request: Option<Request>,
+ _return_raw_connector_response: Option<bool>,
+ context: RouterGatewayContext,
+ ) -> CustomResult<
+ RouterData<Self, types::PaymentsCaptureData, types::PaymentsResponseData>,
+ ConnectorError,
+ > {
+ let merchant_connector_account = context.merchant_connector_account;
+ let platform = &context.platform;
+ let lineage_ids = context.lineage_ids;
+ let header_payload = context.header_payload;
+ let unified_connector_service_execution_mode = context.execution_mode;
+ let merchant_order_reference_id = header_payload.x_reference_id.clone();
+ let client = state
+ .grpc_client
+ .unified_connector_service_client
+ .clone()
+ .ok_or(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to fetch Unified Connector Service client")?;
+
+ let payment_capture_request =
+ payments_grpc::PaymentServiceCaptureRequest::foreign_try_from(router_data)
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct Payment Capture Request")?;
+
+ let connector_auth_metadata =
+ unified_connector_service::build_unified_connector_service_auth_metadata(
+ merchant_connector_account,
+ platform,
+ router_data.connector.clone(),
+ )
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct request metadata")?;
+ let merchant_reference_id = header_payload
+ .x_reference_id
+ .clone()
+ .or(merchant_order_reference_id)
+ .map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
+ .transpose()
+ .inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
+ .ok()
+ .flatten()
+ .map(ucs_types::UcsReferenceId::Payment);
+ let header_payload = state
+ .get_grpc_headers_ucs(unified_connector_service_execution_mode)
+ .external_vault_proxy_metadata(None)
+ .merchant_reference_id(merchant_reference_id)
+ .lineage_ids(lineage_ids);
+ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
+ router_data.clone(),
+ state,
+ payment_capture_request,
+ header_payload,
+ |mut router_data, payment_capture_request, grpc_headers| async move {
+ let response = client
+ .payment_capture(
+ payment_capture_request,
+ connector_auth_metadata,
+ grpc_headers,
+ )
+ .await
+ .attach_printable("Failed to capture payment")?;
+
+ let payment_capture_response = response.into_inner();
+
+ let (router_data_response, status_code) =
+ unified_connector_service::handle_unified_connector_service_response_for_payment_capture(
+ payment_capture_response.clone(),
+ )
+ .attach_printable("Failed to deserialize UCS response")?;
+
+ let router_data_response = router_data_response.map(|(response, status)| {
+ router_data.status = status;
+ response
+ });
+ router_data.response = router_data_response;
+ router_data.amount_captured = payment_capture_response.captured_amount;
+ router_data.minor_amount_captured = payment_capture_response
+ .minor_captured_amount
+ .map(MinorUnit::new);
+ router_data.connector_http_status_code = Some(status_code);
+
+ Ok((router_data, (), payment_capture_response))
+ },
+ ))
+ .await
+ .map(|(router_data, _)| router_data)
+ .change_context(ConnectorError::ResponseHandlingFailed)
+ }
+}
+
+/// Implementation of FlowGateway for api::PSync
+///
+/// This allows the flow to provide its specific gateway based on execution path
+impl<RCD>
+ payment_gateway::FlowGateway<
+ SessionState,
+ RCD,
+ types::PaymentsCaptureData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ > for domain::Capture
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PaymentsCaptureData, types::PaymentsResponseData>,
+{
+ fn get_gateway(
+ execution_path: ExecutionPath,
+ ) -> Box<
+ dyn payment_gateway::PaymentGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PaymentsCaptureData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ >,
+ > {
+ match execution_path {
+ ExecutionPath::Direct => Box::new(payment_gateway::DirectGateway),
+ ExecutionPath::UnifiedConnectorService
+ | ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),
+ }
+ }
+}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index f71f099397..59cce629f0 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -11,8 +11,6 @@ use api_models::{
payments::{additional_info as payment_additional_types, RequestSurchargeDetails},
};
use base64::Engine;
-#[cfg(feature = "v1")]
-use common_enums::enums::{CallConnectorAction, GatewaySystem};
use common_enums::{enums::ExecutionMode, ConnectorType};
#[cfg(feature = "v2")]
use common_utils::id_type::GenerateId;
@@ -31,8 +29,6 @@ use common_utils::{
use diesel_models::enums;
// TODO : Evaluate all the helper functions ()
use error_stack::{report, ResultExt};
-#[cfg(feature = "v1")]
-use external_services::grpc_client;
use futures::future::Either;
pub use hyperswitch_domain_models::customer;
#[cfg(feature = "v1")]
@@ -62,7 +58,7 @@ use openssl::{
use rand::Rng;
#[cfg(feature = "v2")]
use redis_interface::errors::RedisError;
-use router_env::{instrument, logger, tracing, tracing::Instrument};
+use router_env::{instrument, logger, tracing};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@@ -74,19 +70,9 @@ use super::{
};
#[cfg(feature = "v1")]
use crate::core::{
- payments::{
- call_connector_service, customers,
- flows::{ConstructFlowSpecificData, Feature},
- gateway::context as gateway_context,
- operations::ValidateResult as OperationsValidateResult,
- should_add_task_to_process_tracker, OperationSessionGetters, OperationSessionSetters,
- TokenizationAction,
- },
- unified_connector_service::update_gateway_system_in_feature_metadata,
+ payments::{OperationSessionGetters, OperationSessionSetters},
utils as core_utils,
};
-#[cfg(feature = "v1")]
-use crate::routes;
use crate::{
configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig},
connector,
@@ -125,8 +111,7 @@ use crate::{
use crate::{core::admin as core_admin, headers, types::ConnectorAuthType};
#[cfg(feature = "v1")]
use crate::{
- core::{payment_methods::cards::create_encrypted_data, unified_connector_service},
- types::storage::CustomerUpdate::Update,
+ core::payment_methods::cards::create_encrypted_data, types::storage::CustomerUpdate::Update,
};
#[instrument(skip_all)]
@@ -8170,734 +8155,3 @@ where
.map(|profile_id| format!("{}_{}", connector_name, profile_id.get_string_repr()))
}
}
-
-#[cfg(feature = "v1")]
-/// Helper function to populate connector_customer_id from database before calling UCS
-/// This checks if a connector_customer_id already exists in the database and populates it into router_data
-/// Returns true if connector_customer_id was found and populated from DB, false otherwise
-async fn populate_connector_customer_from_db_before_ucs(
- state: &SessionState,
- connector_label: Option<&str>,
- payment_attempt: &PaymentAttempt,
- payment_id: &str,
- customer: &Option<domain::Customer>,
- merchant_connector_account: &MerchantConnectorAccountType,
-) -> RouterResult<Option<String>> {
- match (connector_label, payment_attempt.connector.as_ref()) {
- (Some(label), Some(connector_name)) => {
- let connector = api::ConnectorData::get_connector_by_name(
- &state.conf.connectors,
- connector_name,
- api::GetToken::Connector,
- merchant_connector_account.get_mca_id(),
- )
- .inspect_err(|e| {
- router_env::logger::warn!(
- payment_id = %payment_id,
- connector_name = %connector_name,
- error = ?e,
- "Failed to get connector by name while populating connector_customer_id"
- )
- })?;
-
- let (should_call_connector, existing_connector_customer_id) =
- customers::should_call_connector_create_customer(
- &connector,
- customer,
- payment_attempt,
- label,
- );
-
- match existing_connector_customer_id {
- Some(connector_customer_id) => {
- router_env::logger::info!(
- connector_customer_id = %connector_customer_id,
- payment_id = %payment_id,
- connector_label = %label,
- should_call_connector = %should_call_connector,
- "Populating connector_customer from DB before UCS call"
- );
- Ok(Some(connector_customer_id.to_string()))
- }
- None => {
- router_env::logger::info!(
- payment_id = %payment_id,
- connector_label = %label,
- should_call_connector = %should_call_connector,
- "No connector_customer_id found in DB for UCS call"
- );
- Ok(None)
- }
- }
- }
- (Some(label), None) => {
- router_env::logger::debug!(
- payment_id = %payment_id,
- connector_label = %label,
- "No connector name available, skipping connector_customer_id population"
- );
- Ok(None)
- }
- (None, Some(connector_name)) => {
- router_env::logger::debug!(
- payment_id = %payment_id,
- connector_name = %connector_name,
- "No connector label available, skipping connector_customer_id population"
- );
- Ok(None)
- }
- (None, None) => Ok(None),
- }
-}
-
-#[cfg(feature = "v1")]
-#[allow(clippy::too_many_arguments)]
-/// Helper function to save connector_customer_id after UCS call with proper error logging
-/// Handles the logic of checking if ID was already in DB and logging appropriately
-async fn save_connector_customer_id_after_ucs<F, Req>(
- state: &SessionState,
- router_data: &RouterData<F, Req, PaymentsResponseData>,
- connector_customer_id_was_populated_from_db: Option<String>,
- connector_label: &Option<String>,
- customer: &Option<domain::Customer>,
- platform: &domain::Platform,
- payment_id: String,
-) -> RouterResult<()> {
- match connector_customer_id_was_populated_from_db {
- None => {
- match (
- router_data.connector_customer.as_ref(),
- connector_label.as_ref(),
- ) {
- (Some(connector_customer_id), Some(connector_label_str)) => {
- save_new_connector_customer_id_from_ucs(
- state,
- connector_customer_id,
- connector_label_str,
- customer,
- platform,
- payment_id.clone(),
- )
- .await
- .inspect_err(|e| {
- router_env::logger::warn!(
- payment_id = %payment_id,
- error = ?e,
- "Failed to save connector_customer_id from UCS"
- )
- })
- }
- (None, Some(label)) => {
- router_env::logger::debug!(
- payment_id = %payment_id,
- connector_label = %label,
- "Missing connector_customer_id, skipping save"
- );
- Ok(())
- }
- (Some(id), None) => {
- router_env::logger::debug!(
- payment_id = %payment_id,
- connector_customer_id = %id,
- "Missing connector_label, skipping save"
- );
- Ok(())
- }
- (None, None) => {
- router_env::logger::debug!(
- payment_id = %payment_id,
- "Missing both connector_customer_id and connector_label, skipping save"
- );
- Ok(())
- }
- }
- }
- Some(existing_id) => {
- router_env::logger::debug!(
- payment_id = %payment_id,
- existing_connector_customer_id = %existing_id,
- "Connector customer ID already exists in DB, skipping save"
- );
- Ok(())
- }
- }
-}
-
-#[cfg(feature = "v1")]
-#[allow(clippy::too_many_arguments)]
-/// Helper function to save a new connector_customer_id from UCS to database
-/// This only saves if the ID doesn't already exist in the database
-async fn save_new_connector_customer_id_from_ucs(
- state: &SessionState,
- connector_customer_id: &str,
- connector_label: &str,
- customer: &Option<domain::Customer>,
- platform: &domain::Platform,
- payment_id: String,
-) -> RouterResult<()> {
- // Process only if customer exists
- match customer.as_ref() {
- Some(customer_data) => {
- router_env::logger::info!(
- "Saving new connector_customer_id from UCS to DB for payment_id={}, connector_label={}",
- payment_id,
- connector_label
- );
-
- // Create and save customer update
- match customers::update_connector_customer_in_customers(
- connector_label,
- Some(customer_data),
- Some(connector_customer_id.to_string()),
- )
- .await
- {
- Some(update) => {
- let db = &*state.store;
- let _ = db
- .update_customer_by_customer_id_merchant_id(
- customer_data.customer_id.clone(),
- customer_data.merchant_id.clone(),
- customer_data.clone(),
- update,
- platform.get_processor().get_key_store(),
- platform.get_processor().get_account().storage_scheme,
- )
- .await
- .inspect_err(|e| {
- router_env::logger::warn!(
- "Failed to save connector_customer_id to DB: {:?}",
- e
- )
- });
- Ok(())
- }
- None => {
- router_env::logger::error!(
- payment_id = %payment_id,
- connector_label = %connector_label,
- "No update generated for saving connector_customer_id"
- );
- Ok(())
- }
- }
- }
- None => {
- router_env::logger::debug!(
- "No customer data available, skipping connector_customer_id save for payment_id={}, connector_label={}",
- payment_id,
- connector_label
- );
- Ok(())
- }
- }
-}
-
-#[cfg(feature = "v1")]
-#[allow(clippy::too_many_arguments)]
-#[instrument(skip_all)]
-// Helper function to process through UCS gateway
-pub async fn process_through_ucs<'a, F, RouterDReq, ApiRequest, D>(
- state: &'a SessionState,
- req_state: routes::app::ReqState,
- platform: &'a domain::Platform,
- operation: &'a BoxedOperation<'a, F, ApiRequest, D>,
- payment_data: &'a mut D,
- customer: &Option<domain::Customer>,
- call_connector_action: CallConnectorAction,
- validate_result: &'a OperationsValidateResult,
- schedule_time: Option<time::PrimitiveDateTime>,
- header_payload: domain_payments::HeaderPayload,
- frm_suggestion: Option<enums::FrmSuggestion>,
- business_profile: &'a domain::Profile,
- merchant_connector_account: MerchantConnectorAccountType,
- connector_data: &api::ConnectorData,
- router_data: RouterData<F, RouterDReq, PaymentsResponseData>,
-) -> RouterResult<(
- RouterData<F, RouterDReq, PaymentsResponseData>,
- MerchantConnectorAccountType,
-)>
-where
- F: Send + Clone + Sync + 'static,
- RouterDReq: Send + Sync + Clone + 'static + Serialize,
- D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
- D: ConstructFlowSpecificData<F, RouterDReq, PaymentsResponseData>,
- RouterData<F, RouterDReq, PaymentsResponseData>:
- Feature<F, RouterDReq> + Send + Clone + Serialize,
- dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, PaymentsResponseData>,
-{
- router_env::logger::info!(
- "Processing payment through UCS gateway system - payment_id={}, attempt_id={}",
- payment_data
- .get_payment_intent()
- .payment_id
- .get_string_repr(),
- payment_data.get_payment_attempt().attempt_id
- );
-
- // Add task to process tracker if needed
- if should_add_task_to_process_tracker(payment_data) {
- operation
- .to_domain()?
- .add_task_to_process_tracker(
- state,
- payment_data.get_payment_attempt(),
- validate_result.requeue,
- schedule_time,
- )
- .await
- .map_err(|error| router_env::logger::error!(process_tracker_error=?error))
- .ok();
- }
-
- // Update feature metadata to track UCS usage for stickiness
- update_gateway_system_in_feature_metadata(
- payment_data,
- GatewaySystem::UnifiedConnectorService,
- )?;
-
- let lineage_ids = grpc_client::LineageIds::new(
- business_profile.merchant_id.clone(),
- business_profile.get_id().clone(),
- );
- // Extract merchant_order_reference_id from payment data for UCS audit trail
- let merchant_order_reference_id = payment_data
- .get_payment_intent()
- .merchant_order_reference_id
- .clone();
- let (mut router_data, should_continue) = router_data
- .call_preprocessing_through_unified_connector_service(
- state,
- &header_payload,
- &lineage_ids,
- merchant_connector_account.clone(),
- platform,
- connector_data,
- ExecutionMode::Primary, // UCS is called in primary mode
- merchant_order_reference_id.clone(),
- )
- .await?;
-
- // Update trackers
- (_, *payment_data) = operation
- .to_update_tracker()?
- .update_trackers(
- state,
- req_state,
- payment_data.clone(),
- customer.clone(),
- platform.get_processor().get_account().storage_scheme,
- None,
- platform.get_processor().get_key_store(),
- frm_suggestion,
- header_payload.clone(),
- )
- .await?;
- let creds_identifier = payment_data.get_creds_identifier().map(str::to_owned);
- // Calculate connector label once for reuse
- let connector_label =
- get_connector_label_for_customer(&merchant_connector_account, payment_data);
-
- // Populate connector_customer_id from database before calling UCS
- // Track whether ID was found in DB to avoid redundant save later
- let connector_customer_id_was_populated_from_db =
- populate_connector_customer_from_db_before_ucs(
- state,
- connector_label.as_deref(),
- payment_data.get_payment_attempt(),
- payment_data
- .get_payment_intent()
- .payment_id
- .get_string_repr(),
- customer,
- &merchant_connector_account,
- )
- .await?;
-
- connector_customer_id_was_populated_from_db
- .as_ref()
- .map(|id| {
- router_data.connector_customer = Some(id.clone());
- });
-
- // Based on the preprocessing response, decide whether to continue with UCS call
- if should_continue {
- router_data
- .call_unified_connector_service(
- state,
- &header_payload,
- lineage_ids,
- merchant_connector_account.clone(),
- platform,
- connector_data,
- ExecutionMode::Primary, // UCS is called in primary mode
- merchant_order_reference_id,
- call_connector_action,
- creds_identifier,
- )
- .await?;
- }
-
- // Save connector_customer_id from UCS to database if needed
- let payment_id = payment_data
- .get_payment_intent()
- .payment_id
- .get_string_repr()
- .to_string();
- let _ = save_connector_customer_id_after_ucs(
- state,
- &router_data,
- connector_customer_id_was_populated_from_db,
- &connector_label,
- customer,
- platform,
- payment_id.clone(),
- )
- .await
- .inspect_err(|e| {
- router_env::logger::warn!(
- "Failed to save connector_customer_id after UCS call - payment_id={}, error={:?}",
- payment_id,
- e
- )
- }); // Don't fail payment if save fails
-
- Ok((router_data, merchant_connector_account))
-}
-
-#[cfg(feature = "v1")]
-#[allow(clippy::too_many_arguments)]
-#[instrument(skip_all)]
-// Helper function to process through Direct gateway
-pub async fn process_through_direct<'a, F, RouterDReq, ApiRequest, D>(
- state: &'a SessionState,
- req_state: routes::app::ReqState,
- platform: &'a domain::Platform,
- connector: api::ConnectorData,
- operation: &'a BoxedOperation<'a, F, ApiRequest, D>,
- payment_data: &'a mut D,
- customer: &Option<domain::Customer>,
- call_connector_action: CallConnectorAction,
- validate_result: &'a OperationsValidateResult,
- schedule_time: Option<time::PrimitiveDateTime>,
- header_payload: domain_payments::HeaderPayload,
- frm_suggestion: Option<enums::FrmSuggestion>,
- business_profile: &'a domain::Profile,
- is_retry_payment: bool,
- all_keys_required: Option<bool>,
- merchant_connector_account: MerchantConnectorAccountType,
- router_data: RouterData<F, RouterDReq, PaymentsResponseData>,
- tokenization_action: TokenizationAction,
-) -> RouterResult<(
- RouterData<F, RouterDReq, PaymentsResponseData>,
- MerchantConnectorAccountType,
-)>
-where
- F: Send + Clone + Sync + 'static,
- RouterDReq: Send + Sync + Clone + 'static + Serialize,
- D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
- D: ConstructFlowSpecificData<F, RouterDReq, PaymentsResponseData>,
- RouterData<F, RouterDReq, PaymentsResponseData>:
- Feature<F, RouterDReq> + Send + Clone + Serialize,
- dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, PaymentsResponseData>,
-{
- router_env::logger::info!(
- "Processing payment through Direct gateway system - payment_id={}, attempt_id={}",
- payment_data
- .get_payment_intent()
- .payment_id
- .get_string_repr(),
- payment_data.get_payment_attempt().attempt_id
- );
-
- // Update feature metadata to track Direct routing usage for stickiness
- update_gateway_system_in_feature_metadata(payment_data, GatewaySystem::Direct)?;
-
- let gateway_context = gateway_context::RouterGatewayContext::direct(
- platform.clone(),
- merchant_connector_account.clone(),
- business_profile.merchant_id.clone(),
- business_profile.get_id().clone(),
- payment_data.get_creds_identifier().map(str::to_owned),
- );
-
- call_connector_service(
- state,
- req_state,
- platform,
- connector,
- operation,
- payment_data,
- customer,
- call_connector_action,
- validate_result,
- schedule_time,
- header_payload,
- frm_suggestion,
- business_profile,
- is_retry_payment,
- all_keys_required,
- merchant_connector_account,
- router_data,
- tokenization_action,
- gateway_context,
- )
- .await
-}
-
-#[cfg(feature = "v1")]
-#[allow(clippy::too_many_arguments)]
-#[instrument(skip_all)]
-// Helper function to process through Direct with Shadow UCS
-pub async fn process_through_direct_with_shadow_unified_connector_service<
- 'a,
- F,
- RouterDReq,
- ApiRequest,
- D,
->(
- state: &'a SessionState,
- req_state: routes::app::ReqState,
- platform: &'a domain::Platform,
- connector: api::ConnectorData,
- operation: &'a BoxedOperation<'a, F, ApiRequest, D>,
- payment_data: &'a mut D,
- customer: &Option<domain::Customer>,
- call_connector_action: CallConnectorAction,
- shadow_ucs_call_connector_action: Option<CallConnectorAction>,
- validate_result: &'a OperationsValidateResult,
- schedule_time: Option<time::PrimitiveDateTime>,
- header_payload: domain_payments::HeaderPayload,
- frm_suggestion: Option<enums::FrmSuggestion>,
- business_profile: &'a domain::Profile,
- is_retry_payment: bool,
- all_keys_required: Option<bool>,
- merchant_connector_account: MerchantConnectorAccountType,
- router_data: RouterData<F, RouterDReq, PaymentsResponseData>,
- tokenization_action: TokenizationAction,
-) -> RouterResult<(
- RouterData<F, RouterDReq, PaymentsResponseData>,
- MerchantConnectorAccountType,
-)>
-where
- F: Send + Clone + Sync + 'static,
- RouterDReq: Send + Sync + Clone + 'static + Serialize,
- D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
- D: ConstructFlowSpecificData<F, RouterDReq, PaymentsResponseData>,
- RouterData<F, RouterDReq, PaymentsResponseData>:
- Feature<F, RouterDReq> + Send + Clone + Serialize,
- dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, PaymentsResponseData>,
-{
- router_env::logger::info!(
- "Processing payment through Direct gateway system with UCS in shadow mode - payment_id={}, attempt_id={}",
- payment_data.get_payment_intent().payment_id.get_string_repr(),
- payment_data.get_payment_attempt().attempt_id
- );
-
- // Extract merchant_order_reference_id from payment data for UCS audit trail
- let merchant_order_reference_id = payment_data
- .get_payment_intent()
- .merchant_order_reference_id
- .clone();
-
- // Calculate connector_label before cloning data for shadow UCS
- let unified_connector_service_connector_label =
- get_connector_label_for_customer(&merchant_connector_account, payment_data);
-
- let creds_identifier = payment_data.get_creds_identifier().map(str::to_owned);
-
- // Clone data needed for shadow UCS call
- let unified_connector_service_router_data = router_data.clone();
- let unified_connector_service_merchant_connector_account = merchant_connector_account.clone();
- let unified_connector_service_platform = platform.clone();
- let unified_connector_service_header_payload = header_payload.clone();
- let unified_connector_service_state = state.clone();
- let unified_connector_service_merchant_order_reference_id = merchant_order_reference_id;
- let unified_connector_service_creds_identifier = creds_identifier.clone();
- let unified_connector_service_customer = customer.clone();
- let unified_connector_service_payment_attempt_data = payment_data.get_payment_attempt().clone();
- let unified_connector_service_connector_payment_id = payment_data
- .get_payment_intent()
- .payment_id
- .get_string_repr()
- .to_string();
-
- let lineage_ids = grpc_client::LineageIds::new(
- business_profile.merchant_id.clone(),
- business_profile.get_id().clone(),
- );
-
- let gateway_context = gateway_context::RouterGatewayContext::direct(
- platform.clone(),
- merchant_connector_account.clone(),
- business_profile.merchant_id.clone(),
- business_profile.get_id().clone(),
- creds_identifier,
- );
-
- // Update feature metadata to track Direct routing usage for stickiness
- update_gateway_system_in_feature_metadata(payment_data, GatewaySystem::Direct)?;
-
- // Call Direct connector service
- let result = call_connector_service(
- state,
- req_state,
- platform,
- connector.clone(),
- operation,
- payment_data,
- customer,
- call_connector_action.clone(),
- validate_result,
- schedule_time,
- header_payload,
- frm_suggestion,
- business_profile,
- is_retry_payment,
- all_keys_required,
- merchant_connector_account,
- router_data,
- tokenization_action,
- gateway_context,
- )
- .await;
-
- // Spawn shadow UCS call in background regardless of HS result
- // Use the initial router_data as fallback when HS fails
- let direct_router_data = match &result {
- Ok(success_data) => Some(success_data.0.clone()),
- Err(_) => None,
- };
-
- tokio::spawn(
- async move {
- execute_shadow_unified_connector_service_call(
- unified_connector_service_state,
- unified_connector_service_router_data,
- direct_router_data,
- unified_connector_service_header_payload,
- lineage_ids,
- unified_connector_service_merchant_connector_account,
- &connector,
- unified_connector_service_platform,
- unified_connector_service_merchant_order_reference_id,
- call_connector_action,
- shadow_ucs_call_connector_action,
- unified_connector_service_creds_identifier,
- unified_connector_service_customer,
- unified_connector_service_payment_attempt_data,
- unified_connector_service_connector_label,
- unified_connector_service_connector_payment_id,
- )
- .await
- .map_err(|e| {
- router_env::logger::debug!(
- "Shadow UCS call in Direct with shadow UCS processing failed: {:?}",
- e
- )
- })
- .ok()
- }
- .instrument(tracing::Span::current()),
- );
-
- result
-}
-
-#[cfg(feature = "v1")]
-#[allow(clippy::too_many_arguments)]
-#[instrument(skip_all)]
-// Helper function to execute shadow UCS call
-pub async fn execute_shadow_unified_connector_service_call<F, RouterDReq>(
- state: SessionState,
- mut unified_connector_service_router_data: RouterData<F, RouterDReq, PaymentsResponseData>,
- direct_router_data: Option<RouterData<F, RouterDReq, PaymentsResponseData>>,
- header_payload: domain_payments::HeaderPayload,
- lineage_ids: grpc_client::LineageIds,
- merchant_connector_account: MerchantConnectorAccountType,
- connector_data: &api::ConnectorData,
- platform: domain::Platform,
- merchant_order_reference_id: Option<String>,
- call_connector_action: CallConnectorAction,
- shadow_ucs_call_connector_action: Option<CallConnectorAction>,
- creds_identifier: Option<String>,
- customer: Option<domain::Customer>,
- payment_attempt_data: PaymentAttempt,
- unified_connector_service_connector_label: Option<String>,
- unified_connector_service_payment_id: String,
-) -> RouterResult<()>
-where
- F: Send + Clone + Sync + 'static,
- RouterDReq: Send + Sync + Clone + 'static + Serialize,
- RouterData<F, RouterDReq, PaymentsResponseData>:
- Feature<F, RouterDReq> + Send + Clone + Serialize,
- dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, PaymentsResponseData>,
-{
- let connector_customer_id_was_populated_from_db =
- populate_connector_customer_from_db_before_ucs(
- &state,
- unified_connector_service_connector_label.as_deref(),
- &payment_attempt_data,
- &unified_connector_service_payment_id,
- &customer,
- &merchant_connector_account,
- )
- .await?;
-
- connector_customer_id_was_populated_from_db.map(|id| {
- unified_connector_service_router_data.connector_customer = Some(id);
- });
- // Call UCS in shadow mode
- let unified_connector_service_result = unified_connector_service_router_data
- .call_unified_connector_service(
- &state,
- &header_payload,
- lineage_ids,
- merchant_connector_account,
- &platform,
- connector_data,
- ExecutionMode::Shadow, // Shadow mode for UCS
- merchant_order_reference_id,
- shadow_ucs_call_connector_action.unwrap_or(call_connector_action),
- creds_identifier,
- )
- .await;
-
- match (direct_router_data, unified_connector_service_result) {
- (Some(direct_data), Ok(_)) => {
- // Compare results
- match unified_connector_service::serialize_router_data_and_send_to_comparison_service(
- &state,
- direct_data,
- unified_connector_service_router_data,
- )
- .await
- {
- Ok(_) => {
- router_env::logger::debug!("Shadow UCS comparison completed successfully");
- Ok(())
- }
- Err(e) => {
- router_env::logger::debug!("Shadow UCS comparison failed: {:?}", e);
- Ok(())
- }
- }
- }
- (None, _) => {
- router_env::logger::debug!(
- "Direct call failed, skipping UCS router data comparison for payment_id={}",
- unified_connector_service_payment_id
- );
- Ok(())
- }
- (_, Err(e)) => {
- router_env::logger::debug!(
- "
- Skiping UCS router data comparison Shadow UCS call failed for payment_id={}: {:?}",
- unified_connector_service_payment_id,
- e
- );
- Ok(())
- }
- }
-}