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: Added HS<>UCS create_connector_customer flow support and populated router_data fields received from UCS (#9984)

Amitsingh Tanwar82458387b99e
diff --git a/Cargo.lock b/Cargo.lock
index ceeb9451a5..02b0037dd2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4418,6 +4418,7 @@ dependencies = [
"async-trait",
"bytes 1.10.1",
"common_enums",
+ "common_types",
"common_utils",
"dyn-clone",
"error-stack 0.4.1",
diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.toml
index 043793acf6..d7c08f3423 100644
--- a/crates/hyperswitch_interfaces/Cargo.toml
+++ b/crates/hyperswitch_interfaces/Cargo.toml
@@ -37,6 +37,7 @@ hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_m
masking = { version = "0.1.0", path = "../masking" }
api_models = { version = "0.1.0", path = "../api_models" }
common_enums = { version = "0.1.0", path = "../common_enums" }
+common_types = { version = "0.1.0", path = "../common_types" }
common_utils = { version = "0.1.0", path = "../common_utils" }
router_env = { version = "0.1.0", path = "../router_env" }
diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
index fbadb7470c..4b0fce8fba 100644
--- a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
@@ -1,6 +1,11 @@
use common_enums::AttemptStatus;
+use common_types::primitive_wrappers::{ExtendedAuthorizationAppliedBool, OvercaptureEnabledBool};
use hyperswitch_domain_models::{
- router_data::ErrorResponse, router_response_types::PaymentsResponseData,
+ router_data::{
+ AdditionalPaymentMethodConnectorResponse, ConnectorResponseData, ErrorResponse,
+ ExtendedAuthorizationResponseData,
+ },
+ router_response_types::PaymentsResponseData,
};
use crate::{helpers::ForeignTryFrom, unified_connector_service::payments_grpc};
@@ -243,6 +248,82 @@ impl ForeignTryFrom<payments_grpc::PaymentStatus> for AttemptStatus {
}
}
+// Transformer for ConnectorResponseData from UCS proto to Hyperswitch domain type
+impl ForeignTryFrom<payments_grpc::ConnectorResponseData> for ConnectorResponseData {
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(value: payments_grpc::ConnectorResponseData) -> Result<Self, Self::Error> {
+ // Extract additional_payment_method_data
+ let additional_payment_method_data = value
+ .additional_payment_method_data
+ .map(AdditionalPaymentMethodConnectorResponse::foreign_try_from)
+ .transpose()?;
+
+ let extended_authorization_response_data =
+ value.extended_authorization_response_data.map(|data| {
+ ExtendedAuthorizationResponseData {
+ capture_before: data
+ .capture_before
+ .and_then(|ts| time::OffsetDateTime::from_unix_timestamp(ts).ok())
+ .map(|offset_dt| {
+ time::PrimitiveDateTime::new(offset_dt.date(), offset_dt.time())
+ }),
+ extended_authentication_applied: data
+ .extended_authentication_applied
+ .map(ExtendedAuthorizationAppliedBool::from),
+ }
+ });
+
+ let is_overcapture_enabled = value
+ .is_overcapture_enabled
+ .map(OvercaptureEnabledBool::new);
+
+ Ok(Self::new(
+ additional_payment_method_data,
+ is_overcapture_enabled,
+ extended_authorization_response_data,
+ ))
+ }
+}
+
+// Transformer for AdditionalPaymentMethodConnectorResponse
+impl ForeignTryFrom<payments_grpc::AdditionalPaymentMethodConnectorResponse>
+ for AdditionalPaymentMethodConnectorResponse
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ value: payments_grpc::AdditionalPaymentMethodConnectorResponse,
+ ) -> Result<Self, Self::Error> {
+ let card_data = value.card.unwrap_or_default();
+
+ Ok(Self::Card {
+ authentication_data: card_data.authentication_data.and_then(|data| {
+ serde_json::from_slice(&data)
+ .inspect_err(|e| {
+ router_env::logger::warn!(
+ deserialization_error=?e,
+ "Failed to deserialize authentication_data from UCS connector response"
+ );
+ })
+ .ok()
+ }),
+ payment_checks: card_data.payment_checks.and_then(|data| {
+ serde_json::from_slice(&data)
+ .inspect_err(|e| {
+ router_env::logger::warn!(
+ deserialization_error=?e,
+ "Failed to deserialize payment_checks from UCS connector response"
+ );
+ })
+ .ok()
+ }),
+ card_network: card_data.card_network,
+ domestic_network: card_data.domestic_network,
+ })
+ }
+}
+
#[allow(missing_docs)]
pub fn convert_connector_service_status_code(
status_code: u32,
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index f1654ae984..e77f5b51f1 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -973,14 +973,13 @@ async fn call_unified_connector_service_authorize(
let payment_authorize_response = response.into_inner();
- let (router_data_response, status_code) =
- handle_unified_connector_service_response_for_payment_authorize(
- payment_authorize_response.clone(),
- )
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to deserialize UCS response")?;
+ let ucs_data = 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 = router_data_response.map(|(response, status)| {
+ let router_data_response = ucs_data.router_data_response.map(|(response, status)| {
router_data.status = status;
response
});
@@ -989,7 +988,16 @@ async fn call_unified_connector_service_authorize(
.raw_connector_response
.clone()
.map(|raw_connector_response| raw_connector_response.expose().into());
- router_data.connector_http_status_code = Some(status_code);
+ 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(|customer_response| {
+ router_data.connector_response = Some(customer_response);
+ });
Ok((router_data, payment_authorize_response))
},
@@ -1159,14 +1167,13 @@ async fn call_unified_connector_service_repeat_payment(
let payment_repeat_response = response.into_inner();
- let (router_data_response, status_code) =
- handle_unified_connector_service_response_for_payment_repeat(
- payment_repeat_response.clone(),
- )
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to deserialize UCS response")?;
+ let ucs_data = handle_unified_connector_service_response_for_payment_repeat(
+ payment_repeat_response.clone(),
+ )
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to deserialize UCS response")?;
- let router_data_response = router_data_response.map(|(response, status)| {
+ let router_data_response = ucs_data.router_data_response.map(|(response, status)| {
router_data.status = status;
response
});
@@ -1175,7 +1182,17 @@ async fn call_unified_connector_service_repeat_payment(
.raw_connector_response
.clone()
.map(|raw_connector_response| raw_connector_response.expose().into());
- router_data.connector_http_status_code = Some(status_code);
+ 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);
+ });
+
+ // Populate connector_response if present
+ ucs_data.connector_response.map(|connector_response| {
+ router_data.connector_response = Some(connector_response);
+ });
Ok((router_data, payment_repeat_response))
},
diff --git a/crates/router/src/core/payments/flows/external_proxy_flow.rs b/crates/router/src/core/payments/flows/external_proxy_flow.rs
index c1617c3c7b..3c8437d8d6 100644
--- a/crates/router/src/core/payments/flows/external_proxy_flow.rs
+++ b/crates/router/src/core/payments/flows/external_proxy_flow.rs
@@ -436,14 +436,14 @@ impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>
let payment_authorize_response = response.into_inner();
- let (router_data_response, status_code) =
+ let ucs_data =
unified_connector_service::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 = router_data_response.map(|(response, status)|{
+ let router_data_response = ucs_data.router_data_response.map(|(response, status)|{
router_data.status = status;
response
});
@@ -452,7 +452,7 @@ impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>
.raw_connector_response
.clone()
.map(|raw_connector_response| raw_connector_response.expose().into());
- router_data.connector_http_status_code = Some(status_code);
+ router_data.connector_http_status_code = Some(ucs_data.status_code);
Ok((router_data, payment_authorize_response))
}
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 752441bc44..a9336b2f37 100644
--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs
+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
@@ -342,19 +342,24 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup
let payment_register_response = response.into_inner();
- let (router_data_response, status_code) =
- handle_unified_connector_service_response_for_payment_register(
- payment_register_response.clone(),
- )
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to deserialize UCS response")?;
+ 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")?;
- let router_data_response = router_data_response.map(|(response, status)| {
- router_data.status = status;
- 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(status_code);
+ 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);
+ });
Ok((router_data, payment_register_response))
},
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index dc07123537..afdeca19ba 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -34,6 +34,7 @@ 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")]
use hyperswitch_domain_models::payments::payment_intent::CustomerData;
use hyperswitch_domain_models::{
@@ -74,7 +75,7 @@ use super::{
#[cfg(feature = "v1")]
use crate::core::{
payments::{
- call_connector_service,
+ call_connector_service, customers,
flows::{ConstructFlowSpecificData, Feature},
operations::ValidateResult as OperationsValidateResult,
should_add_task_to_process_tracker, OperationSessionGetters, OperationSessionSetters,
@@ -83,6 +84,7 @@ use crate::core::{
unified_connector_service::{
send_comparison_data, update_gateway_system_in_feature_metadata, ComparisonData,
},
+ utils as core_utils,
};
#[cfg(feature = "v1")]
use crate::routes;
@@ -7967,6 +7969,273 @@ pub fn is_stored_credential(
}
}
+#[cfg(feature = "v1")]
+/// Helper function to get the connector label used for storing connector_customer_id
+/// Returns None if the merchant_connector_account ID is not present
+pub fn get_connector_label_for_customer<F, D>(
+ merchant_connector_account: &MerchantConnectorAccountType,
+ payment_data: &D,
+) -> Option<String>
+where
+ D: OperationSessionGetters<F>,
+{
+ // Get connector name from payment attempt
+ let connector_name = payment_data.get_payment_attempt().connector.as_ref()?;
+
+ // Generate the connector_label using the same logic as when storing connector_customer_id
+ let connector_label = core_utils::get_connector_label(
+ payment_data.get_payment_intent().business_country,
+ payment_data.get_payment_intent().business_label.as_ref(),
+ payment_data
+ .get_payment_attempt()
+ .business_sub_label
+ .as_ref(),
+ connector_name,
+ );
+
+ // Use the same priority as in call_create_connector_customer_if_required
+ // 1. Try merchant_connector_account ID first
+ // 2. Try the dynamically generated connector_label
+ // 3. Fallback to format!("{connector_name}_{profile_id}")
+ if let Some(connector_label) = merchant_connector_account
+ .get_mca_id()
+ .map(|mca_id| mca_id.get_string_repr().to_string())
+ .or(connector_label)
+ {
+ Some(connector_label)
+ } else {
+ // Fallback to connector_name_profileId
+ payment_data
+ .get_payment_intent()
+ .profile_id
+ .as_ref()
+ .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>,
+ merchant_context: &domain::MerchantContext,
+ 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,
+ merchant_context,
+ 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>,
+ merchant_context: &domain::MerchantContext,
+ 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(
+ &state.into(),
+ customer_data.customer_id.clone(),
+ customer_data.merchant_id.clone(),
+ customer_data.clone(),
+ update,
+ merchant_context.get_merchant_key_store(),
+ merchant_context.get_merchant_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)]
@@ -8068,6 +8337,32 @@ where
)
.await?;
+ // 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
@@ -8085,6 +8380,30 @@ where
.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,
+ merchant_context,
+ 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))
}
@@ -8213,6 +8532,10 @@ where
.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);
+
// 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();
@@ -8220,6 +8543,13 @@ where
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_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(),
@@ -8266,8 +8596,19 @@ where
unified_connector_service_merchant_context,
unified_connector_service_merchant_order_reference_id,
call_connector_action,
+ 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()
});
Ok(result)
@@ -8288,13 +8629,32 @@ pub async fn execute_shadow_unified_connector_service_call<F, RouterDReq>(
merchant_context: domain::MerchantContext,
merchant_order_reference_id: Option<String>,
call_connector_action: CallConnectorAction,
-) where
+ 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(
@@ -8319,8 +8679,14 @@ pub async fn execute_shadow_unified_connector_service_call<F, RouterDReq>(
)
.await
{
- Ok(_) => router_env::logger::debug!("Shadow UCS comparison completed successfully"),
- Err(e) => router_env::logger::debug!("Shadow UCS comparison failed: {:?}", e),
+ Ok(_) => {
+ router_env::logger::debug!("Shadow UCS comparison completed successfully");
+ Ok(())
+ }
+ Err(e) => {
+ router_env::logger::debug!("Shadow UCS comparison failed: {:?}", e);
+ Ok(())
+ }
}
}
diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs
index d8aef22f6d..3aa77c591a 100644
--- a/crates/router/src/core/unified_connector_service.rs
+++ b/crates/router/src/core/unified_connector_service.rs
@@ -61,7 +61,10 @@ use crate::{
events::connector_api_logs::ConnectorEvent,
headers::{CONTENT_TYPE, X_REQUEST_ID},
routes::SessionState,
- types::transformers::ForeignTryFrom,
+ types::{
+ transformers::ForeignTryFrom, UcsAuthorizeResponseData, UcsRepeatPaymentResponseData,
+ UcsSetupMandateResponseData,
+ },
};
pub mod transformers;
@@ -854,13 +857,25 @@ pub fn build_unified_connector_service_external_vault_proxy_metadata(
pub fn handle_unified_connector_service_response_for_payment_authorize(
response: PaymentServiceAuthorizeResponse,
-) -> UnifiedConnectorServiceResult {
+) -> CustomResult<UcsAuthorizeResponseData, UnifiedConnectorServiceError> {
let status_code = transformers::convert_connector_service_status_code(response.status_code)?;
let router_data_response =
- Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(response)?;
+ Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(
+ response.clone(),
+ )?;
- Ok((router_data_response, status_code))
+ let connector_customer_id =
+ extract_connector_customer_id_from_ucs_state(response.state.as_ref());
+ let connector_response =
+ extract_connector_response_from_ucs(response.connector_response.as_ref());
+
+ Ok(UcsAuthorizeResponseData {
+ router_data_response,
+ status_code,
+ connector_customer_id,
+ connector_response,
+ })
}
pub fn handle_unified_connector_service_response_for_payment_pre_authenticate(
@@ -887,24 +902,74 @@ pub fn handle_unified_connector_service_response_for_payment_capture(
pub fn handle_unified_connector_service_response_for_payment_register(
response: payments_grpc::PaymentServiceRegisterResponse,
-) -> UnifiedConnectorServiceResult {
+) -> CustomResult<UcsSetupMandateResponseData, UnifiedConnectorServiceError> {
let status_code = transformers::convert_connector_service_status_code(response.status_code)?;
let router_data_response =
- Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(response)?;
+ Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(
+ response.clone(),
+ )?;
- Ok((router_data_response, status_code))
+ let connector_customer_id =
+ extract_connector_customer_id_from_ucs_state(response.state.as_ref());
+
+ Ok(UcsSetupMandateResponseData {
+ router_data_response,
+ status_code,
+ connector_customer_id,
+ })
}
pub fn handle_unified_connector_service_response_for_payment_repeat(
response: payments_grpc::PaymentServiceRepeatEverythingResponse,
-) -> UnifiedConnectorServiceResult {
+) -> CustomResult<UcsRepeatPaymentResponseData, UnifiedConnectorServiceError> {
let status_code = transformers::convert_connector_service_status_code(response.status_code)?;
let router_data_response =
- Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(response)?;
+ Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(
+ response.clone(),
+ )?;
- Ok((router_data_response, status_code))
+ let connector_customer_id =
+ extract_connector_customer_id_from_ucs_state(response.state.as_ref());
+ let connector_response =
+ extract_connector_response_from_ucs(response.connector_response.as_ref());
+
+ Ok(UcsRepeatPaymentResponseData {
+ router_data_response,
+ status_code,
+ connector_customer_id,
+ connector_response,
+ })
+}
+
+/// Extracts connector_customer_id from UCS state
+pub fn extract_connector_customer_id_from_ucs_state(
+ ucs_state: Option<&payments_grpc::ConnectorState>,
+) -> Option<String> {
+ ucs_state.and_then(|state| {
+ state
+ .connector_customer_id
+ .as_ref()
+ .map(|id| id.to_string())
+ })
+}
+
+/// Extracts connector_response from UCS response
+pub fn extract_connector_response_from_ucs(
+ connector_response: Option<&payments_grpc::ConnectorResponseData>,
+) -> Option<hyperswitch_domain_models::router_data::ConnectorResponseData> {
+ connector_response.and_then(|data| {
+ <hyperswitch_domain_models::router_data::ConnectorResponseData as hyperswitch_interfaces::helpers::ForeignTryFrom<payments_grpc::ConnectorResponseData>>::foreign_try_from(data.clone())
+ .map_err(|e| {
+ logger::warn!(
+ error=?e,
+ "Failed to deserialize connector_response from UCS"
+ );
+ e
+ })
+ .ok()
+ })
}
pub fn handle_unified_connector_service_response_for_payment_cancel(
diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs
index eefc4e6d11..3be51f7bce 100644
--- a/crates/router/src/core/unified_connector_service/transformers.rs
+++ b/crates/router/src/core/unified_connector_service/transformers.rs
@@ -350,6 +350,19 @@ impl
connector_metadata_string
.map(|connector_metadata| ("connector_meta_data".to_string(), connector_metadata)),
);
+ 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()?;
+
Ok(Self {
amount: router_data.request.amount,
currency: currency.into(),
@@ -382,9 +395,9 @@ impl
capture_method: capture_method.map(|capture_method| capture_method.into()),
webhook_url: router_data.request.webhook_url.clone(),
complete_authorize_url: router_data.request.complete_authorize_url.clone(),
- setup_future_usage: None,
- off_session: None,
- customer_acceptance: None,
+ setup_future_usage: setup_future_usage.map(|s| s.into()),
+ off_session: router_data.request.off_session,
+ customer_acceptance,
order_category: router_data.request.order_category.clone(),
payment_experience: None,
authentication_data,
@@ -466,6 +479,19 @@ impl
.map(payments_grpc::AuthenticationData::foreign_try_from)
.transpose()?;
+ 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()?;
+
Ok(Self {
amount: router_data.request.amount,
currency: currency.into(),
@@ -498,9 +524,9 @@ impl
capture_method: capture_method.map(|capture_method| capture_method.into()),
webhook_url: router_data.request.webhook_url.clone(),
complete_authorize_url: router_data.request.complete_authorize_url.clone(),
- setup_future_usage: None,
- off_session: None,
- customer_acceptance: None,
+ setup_future_usage: setup_future_usage.map(|s| s.into()),
+ off_session: router_data.request.off_session,
+ customer_acceptance,
order_category: router_data.request.order_category.clone(),
payment_experience: None,
authentication_data,
@@ -882,7 +908,7 @@ impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceAuthorizeResponse
}
};
- let (connector_metadata, redirection_data) = match response.redirection_data.clone() {
+ let (mut connector_metadata, redirection_data) = match response.redirection_data.clone() {
Some(redirection_data) => match redirection_data.form_type {
Some(ref form_type) => match form_type {
payments_grpc::redirect_form::FormType::Uri(uri) => {
@@ -908,6 +934,20 @@ impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceAuthorizeResponse
None => (None, None),
};
+ // Extract connector_metadata from response if present and not already set by UPI intent handling
+ if connector_metadata.is_none() && !response.connector_metadata.is_empty() {
+ connector_metadata = serde_json::to_value(&response.connector_metadata)
+ .map_err(|e| {
+ tracing::warn!(
+ serialization_error=?e,
+ metadata=?response.connector_metadata,
+ "Failed to serialize connector_metadata from UCS response"
+ );
+ e
+ })
+ .ok();
+ }
+
let status_code = convert_connector_service_status_code(response.status_code)?;
let response = if response.error_code.is_some() {
@@ -935,7 +975,14 @@ impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceAuthorizeResponse
PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data: Box::new(redirection_data),
- mandate_reference: Box::new(None),
+ mandate_reference: Box::new(response.mandate_reference.map(|grpc_mandate| {
+ hyperswitch_domain_models::router_response_types::MandateReference {
+ connector_mandate_id: grpc_mandate.mandate_id,
+ payment_method_id: grpc_mandate.payment_method_id,
+ mandate_metadata: None,
+ connector_mandate_request_reference_id: None,
+ }
+ })),
connector_metadata,
network_txn_id: response.network_txn_id.clone(),
connector_response_reference_id,
@@ -1170,6 +1217,22 @@ impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceRepeatEverythingR
let status_code = convert_connector_service_status_code(response.status_code)?;
+ // Extract connector_metadata from response if present
+ let connector_metadata = (!response.connector_metadata.is_empty())
+ .then(|| {
+ serde_json::to_value(&response.connector_metadata)
+ .map_err(|e| {
+ tracing::warn!(
+ serialization_error=?e,
+ metadata=?response.connector_metadata,
+ "Failed to serialize connector_metadata from UCS repeat payment response"
+ );
+ e
+ })
+ .ok()
+ })
+ .flatten();
+
let response = if response.error_code.is_some() {
let attempt_status = match response.status() {
payments_grpc::PaymentStatus::AttemptStatusUnspecified => None,
@@ -1202,7 +1265,7 @@ impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceRepeatEverythingR
},
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
- connector_metadata: None,
+ connector_metadata,
network_txn_id: response.network_txn_id.clone(),
connector_response_reference_id,
incremental_authorization_allowed: None,
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index d0d30db0a4..2cff2a4d02 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -721,6 +721,30 @@ pub struct PspTokenResult {
pub token: Result<String, ErrorResponse>,
}
+/// Data extracted from UCS response
+pub struct UcsAuthorizeResponseData {
+ pub router_data_response:
+ Result<(PaymentsResponseData, common_enums::AttemptStatus), ErrorResponse>,
+ pub status_code: u16,
+ pub connector_customer_id: Option<String>,
+ pub connector_response: Option<ConnectorResponseData>,
+}
+
+pub struct UcsRepeatPaymentResponseData {
+ pub router_data_response:
+ Result<(PaymentsResponseData, common_enums::AttemptStatus), ErrorResponse>,
+ pub status_code: u16,
+ pub connector_customer_id: Option<String>,
+ pub connector_response: Option<ConnectorResponseData>,
+}
+
+pub struct UcsSetupMandateResponseData {
+ pub router_data_response:
+ Result<(PaymentsResponseData, common_enums::AttemptStatus), ErrorResponse>,
+ pub status_code: u16,
+ pub connector_customer_id: Option<String>,
+}
+
#[derive(Debug, Clone, Copy)]
pub enum Redirection {
Redirect,