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: implement granular authentication flow for UCS gateway interfaces (#10622)

Hrithikesh568c201756b7
diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource.rs b/crates/hyperswitch_connectors/src/connectors/cybersource.rs
index 22b6ff9be1..ffa17f6ea6 100644
--- a/crates/hyperswitch_connectors/src/connectors/cybersource.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cybersource.rs
@@ -2288,7 +2288,10 @@ impl ConnectorSpecifications for Cybersource {
// during authorize flow, there is no pre processing flow. Only alternate PreAuthenticate flow
None
}
- api::CurrentFlowInfo::CompleteAuthorize { request_data } => {
+ api::CurrentFlowInfo::CompleteAuthorize {
+ request_data,
+ payment_method: _,
+ } => {
// TODO: add logic before deciding the pre processing flow Authenticate or PostAuthenticate
let redirect_response = request_data.redirect_response.as_ref()?;
match redirect_response.params.as_ref() {
@@ -2336,7 +2339,10 @@ impl ConnectorSpecifications for Cybersource {
// during authorize flow, there is no post_authentication call needed
false
}
- api::CurrentFlowInfo::CompleteAuthorize { request_data } => {
+ api::CurrentFlowInfo::CompleteAuthorize {
+ request_data,
+ payment_method: _,
+ } => {
// TODO: add logic before deciding the pre processing flow Authenticate or PostAuthenticate
let redirection_params = request_data
.redirect_response
@@ -2356,7 +2362,10 @@ impl ConnectorSpecifications for Cybersource {
// during authorize flow, there is no post_authentication call needed
false
}
- api::CurrentFlowInfo::CompleteAuthorize { request_data } => {
+ api::CurrentFlowInfo::CompleteAuthorize {
+ request_data,
+ payment_method: _,
+ } => {
// TODO: add logic before deciding the pre processing flow Authenticate or PostAuthenticate
let redirection_params = request_data
.redirect_response
diff --git a/crates/hyperswitch_connectors/src/connectors/paypal.rs b/crates/hyperswitch_connectors/src/connectors/paypal.rs
index 09eb6358d5..f08a7bc1c3 100644
--- a/crates/hyperswitch_connectors/src/connectors/paypal.rs
+++ b/crates/hyperswitch_connectors/src/connectors/paypal.rs
@@ -2568,6 +2568,15 @@ static PAYPAL_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 3] = [
];
impl ConnectorSpecifications for Paypal {
+ fn is_post_authentication_flow_required(&self, current_flow: api::CurrentFlowInfo<'_>) -> bool {
+ match current_flow {
+ api::CurrentFlowInfo::Authorize { .. } => false,
+ api::CurrentFlowInfo::CompleteAuthorize {
+ request_data: _,
+ payment_method,
+ } => payment_method == Some(enums::PaymentMethod::Card),
+ }
+ }
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&PAYPAL_CONNECTOR_INFO)
}
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index b6558a972d..7c23add1cd 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -821,6 +821,7 @@ pub struct CompleteAuthorizeData {
pub complete_authorize_url: Option<String>,
pub metadata: Option<serde_json::Value>,
pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
+ pub request_incremental_authorization: bool,
pub authentication_data: Option<UcsAuthenticationData>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
// New amount for amount frame work
diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs
index de1af03444..afd1cf8178 100644
--- a/crates/hyperswitch_interfaces/src/api.rs
+++ b/crates/hyperswitch_interfaces/src/api.rs
@@ -400,6 +400,8 @@ pub enum CurrentFlowInfo<'a> {
CompleteAuthorize {
/// The payment authorize request data
request_data: &'a router_request_types::CompleteAuthorizeData,
+ /// The payment method that is used
+ payment_method: Option<PaymentMethod>,
},
}
diff --git a/crates/hyperswitch_interfaces/src/api/gateway.rs b/crates/hyperswitch_interfaces/src/api/gateway.rs
index 78ac3f546b..0c79d4be17 100644
--- a/crates/hyperswitch_interfaces/src/api/gateway.rs
+++ b/crates/hyperswitch_interfaces/src/api/gateway.rs
@@ -34,6 +34,25 @@ pub trait GatewayContext: Clone + Send + Sync {
fn execution_mode(&self) -> ExecutionMode;
}
+/// Trait to extract RouterData from various output types
+///
+pub trait GetRouterData<F, Req, Resp> {
+ /// Get a reference to the RouterData
+ fn get_router_data(&self) -> &RouterData<F, Req, Resp>;
+}
+
+impl<F, Req, Resp> GetRouterData<F, Req, Resp> for RouterData<F, Req, Resp> {
+ fn get_router_data(&self) -> &Self {
+ self
+ }
+}
+
+impl<F, Req, Resp, T> GetRouterData<F, Req, Resp> for (RouterData<F, Req, Resp>, Option<T>) {
+ fn get_router_data(&self) -> &RouterData<F, Req, Resp> {
+ &self.0
+ }
+}
+
/// Payment gateway trait
///
/// Defines the interface for executing payment operations through different gateway types.
@@ -48,8 +67,15 @@ pub trait GatewayContext: Clone + Send + Sync {
/// * `Context` - Gateway context type (must implement GatewayContext trait)
#[async_trait]
#[allow(clippy::too_many_arguments)]
-pub trait PaymentGateway<State, ConnectorData, F, Req, Resp, Context>: Send + Sync
-where
+pub trait PaymentGateway<
+ State,
+ ConnectorData,
+ F,
+ Req,
+ Resp,
+ Context,
+ FlowOutput = RouterData<F, Req, Resp>,
+>: Send + Sync where
State: Clone + Send + Sync + 'static + ApiClientWrapper,
ConnectorData: Clone + RouterDataConversion<F, Req, Resp> + Send + Sync + 'static,
F: Clone + std::fmt::Debug + Send + Sync + 'static,
@@ -67,7 +93,7 @@ where
connector_request: Option<Request>,
return_raw_connector_response: Option<bool>,
context: Context,
- ) -> CustomResult<RouterData<F, Req, Resp>, ConnectorError>;
+ ) -> CustomResult<FlowOutput, ConnectorError>;
}
/// Direct gateway implementation
@@ -112,14 +138,63 @@ where
}
}
+#[async_trait]
+impl<State, ConnectorData, F, Req, Resp, Context, T>
+ PaymentGateway<
+ State,
+ ConnectorData,
+ F,
+ Req,
+ Resp,
+ Context,
+ (RouterData<F, Req, Resp>, Option<T>),
+ > for DirectGateway
+where
+ State: Clone + Send + Sync + 'static + ApiClientWrapper,
+ ConnectorData: Clone + RouterDataConversion<F, Req, Resp> + Send + Sync + 'static,
+ F: Clone + std::fmt::Debug + Send + Sync + 'static,
+ Req: std::fmt::Debug + Clone + Send + Sync + 'static,
+ Resp: std::fmt::Debug + Clone + Send + Sync + 'static,
+ Context: GatewayContext + 'static,
+{
+ async fn execute(
+ self: Box<Self>,
+ state: &State,
+ connector_integration: BoxedConnectorIntegrationInterface<F, ConnectorData, Req, Resp>,
+ router_data: &RouterData<F, Req, Resp>,
+ call_connector_action: CallConnectorAction,
+ connector_request: Option<Request>,
+ return_raw_connector_response: Option<bool>,
+ _context: Context,
+ ) -> CustomResult<(RouterData<F, Req, Resp>, Option<T>), ConnectorError> {
+ // Direct gateway delegates to the existing execute_connector_processing_step
+ // This maintains backward compatibility with the traditional HTTP-based flow
+ api_client::execute_connector_processing_step(
+ state,
+ connector_integration,
+ router_data,
+ call_connector_action,
+ connector_request,
+ return_raw_connector_response,
+ )
+ .await
+ .map(|router_data| (router_data, None))
+ }
+}
+
/// Flow gateway trait for determining execution path
///
/// This trait allows flows to specify which gateway implementation should be used
/// based on the execution path. Each flow implements this trait to provide
/// flow-specific gateway selection logic.
-pub trait FlowGateway<State, ConnectorData, Req, Resp, Context>:
- Clone + std::fmt::Debug + Send + Sync + 'static
-where
+pub trait FlowGateway<
+ State,
+ ConnectorData,
+ Req,
+ Resp,
+ Context,
+ FlowOutput = RouterData<Self, Req, Resp>,
+>: Clone + std::fmt::Debug + Send + Sync + 'static where
State: Clone + Send + Sync + 'static + ApiClientWrapper,
ConnectorData: Clone + RouterDataConversion<Self, Req, Resp> + Send + Sync + 'static,
Req: std::fmt::Debug + Clone + Send + Sync + 'static,
@@ -133,14 +208,14 @@ where
/// - Flow-specific UCS gateway for gRPC integration
fn get_gateway(
execution_path: ExecutionPath,
- ) -> Box<dyn PaymentGateway<State, ConnectorData, Self, Req, Resp, Context>>;
+ ) -> Box<dyn PaymentGateway<State, ConnectorData, Self, Req, Resp, Context, FlowOutput>>;
}
/// Execute payment gateway operation (backward compatible version)
///
/// This version maintains backward compatibility by using direct execution when no context is provided.
/// Use `execute_payment_gateway_with_context` for UCS support.
-pub async fn execute_payment_gateway<State, ConnectorData, F, Req, Resp, Context>(
+pub async fn execute_payment_gateway<State, ConnectorData, F, Req, Resp, Context, FlowOutput>(
state: &State,
connector_integration: BoxedConnectorIntegrationInterface<F, ConnectorData, Req, Resp>,
router_data: &RouterData<F, Req, Resp>,
@@ -148,7 +223,7 @@ pub async fn execute_payment_gateway<State, ConnectorData, F, Req, Resp, Context
connector_request: Option<Request>,
return_raw_connector_response: Option<bool>,
context: Context,
-) -> CustomResult<RouterData<F, Req, Resp>, ConnectorError>
+) -> CustomResult<FlowOutput, ConnectorError>
where
State: Clone + Send + Sync + 'static + ApiClientWrapper + helpers::GetComparisonServiceConfig,
ConnectorData: Clone + RouterDataConversion<F, Req, Resp> + Send + Sync + 'static,
@@ -157,32 +232,38 @@ where
+ Send
+ Sync
+ 'static
- + FlowGateway<State, ConnectorData, Req, Resp, Context>,
+ + FlowGateway<State, ConnectorData, Req, Resp, Context, FlowOutput>,
Req: std::fmt::Debug + Clone + Send + Sync + serde::Serialize + 'static,
Resp: std::fmt::Debug + Clone + Send + Sync + serde::Serialize + 'static,
Context: GatewayContext + 'static,
+ FlowOutput: Clone + Send + Sync + GetRouterData<F, Req, Resp> + 'static,
{
let execution_path = context.execution_path();
match execution_path {
ExecutionPath::Direct => {
- // Use direct execution for backward compatibility
- api_client::execute_connector_processing_step(
- state,
- connector_integration,
- router_data,
- call_connector_action,
- connector_request,
- return_raw_connector_response,
- )
- .await
+ let gateway: Box<
+ dyn PaymentGateway<State, ConnectorData, F, Req, Resp, Context, FlowOutput>,
+ > = F::get_gateway(ExecutionPath::Direct);
+ gateway
+ .execute(
+ state,
+ connector_integration,
+ router_data,
+ call_connector_action,
+ connector_request,
+ return_raw_connector_response,
+ context,
+ )
+ .await
}
ExecutionPath::UnifiedConnectorService => {
- let gateway: Box<dyn PaymentGateway<State, ConnectorData, F, Req, Resp, Context>> =
- F::get_gateway(execution_path);
+ let gateway: Box<
+ dyn PaymentGateway<State, ConnectorData, F, Req, Resp, Context, FlowOutput>,
+ > = F::get_gateway(ExecutionPath::UnifiedConnectorService);
// Execute through selected gateway
- gateway
+ let ucs_result = gateway
.execute(
state,
connector_integration,
@@ -193,28 +274,34 @@ where
context,
)
.await
- .attach_printable("Gateway execution failed")
+ .attach_printable("Gateway execution failed")?;
+ Ok(ucs_result)
}
ExecutionPath::ShadowUnifiedConnectorService => {
- let direct_router_data = api_client::execute_connector_processing_step(
- state,
- connector_integration.clone_box(),
- router_data,
- call_connector_action.clone(),
- connector_request,
- return_raw_connector_response,
- )
- .await?;
+ let gateway: Box<
+ dyn PaymentGateway<State, ConnectorData, F, Req, Resp, Context, FlowOutput>,
+ > = F::get_gateway(ExecutionPath::Direct);
+ let direct_router_data = gateway
+ .execute(
+ state,
+ connector_integration.clone_box(),
+ router_data,
+ call_connector_action.clone(),
+ connector_request,
+ return_raw_connector_response,
+ context.clone(),
+ )
+ .await?;
let state_clone = state.clone();
let router_data_clone = router_data.clone();
let direct_router_data_clone = direct_router_data.clone();
let return_raw_connector_response_clone = return_raw_connector_response;
- let context_clone = context.clone();
+ let context_clone = context;
tokio::spawn(
async move {
let gateway: Box<
- dyn PaymentGateway<State, ConnectorData, F, Req, Resp, Context>,
- > = F::get_gateway(execution_path);
+ dyn PaymentGateway<State, ConnectorData, F, Req, Resp, Context, FlowOutput>,
+ > = F::get_gateway(ExecutionPath::ShadowUnifiedConnectorService);
let ucs_shadow_result = gateway
.execute(
&state_clone,
@@ -238,8 +325,8 @@ where
let _ =
helpers::serialize_router_data_and_send_to_comparison_service(
&state_clone,
- direct_router_data_clone,
- ucs_router_data,
+ direct_router_data_clone.get_router_data().clone(),
+ ucs_router_data.get_router_data().clone(),
comparison_service_config,
request_id,
)
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index 162735e6fb..50b2de8890 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -3,16 +3,20 @@ 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::{id_type, types::MinorUnit, ucs_types};
+use common_utils::{errors, id_type, types::MinorUnit, ucs_types};
use error_stack::ResultExt;
use external_services::grpc_client;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payments::PaymentConfirmData;
use hyperswitch_domain_models::{
errors::api_error_response::ApiErrorResponse, payments as domain_payments,
- router_response_types,
+ router_data_v2::PaymentFlowData, router_response_types,
+};
+use hyperswitch_interfaces::{
+ api::{self as api_interface, gateway, ConnectorSpecifications},
+ errors as interface_errors,
+ unified_connector_service::transformers as ucs_transformers,
};
-use hyperswitch_interfaces::api::{self as api_interface, gateway, ConnectorSpecifications};
use masking::ExposeInterface;
use unified_connector_service_client::payments as payments_grpc;
use unified_connector_service_masking::ExposeInterface as UcsMaskingExposeInterface;
@@ -24,15 +28,15 @@ use crate::{
errors::{ConnectorErrorExt, RouterResult},
mandate,
payments::{
- self, access_token, customers, flows::gateway_context, helpers, session_token,
- tokenization, transformers, PaymentData,
+ self, access_token, customers, flows::gateway_context, gateway as payments_gateway,
+ 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, ucs_logging_wrapper_granular,
},
},
logger,
@@ -342,7 +346,13 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
pre_authenticate_request_data,
pre_authenticate_response_data,
);
- let pre_authenticate_router_data = Box::pin(handle_pre_authenticate_connector_call(
+ let pre_authenticate_router_data = Box::pin(payments_gateway::handle_gateway_call::<
+ _,
+ _,
+ _,
+ PaymentFlowData,
+ _,
+ >(
state,
pre_authenticate_router_data,
connector,
@@ -618,7 +628,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
types::PaymentsResponseData,
types::ErrorResponse,
> = Err(types::ErrorResponse::default());
- let mut pre_authenticate_router_data = helpers::router_data_type_conversion::<
+ let pre_authenticate_router_data = helpers::router_data_type_conversion::<
_,
api::PreAuthenticate,
_,
@@ -630,18 +640,20 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
pre_authneticate_request_data,
pre_authneticate_response_data,
);
- let _ = call_unified_connector_service_pre_authenticate(
- &mut pre_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;
+ let (pre_authenticate_router_data, _) =
+ call_unified_connector_service_pre_authenticate(
+ &pre_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()?;
// Convert back to authorize router data while preserving preprocessing response data.
let pre_authenticate_response = pre_authenticate_router_data.response.clone();
let authorize_router_data =
@@ -651,7 +663,6 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
pre_authenticate_response,
);
*self = authorize_router_data;
-
Ok(())
}
None => {
@@ -1101,7 +1112,10 @@ async fn call_unified_connector_service_authorize(
fn transform_redirection_response_for_pre_authenticate_flow(
connector: enums::connector_enums::Connector,
response_data: router_response_types::RedirectForm,
-) -> RouterResult<router_response_types::RedirectForm> {
+) -> errors::CustomResult<
+ router_response_types::RedirectForm,
+ ucs_transformers::UnifiedConnectorServiceError,
+> {
match (connector, &response_data) {
(
enums::connector_enums::Connector::Cybersource,
@@ -1112,13 +1126,13 @@ fn transform_redirection_response_for_pre_authenticate_flow(
},
) => {
let access_token = form_fields.get("access_token").cloned().ok_or(
- ApiErrorResponse::MissingRequiredField {
+ ucs_transformers::UnifiedConnectorServiceError::MissingRequiredField {
field_name: "access_token",
},
)?;
let ddc_url = form_fields.get("ddc_url").unwrap_or(endpoint).clone();
let reference_id = form_fields.get("reference_id").cloned().ok_or(
- ApiErrorResponse::MissingRequiredField {
+ ucs_transformers::UnifiedConnectorServiceError::MissingRequiredField {
field_name: "reference_id",
},
)?;
@@ -1134,7 +1148,10 @@ fn transform_redirection_response_for_pre_authenticate_flow(
fn transform_response_for_pre_authenticate_flow(
connector: enums::connector_enums::Connector,
response_data: router_response_types::PaymentsResponseData,
-) -> RouterResult<router_response_types::PaymentsResponseData> {
+) -> errors::CustomResult<
+ router_response_types::PaymentsResponseData,
+ ucs_transformers::UnifiedConnectorServiceError,
+> {
match (connector, response_data.clone()) {
(
enums::connector_enums::Connector::Cybersource,
@@ -1178,8 +1195,8 @@ fn transform_response_for_pre_authenticate_flow(
}
#[allow(clippy::too_many_arguments)]
-async fn call_unified_connector_service_pre_authenticate(
- router_data: &mut types::RouterData<
+pub async fn call_unified_connector_service_pre_authenticate(
+ router_data: &types::RouterData<
api::PreAuthenticate,
types::PaymentsPreAuthenticateData,
types::PaymentsResponseData,
@@ -1193,17 +1210,27 @@ async fn call_unified_connector_service_pre_authenticate(
connector: enums::connector_enums::Connector,
unified_connector_service_execution_mode: enums::ExecutionMode,
merchant_order_reference_id: Option<String>,
-) -> RouterResult<()> {
+) -> errors::CustomResult<
+ (
+ types::RouterData<
+ api::PreAuthenticate,
+ types::PaymentsPreAuthenticateData,
+ types::PaymentsResponseData,
+ >,
+ (),
+ ),
+ interface_errors::ConnectorError,
+> {
let client = state
.grpc_client
.unified_connector_service_client
.clone()
- .ok_or(ApiErrorResponse::InternalServerError)
+ .ok_or(interface_errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let payment_pre_authenticate_request =
- payments_grpc::PaymentServicePreAuthenticateRequest::foreign_try_from(&*router_data)
- .change_context(ApiErrorResponse::InternalServerError)
+ payments_grpc::PaymentServicePreAuthenticateRequest::foreign_try_from(router_data)
+ .change_context(interface_errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct Payment Authorize Request")?;
let connector_auth_metadata = build_unified_connector_service_auth_metadata(
@@ -1211,7 +1238,7 @@ async fn call_unified_connector_service_pre_authenticate(
platform,
router_data.connector.clone(),
)
- .change_context(ApiErrorResponse::InternalServerError)
+ .change_context(interface_errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct request metadata")?;
let merchant_reference_id = header_payload
.x_reference_id
@@ -1228,7 +1255,7 @@ async fn call_unified_connector_service_pre_authenticate(
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
- let (updated_router_data, _) = Box::pin(ucs_logging_wrapper(
+ Box::pin(ucs_logging_wrapper_granular(
router_data.clone(),
state,
payment_pre_authenticate_request,
@@ -1241,7 +1268,6 @@ async fn call_unified_connector_service_pre_authenticate(
grpc_headers,
)
.await
- .change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to authorize payment")?;
let payment_pre_authenticate_response = response.into_inner();
@@ -1250,7 +1276,6 @@ async fn call_unified_connector_service_pre_authenticate(
unified_connector_service::handle_unified_connector_service_response_for_payment_pre_authenticate(
payment_pre_authenticate_response.clone(),
)
- .change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response = router_data_response.map(|(response, status)| {
@@ -1268,50 +1293,11 @@ async fn call_unified_connector_service_pre_authenticate(
.map(|raw_connector_response| raw_connector_response.expose().into());
router_data.connector_http_status_code = Some(status_code);
- Ok((router_data,(), payment_pre_authenticate_response))
+ Ok((router_data, (), payment_pre_authenticate_response))
},
))
- .await?;
-
- // Copy back the updated data
- *router_data = updated_router_data;
- Ok(())
-}
-
-pub async fn handle_pre_authenticate_connector_call(
- state: &SessionState,
- router_data: types::RouterData<
- api::PreAuthenticate,
- types::PaymentsPreAuthenticateData,
- types::PaymentsResponseData,
- >,
- connector: &api::ConnectorData,
- _gateway_context: &gateway_context::RouterGatewayContext,
-) -> RouterResult<
- types::RouterData<
- api::PreAuthenticate,
- types::PaymentsPreAuthenticateData,
- types::PaymentsResponseData,
- >,
-> {
- let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
- api::PreAuthenticate,
- types::PaymentsPreAuthenticateData,
- types::PaymentsResponseData,
- > = connector.connector.get_connector_integration();
- // TODO: Handle gateway_context later
- let resp = services::execute_connector_processing_step(
- state,
- connector_integration,
- &router_data,
- payments::CallConnectorAction::Trigger,
- None,
- None,
- // gateway_context.clone(),
- )
.await
- .to_payment_failed_response()?;
- Ok(resp)
+ .change_context(interface_errors::ConnectorError::ResponseHandlingFailed)
}
#[allow(clippy::too_many_arguments)]
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 678f8b6616..8f0e7f3d4e 100644
--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs
@@ -2,11 +2,18 @@ use std::str::FromStr;
use async_trait::async_trait;
use common_enums::connector_enums;
-use common_utils::{id_type, ucs_types};
+use common_utils::{errors, id_type, ucs_types};
use error_stack::ResultExt;
use external_services::grpc_client;
-use hyperswitch_domain_models::{router_request_types, router_response_types};
-use hyperswitch_interfaces::{api as api_interface, api::ConnectorSpecifications};
+use hyperswitch_domain_models::{
+ router_data_v2::PaymentFlowData, router_request_types, router_response_types,
+};
+use hyperswitch_interfaces::{
+ api as api_interface,
+ api::{gateway, ConnectorSpecifications},
+ errors as interface_errors,
+ unified_connector_service::transformers as ucs_transformers,
+};
use masking::{self, ExposeInterface};
use unified_connector_service_client::payments as payments_grpc;
use unified_connector_service_masking::ExposeInterface as UcsMaskingExposeInterface;
@@ -16,8 +23,8 @@ use crate::{
core::{
errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult},
payments::{
- self, access_token, gateway::context as gateway_context, helpers, transformers,
- PaymentData,
+ self, access_token, gateway as payments_gateway, gateway::context as gateway_context,
+ helpers, transformers, PaymentData,
},
unified_connector_service as ucs_core,
},
@@ -118,13 +125,14 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
- let mut complete_authorize_router_data = services::execute_connector_processing_step(
+ let mut complete_authorize_router_data = gateway::execute_payment_gateway(
state,
connector_integration,
&self,
call_connector_action.clone(),
connector_request,
None,
+ gateway_context.clone(),
)
.await
.to_payment_failed_response()?;
@@ -248,6 +256,7 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>
if connector.connector.is_authentication_flow_required(
api_interface::CurrentFlowInfo::CompleteAuthorize {
request_data: &self.request,
+ payment_method: Some(self.payment_method),
},
) {
let router_data = self;
@@ -270,13 +279,20 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>
);
// Call UCS for Authenticate flow and store authentication result for next step
- let authenticate_router_data = Box::pin(handle_authenticate_connector_call(
- state,
- authenticate_router_data,
- connector,
- gateway_context,
- ))
- .await?;
+ let (authenticate_router_data, authentication_data) =
+ Box::pin(payments_gateway::handle_gateway_call::<
+ _,
+ _,
+ _,
+ PaymentFlowData,
+ _,
+ >(
+ state,
+ authenticate_router_data,
+ connector,
+ gateway_context,
+ ))
+ .await?;
// Convert back to CompleteAuthorize router data while preserving preprocessing response data
let authenticate_response = authenticate_router_data.response.clone();
@@ -286,6 +302,7 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>
{
connector_metadata.clone_into(&mut complete_authorize_request_data.connector_meta);
};
+ complete_authorize_request_data.authentication_data = authentication_data;
let complete_authorize_router_data =
helpers::router_data_type_conversion::<_, api::CompleteAuthorize, _, _, _, _>(
authenticate_router_data,
@@ -320,6 +337,7 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>
if connector.connector.is_post_authentication_flow_required(
api_interface::CurrentFlowInfo::CompleteAuthorize {
request_data: &self.request,
+ payment_method: Some(self.payment_method),
},
) {
let router_data = self;
@@ -342,13 +360,20 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>
post_authenticate_response_data,
);
- let post_authenticate_router_data = Box::pin(handle_post_authenticate_connector_call(
- state,
- post_authenticate_router_data,
- connector,
- gateway_context,
- ))
- .await?;
+ let (post_authenticate_router_data, authentication_data) =
+ Box::pin(payments_gateway::handle_gateway_call::<
+ _,
+ _,
+ _,
+ PaymentFlowData,
+ _,
+ >(
+ state,
+ post_authenticate_router_data,
+ connector,
+ gateway_context,
+ ))
+ .await?;
// Convert back to CompleteAuthorize router data while preserving preprocessing response data
let post_authenticate_response = post_authenticate_router_data.response.clone();
if let Ok(types::PaymentsResponseData::TransactionResponse {
@@ -357,6 +382,7 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>
{
connector_metadata.clone_into(&mut complete_authorize_request_data.connector_meta);
};
+ complete_authorize_request_data.authentication_data = authentication_data;
let complete_authorize_router_data =
helpers::router_data_type_conversion::<_, api::CompleteAuthorize, _, _, _, _>(
post_authenticate_router_data,
@@ -394,6 +420,7 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>
) -> 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
@@ -463,7 +490,7 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>
#[allow(clippy::too_many_arguments)]
async fn handle_preprocessing_through_unified_connector_service(
- mut router_data: types::RouterData<
+ router_data: types::RouterData<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
@@ -495,7 +522,7 @@ async fn handle_preprocessing_through_unified_connector_service(
types::PaymentsResponseData,
types::ErrorResponse,
> = Err(types::ErrorResponse::default());
- let mut authenticate_router_data =
+ let authenticate_router_data =
helpers::router_data_type_conversion::<_, api::Authenticate, _, _, _, _>(
router_data.clone(),
authenticate_request_data,
@@ -503,9 +530,9 @@ async fn handle_preprocessing_through_unified_connector_service(
);
// Call UCS for Authenticate flow and store authentication result for next step
- complete_authorize_request_data.authentication_data =
+ let (authenticate_router_data, authentication_data) =
call_unified_connector_service_authenticate(
- &mut authenticate_router_data,
+ &authenticate_router_data,
state,
header_payload,
lineage_ids,
@@ -515,8 +542,9 @@ async fn handle_preprocessing_through_unified_connector_service(
unified_connector_service_execution_mode,
merchant_order_reference_id,
)
- .await?;
-
+ .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 =
@@ -525,9 +553,7 @@ async fn handle_preprocessing_through_unified_connector_service(
complete_authorize_request_data,
authenticate_response,
);
- router_data = complete_authorize_router_data;
-
- Ok(router_data)
+ Ok(complete_authorize_router_data)
}
api_interface::PreProcessingFlowName::PostAuthenticate => {
// Convert CompleteAuthorize to PostAuthenticate for UCS call
@@ -538,7 +564,7 @@ async fn handle_preprocessing_through_unified_connector_service(
types::PaymentsResponseData,
types::ErrorResponse,
> = Err(types::ErrorResponse::default());
- let mut post_authenticate_router_data =
+ let post_authenticate_router_data =
helpers::router_data_type_conversion::<_, api::PostAuthenticate, _, _, _, _>(
router_data.clone(),
post_authenticate_request_data,
@@ -546,9 +572,9 @@ async fn handle_preprocessing_through_unified_connector_service(
);
// Call UCS for PostAuthenticate flow and store authentication result for next step
- complete_authorize_request_data.authentication_data =
+ let (post_authenticate_router_data, authentication_data) =
call_unified_connector_service_post_authenticate(
- &mut post_authenticate_router_data,
+ &post_authenticate_router_data,
state,
header_payload,
lineage_ids,
@@ -557,8 +583,9 @@ async fn handle_preprocessing_through_unified_connector_service(
unified_connector_service_execution_mode,
merchant_order_reference_id,
)
- .await?;
-
+ .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 =
@@ -567,90 +594,18 @@ async fn handle_preprocessing_through_unified_connector_service(
complete_authorize_request_data,
post_authenticate_response,
);
- router_data = complete_authorize_router_data;
-
- Ok(router_data)
+ Ok(complete_authorize_router_data)
}
}
}
-pub async fn handle_authenticate_connector_call(
- state: &SessionState,
- router_data: types::RouterData<
- api::Authenticate,
- types::PaymentsAuthenticateData,
- types::PaymentsResponseData,
- >,
- connector: &api::ConnectorData,
- _gateway_context: &gateway_context::RouterGatewayContext,
-) -> RouterResult<
- types::RouterData<
- api::Authenticate,
- types::PaymentsAuthenticateData,
- types::PaymentsResponseData,
- >,
-> {
- let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
- api::Authenticate,
- types::PaymentsAuthenticateData,
- types::PaymentsResponseData,
- > = connector.connector.get_connector_integration();
-
- // TODO: Handle gateway_context later
- let resp = services::execute_connector_processing_step(
- state,
- connector_integration,
- &router_data,
- payments::CallConnectorAction::Trigger,
- None,
- None,
- // gateway_context.clone(),
- )
- .await
- .to_payment_failed_response()?;
- Ok(resp)
-}
-
-pub async fn handle_post_authenticate_connector_call(
- state: &SessionState,
- router_data: types::RouterData<
- api::PostAuthenticate,
- types::PaymentsPostAuthenticateData,
- types::PaymentsResponseData,
- >,
- connector: &api::ConnectorData,
- _gateway_context: &gateway_context::RouterGatewayContext,
-) -> RouterResult<
- types::RouterData<
- api::PostAuthenticate,
- types::PaymentsPostAuthenticateData,
- types::PaymentsResponseData,
- >,
-> {
- let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
- api::PostAuthenticate,
- types::PaymentsPostAuthenticateData,
- types::PaymentsResponseData,
- > = connector.connector.get_connector_integration();
- // TODO: Handle gateway_context later
- let resp = services::execute_connector_processing_step(
- state,
- connector_integration,
- &router_data,
- payments::CallConnectorAction::Trigger,
- None,
- None,
- // gateway_context.clone(),
- )
- .await
- .to_payment_failed_response()?;
- Ok(resp)
-}
-
fn transform_redirection_response_for_authenticate_flow(
connector: connector_enums::Connector,
response_data: router_response_types::RedirectForm,
-) -> RouterResult<router_response_types::RedirectForm> {
+) -> errors::CustomResult<
+ router_response_types::RedirectForm,
+ ucs_transformers::UnifiedConnectorServiceError,
+> {
match (connector, &response_data) {
(
connector_enums::Connector::Cybersource,
@@ -661,7 +616,7 @@ fn transform_redirection_response_for_authenticate_flow(
},
) => {
let access_token = form_fields.get("access_token").cloned().ok_or(
- ApiErrorResponse::MissingRequiredField {
+ ucs_transformers::UnifiedConnectorServiceError::MissingRequiredField {
field_name: "access_token",
},
)?;
@@ -679,7 +634,10 @@ fn transform_redirection_response_for_authenticate_flow(
fn transform_response_for_authenticate_flow(
connector: connector_enums::Connector,
response_data: router_response_types::PaymentsResponseData,
-) -> RouterResult<router_response_types::PaymentsResponseData> {
+) -> errors::CustomResult<
+ router_response_types::PaymentsResponseData,
+ ucs_transformers::UnifiedConnectorServiceError,
+> {
match (connector, response_data.clone()) {
(
connector_enums::Connector::Cybersource,
@@ -723,8 +681,8 @@ fn transform_response_for_authenticate_flow(
}
#[allow(dead_code, clippy::too_many_arguments)]
-async fn call_unified_connector_service_authenticate(
- router_data: &mut types::RouterData<
+pub async fn call_unified_connector_service_authenticate(
+ router_data: &types::RouterData<
api::Authenticate,
types::PaymentsAuthenticateData,
types::PaymentsResponseData,
@@ -738,17 +696,27 @@ async fn call_unified_connector_service_authenticate(
connector: connector_enums::Connector,
unified_connector_service_execution_mode: common_enums::ExecutionMode,
merchant_order_reference_id: Option<String>,
-) -> RouterResult<Option<router_request_types::UcsAuthenticationData>> {
+) -> errors::CustomResult<
+ (
+ types::RouterData<
+ api::Authenticate,
+ types::PaymentsAuthenticateData,
+ types::PaymentsResponseData,
+ >,
+ Option<router_request_types::UcsAuthenticationData>,
+ ),
+ interface_errors::ConnectorError,
+> {
let client = state
.grpc_client
.unified_connector_service_client
.clone()
- .ok_or(ApiErrorResponse::InternalServerError)
+ .ok_or(interface_errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let payment_authenticate_request =
- payments_grpc::PaymentServiceAuthenticateRequest::foreign_try_from(&*router_data)
- .change_context(ApiErrorResponse::InternalServerError)
+ payments_grpc::PaymentServiceAuthenticateRequest::foreign_try_from(router_data)
+ .change_context(interface_errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct Payment Authorize Request")?;
let connector_auth_metadata = ucs_core::build_unified_connector_service_auth_metadata(
@@ -756,7 +724,7 @@ async fn call_unified_connector_service_authenticate(
platform,
router_data.connector.clone(),
)
- .change_context(ApiErrorResponse::InternalServerError)
+ .change_context(interface_errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct request metadata")?;
let merchant_reference_id = header_payload
.x_reference_id
@@ -773,7 +741,7 @@ async fn call_unified_connector_service_authenticate(
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
- let (updated_router_data, authentication_data) = Box::pin(ucs_core::ucs_logging_wrapper(
+ Box::pin(ucs_core::ucs_logging_wrapper_granular(
router_data.clone(),
state,
payment_authenticate_request,
@@ -786,7 +754,6 @@ async fn call_unified_connector_service_authenticate(
grpc_headers,
)
.await
- .change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to authorize payment")?;
let payment_authenticate_response = response.into_inner();
@@ -795,7 +762,6 @@ async fn call_unified_connector_service_authenticate(
ucs_core::handle_unified_connector_service_response_for_payment_authenticate(
payment_authenticate_response.clone(),
)
- .change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response = router_data_response.map(|(response, status)| {
@@ -824,7 +790,6 @@ async fn call_unified_connector_service_authenticate(
)
})
.transpose()
- .change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to Convert to domain AuthenticationData")?;
Ok((
@@ -834,16 +799,13 @@ async fn call_unified_connector_service_authenticate(
))
},
))
- .await?;
-
- // Copy back the updated data
- *router_data = updated_router_data;
- Ok(authentication_data)
+ .await
+ .change_context(interface_errors::ConnectorError::ResponseHandlingFailed)
}
#[allow(dead_code, clippy::too_many_arguments)]
-async fn call_unified_connector_service_post_authenticate(
- router_data: &mut types::RouterData<
+pub async fn call_unified_connector_service_post_authenticate(
+ router_data: &types::RouterData<
api::PostAuthenticate,
types::PaymentsPostAuthenticateData,
types::PaymentsResponseData,
@@ -856,17 +818,27 @@ async fn call_unified_connector_service_post_authenticate(
platform: &domain::Platform,
unified_connector_service_execution_mode: common_enums::ExecutionMode,
merchant_order_reference_id: Option<String>,
-) -> RouterResult<Option<router_request_types::UcsAuthenticationData>> {
+) -> errors::CustomResult<
+ (
+ types::RouterData<
+ api::PostAuthenticate,
+ types::PaymentsPostAuthenticateData,
+ types::PaymentsResponseData,
+ >,
+ Option<router_request_types::UcsAuthenticationData>,
+ ),
+ interface_errors::ConnectorError,
+> {
let client = state
.grpc_client
.unified_connector_service_client
.clone()
- .ok_or(ApiErrorResponse::InternalServerError)
+ .ok_or(interface_errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let payment_post_authenticate_request =
- payments_grpc::PaymentServicePostAuthenticateRequest::foreign_try_from(&*router_data)
- .change_context(ApiErrorResponse::InternalServerError)
+ payments_grpc::PaymentServicePostAuthenticateRequest::foreign_try_from(router_data)
+ .change_context(interface_errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct Payment Authorize Request")?;
let connector_auth_metadata = ucs_core::build_unified_connector_service_auth_metadata(
@@ -874,7 +846,7 @@ async fn call_unified_connector_service_post_authenticate(
platform,
router_data.connector.clone(),
)
- .change_context(ApiErrorResponse::InternalServerError)
+ .change_context(interface_errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct request metadata")?;
let merchant_reference_id = header_payload
.x_reference_id
@@ -891,7 +863,7 @@ async fn call_unified_connector_service_post_authenticate(
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
- let (updated_router_data, authentication_data) = Box::pin(ucs_core::ucs_logging_wrapper(
+ Box::pin(ucs_core::ucs_logging_wrapper_granular(
router_data.clone(),
state,
payment_post_authenticate_request,
@@ -904,7 +876,6 @@ async fn call_unified_connector_service_post_authenticate(
grpc_headers,
)
.await
- .change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to authorize payment")?;
let payment_post_authenticate_response = response.into_inner();
@@ -913,7 +884,6 @@ async fn call_unified_connector_service_post_authenticate(
ucs_core::handle_unified_connector_service_response_for_payment_post_authenticate(
payment_post_authenticate_response.clone(),
)
- .change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response = router_data_response.map(|(response, status)| {
@@ -936,7 +906,6 @@ async fn call_unified_connector_service_post_authenticate(
)
})
.transpose()
- .change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to Convert to domain AuthenticationData")?;
Ok((
@@ -946,11 +915,8 @@ async fn call_unified_connector_service_post_authenticate(
))
},
))
- .await?;
-
- // Copy back the updated data
- *router_data = updated_router_data;
- Ok(authentication_data)
+ .await
+ .change_context(interface_errors::ConnectorError::ResponseHandlingFailed)
}
pub async fn complete_authorize_preprocessing_steps<F: Clone>(
diff --git a/crates/router/src/core/payments/gateway.rs b/crates/router/src/core/payments/gateway.rs
index 12fc402417..b649f8826a 100644
--- a/crates/router/src/core/payments/gateway.rs
+++ b/crates/router/src/core/payments/gateway.rs
@@ -1,22 +1,81 @@
pub mod access_token_gateway;
+pub mod authenticate_gateway;
pub mod authorize_gateway;
+pub mod complete_authorize_gateway;
pub mod context;
pub mod create_customer_gateway;
pub mod create_order_gateway;
pub mod payment_method_token_create_gateway;
+pub mod post_authenticate_gateway;
+pub mod pre_authenticate_gateway;
pub mod psync_gateway;
pub mod session_gateway;
pub mod session_token_gateway;
pub mod setup_mandate;
use std::sync;
-use hyperswitch_domain_models::router_flow_types::payments;
+use common_enums;
+use hyperswitch_domain_models::{router_data_v2::PaymentFlowData, router_flow_types::payments};
+use hyperswitch_interfaces::{
+ api::{gateway, Connector, ConnectorIntegration},
+ connector_integration_v2::{ConnectorIntegrationV2, ConnectorV2},
+};
+
+use crate::{
+ core::{errors::utils::ConnectorErrorExt, payments::gateway::context as gateway_context},
+ errors::RouterResult,
+ services, types,
+ types::api,
+ SessionState,
+};
pub static GRANULAR_GATEWAY_SUPPORTED_FLOWS: sync::LazyLock<Vec<&'static str>> =
sync::LazyLock::new(|| {
vec![
std::any::type_name::<payments::PSync>(),
std::any::type_name::<payments::Authorize>(),
+ std::any::type_name::<payments::CompleteAuthorize>(),
std::any::type_name::<payments::SetupMandate>(),
]
});
+
+pub async fn handle_gateway_call<Flow, Req, Resp, ResourceCommonData, FlowOutput>(
+ state: &SessionState,
+ router_data: types::RouterData<Flow, Req, Resp>,
+ connector: &api::ConnectorData,
+ gateway_context: &gateway_context::RouterGatewayContext,
+) -> RouterResult<FlowOutput>
+where
+ Flow: gateway::FlowGateway<
+ SessionState,
+ PaymentFlowData,
+ Req,
+ Resp,
+ gateway_context::RouterGatewayContext,
+ FlowOutput,
+ >,
+ FlowOutput: Clone + Send + Sync + gateway::GetRouterData<Flow, Req, Resp> + 'static,
+ Req: std::fmt::Debug + Clone + Send + Sync + serde::Serialize + 'static,
+ Resp: std::fmt::Debug + Clone + Send + Sync + serde::Serialize + 'static,
+ dyn Connector + Sync: ConnectorIntegration<Flow, Req, Resp>,
+ dyn ConnectorV2 + Sync: ConnectorIntegrationV2<Flow, PaymentFlowData, Req, Resp>,
+{
+ let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
+ Flow,
+ Req,
+ Resp,
+ > = connector.connector.get_connector_integration();
+ // TODO: Handle gateway_context later
+ let resp = gateway::execute_payment_gateway(
+ state,
+ connector_integration,
+ &router_data,
+ common_enums::CallConnectorAction::Trigger,
+ None,
+ None,
+ gateway_context.clone(),
+ )
+ .await
+ .to_payment_failed_response()?;
+ Ok(resp)
+}
diff --git a/crates/router/src/core/payments/gateway/access_token_gateway.rs b/crates/router/src/core/payments/gateway/access_token_gateway.rs
index 405750871e..cf8677aab3 100644
--- a/crates/router/src/core/payments/gateway/access_token_gateway.rs
+++ b/crates/router/src/core/payments/gateway/access_token_gateway.rs
@@ -120,7 +120,7 @@ where
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
- let updated_router_data = Box::pin(unified_connector_service::ucs_logging_wrapper_new(
+ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
router_data.clone(),
state,
create_access_token_request,
@@ -146,13 +146,12 @@ where
router_data.response = access_token_result;
router_data.connector_http_status_code = Some(status_code);
- Ok((router_data, create_access_token_response))
+ Ok((router_data,(), create_access_token_response))
},
))
.await
- .change_context(ConnectorError::ResponseHandlingFailed)?;
-
- Ok(updated_router_data)
+ .map(|(router_data, _)| router_data)
+ .change_context(ConnectorError::ResponseHandlingFailed)
}
}
diff --git a/crates/router/src/core/payments/gateway/authenticate_gateway.rs b/crates/router/src/core/payments/gateway/authenticate_gateway.rs
new file mode 100644
index 0000000000..186162711c
--- /dev/null
+++ b/crates/router/src/core/payments/gateway/authenticate_gateway.rs
@@ -0,0 +1,142 @@
+use std::str::FromStr;
+
+use async_trait::async_trait;
+use common_enums::{CallConnectorAction, ExecutionPath};
+use common_utils::{errors::CustomResult, request::Request};
+use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ router_data::RouterData, router_flow_types as domain, router_request_types,
+};
+use hyperswitch_interfaces::{
+ api::gateway as payment_gateway,
+ connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
+ errors::ConnectorError,
+};
+
+use crate::{
+ core::payments::{flows::complete_authorize_flow, gateway::context::RouterGatewayContext},
+ routes::SessionState,
+ types,
+};
+
+// =============================================================================
+// PaymentGateway Implementation for domain::Authenticate
+// =============================================================================
+
+/// Implementation of PaymentGateway for api::Authenticate flow
+#[async_trait]
+impl<RCD>
+ payment_gateway::PaymentGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PaymentsAuthenticateData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ (
+ RouterData<Self, types::PaymentsAuthenticateData, types::PaymentsResponseData>,
+ Option<router_request_types::UcsAuthenticationData>,
+ ),
+ > for domain::Authenticate
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PaymentsAuthenticateData, types::PaymentsResponseData>,
+{
+ async fn execute(
+ self: Box<Self>,
+ state: &SessionState,
+ _connector_integration: BoxedConnectorIntegrationInterface<
+ Self,
+ RCD,
+ types::PaymentsAuthenticateData,
+ types::PaymentsResponseData,
+ >,
+ router_data: &RouterData<
+ Self,
+ types::PaymentsAuthenticateData,
+ types::PaymentsResponseData,
+ >,
+ _call_connector_action: CallConnectorAction,
+ _connector_request: Option<Request>,
+ _return_raw_connector_response: Option<bool>,
+ context: RouterGatewayContext,
+ ) -> CustomResult<
+ (
+ RouterData<Self, types::PaymentsAuthenticateData, types::PaymentsResponseData>,
+ Option<router_request_types::UcsAuthenticationData>,
+ ),
+ 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 connector_enum =
+ common_enums::connector_enums::Connector::from_str(&router_data.connector)
+ .change_context(ConnectorError::InvalidConnectorName)
+ .attach_printable("Invalid connector name")?;
+ complete_authorize_flow::call_unified_connector_service_authenticate(
+ router_data,
+ state,
+ &header_payload,
+ lineage_ids,
+ merchant_connector_account,
+ &platform,
+ connector_enum,
+ unified_connector_service_execution_mode,
+ merchant_order_reference_id,
+ )
+ .await
+ }
+}
+
+/// 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::PaymentsAuthenticateData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ (
+ RouterData<Self, types::PaymentsAuthenticateData, types::PaymentsResponseData>,
+ Option<router_request_types::UcsAuthenticationData>,
+ ),
+ > for domain::Authenticate
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PaymentsAuthenticateData, types::PaymentsResponseData>,
+{
+ fn get_gateway(
+ execution_path: ExecutionPath,
+ ) -> Box<
+ dyn payment_gateway::PaymentGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PaymentsAuthenticateData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ (
+ RouterData<Self, types::PaymentsAuthenticateData, types::PaymentsResponseData>,
+ Option<router_request_types::UcsAuthenticationData>,
+ ),
+ >,
+ > {
+ 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/authorize_gateway.rs b/crates/router/src/core/payments/gateway/authorize_gateway.rs
index 0ca876f213..8c46f263fa 100644
--- a/crates/router/src/core/payments/gateway/authorize_gateway.rs
+++ b/crates/router/src/core/payments/gateway/authorize_gateway.rs
@@ -122,7 +122,7 @@ where
.change_context(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct Payment Repeat Request")?;
- Box::pin(unified_connector_service::ucs_logging_wrapper_new(
+ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
router_data.clone(),
state,
payment_repeat_request,
@@ -169,10 +169,11 @@ where
router_data.connector_response = Some(connector_response);
});
- Ok((router_data, payment_repeat_response))
+ Ok((router_data, (), payment_repeat_response))
},
))
.await
+ .map(|(router_data, _)| router_data)
.change_context(ConnectorError::ResponseHandlingFailed)?
} else {
logger::debug!("Granular Gateway: Regular authorize flow");
@@ -184,7 +185,7 @@ where
.change_context(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct Payment Get Request")?;
- Box::pin(unified_connector_service::ucs_logging_wrapper_new(
+ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
router_data.clone(),
state,
granular_authorize_request,
@@ -226,10 +227,11 @@ where
router_data.connector_response = Some(customer_response);
});
- Ok((router_data, payment_authorize_response))
+ Ok((router_data, (), payment_authorize_response))
},
))
.await
+ .map(|(router_data, _)| router_data)
.change_context(ConnectorError::ResponseHandlingFailed)?
};
diff --git a/crates/router/src/core/payments/gateway/complete_authorize_gateway.rs b/crates/router/src/core/payments/gateway/complete_authorize_gateway.rs
new file mode 100644
index 0000000000..b64a0f81f0
--- /dev/null
+++ b/crates/router/src/core/payments/gateway/complete_authorize_gateway.rs
@@ -0,0 +1,197 @@
+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 unified_connector_service_masking::ExposeInterface as UcsMaskingExposeInterface;
+
+use crate::{
+ core::{
+ payments::gateway::context::RouterGatewayContext, unified_connector_service,
+ unified_connector_service::handle_unified_connector_service_response_for_payment_authorize,
+ },
+ routes::SessionState,
+ services::logger,
+ types::{self, transformers::ForeignTryFrom, MinorUnit},
+};
+
+// =============================================================================
+// PaymentGateway Implementation for domain::CompleteAuthorize
+// =============================================================================
+
+/// Implementation of PaymentGateway for api::CompleteAuthorize flow
+#[async_trait]
+impl<RCD>
+ payment_gateway::PaymentGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::CompleteAuthorizeData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ > for domain::CompleteAuthorize
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::CompleteAuthorizeData, types::PaymentsResponseData>,
+{
+ async fn execute(
+ self: Box<Self>,
+ state: &SessionState,
+ _connector_integration: BoxedConnectorIntegrationInterface<
+ Self,
+ RCD,
+ types::CompleteAuthorizeData,
+ types::PaymentsResponseData,
+ >,
+ router_data: &RouterData<Self, types::CompleteAuthorizeData, types::PaymentsResponseData>,
+ call_connector_action: CallConnectorAction,
+ _connector_request: Option<Request>,
+ _return_raw_connector_response: Option<bool>,
+ context: RouterGatewayContext,
+ ) -> CustomResult<
+ RouterData<Self, types::CompleteAuthorizeData, 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 granular_authorize_request =
+ payments_grpc::PaymentServiceAuthorizeOnlyRequest::foreign_try_from((
+ router_data,
+ call_connector_action,
+ ))
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct Payment Get 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,
+ granular_authorize_request,
+ header_payload,
+ |mut router_data, granular_authorize_request, grpc_headers| async move {
+ let response = Box::pin(client.payment_authorize_granular(
+ granular_authorize_request,
+ connector_auth_metadata,
+ grpc_headers,
+ ))
+ .await
+ .attach_printable("Failed to get payment")?;
+
+ let payment_authorize_response = response.into_inner();
+
+ let ucs_data = handle_unified_connector_service_response_for_payment_authorize(
+ payment_authorize_response.clone(),
+ )
+ .attach_printable("Failed to deserialize UCS 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.amount_captured = payment_authorize_response.captured_amount;
+ router_data.minor_amount_captured = payment_authorize_response
+ .minor_captured_amount
+ .map(MinorUnit::new);
+ 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_data.status_code);
+
+ ucs_data.connector_response.map(|customer_response| {
+ router_data.connector_response = Some(customer_response);
+ });
+
+ Ok((router_data, (), payment_authorize_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::CompleteAuthorizeData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ > for domain::CompleteAuthorize
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::CompleteAuthorizeData, types::PaymentsResponseData>,
+{
+ fn get_gateway(
+ execution_path: ExecutionPath,
+ ) -> Box<
+ dyn payment_gateway::PaymentGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::CompleteAuthorizeData,
+ 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/create_customer_gateway.rs b/crates/router/src/core/payments/gateway/create_customer_gateway.rs
index 1bd8c86168..7ca5a3fcfd 100644
--- a/crates/router/src/core/payments/gateway/create_customer_gateway.rs
+++ b/crates/router/src/core/payments/gateway/create_customer_gateway.rs
@@ -101,7 +101,7 @@ where
.external_vault_proxy_metadata(None)
.merchant_reference_id(None)
.lineage_ids(lineage_ids);
- let updated_router_data = Box::pin(unified_connector_service::ucs_logging_wrapper_new(
+ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
router_data.clone(),
state,
create_connector_customer_request,
@@ -126,13 +126,12 @@ where
router_data.response = connector_customer_result;
router_data.connector_http_status_code = Some(status_code);
- Ok((router_data, create_connector_customer_response))
+ Ok((router_data, (), create_connector_customer_response))
},
))
.await
- .change_context(ConnectorError::ResponseHandlingFailed)?;
-
- Ok(updated_router_data)
+ .map(|(router_data, _)| router_data)
+ .change_context(ConnectorError::ResponseHandlingFailed)
}
}
diff --git a/crates/router/src/core/payments/gateway/create_order_gateway.rs b/crates/router/src/core/payments/gateway/create_order_gateway.rs
index 7144b11a26..0d35a70021 100644
--- a/crates/router/src/core/payments/gateway/create_order_gateway.rs
+++ b/crates/router/src/core/payments/gateway/create_order_gateway.rs
@@ -105,7 +105,7 @@ where
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
- let updated_router_data = Box::pin(unified_connector_service::ucs_logging_wrapper_new(
+ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
router_data.clone(),
state,
create_order_request,
@@ -129,13 +129,12 @@ where
router_data.response = router_data_response;
router_data.connector_http_status_code = Some(status_code);
- Ok((router_data, create_order_response))
+ Ok((router_data, (), create_order_response))
},
))
.await
- .change_context(ConnectorError::ResponseHandlingFailed)?;
-
- Ok(updated_router_data)
+ .map(|(router_data, _)| router_data)
+ .change_context(ConnectorError::ResponseHandlingFailed)
}
}
diff --git a/crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rs b/crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rs
index 3fd3cc1c51..7948927cd0 100644
--- a/crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rs
+++ b/crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rs
@@ -113,7 +113,7 @@ where
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
- let updated_router_data = Box::pin(unified_connector_service::ucs_logging_wrapper_new(
+ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
router_data.clone(),
state,
pm_token_create_request,
@@ -138,13 +138,12 @@ where
router_data.response = router_data_response;
router_data.connector_http_status_code = Some(status_code);
- Ok((router_data, pm_token_create_response))
+ Ok((router_data, (), pm_token_create_response))
},
))
.await
- .change_context(ConnectorError::ResponseHandlingFailed)?;
-
- Ok(updated_router_data)
+ .map(|(router_data, _)| router_data)
+ .change_context(ConnectorError::ResponseHandlingFailed)
}
}
diff --git a/crates/router/src/core/payments/gateway/post_authenticate_gateway.rs b/crates/router/src/core/payments/gateway/post_authenticate_gateway.rs
new file mode 100644
index 0000000000..15b767c407
--- /dev/null
+++ b/crates/router/src/core/payments/gateway/post_authenticate_gateway.rs
@@ -0,0 +1,134 @@
+use async_trait::async_trait;
+use common_enums::{CallConnectorAction, ExecutionPath};
+use common_utils::{errors::CustomResult, request::Request};
+use hyperswitch_domain_models::{
+ router_data::RouterData, router_flow_types as domain, router_request_types,
+};
+use hyperswitch_interfaces::{
+ api::gateway as payment_gateway,
+ connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
+ errors::ConnectorError,
+};
+
+use crate::{
+ core::payments::{flows::complete_authorize_flow, gateway::context::RouterGatewayContext},
+ routes::SessionState,
+ types,
+};
+
+// =============================================================================
+// PaymentGateway Implementation for domain::PostAuthenticate
+// =============================================================================
+
+/// Implementation of PaymentGateway for api::PostAuthenticate flow
+#[async_trait]
+impl<RCD>
+ payment_gateway::PaymentGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PaymentsPostAuthenticateData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ (
+ RouterData<Self, types::PaymentsPostAuthenticateData, types::PaymentsResponseData>,
+ Option<router_request_types::UcsAuthenticationData>,
+ ),
+ > for domain::PostAuthenticate
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PaymentsPostAuthenticateData, types::PaymentsResponseData>,
+{
+ async fn execute(
+ self: Box<Self>,
+ state: &SessionState,
+ _connector_integration: BoxedConnectorIntegrationInterface<
+ Self,
+ RCD,
+ types::PaymentsPostAuthenticateData,
+ types::PaymentsResponseData,
+ >,
+ router_data: &RouterData<
+ Self,
+ types::PaymentsPostAuthenticateData,
+ types::PaymentsResponseData,
+ >,
+ _call_connector_action: CallConnectorAction,
+ _connector_request: Option<Request>,
+ _return_raw_connector_response: Option<bool>,
+ context: RouterGatewayContext,
+ ) -> CustomResult<
+ (
+ RouterData<Self, types::PaymentsPostAuthenticateData, types::PaymentsResponseData>,
+ Option<router_request_types::UcsAuthenticationData>,
+ ),
+ 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();
+ complete_authorize_flow::call_unified_connector_service_post_authenticate(
+ router_data,
+ state,
+ &header_payload,
+ lineage_ids,
+ merchant_connector_account,
+ &platform,
+ unified_connector_service_execution_mode,
+ merchant_order_reference_id,
+ )
+ .await
+ }
+}
+
+/// 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::PaymentsPostAuthenticateData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ (
+ RouterData<Self, types::PaymentsPostAuthenticateData, types::PaymentsResponseData>,
+ Option<router_request_types::UcsAuthenticationData>,
+ ),
+ > for domain::PostAuthenticate
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PaymentsPostAuthenticateData, types::PaymentsResponseData>,
+{
+ fn get_gateway(
+ execution_path: ExecutionPath,
+ ) -> Box<
+ dyn payment_gateway::PaymentGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PaymentsPostAuthenticateData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ (
+ RouterData<Self, types::PaymentsPostAuthenticateData, types::PaymentsResponseData>,
+ Option<router_request_types::UcsAuthenticationData>,
+ ),
+ >,
+ > {
+ 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/pre_authenticate_gateway.rs b/crates/router/src/core/payments/gateway/pre_authenticate_gateway.rs
new file mode 100644
index 0000000000..c9febe38e6
--- /dev/null
+++ b/crates/router/src/core/payments/gateway/pre_authenticate_gateway.rs
@@ -0,0 +1,126 @@
+use std::str::FromStr;
+
+use async_trait::async_trait;
+use common_enums::{CallConnectorAction, ExecutionPath};
+use common_utils::{errors::CustomResult, request::Request};
+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 crate::{
+ core::payments::{flows::authorize_flow, gateway::context::RouterGatewayContext},
+ routes::SessionState,
+ types,
+};
+
+// =============================================================================
+// PaymentGateway Implementation for domain::PreAuthenticate
+// =============================================================================
+
+/// Implementation of PaymentGateway for api::PSync flow
+#[async_trait]
+impl<RCD>
+ payment_gateway::PaymentGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PaymentsPreAuthenticateData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ > for domain::PreAuthenticate
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PaymentsPreAuthenticateData, types::PaymentsResponseData>,
+{
+ async fn execute(
+ self: Box<Self>,
+ state: &SessionState,
+ _connector_integration: BoxedConnectorIntegrationInterface<
+ Self,
+ RCD,
+ types::PaymentsPreAuthenticateData,
+ types::PaymentsResponseData,
+ >,
+ router_data: &RouterData<
+ Self,
+ types::PaymentsPreAuthenticateData,
+ types::PaymentsResponseData,
+ >,
+ _call_connector_action: CallConnectorAction,
+ _connector_request: Option<Request>,
+ _return_raw_connector_response: Option<bool>,
+ context: RouterGatewayContext,
+ ) -> CustomResult<
+ RouterData<Self, types::PaymentsPreAuthenticateData, 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 connector_enum =
+ common_enums::connector_enums::Connector::from_str(&router_data.connector)
+ .change_context(ConnectorError::InvalidConnectorName)
+ .attach_printable("Invalid connector name")?;
+ authorize_flow::call_unified_connector_service_pre_authenticate(
+ router_data,
+ state,
+ &header_payload,
+ lineage_ids,
+ merchant_connector_account,
+ &platform,
+ connector_enum,
+ unified_connector_service_execution_mode,
+ merchant_order_reference_id,
+ )
+ .await
+ .map(|(router_data, _)| router_data)
+ }
+}
+
+/// 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::PaymentsPreAuthenticateData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ > for domain::PreAuthenticate
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::PaymentsPreAuthenticateData, types::PaymentsResponseData>,
+{
+ fn get_gateway(
+ execution_path: ExecutionPath,
+ ) -> Box<
+ dyn payment_gateway::PaymentGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::PaymentsPreAuthenticateData,
+ 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/psync_gateway.rs b/crates/router/src/core/payments/gateway/psync_gateway.rs
index ac861ef72f..361e593ad3 100644
--- a/crates/router/src/core/payments/gateway/psync_gateway.rs
+++ b/crates/router/src/core/payments/gateway/psync_gateway.rs
@@ -129,7 +129,7 @@ where
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
let connector_name = router_data.connector.clone();
- let updated_router_data = Box::pin(unified_connector_service::ucs_logging_wrapper_new(
+ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
router_data.clone(),
state,
payment_get_request,
@@ -194,13 +194,12 @@ where
.map(|raw_connector_response| raw_connector_response.expose().into());
router_data.connector_http_status_code = Some(status_code);
- Ok((router_data, payment_get_response))
+ Ok((router_data, (), payment_get_response))
},
))
.await
- .change_context(ConnectorError::ResponseHandlingFailed)?;
-
- Ok(updated_router_data)
+ .map(|(router_data, _)| router_data)
+ .change_context(ConnectorError::ResponseHandlingFailed)
}
}
diff --git a/crates/router/src/core/payments/gateway/session_gateway.rs b/crates/router/src/core/payments/gateway/session_gateway.rs
index f5fc73b872..faf4cc1768 100644
--- a/crates/router/src/core/payments/gateway/session_gateway.rs
+++ b/crates/router/src/core/payments/gateway/session_gateway.rs
@@ -105,36 +105,38 @@ where
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
- let updated_router_data = Box::pin(unified_connector_service::ucs_logging_wrapper_new(
- router_data.clone(),
- state,
- sdk_session_token_request,
- header_payload,
- |mut router_data, sdk_session_token_request, grpc_headers| async move {
- let response = Box::pin(client.sdk_session_token(
- sdk_session_token_request,
- connector_auth_metadata,
- grpc_headers,
- ))
- .await
- .attach_printable("Failed to get payment")?;
+ let updated_router_data =
+ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
+ router_data.clone(),
+ state,
+ sdk_session_token_request,
+ header_payload,
+ |mut router_data, sdk_session_token_request, grpc_headers| async move {
+ let response = Box::pin(client.sdk_session_token(
+ sdk_session_token_request,
+ connector_auth_metadata,
+ grpc_headers,
+ ))
+ .await
+ .attach_printable("Failed to get payment")?;
- let sdk_session_token_response = response.into_inner();
+ let sdk_session_token_response = response.into_inner();
- let (router_data_response, status_code) =
- handle_unified_connector_service_response_for_sdk_session_token(
- sdk_session_token_response.clone(),
- )
- .attach_printable("Failed to deserialize UCS response")?;
+ let (router_data_response, status_code) =
+ handle_unified_connector_service_response_for_sdk_session_token(
+ sdk_session_token_response.clone(),
+ )
+ .attach_printable("Failed to deserialize UCS response")?;
- router_data.response = router_data_response;
- router_data.connector_http_status_code = Some(status_code);
+ router_data.response = router_data_response;
+ router_data.connector_http_status_code = Some(status_code);
- Ok((router_data, sdk_session_token_response))
- },
- ))
- .await
- .change_context(ConnectorError::ResponseHandlingFailed)?;
+ Ok((router_data, (), sdk_session_token_response))
+ },
+ ))
+ .await
+ .map(|(router_data, _)| router_data)
+ .change_context(ConnectorError::ResponseHandlingFailed)?;
Ok(updated_router_data)
}
diff --git a/crates/router/src/core/payments/gateway/session_token_gateway.rs b/crates/router/src/core/payments/gateway/session_token_gateway.rs
index cce70030d2..0643f7f492 100644
--- a/crates/router/src/core/payments/gateway/session_token_gateway.rs
+++ b/crates/router/src/core/payments/gateway/session_token_gateway.rs
@@ -108,7 +108,7 @@ where
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
- let updated_router_data = Box::pin(unified_connector_service::ucs_logging_wrapper_new(
+ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
router_data.clone(),
state,
authorize_session_token_request,
@@ -133,13 +133,12 @@ where
router_data.response = router_data_response;
router_data.connector_http_status_code = Some(status_code);
- Ok((router_data, payment_session_token_response))
+ Ok((router_data, (), payment_session_token_response))
},
))
.await
- .change_context(ConnectorError::ResponseHandlingFailed)?;
-
- Ok(updated_router_data)
+ .map(|(router_data, _)| router_data)
+ .change_context(ConnectorError::ResponseHandlingFailed)
}
}
diff --git a/crates/router/src/core/payments/gateway/setup_mandate.rs b/crates/router/src/core/payments/gateway/setup_mandate.rs
index 08872b980b..6a0d7f013a 100644
--- a/crates/router/src/core/payments/gateway/setup_mandate.rs
+++ b/crates/router/src/core/payments/gateway/setup_mandate.rs
@@ -103,7 +103,7 @@ where
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
- let updated_router_data = Box::pin(unified_connector_service::ucs_logging_wrapper_new(
+ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
router_data.clone(),
state,
setup_mandate_request,
@@ -137,13 +137,12 @@ where
router_data.connector_customer = Some(connector_customer_id);
});
- Ok((router_data, setup_mandate_response))
+ Ok((router_data, (), setup_mandate_response))
},
))
.await
- .change_context(ConnectorError::ResponseHandlingFailed)?;
-
- Ok(updated_router_data)
+ .map(|(router_data, _)| router_data)
+ .change_context(ConnectorError::ResponseHandlingFailed)
}
}
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index e40e556f4d..3042d91153 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -6082,6 +6082,12 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz
minor_amount: amount,
currency: payment_data.currency,
browser_info,
+ request_incremental_authorization: matches!(
+ payment_data
+ .payment_intent
+ .request_incremental_authorization,
+ Some(RequestIncrementalAuthorization::True)
+ ),
email: payment_data.email,
payment_method_data: payment_data.payment_method_data,
connector_transaction_id: payment_data
diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs
index 6b20823e1b..00d090b2d9 100644
--- a/crates/router/src/core/unified_connector_service.rs
+++ b/crates/router/src/core/unified_connector_service.rs
@@ -1540,13 +1540,13 @@ where
/// This function wraps UCS calls with comprehensive event logging.
/// It logs the actual gRPC request/response data, timing, and error information.
#[instrument(skip_all, fields(connector_name, flow_type, payment_id))]
-pub async fn ucs_logging_wrapper_new<T, F, Fut, Req, Resp, GrpcReq, GrpcResp>(
+pub async fn ucs_logging_wrapper_granular<T, F, Fut, Req, Resp, GrpcReq, FlowOutput, GrpcResp>(
router_data: RouterData<T, Req, Resp>,
state: &SessionState,
grpc_request: GrpcReq,
grpc_header_builder: external_services::grpc_client::GrpcHeadersUcsBuilderFinal,
handler: F,
-) -> CustomResult<RouterData<T, Req, Resp>, UnifiedConnectorServiceError>
+) -> CustomResult<(RouterData<T, Req, Resp>, FlowOutput), UnifiedConnectorServiceError>
where
T: std::fmt::Debug + Clone + Send + 'static,
Req: std::fmt::Debug + Clone + Send + Sync + 'static,
@@ -1561,7 +1561,7 @@ where
+ Send,
Fut: std::future::Future<
Output = CustomResult<
- (RouterData<T, Req, Resp>, GrpcResp),
+ (RouterData<T, Req, Resp>, FlowOutput, GrpcResp),
UnifiedConnectorServiceError,
>,
> + Send,
@@ -1603,7 +1603,7 @@ where
// Create and emit connector event after UCS call
let (status_code, response_body, router_result) = match result {
- Ok((updated_router_data, grpc_response)) => {
+ Ok((updated_router_data, flow_output, grpc_response)) => {
let status = updated_router_data
.connector_http_status_code
.unwrap_or(200);
@@ -1613,7 +1613,11 @@ where
|_| serde_json::json!({"error": "failed_to_serialize_grpc_response"}),
);
- (status, Some(grpc_response_body), Ok(updated_router_data))
+ (
+ status,
+ Some(grpc_response_body),
+ Ok((updated_router_data, flow_output)),
+ )
}
Err(error) => {
// Update error metrics for UCS calls
@@ -1663,8 +1667,8 @@ where
// 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.0.external_latency =
+ Some(router_data.0.external_latency.unwrap_or(0) + external_latency);
router_data
})
}
diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs
index c62261f408..a7eb0c3663 100644
--- a/crates/router/src/core/unified_connector_service/transformers.rs
+++ b/crates/router/src/core/unified_connector_service/transformers.rs
@@ -383,6 +383,169 @@ impl
}
}
+impl
+ transformers::ForeignTryFrom<(
+ &RouterData<
+ api::CompleteAuthorize,
+ router_request_types::CompleteAuthorizeData,
+ PaymentsResponseData,
+ >,
+ common_enums::CallConnectorAction,
+ )> for payments_grpc::PaymentServiceAuthorizeOnlyRequest
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ (router_data, _call_connector_action): (
+ &RouterData<
+ api::CompleteAuthorize,
+ router_request_types::CompleteAuthorizeData,
+ PaymentsResponseData,
+ >,
+ common_enums::CallConnectorAction,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let currency = payments_grpc::Currency::foreign_try_from(router_data.request.currency)?;
+
+ let payment_method = router_data
+ .request
+ .payment_method_data
+ .clone()
+ .map(|payment_method_data| {
+ unified_connector_service::build_unified_connector_service_payment_method(
+ payment_method_data,
+ router_data.request.payment_method_type,
+ )
+ })
+ .transpose()?;
+
+ let address = payments_grpc::PaymentAddress::foreign_try_from(router_data.address.clone())?;
+
+ let auth_type = payments_grpc::AuthenticationType::foreign_try_from(router_data.auth_type)?;
+
+ let browser_info = router_data
+ .request
+ .browser_info
+ .clone()
+ .map(payments_grpc::BrowserInformation::foreign_try_from)
+ .transpose()?;
+
+ let capture_method = router_data
+ .request
+ .capture_method
+ .map(payments_grpc::CaptureMethod::foreign_try_from)
+ .transpose()?;
+
+ let authentication_data = router_data
+ .request
+ .authentication_data
+ .clone()
+ .map(payments_grpc::AuthenticationData::foreign_try_from)
+ .transpose()?;
+ let merchant_account_metadata = router_data
+ .connector_meta_data
+ .as_ref()
+ .and_then(|val| val.peek().as_object())
+ .map(|map| {
+ map.iter()
+ .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
+ .collect::<HashMap<String, String>>()
+ })
+ .unwrap_or_default();
+ let metadata = router_data
+ .request
+ .metadata
+ .as_ref()
+ .and_then(|val| val.as_object())
+ .map(|map| {
+ map.iter()
+ .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
+ .collect::<HashMap<String, String>>()
+ })
+ .unwrap_or_default();
+ let setup_future_usage = router_data
+ .request
+ .setup_future_usage
+ .map(payments_grpc::FutureUsage::foreign_try_from)
+ .transpose()?;
+
+ let customer_acceptance = router_data
+ .request
+ .customer_acceptance
+ .clone()
+ .map(payments_grpc::CustomerAcceptance::foreign_try_from)
+ .transpose()?;
+
+ let state = router_data
+ .access_token
+ .as_ref()
+ .map(ConnectorState::foreign_from);
+
+ Ok(Self {
+ order_id: None,
+ amount: router_data.request.amount,
+ currency: currency.into(),
+ payment_method,
+ return_url: router_data.request.router_return_url.clone(),
+ address: Some(address),
+ auth_type: auth_type.into(),
+ enrolled_for_3ds: true,
+ request_incremental_authorization: router_data
+ .request
+ .request_incremental_authorization,
+ minor_amount: router_data.request.amount,
+ email: router_data
+ .request
+ .email
+ .clone()
+ .map(|e| e.expose().expose().into()),
+ browser_info,
+
+ session_token: router_data.session_token.clone(),
+ order_tax_amount: None,
+ customer_name: None,
+ capture_method: capture_method.map(|capture_method| capture_method.into()),
+ webhook_url: None,
+ complete_authorize_url: router_data.request.complete_authorize_url.clone(),
+ setup_future_usage: setup_future_usage.map(|s| s.into()),
+ off_session: router_data.request.off_session,
+ customer_acceptance,
+ order_category: None,
+ payment_experience: None,
+ authentication_data,
+ request_extended_authorization: None,
+ merchant_order_reference_id: None,
+ shipping_cost: None,
+ request_ref_id: Some(Identifier {
+ id_type: Some(payments_grpc::identifier::IdType::Id(
+ router_data.connector_request_reference_id.clone(),
+ )),
+ }),
+ customer_id: None,
+ metadata,
+ test_mode: router_data.test_mode,
+ connector_customer_id: router_data.connector_customer.clone(),
+ state,
+ payment_method_token: router_data
+ .payment_method_token
+ .as_ref()
+ .and_then(|pmt| pmt.get_payment_method_token())
+ .map(ExposeInterface::expose),
+ merchant_account_metadata,
+ description: router_data.description.clone(),
+ setup_mandate_details: router_data
+ .request
+ .setup_mandate_details
+ .as_ref()
+ .map(payments_grpc::SetupMandateDetails::foreign_try_from)
+ .transpose()?,
+ statement_descriptor_name: None,
+ statement_descriptor_suffix: None,
+ order_details: vec![],
+ })
+ }
+}
+
impl
transformers::ForeignTryFrom<
&RouterData<