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
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(external-3ds-vgs): Netcetera external 3DS authentication over VGS external vault (v1) (#13515)
Shankar Singh Ca2ab53fbf449
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex dc68e43bb0..51ea144163 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -9472,6 +9472,16 @@ impl TransactionStatus {}}+impl From<TransactionStatus> for DecoupledAuthenticationType {+ fn from(trans_status: TransactionStatus) -> Self {+ match trans_status {+ TransactionStatus::ChallengeRequired+ | TransactionStatus::ChallengeRequiredDecoupledAuthentication => Self::Challenge,+ _ => Self::Frictionless,+ }+ }+}+#[derive(Clone,Copy,diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rsindex 4daf45f0c6..df84b1401d 100644--- a/crates/diesel_models/src/payment_attempt.rs+++ b/crates/diesel_models/src/payment_attempt.rs@@ -4078,6 +4078,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {authentication_connector,authentication_id,updated_by,+ payment_method: None,+ payment_method_type: None,amount: None,net_amount: None,currency: None,@@ -4085,7 +4087,6 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {amount_to_capture: None,connector: None,authentication_type: None,- payment_method: None,error_message: None,payment_method_id: None,cancellation_reason: None,@@ -4095,7 +4096,6 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {error_code: None,connector_metadata: None,payment_method_data: None,- payment_method_type: None,payment_experience: None,business_sub_label: None,straight_through_algorithm: None,diff --git a/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs b/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rsindex d5ace8bceb..71d2164234 100644--- a/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs@@ -676,6 +676,10 @@ impl ForeignTryFrom<&BarclaycardConsumerAuthValidateResponse> for UcsAuthenticattrans_status: None,transaction_id: value.xid.clone(),ucaf_collection_indicator: value.ucaf_collection_indicator.clone(),+ challenge_code: None,+ challenge_cancel: None,+ challenge_code_reason: None,+ message_extension: None,})}}diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rsindex 9133d7e3af..632a91c9ce 100644--- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs@@ -4044,6 +4044,10 @@ impl ForeignTryFrom<&CybersourceConsumerAuthValidateResponse> for UcsAuthenticattrans_status: None,transaction_id: value.xid.clone(),ucaf_collection_indicator: value.ucaf_collection_indicator.clone(),+ challenge_code: None,+ challenge_cancel: None,+ challenge_code_reason: None,+ message_extension: None,})}}diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rsindex 66dd6fe03c..7e519aa066 100644--- a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs@@ -489,6 +489,10 @@ impl ForeignTryFrom<(&ThreeDSAuthResult, String)> for UcsAuthenticationData {acs_trans_id: None,// CRITICAL: Store operationId in transaction_id for Authorize flowtransaction_id: Some(operation_id),+ challenge_code: None,+ challenge_cancel: None,+ challenge_code_reason: None,+ message_extension: None,})}}diff --git a/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs b/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rsindex 49274cc948..1a60d34ac5 100644--- a/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs@@ -880,6 +880,10 @@ impl ForeignTryFrom<&RedsysThreeDsInvokeData> for router_request_types::UcsAuthetrans_status: None,transaction_id: None,ucaf_collection_indicator: None,+ challenge_code: None,+ challenge_cancel: None,+ challenge_code_reason: None,+ message_extension: None,})}}@@ -901,6 +905,10 @@ impl ForeignTryFrom<&ThreeDsInvokeExempt> for router_request_types::UcsAuthentictrans_status: None,transaction_id: None,ucaf_collection_indicator: None,+ challenge_code: None,+ challenge_cancel: None,+ challenge_code_reason: None,+ message_extension: None,})}}diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rsindex 6cb24e0340..06feea9da5 100644--- a/crates/hyperswitch_domain_models/src/router_request_types.rs+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs@@ -936,6 +936,9 @@ impl TryFrom<PaymentsAuthorizeData> for PaymentsAuthenticateData {// This is hard coded to None to avoid back and forth authentication_data conversion between UcsAuthenticationData and AuthenticationData.// This is handled within authentication_step function in authorize_flow.rsauthentication_data: None,+ sdk_information: None,+ device_channel: None,+ webhook_url: data.webhook_url,})}}@@ -953,6 +956,9 @@ pub struct PaymentsAuthenticateData {pub minor_amount: Option<MinorUnit>,pub capture_method: Option<storage_enums::CaptureMethod>,pub authentication_data: Option<UcsAuthenticationData>,+ pub sdk_information: Option<api_models::payments::SdkInformation>,+ pub device_channel: Option<api_models::payments::DeviceChannel>,+ pub webhook_url: Option<String>,}impl TryFrom<CompleteAuthorizeData> for PaymentsAuthenticateData {@@ -971,6 +977,9 @@ impl TryFrom<CompleteAuthorizeData> for PaymentsAuthenticateData {redirect_response: data.redirect_response,capture_method: data.capture_method,authentication_data: data.authentication_data,+ sdk_information: None,+ device_channel: None,+ webhook_url: None,})}}@@ -1437,6 +1446,10 @@ pub struct UcsAuthenticationData {pub trans_status: Option<common_enums::TransactionStatus>,pub transaction_id: Option<String>,pub ucaf_collection_indicator: Option<String>,+ pub challenge_code: Option<String>,+ pub challenge_cancel: Option<String>,+ pub challenge_code_reason: Option<String>,+ pub message_extension: Option<pii::SecretSerdeValue>,}#[derive(Debug, Clone, Serialize)]diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex 15042ddb1b..3480440c7e 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -380,9 +380,20 @@ pub const UCS_AUTH_MULTI_KEY: &str = "multi-auth-key";/// Header value indicating that currency-auth-key-based authentication is used.pub const UCS_AUTH_CURRENCY_AUTH_KEY: &str = "currency-auth-key";+/// Header value indicating that no credentials are required (e.g. external-3DS+/// over VGS where mTLS is handled on the outbound proxy route, not by UCS).+pub const UCS_AUTH_NO_KEY: &str = "no-key";+/// Form field name for challenge request during creq submissionpub const CREQ_CHALLENGE_REQUEST_KEY: &str = "creq";+/// `RedirectForm::Form.form_fields` keys UCS's Netcetera integration uses to carry 3DS Method+/// (DDC) data — there's no typed proto slot for it, so connector-service stuffs it into the same+/// generic form-fields map used for the challenge (see its `netcetera/transformers.rs`, the+/// `form_fields.insert("threeDsMethodData"/"threeDsMethodUrl", ...)` call).+pub const UCS_DDC_METHOD_DATA_KEY: &str = "threeDsMethodData";+pub const UCS_DDC_METHOD_URL_KEY: &str = "threeDsMethodUrl";+/// Superposition configuration keyspub mod superposition {/// Offer Engine master gate key: boolean, `false` (default) disables all Offer Engine calls.diff --git a/crates/router/src/core/authentication.rs b/crates/router/src/core/authentication.rsindex ccbde05654..866edcfbec 100644--- a/crates/router/src/core/authentication.rs+++ b/crates/router/src/core/authentication.rs@@ -5,20 +5,26 @@ pub mod types;use api_models::payments;use common_enums::Currency;-use common_utils::errors::CustomResult;+use common_utils::{errors::CustomResult, ext_traits::ValueExt};use error_stack::ResultExt;use hyperswitch_domain_models::authentication;use hyperswitch_masking::ExposeInterface;use super::errors::StorageErrorExt;use crate::{- core::{errors::ApiErrorResponse, payments as payments_core},+ consts,+ core::{+ errors::ApiErrorResponse, payment_methods::vault, payments as payments_core,+ unified_connector_service,+ },routes::SessionState,types::{self as core_types, api,domain::{self},+ storage::PaymentAttemptUpdate,+ transformers::ForeignFrom,},- utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata,+ utils::{check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata, OptionExt},};#[allow(clippy::too_many_arguments)]@@ -137,7 +143,7 @@ pub async fn perform_post_authentication(let authentication = state.store.find_authentication_by_processor_merchant_id_authentication_id(- &business_profile.merchant_id,+ processor.get_account().get_id(),&authentication_id,processor.get_key_store(),key_state,@@ -199,7 +205,7 @@ pub async fn perform_post_authentication(};// getting authentication value from temp locker before moving ahead with authrisation- let tokenized_data = crate::core::payment_methods::vault::get_tokenized_data(+ let tokenized_data = vault::get_tokenized_data(state,authentication_id.get_string_repr(),false,@@ -369,3 +375,1418 @@ pub async fn perform_pre_authentication(},)}++#[cfg(feature = "v1")]+struct ProxyUcsGatewayContext {+ execution_mode: common_enums::ExecutionMode,+ session_state: SessionState,+ platform: domain::Platform,+ external_vault_merchant_connector_account: payments_core::helpers::MerchantConnectorAccountType,+}++/// Shared by `perform_pre_authentication_proxy` and `perform_post_authentication_proxy`: resolves+/// the UCS gateway/execution mode and vault MCA for the PSP connector, or `None` if UCS isn't+/// enabled for it.+#[cfg(feature = "v1")]+async fn resolve_proxy_ucs_gateway_and_vault_mca<PayF: Clone, RdF: Clone, T, R>(+ state: &SessionState,+ processor: &domain::Processor,+ initiator: Option<&domain::Initiator>,+ business_profile: &domain::Profile,+ payment_data: &payments_core::PaymentData<PayF>,+ psp_router_data: &core_types::RouterData<RdF, T, R>,+) -> CustomResult<Option<ProxyUcsGatewayContext>, ApiErrorResponse>+where+ R: Send + Sync + Clone,+{+ let (execution_path, updated_state) =+ unified_connector_service::should_call_unified_connector_service(+ state,+ processor,+ psp_router_data,+ unified_connector_service::extract_gateway_system_from_payment_intent(payment_data),+ payments_core::CallConnectorAction::Trigger,+ None,+ common_enums::TransactionType::Payment,+ )+ .await?;+ let execution_mode = match execution_path {+ common_enums::ExecutionPath::UnifiedConnectorService => {+ Some(common_enums::ExecutionMode::Primary)+ }+ common_enums::ExecutionPath::ShadowUnifiedConnectorService => {+ Some(common_enums::ExecutionMode::Shadow)+ }+ common_enums::ExecutionPath::Direct => None,+ };++ if let Some(execution_mode) = execution_mode {+ let provider_merchant_id = payment_data.payment_intent.merchant_id.clone();+ let provider_key_store = state+ .store+ .get_merchant_key_store_by_merchant_id(+ &provider_merchant_id,+ &state.store.get_master_key().to_vec().into(),+ )+ .await+ .to_not_found_response(ApiErrorResponse::InternalServerError)+ .attach_printable("Error while fetching the key store for provider merchant")?;+ let provider_account = state+ .store+ .find_merchant_account_by_merchant_id(&provider_merchant_id, &provider_key_store)+ .await+ .to_not_found_response(ApiErrorResponse::InternalServerError)+ .attach_printable("Error while fetching the merchant account for provider")?;+ let platform = domain::Platform::new(+ provider_account,+ provider_key_store,+ processor.get_account().clone(),+ processor.get_key_store().clone(),+ initiator.cloned(),+ );+ let provider_business_profile =+ payments_core::helpers::resolve_provider_profile(state, &platform, business_profile)+ .await?;+ let external_vault_mca_id = provider_business_profile+ .external_vault_details+ .get_vault_connector_id()+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable("external vault is not enabled for this business profile")?;+ let external_vault_merchant_connector_account =+ payments_core::helpers::MerchantConnectorAccountType::DbVal(Box::new(+ state+ .store+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(+ platform.get_provider().get_account().get_id(),+ &external_vault_mca_id,+ platform.get_provider().get_key_store(),+ )+ .await+ .to_not_found_response(ApiErrorResponse::MerchantConnectorAccountNotFound {+ id: external_vault_mca_id.get_string_repr().to_string(),+ })?,+ ));++ Ok(Some(ProxyUcsGatewayContext {+ execution_mode,+ session_state: updated_state,+ platform,+ external_vault_merchant_connector_account,+ }))+ } else {+ Ok(None)+ }+}++/// Drives the live UCS pre-authenticate call. Returns `Ok(Err(ErrorResponse))` (not a hard `Err`)+/// for a UCS/connector-level failure, so the caller can persist it via a single `update_trackers` call.+#[cfg(feature = "v1")]+#[allow(clippy::too_many_arguments)]+async fn call_ucs_pre_authenticate_proxy(+ pre_authenticate_router_data: &core_types::RouterData<+ api::PreAuthenticate,+ core_types::PaymentsPreAuthenticateData,+ core_types::PaymentsResponseData,+ >,+ external_vault_pmd: &domain::ExternalVaultPaymentMethodData,+ state: &SessionState,+ header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ lineage_ids: external_services::grpc_client::LineageIds,+ auth_merchant_connector_account: payments_core::helpers::MerchantConnectorAccountType,+ external_vault_merchant_connector_account: payments_core::helpers::MerchantConnectorAccountType,+ processor: &domain::Processor,+ connector_enum: common_enums::connector_enums::Connector,+ execution_mode: common_enums::ExecutionMode,+) -> CustomResult<+ Result<core_types::authentication::AuthenticationResponseData, core_types::ErrorResponse>,+ ApiErrorResponse,+> {+ let pre_authenticate_router_data = Box::pin(+ payments_core::flows::authorize_flow::call_unified_connector_service_pre_authenticate_proxy(+ pre_authenticate_router_data,+ external_vault_pmd,+ state,+ header_payload,+ lineage_ids,+ auth_merchant_connector_account,+ external_vault_merchant_connector_account,+ processor,+ connector_enum,+ execution_mode,+ ),+ )+ .await;++ let pre_authenticate_result = match pre_authenticate_router_data {+ Ok(pre_authenticate_router_data) => match pre_authenticate_router_data.response {+ Ok(core_types::PaymentsResponseData::TransactionResponse {+ authentication_data,+ redirection_data,+ ..+ }) => Ok((authentication_data.map(|boxed| *boxed), *redirection_data)),+ Ok(_) => Ok((None, None)),+ Err(err) => Err(err),+ },+ Err(err) => Err(core_types::ErrorResponse {+ message: format!("UCS pre-authenticate call failed: {err}"),+ ..Default::default()+ }),+ };+ match pre_authenticate_result {+ Err(err) => Ok(Err(err)),+ Ok((ucs_authentication_data, ddc_redirection_data)) => {+ let (three_ds_method_data, three_ds_method_url) = match &ddc_redirection_data {+ Some(hyperswitch_domain_models::router_response_types::RedirectForm::Form {+ form_fields,+ ..+ }) => (+ form_fields.get(consts::UCS_DDC_METHOD_DATA_KEY).cloned(),+ form_fields.get(consts::UCS_DDC_METHOD_URL_KEY).cloned(),+ ),+ _ => (None, None),+ };++ let message_version = ucs_authentication_data+ .as_ref()+ .and_then(|data| data.message_version.clone())+ .unwrap_or_else(|| common_utils::types::SemanticVersion::new(2, 2, 0));+ let threeds_server_transaction_id = ucs_authentication_data+ .as_ref()+ .and_then(|data| data.threeds_server_transaction_id.clone())+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable(+ "UCS pre-authenticate response missing threeds_server_transaction_id",+ )?;+ let directory_server_id = ucs_authentication_data+ .as_ref()+ .and_then(|data| data.ds_trans_id.clone());++ Ok(Ok(+ core_types::authentication::AuthenticationResponseData::PreAuthNResponse {+ connector_authentication_id: threeds_server_transaction_id.clone(),+ threeds_server_transaction_id,+ maximum_supported_3ds_version: message_version.clone(),+ three_ds_method_data,+ three_ds_method_url,+ message_version,+ connector_metadata: None,+ directory_server_id,+ scheme_id: None,+ },+ ))+ }+ }+}++/// Proxy analogue of `perform_pre_authentication`, driving the auth connector over UCS. Fails+/// closed (hard `Err`) if UCS isn't enabled for the connector, since the merchant explicitly+/// requested external 3DS for this payment.+#[cfg(feature = "v1")]+pub async fn perform_pre_authentication_proxy<F: Clone>(+ state: &SessionState,+ processor: &domain::Processor,+ initiator: Option<&domain::Initiator>,+ business_profile: &domain::Profile,+ payment_data: &payments_core::PaymentData<F>,+) -> CustomResult<+ (+ Option<+ hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore,+ >,+ Option<String>,+ ),+ ApiErrorResponse,+> {+ let external_vault_pmd = payment_data+ .external_vault_pmd+ .clone()+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable("external_vault_pmd is required for the pre-authentication proxy flow")?;++ let psp_connector_name = payment_data+ .payment_attempt+ .connector+ .clone()+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable("connector missing on attempt for external vault 3DS pre-authenticate")?;+ let psp_merchant_connector_account = payments_core::helpers::get_merchant_connector_account(+ state,+ processor,+ None,+ business_profile.get_id(),+ psp_connector_name.as_str(),+ payment_data.payment_attempt.merchant_connector_id.as_ref(),+ )+ .await?;++ let payment_method = payment_data+ .payment_attempt+ .payment_method+ .unwrap_or(common_enums::PaymentMethod::Card);++ let pre_authenticate_request_data = core_types::PaymentsPreAuthenticateData {+ payment_method_data: domain::PaymentMethodData::Card(domain::Card::default()),+ amount: payment_data+ .payment_attempt+ .get_total_amount()+ .get_amount_as_i64(),+ minor_amount: payment_data.payment_attempt.get_total_amount(),+ email: None,+ capture_method: payment_data.payment_attempt.capture_method,+ currency: payment_data.payment_intent.currency,+ payment_method_type: payment_data.payment_attempt.payment_method_type,+ router_return_url: payment_data.payment_intent.return_url.clone(),+ complete_authorize_url: None,+ browser_info: None,+ enrolled_for_3ds: true,+ customer_name: None,+ metadata: None,+ webhook_url: None,+ };++ let psp_router_data: core_types::RouterData<+ api::PreAuthenticate,+ core_types::PaymentsPreAuthenticateData,+ core_types::PaymentsResponseData,+ > = transformers::construct_router_data(+ state,+ psp_connector_name,+ payment_method,+ business_profile.merchant_id.clone(),+ payment_data.address.clone(),+ pre_authenticate_request_data,+ &psp_merchant_connector_account,+ payment_data.payment_intent.psd2_sca_exemption_type,+ payment_data.payment_attempt.payment_id.clone(),+ )?;++ let ProxyUcsGatewayContext {+ execution_mode,+ session_state: updated_state,+ platform: _,+ external_vault_merchant_connector_account,+ } = resolve_proxy_ucs_gateway_and_vault_mca(+ state,+ processor,+ initiator,+ business_profile,+ payment_data,+ &psp_router_data,+ )+ .await?+ .ok_or_else(|| {+ error_stack::report!(ApiErrorResponse::PreconditionFailed {+ message: "External 3DS authentication was requested for this payment, but UCS is \+ not enabled for this connector; cannot proceed without performing 3DS"+ .to_string(),+ })+ })?;++ let (authentication_connector, auth_merchant_connector_account) =+ utils::get_authentication_connector_data(state, processor, business_profile, None).await?;+ let connector_enum = authentication_connector+ .to_string()+ .parse::<common_enums::connector_enums::Connector>()+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Invalid authentication connector name for UCS external vault 3DS auth leg",+ )?;++ let merchant_connector_id = auth_merchant_connector_account+ .get_mca_id()+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable("Error while finding mca_id from merchant_connector_account")?;++ let auth_webhook_url = auth_merchant_connector_account.get_mca_id().map(|mca_id| {+ payments_core::helpers::create_webhook_url(+ &state.base_url,+ &business_profile.merchant_id,+ mca_id.get_string_repr(),+ )+ });++ let browser_info: Option<core_types::BrowserInformation> = payment_data+ .payment_attempt+ .browser_info+ .clone()+ .map(|browser_info| browser_info.parse_value("BrowserInformation"))+ .transpose()+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse browser_info from payment_attempt")?;++ let authentication_connector_name = authentication_connector.to_string();+ let authentication = utils::create_new_authentication(+ state,+ business_profile.merchant_id.clone(),+ authentication_connector_name,+ common_utils::generate_id(consts::ID_LENGTH, "authn"),+ business_profile,+ payment_data.payment_attempt.payment_id.clone(),+ merchant_connector_id,+ payment_data.payment_attempt.organization_id.clone(),+ payment_data.payment_intent.force_3ds_challenge,+ payment_data.payment_intent.psd2_sca_exemption_type,+ processor,+ initiator,+ &domain::Card::default(),+ browser_info.as_ref(),+ None,+ payment_data.address.get_payment_method_billing(),+ payment_data.address.get_shipping(),+ Some(payment_data.payment_intent.amount),+ payment_data.payment_intent.currency,+ )+ .await?;++ let mut pre_authenticate_router_data = psp_router_data;+ pre_authenticate_router_data.connector = connector_enum.to_string();+ pre_authenticate_router_data.request.webhook_url = auth_webhook_url;++ let lineage_ids = external_services::grpc_client::LineageIds::new(+ business_profile.merchant_id.clone(),+ business_profile.get_id().clone(),+ );+ let header_payload = hyperswitch_domain_models::payments::HeaderPayload::default();++ let pre_authenticate_response_data = call_ucs_pre_authenticate_proxy(+ &pre_authenticate_router_data,+ &external_vault_pmd,+ &updated_state,+ &header_payload,+ lineage_ids,+ auth_merchant_connector_account.clone(),+ external_vault_merchant_connector_account,+ processor,+ connector_enum,+ execution_mode,+ )+ .await?;++ let mut pre_authenticate_router_data: core_types::RouterData<+ api::PreAuthentication,+ (),+ core_types::authentication::AuthenticationResponseData,+ > = transformers::construct_router_data(+ state,+ authentication_connector.to_string(),+ payment_method,+ business_profile.merchant_id.clone(),+ payment_data.address.clone(),+ (),+ &auth_merchant_connector_account,+ payment_data.payment_intent.psd2_sca_exemption_type,+ payment_data.payment_attempt.payment_id.clone(),+ )?;+ pre_authenticate_router_data.response = pre_authenticate_response_data;++ let authentication_info =+ hyperswitch_domain_models::router_request_types::authentication::AuthenticationInfo {+ billing_address: payment_data.address.get_payment_method_billing().cloned(),+ shipping_address: payment_data.address.get_shipping().cloned(),+ browser_info,+ email: None,+ device_details: None,+ merchant_category_code: None,+ merchant_country_code: None,+ platform: None,+ };++ let authentication = Box::pin(utils::update_trackers(+ state,+ pre_authenticate_router_data,+ authentication,+ None,+ processor.get_key_store(),+ authentication_info,+ processor.get_account().storage_scheme,+ ))+ .await?;++ let alias_token = payment_data+ .token+ .clone()+ .get_required_value("token")+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable(+ "payment_data.token should not be None while making external vault pre authentication call",+ )?;++ Ok((+ Some(+ hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {+ cavv: None,+ authentication,+ },+ ),+ Some(alias_token),+ ))+}++/// Drives the live UCS post-authenticate call. Returns `Ok(Err(ErrorResponse))` (not a hard `Err`)+/// for any 3DS-outcome failure, so the caller can persist it via a single `update_trackers` call.+#[cfg(feature = "v1")]+#[allow(clippy::too_many_arguments)]+async fn call_ucs_post_authenticate_proxy<F: Clone>(+ state: &SessionState,+ processor: &domain::Processor,+ initiator: Option<&domain::Initiator>,+ business_profile: &domain::Profile,+ payment_data: &payments_core::PaymentData<F>,+ authentication: &authentication::Authentication,+ auth_connector_enum: common_enums::connector_enums::Connector,+ auth_merchant_connector_account: payments_core::helpers::MerchantConnectorAccountType,+ payment_method: common_enums::PaymentMethod,+) -> CustomResult<+ Result<core_types::authentication::AuthenticationResponseData, core_types::ErrorResponse>,+ ApiErrorResponse,+> {+ let psp_connector_name = payment_data+ .payment_attempt+ .connector+ .clone()+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable(+ "connector missing on attempt for external vault 3DS post-authenticate",+ )?;+ let psp_merchant_connector_account = payments_core::helpers::get_merchant_connector_account(+ state,+ processor,+ None,+ business_profile.get_id(),+ psp_connector_name.as_str(),+ payment_data.payment_attempt.merchant_connector_id.as_ref(),+ )+ .await?;++ let browser_info: Option<core_types::BrowserInformation> = payment_data+ .payment_attempt+ .browser_info+ .clone()+ .map(|browser_information| browser_information.parse_value("BrowserInformation"))+ .transpose()+ .change_context(ApiErrorResponse::InvalidDataValue {+ field_name: "browser_info",+ })?;++ let amount = payment_data.payment_attempt.get_total_amount();+ let post_authenticate_request_data = core_types::PaymentsPostAuthenticateData {+ payment_method_data: None,+ payment_method_type: payment_data.payment_attempt.payment_method_type,+ amount: Some(amount.get_amount_as_i64()),+ minor_amount: Some(amount),+ email: None,+ currency: payment_data.payment_intent.currency,+ capture_method: payment_data.payment_attempt.capture_method,+ browser_info,+ connector_transaction_id: authentication.threeds_server_transaction_id.clone(),+ redirect_response: authentication+ .threeds_server_transaction_id+ .clone()+ .map(|tds| {+ hyperswitch_domain_models::router_request_types::CompleteAuthorizeRedirectResponse {+ params: Some(hyperswitch_masking::Secret::new(tds)),+ payload: None,+ }+ }),+ metadata: None,+ complete_authorize_url: None,+ };++ let psp_router_data: core_types::RouterData<+ api::PostAuthenticate,+ core_types::PaymentsPostAuthenticateData,+ core_types::PaymentsResponseData,+ > = transformers::construct_router_data(+ state,+ psp_connector_name,+ payment_method,+ business_profile.merchant_id.clone(),+ payment_data.address.clone(),+ post_authenticate_request_data,+ &psp_merchant_connector_account,+ payment_data.payment_intent.psd2_sca_exemption_type,+ payment_data.payment_attempt.payment_id.clone(),+ )?;++ let Some(ProxyUcsGatewayContext {+ execution_mode,+ session_state: updated_state,+ platform,+ external_vault_merchant_connector_account,+ }) = resolve_proxy_ucs_gateway_and_vault_mca(+ state,+ processor,+ initiator,+ business_profile,+ payment_data,+ &psp_router_data,+ )+ .await?+ else {+ return Ok(Err(core_types::ErrorResponse {+ message: "UCS is not enabled for this connector; external vault 3DS post-authenticate over UCS is unavailable".to_string(),+ ..Default::default()+ }));+ };++ let mut post_authenticate_router_data = psp_router_data;+ post_authenticate_router_data.connector = auth_connector_enum.to_string();++ let lineage_ids = external_services::grpc_client::LineageIds::new(+ business_profile.merchant_id.clone(),+ business_profile.get_id().clone(),+ );++ let post_auth_payment_token = payment_data+ .payment_attempt+ .payment_token+ .clone()+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable(+ "payment_token missing on attempt for external vault 3DS post-authenticate",+ )?;+ let post_auth_payment_method = payment_data+ .payment_attempt+ .payment_method+ .unwrap_or(common_enums::PaymentMethod::Card);+ let external_vault_pmd = payments_core::resolve_external_vault_alias_from_payment_token(+ state,+ &platform,+ post_auth_payment_token,+ post_auth_payment_method,+ )+ .await?;++ let header_payload = hyperswitch_domain_models::payments::HeaderPayload::default();++ let post_authenticate_router_data = Box::pin(+ payments_core::flows::complete_authorize_flow::call_unified_connector_service_post_authenticate_proxy(+ &post_authenticate_router_data,+ &external_vault_pmd,+ &updated_state,+ &header_payload,+ lineage_ids,+ auth_merchant_connector_account,+ external_vault_merchant_connector_account,+ processor,+ execution_mode,+ ),+ )+ .await;++ let post_authenticate_router_data = match post_authenticate_router_data {+ Ok(router_data) => router_data,+ Err(err) => {+ return Ok(Err(core_types::ErrorResponse {+ message: format!("UCS post-authenticate call failed: {err}"),+ ..Default::default()+ }));+ }+ };++ let post_auth_authentication_data = match post_authenticate_router_data.response {+ Ok(core_types::PaymentsResponseData::TransactionResponse {+ authentication_data,+ ..+ }) => authentication_data.map(|boxed| *boxed),+ Ok(_) => None,+ Err(err) => return Ok(Err(err)),+ };++ let trans_status = post_auth_authentication_data+ .as_ref()+ .and_then(|data| data.trans_status.clone())+ .or_else(|| authentication.trans_status.clone())+ .unwrap_or(common_enums::TransactionStatus::VerificationNotPerformed);+ let eci = post_auth_authentication_data+ .as_ref()+ .and_then(|data| data.eci.clone())+ .or_else(|| authentication.eci.clone());+ let cavv = post_auth_authentication_data+ .as_ref()+ .and_then(|data| data.cavv.clone());++ let authentication_status =+ common_enums::AuthenticationStatus::foreign_from(trans_status.clone());++ if authentication_status != common_enums::AuthenticationStatus::Success || cavv.is_none() {+ return Ok(Err(core_types::ErrorResponse {+ message: "External vault 3DS post-authenticate did not succeed".to_string(),+ reason: Some(format!("trans_status: {trans_status:?}")),+ connector_transaction_id: authentication.threeds_server_transaction_id.clone(),+ ..Default::default()+ }));+ }++ Ok(Ok(+ core_types::authentication::AuthenticationResponseData::PostAuthNResponse {+ trans_status,+ authentication_value: cavv,+ eci,+ challenge_cancel: post_auth_authentication_data+ .as_ref()+ .and_then(|data| data.challenge_cancel.clone()),+ challenge_code_reason: post_auth_authentication_data+ .as_ref()+ .and_then(|data| data.challenge_code_reason.clone()),+ },+ ))+}++/// Proxy analogue of `perform_post_authentication`, driving the auth connector over UCS instead+/// of directly. Mirrors its `!is_terminal_status() && is_pull_mechanism_enabled` gating shape.+#[cfg(feature = "v1")]+pub async fn perform_post_authentication_proxy<F: Clone>(+ state: &SessionState,+ processor: &domain::Processor,+ initiator: Option<&domain::Initiator>,+ business_profile: &domain::Profile,+ payment_data: &payments_core::PaymentData<F>,+ authentication_id: common_utils::id_type::AuthenticationId,+) -> CustomResult<+ hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore,+ ApiErrorResponse,+> {+ let key_store = processor.get_key_store();+ let key_manager_state = state.into();+ let storage_scheme = processor.get_account().storage_scheme;++ let authentication = state+ .store+ .find_authentication_by_processor_merchant_id_authentication_id(+ processor.get_account().get_id(),+ &authentication_id,+ key_store,+ &key_manager_state,+ storage_scheme,+ )+ .await+ .to_not_found_response(ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Error while fetching external vault authentication record for post-authenticate resume",+ )?;++ let (authentication_connector, auth_merchant_connector_account) =+ utils::get_authentication_connector_data(state, processor, business_profile, None).await?;+ let auth_connector_enum = authentication_connector+ .to_string()+ .parse::<common_enums::connector_enums::Connector>()+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Invalid authentication connector name for UCS external vault 3DS auth leg",+ )?;++ let is_pull_mechanism_enabled =+ check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata(+ auth_merchant_connector_account+ .get_metadata()+ .map(|metadata| metadata.expose()),+ );++ let payment_method = payment_data+ .payment_attempt+ .payment_method+ .unwrap_or(common_enums::PaymentMethod::Card);++ let authentication = if !authentication.authentication_status.is_terminal_status()+ && is_pull_mechanism_enabled+ {+ // trigger in case of authenticate flow+ let post_authenticate_response_data = call_ucs_post_authenticate_proxy(+ state,+ processor,+ initiator,+ business_profile,+ payment_data,+ &authentication,+ auth_connector_enum,+ auth_merchant_connector_account.clone(),+ payment_method,+ )+ .await?;++ let mut post_authenticate_tracker_router_data: core_types::RouterData<+ api::PostAuthentication,+ (),+ core_types::authentication::AuthenticationResponseData,+ > = transformers::construct_router_data(+ state,+ authentication_connector.to_string(),+ payment_method,+ business_profile.merchant_id.clone(),+ payment_data.address.clone(),+ (),+ &auth_merchant_connector_account,+ payment_data.payment_intent.psd2_sca_exemption_type,+ payment_data.payment_attempt.payment_id.clone(),+ )?;+ post_authenticate_tracker_router_data.response = post_authenticate_response_data;++ let authentication_info =+ hyperswitch_domain_models::router_request_types::authentication::AuthenticationInfo {+ billing_address: None,+ shipping_address: None,+ browser_info: None,+ email: None,+ device_details: None,+ merchant_category_code: None,+ merchant_country_code: None,+ platform: None,+ };++ Box::pin(utils::update_trackers(+ state,+ post_authenticate_tracker_router_data,+ authentication,+ None,+ key_store,+ authentication_info,+ storage_scheme,+ ))+ .await?+ } else {+ authentication+ };++ let tokenized_data = vault::get_tokenized_data(+ state,+ authentication_id.get_string_repr(),+ false,+ key_store.key.get_inner(),+ )+ .await+ .inspect_err(|err| router_env::logger::error!(external_vault_cavv_vault_lookup_error=?err))+ .attach_printable("cavv not present after authentication flow")+ .ok();++ Ok(+ hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {+ cavv: tokenized_data.map(|data| hyperswitch_masking::Secret::new(data.value1)),+ authentication,+ },+ )+}++#[cfg(feature = "v1")]+struct AuthenticateProxyContext {+ authenticate_router_data: core_types::RouterData<+ api::Authenticate,+ core_types::PaymentsAuthenticateData,+ core_types::PaymentsResponseData,+ >,+ authentication: authentication::Authentication,+ authentication_id: common_utils::id_type::AuthenticationId,+ auth_connector_enum: common_enums::connector_enums::Connector,+ auth_merchant_connector_account: payments_core::helpers::MerchantConnectorAccountType,+ payment_method: common_enums::PaymentMethod,+ browser_info: Option<core_types::BrowserInformation>,+}++#[derive(serde::Serialize, serde::Deserialize)]+struct AcquirerMetadata {+ acquirer_bin: Option<String>,+ acquirer_merchant_id: Option<String>,+ acquirer_country_code: Option<String>,+}++impl AcquirerMetadata {+ fn is_empty(&self) -> bool {+ self.acquirer_bin.is_none()+ && self.acquirer_merchant_id.is_none()+ && self.acquirer_country_code.is_none()+ }+}++/// Drives the live UCS authenticate (AReq) call; response interpretation is+/// `parse_ucs_authenticate_response`'s job.+#[cfg(feature = "v1")]+#[allow(clippy::too_many_arguments)]+async fn call_ucs_authenticate_proxy(+ state: &SessionState,+ platform: &domain::Platform,+ payment_intent: &hyperswitch_domain_models::payments::PaymentIntent,+ payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,+ business_profile: &domain::Profile,+ amount: common_utils::types::MinorUnit,+ currency: Currency,+ billing_address: Option<hyperswitch_domain_models::address::Address>,+ optional_email: Option<common_utils::pii::Email>,+ header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ device_channel: payments::DeviceChannel,+ sdk_information: Option<payments::SdkInformation>,+) -> CustomResult<AuthenticateProxyContext, ApiErrorResponse> {+ let processor = platform.get_processor();+ let key_store = processor.get_key_store();+ let key_manager_state = state.into();+ let storage_scheme = processor.get_account().storage_scheme;+ let processor_merchant_id = processor.get_account().get_id();++ let payment_token = payment_attempt+ .payment_token+ .clone()+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable("payment_token missing on attempt for external vault 3DS authenticate")?;+ let payment_method = payment_attempt+ .payment_method+ .unwrap_or(common_enums::PaymentMethod::Card);+ let external_vault_pmd = payments_core::resolve_external_vault_alias_from_payment_token(+ state,+ platform,+ payment_token,+ payment_method,+ )+ .await?;++ let provider_business_profile =+ payments_core::helpers::resolve_provider_profile(state, platform, business_profile).await?;+ let external_vault_mca_id = provider_business_profile+ .external_vault_details+ .get_vault_connector_id()+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable("external vault is not enabled for this business profile")?;+ let external_vault_merchant_connector_account =+ payments_core::helpers::MerchantConnectorAccountType::DbVal(Box::new(+ state+ .store+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(+ platform.get_provider().get_account().get_id(),+ &external_vault_mca_id,+ platform.get_provider().get_key_store(),+ )+ .await+ .to_not_found_response(ApiErrorResponse::MerchantConnectorAccountNotFound {+ id: external_vault_mca_id.get_string_repr().to_string(),+ })?,+ ));++ let profile_id = business_profile.get_id();+ let psp_connector_name = payment_attempt+ .connector+ .clone()+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable("connector missing on attempt for external vault 3DS authenticate")?;+ let psp_merchant_connector_account = payments_core::helpers::get_merchant_connector_account(+ state,+ processor,+ None,+ profile_id,+ psp_connector_name.as_str(),+ payment_attempt.merchant_connector_id.as_ref(),+ )+ .await?;++ let authentication_id = payment_attempt+ .authentication_id+ .clone()+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable(+ "missing authentication_id on attempt for external vault 3DS authenticate",+ )?;+ let authentication = state+ .store+ .find_authentication_by_processor_merchant_id_authentication_id(+ processor_merchant_id,+ &authentication_id,+ key_store,+ &key_manager_state,+ storage_scheme,+ )+ .await+ .to_not_found_response(ApiErrorResponse::InternalServerError)+ .attach_printable("Error while fetching external vault authentication record")?;++ let ucs_authentication_data =+ hyperswitch_domain_models::router_request_types::UcsAuthenticationData {+ eci: authentication.eci.clone(),+ cavv: None,+ threeds_server_transaction_id: authentication.threeds_server_transaction_id.clone(),+ message_version: authentication.message_version.clone(),+ ds_trans_id: authentication.ds_trans_id.clone(),+ acs_trans_id: authentication.acs_trans_id.clone(),+ trans_status: authentication.trans_status.clone(),+ transaction_id: authentication.connector_authentication_id.clone(),+ ucaf_collection_indicator: None,+ challenge_code: authentication.challenge_code.clone(),+ challenge_cancel: authentication.challenge_cancel.clone(),+ challenge_code_reason: authentication.challenge_code_reason.clone(),+ message_extension: authentication.message_extension.clone(),+ };++ let browser_info: Option<core_types::BrowserInformation> = authentication+ .browser_info+ .clone()+ .map(|browser_information| browser_information.parse_value("BrowserInformation"))+ .transpose()+ .change_context(ApiErrorResponse::InvalidDataValue {+ field_name: "browser_info",+ })?;++ let authenticate_request_data = core_types::PaymentsAuthenticateData {+ payment_method_data: None,+ payment_method_type: payment_attempt.payment_method_type,+ amount: Some(amount.get_amount_as_i64()),+ minor_amount: Some(amount),+ email: optional_email.clone(),+ currency: Some(currency),+ complete_authorize_url: None,+ browser_info: browser_info.clone(),+ redirect_response: None,+ capture_method: payment_attempt.capture_method,+ authentication_data: Some(ucs_authentication_data),+ sdk_information: sdk_information.clone(),+ device_channel: Some(device_channel.clone()),+ webhook_url: None,+ };++ let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new(+ None,+ billing_address.clone(),+ None,+ None,+ );++ let (authentication_connector, auth_merchant_connector_account) =+ utils::get_authentication_connector_data(state, processor, business_profile, None).await?;+ let auth_connector_enum = authentication_connector+ .to_string()+ .parse::<common_enums::connector_enums::Connector>()+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Invalid authentication connector name for UCS external vault 3DS auth leg",+ )?;++ let mut authenticate_router_data: core_types::RouterData<+ api::Authenticate,+ core_types::PaymentsAuthenticateData,+ core_types::PaymentsResponseData,+ > = transformers::construct_router_data(+ state,+ auth_connector_enum.to_string(),+ payment_method,+ business_profile.merchant_id.clone(),+ payment_address,+ authenticate_request_data,+ &auth_merchant_connector_account,+ payment_intent.psd2_sca_exemption_type,+ payment_intent.payment_id.clone(),+ )?;+ authenticate_router_data.request.webhook_url =+ auth_merchant_connector_account.get_mca_id().map(|mca_id| {+ payments_core::helpers::create_webhook_url(+ &state.base_url,+ &business_profile.merchant_id,+ mca_id.get_string_repr(),+ )+ });++ let (execution_path, updated_state) =+ unified_connector_service::should_call_unified_connector_service(+ state,+ processor,+ &authenticate_router_data,+ None,+ payments_core::CallConnectorAction::Trigger,+ None,+ common_enums::TransactionType::Payment,+ )+ .await?;+ let execution_mode = match execution_path {+ common_enums::ExecutionPath::UnifiedConnectorService => {+ Some(common_enums::ExecutionMode::Primary)+ }+ common_enums::ExecutionPath::ShadowUnifiedConnectorService => {+ Some(common_enums::ExecutionMode::Shadow)+ }+ common_enums::ExecutionPath::Direct => None,+ }+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable(+ "UCS is not enabled for this connector; external vault 3DS authenticate over UCS is unavailable",+ )?;++ let lineage_ids = external_services::grpc_client::LineageIds::new(+ business_profile.merchant_id.clone(),+ business_profile.get_id().clone(),+ );++ let notification_url = Some(common_utils::types::Url::wrap(+ url::Url::parse(&payments_core::helpers::create_authorize_url(+ &state.base_url,+ payment_attempt,+ &psp_connector_name,+ ))+ .change_context(ApiErrorResponse::InternalServerError)?,+ ));++ // Prefer acquirer details set directly on the PSP connector's own metadata; fall back to the+ // profile's card-network-keyed acquirer config the same way+ // `get_payment_external_authentication_flow_during_confirm` does for the direct flow — a+ // profile-acquirer-id-specific bucket first, then the profile's network default.+ let acquirer_metadata = psp_merchant_connector_account+ .get_metadata()+ .and_then(|metadata| serde_json::from_value::<AcquirerMetadata>(metadata.expose()).ok())+ .filter(|metadata| !metadata.is_empty())+ .or_else(|| {+ let card_network = match &external_vault_pmd {+ domain::ExternalVaultPaymentMethodData::Card(card) => card.card_network.clone(),+ domain::ExternalVaultPaymentMethodData::VaultToken(_) => None,+ }?;+ let acquirer_config = payment_intent+ .profile_acquirer_id+ .as_ref()+ .and_then(|profile_acquirer_id| {+ business_profile.get_acquirer_details_for_profile_acquirer(+ profile_acquirer_id,+ card_network.clone(),+ )+ })+ .or_else(|| {+ business_profile.get_default_acquirer_details_from_network(card_network)+ })?;+ Some(AcquirerMetadata {+ acquirer_bin: acquirer_config.acquirer_bin,+ acquirer_merchant_id: acquirer_config.acquirer_assigned_merchant_id,+ acquirer_country_code: acquirer_config.acquirer_country_code,+ })+ })+ .and_then(|metadata| serde_json::to_value(metadata).ok());++ let authenticate_router_data = Box::pin(+ payments_core::flows::complete_authorize_flow::call_unified_connector_service_authenticate_proxy(+ &authenticate_router_data,+ &external_vault_pmd,+ &updated_state,+ header_payload,+ lineage_ids,+ auth_merchant_connector_account.clone(),+ external_vault_merchant_connector_account,+ processor,+ execution_mode,+ Some(+ payment_intent+ .force_3ds_challenge+ .unwrap_or(business_profile.force_3ds_challenge),+ ),+ notification_url,+ acquirer_metadata,+ ),+ )+ .await+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to call UCS authenticate for external vault proxy")?;++ Ok(AuthenticateProxyContext {+ authenticate_router_data,+ authentication,+ authentication_id,+ auth_connector_enum,+ auth_merchant_connector_account,+ payment_method,+ browser_info,+ })+}++#[cfg(feature = "v1")]+struct ParsedAuthenticateResponse {+ authenticate_response_data: core_types::authentication::AuthenticationResponseData,+ authentication_type: common_enums::DecoupledAuthenticationType,+ trans_status: common_enums::TransactionStatus,+ acs_url: Option<url::Url>,+ challenge_request: Option<String>,+ acs_reference_number: Option<String>,+ acs_trans_id: Option<String>,+ three_ds_server_transaction_id: Option<String>,+ acs_signed_content: Option<String>,+}++#[cfg(feature = "v1")]+#[derive(serde::Deserialize)]+struct AppChallengeAcsMetadata {+ acs_signed_content: Option<String>,+ acs_reference_number: Option<String>,+ acs_trans_id: Option<String>,+}++/// Interprets a successful UCS authenticate response into `AuthenticationResponseData::AuthNResponse`+/// plus the SDK-facing challenge/ARes fields; `AppChallengeAcsMetadata` reads ACS fields back out+/// of the JSON-stuffed `connector_metadata` since UCS has no typed slots for them. A connector-level+/// error is the caller's responsibility to hard-fail on (mirroring `perform_authentication`'s+/// `response.response.map_err(...)?`) before ever reaching this function.+#[cfg(feature = "v1")]+fn parse_ucs_authenticate_response(+ response: &core_types::PaymentsResponseData,+) -> CustomResult<ParsedAuthenticateResponse, ApiErrorResponse> {+ let (areq_authentication_data, redirection_data, connector_metadata) = match response {+ core_types::PaymentsResponseData::TransactionResponse {+ authentication_data,+ redirection_data,+ connector_metadata,+ ..+ } => (+ authentication_data.clone().map(|boxed| *boxed),+ (**redirection_data).clone(),+ connector_metadata.clone(),+ ),+ _ => (None, None, None),+ };++ let app_acs = connector_metadata.as_ref().and_then(|metadata| {+ serde_json::from_value::<AppChallengeAcsMetadata>(metadata.clone()).ok()+ });++ let (acs_url, challenge_request) = match &redirection_data {+ Some(hyperswitch_domain_models::router_response_types::RedirectForm::Form {+ endpoint,+ form_fields,+ ..+ }) => (+ Some(endpoint.clone()),+ form_fields.get(consts::CREQ_CHALLENGE_REQUEST_KEY).cloned(),+ ),+ _ => (None, None),+ };+ let acs_signed_content = app_acs.as_ref().and_then(|m| m.acs_signed_content.clone());+ let acs_reference_number = app_acs+ .as_ref()+ .and_then(|m| m.acs_reference_number.clone());++ let trans_status = areq_authentication_data+ .as_ref()+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable("UCS authenticate response missing authentication_data")?+ .trans_status+ .clone()+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable("UCS authenticate response missing trans_status")?;+ let acs_trans_id = areq_authentication_data+ .as_ref()+ .and_then(|data| data.acs_trans_id.clone())+ .or_else(|| app_acs.as_ref().and_then(|m| m.acs_trans_id.clone()));+ let eci = areq_authentication_data+ .as_ref()+ .and_then(|data| data.eci.clone());+ let ds_trans_id = areq_authentication_data+ .as_ref()+ .and_then(|data| data.ds_trans_id.clone());+ let three_ds_server_transaction_id = areq_authentication_data+ .as_ref()+ .and_then(|data| data.threeds_server_transaction_id.clone());++ let areq_cavv = areq_authentication_data+ .as_ref()+ .and_then(|data| data.cavv.clone());++ let authentication_type = common_enums::DecoupledAuthenticationType::from(trans_status.clone());++ let acs_url = acs_url+ .map(|url| url::Url::parse(&url))+ .transpose()+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("acs_url returned by UCS authenticate is not a valid URL")?;++ let authn_flow_type = match authentication_type {+ common_enums::DecoupledAuthenticationType::Challenge => {+ hyperswitch_domain_models::router_request_types::authentication::AuthNFlowType::Challenge(Box::new(+ hyperswitch_domain_models::router_request_types::authentication::ChallengeParams {+ acs_url: acs_url.clone(),+ challenge_request: challenge_request.clone(),+ challenge_request_key: None,+ acs_reference_number: acs_reference_number.clone(),+ acs_trans_id: acs_trans_id.clone(),+ three_dsserver_trans_id: three_ds_server_transaction_id.clone(),+ acs_signed_content: acs_signed_content.clone(),+ },+ ))+ }+ common_enums::DecoupledAuthenticationType::Frictionless => {+ hyperswitch_domain_models::router_request_types::authentication::AuthNFlowType::Frictionless+ }+ };++ let authenticate_response_data =+ core_types::authentication::AuthenticationResponseData::AuthNResponse {+ authn_flow_type,+ authentication_value: areq_cavv,+ trans_status: trans_status.clone(),+ connector_metadata: None,+ ds_trans_id,+ eci,+ challenge_code: areq_authentication_data+ .as_ref()+ .and_then(|data| data.challenge_code.clone()),+ challenge_cancel: areq_authentication_data+ .as_ref()+ .and_then(|data| data.challenge_cancel.clone()),+ challenge_code_reason: areq_authentication_data+ .as_ref()+ .and_then(|data| data.challenge_code_reason.clone()),+ message_extension: areq_authentication_data+ .as_ref()+ .and_then(|data| data.message_extension.clone()),+ };++ Ok(ParsedAuthenticateResponse {+ authenticate_response_data,+ authentication_type,+ trans_status,+ acs_url,+ challenge_request,+ acs_reference_number,+ acs_trans_id,+ three_ds_server_transaction_id,+ acs_signed_content,+ })+}++/// Proxy analogue of `perform_authentication` (the AReq step), called from the+/// `/payments/{id}/3ds/authentication` handler for external-vault-proxy payments.+#[cfg(feature = "v1")]+#[allow(clippy::too_many_arguments)]+pub async fn perform_authentication_proxy(+ state: &SessionState,+ platform: &domain::Platform,+ payment_intent: &hyperswitch_domain_models::payments::PaymentIntent,+ payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,+ business_profile: &domain::Profile,+ amount: common_utils::types::MinorUnit,+ currency: Currency,+ billing_address: Option<hyperswitch_domain_models::address::Address>,+ shipping_address: Option<hyperswitch_domain_models::address::Address>,+ optional_email: Option<common_utils::pii::Email>,+ header_payload: hyperswitch_domain_models::payments::HeaderPayload,+ device_channel: payments::DeviceChannel,+ sdk_information: Option<payments::SdkInformation>,+) -> CustomResult<api::authentication::AuthenticationResponse, ApiErrorResponse> {+ let processor = platform.get_processor();+ let key_store = processor.get_key_store();+ let storage_scheme = processor.get_account().storage_scheme;++ let AuthenticateProxyContext {+ authenticate_router_data,+ authentication,+ authentication_id,+ auth_connector_enum,+ auth_merchant_connector_account,+ payment_method,+ browser_info,+ } = Box::pin(call_ucs_authenticate_proxy(+ state,+ platform,+ payment_intent,+ payment_attempt,+ business_profile,+ amount,+ currency,+ billing_address.clone(),+ optional_email.clone(),+ &header_payload,+ device_channel.clone(),+ sdk_information.clone(),+ ))+ .await?;++ let authenticate_response_data_ref =+ authenticate_router_data.response.as_ref().map_err(|err| {+ error_stack::report!(ApiErrorResponse::ExternalConnectorError {+ code: err.code.clone(),+ message: err.message.clone(),+ connector: auth_connector_enum.to_string(),+ status_code: err.status_code,+ reason: err.reason.clone(),+ })+ })?;++ let ParsedAuthenticateResponse {+ authenticate_response_data,+ authentication_type,+ trans_status,+ acs_url,+ challenge_request,+ acs_reference_number,+ acs_trans_id,+ three_ds_server_transaction_id,+ acs_signed_content,+ } = parse_ucs_authenticate_response(authenticate_response_data_ref)?;++ let mut authenticate_tracker_router_data: core_types::RouterData<+ api::Authentication,+ (),+ core_types::authentication::AuthenticationResponseData,+ > = transformers::construct_router_data(+ state,+ auth_connector_enum.to_string(),+ payment_method,+ business_profile.merchant_id.clone(),+ hyperswitch_domain_models::payment_address::PaymentAddress::new(+ None,+ billing_address.clone(),+ None,+ None,+ ),+ (),+ &auth_merchant_connector_account,+ payment_intent.psd2_sca_exemption_type,+ payment_intent.payment_id.clone(),+ )?;+ authenticate_tracker_router_data.response = Ok(authenticate_response_data);++ let authentication_info =+ hyperswitch_domain_models::router_request_types::authentication::AuthenticationInfo {+ billing_address,+ shipping_address,+ browser_info,+ email: optional_email,+ device_details: sdk_information+ .as_ref()+ .and_then(|sdk_information| sdk_information.device_details.clone()),+ merchant_category_code: None,+ merchant_country_code: None,+ platform: Some(device_channel),+ };++ let authentication = Box::pin(utils::update_trackers(+ state,+ authenticate_tracker_router_data,+ authentication,+ None,+ key_store,+ authentication_info,+ storage_scheme,+ ))+ .await?;++ let attempt_update = PaymentAttemptUpdate::AuthenticationUpdate {+ status: payment_attempt.status,+ external_three_ds_authentication_attempted: Some(true),+ external_threeds_authentication_type: Some(authentication_type),+ authentication_connector: authentication.authentication_connector.clone(),+ authentication_id: Some(authentication_id),+ updated_by: storage_scheme.to_string(),+ };+ state+ .store+ .update_payment_attempt_with_attempt_id(+ payment_attempt.clone(),+ attempt_update,+ storage_scheme,+ key_store,+ )+ .await+ .to_not_found_response(ApiErrorResponse::PaymentNotFound)+ .attach_printable(+ "Error while updating the payment_attempt for external vault authenticate",+ )?;++ Ok(api::authentication::AuthenticationResponse {+ trans_status,+ acs_url,+ challenge_request,+ acs_reference_number,+ acs_trans_id,+ three_dsserver_trans_id: three_ds_server_transaction_id,+ acs_signed_content,+ challenge_request_key: None,+ // A connector-level error is now a hard `Err` above, not a value ending up here.+ error_message: None,+ })+}diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex 0201edeb89..85fc4b266b 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -6106,6 +6106,25 @@ impl RawPaymentMethodFetchAccess {}Self::Allowed => {+ // Externally-vaulted (proxy) cards have no PAN in our own vault to retrieve — the+ // card lives at the external vault (e.g. VGS) and is never given a `locker_id`, so+ // a live `retrieve_payment_method_data_from_storage` call always fails with a+ // missing `connector_vault_id`. Short-circuit the same way `Denied` does and hand+ // back the stored alias as a `ProxyCard` instead of attempting a vault fetch.+ let proxy_card_data = payment_method+ .external_vault_token_data+ .clone()+ .map(|enc| enc.into_inner());+ if let Some(external_vault_token_data) = proxy_card_data {+ return Ok(Some(payment_methods::RawPaymentMethodData::ProxyCard(+ payment_methods::RawProxyCardDataResponse {+ card_number: external_vault_token_data.tokenized_card_number,+ card_exp_year: None,+ card_exp_month: None,+ },+ )));+ }+let should_skip_vault_fetch = matches!(payment_method.payment_method_type,Some(enums::PaymentMethod::Wallet) | Some(enums::PaymentMethod::BankRedirect)diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 0b1b2af775..2123b1dc8d 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -3082,190 +3082,255 @@ where).await?;- // Dispatch on the resolved connector call type, mirroring `payments_operation_core`: the- // prerequisites and the unified-connector-service decision both happen inside the match arm.- // The external vault proxy flow currently supports only a single, predetermined connector.- let (connector, merchant_connector_account, router_data) = match connector {- Some(ConnectorCallType::PreDetermined(connector_routing_data)) => {- let connector = connector_routing_data.connector_data;-- // `choose_connector` does not persist the chosen connector in the payment attempt for- // this flow, so set it explicitly — the confirm update tracker reads it back.- payment_data- .set_connector_in_payment_attempt(Some(connector.connector_name.to_string()));+ tokenize_in_router_when_external_authentication_proxy(+ state,+ &mut payment_data,+ &business_profile,+ platform.get_processor().get_key_store(),+ )+ .await?;- let (- merchant_connector_account,- external_vault_merchant_connector_account,- router_data,- ) = call_connector_service_prerequisites_for_external_vault_proxy_v1(+ // Dispatch external 3DS (Netcetera-over-VGS) pre-/post-authentication if eligible, exactly+ // the same trait hook `payments_operation_core` dispatches for the normal flow — never a+ // free function called directly. `should_continue_confirm_transaction=false` means either a+ // challenge is pending (SDK must drive `/3ds/authentication` next) or authentication failed;+ // either way the connector must not be called this round.+ let mut should_continue_confirm_transaction = true;+ if let Some(connector_call_type) = connector.as_ref() {+ operation+ .to_domain()?+ .call_external_three_ds_authentication_if_eligible(state,- &platform,&mut payment_data,- &connector,+ &mut should_continue_confirm_transaction,+ connector_call_type,&business_profile,- header_payload.clone(),+ platform.get_processor(),+ platform.get_initiator(),+ mandate_type,).await?;+ }- let router_data = decide_unified_connector_service_call_for_external_vault_proxy_v1(- state,- req_state.clone(),- &platform,- &operation,- &mut payment_data,- &connector,- merchant_connector_account.clone(),- external_vault_merchant_connector_account,- router_data,- call_connector_action.clone(),- header_payload.clone(),- &business_profile,- &dimensions,- return_raw_connector_response,- )- .await?;+ let (payment_data, connector_http_status_code, external_latency) =+ if should_continue_confirm_transaction {+ // Dispatch on the resolved connector call type, mirroring `payments_operation_core`: the+ // prerequisites and the unified-connector-service decision both happen inside the match arm.+ // The external vault proxy flow currently supports only a single, predetermined connector.+ let (connector, merchant_connector_account, router_data) = match connector {+ Some(ConnectorCallType::PreDetermined(connector_routing_data)) => {+ let connector = connector_routing_data.connector_data;- (connector, merchant_connector_account, router_data)- }- Some(ConnectorCallType::Retryable(connectors)) => {- // The proxy flow does not retry — use the first eligible connector.- let connector = connectors- .into_iter()- .next()- .ok_or_else(|| {- error_stack::report!(errors::ApiErrorResponse::InternalServerError)- .attach_printable("No eligible connector resolved for external vault proxy")- })?- .connector_data;+ // `choose_connector` does not persist the chosen connector in the payment attempt for+ // this flow, so set it explicitly — the confirm update tracker reads it back.+ payment_data.set_connector_in_payment_attempt(Some(+ connector.connector_name.to_string(),+ ));- // `choose_connector` does not persist the chosen connector in the payment attempt for- // this flow, so set it explicitly — the confirm update tracker reads it back.- payment_data- .set_connector_in_payment_attempt(Some(connector.connector_name.to_string()));+ let (+ merchant_connector_account,+ external_vault_merchant_connector_account,+ router_data,+ ) = call_connector_service_prerequisites_for_external_vault_proxy_v1(+ state,+ &platform,+ &mut payment_data,+ &connector,+ &business_profile,+ header_payload.clone(),+ )+ .await?;- let (- merchant_connector_account,- external_vault_merchant_connector_account,- router_data,- ) = call_connector_service_prerequisites_for_external_vault_proxy_v1(- state,- &platform,- &mut payment_data,- &connector,- &business_profile,- header_payload.clone(),- )- .await?;+ let router_data =+ decide_unified_connector_service_call_for_external_vault_proxy_v1(+ state,+ req_state.clone(),+ &platform,+ &operation,+ &mut payment_data,+ &connector,+ merchant_connector_account.clone(),+ external_vault_merchant_connector_account,+ router_data,+ call_connector_action.clone(),+ header_payload.clone(),+ &business_profile,+ &dimensions,+ return_raw_connector_response,+ )+ .await?;- let router_data = decide_unified_connector_service_call_for_external_vault_proxy_v1(- state,- req_state.clone(),- &platform,- &operation,- &mut payment_data,- &connector,- merchant_connector_account.clone(),- external_vault_merchant_connector_account,- router_data,- call_connector_action.clone(),- header_payload.clone(),- &business_profile,- &dimensions,- return_raw_connector_response,- )- .await?;+ (connector, merchant_connector_account, router_data)+ }+ Some(ConnectorCallType::Retryable(connectors)) => {+ // The proxy flow does not retry — use the first eligible connector.+ let connector = connectors+ .into_iter()+ .next()+ .ok_or_else(|| {+ error_stack::report!(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "No eligible connector resolved for external vault proxy",+ )+ })?+ .connector_data;- (connector, merchant_connector_account, router_data)- }- Some(ConnectorCallType::SessionMultiple(_)) => {- return Err(- error_stack::report!(errors::ApiErrorResponse::InternalServerError)- .attach_printable(- "SessionMultiple connector call type is not supported for external vault proxy",- ),- )- }- None => {- return Err(- error_stack::report!(errors::ApiErrorResponse::InternalServerError)- .attach_printable("No eligible connector resolved for external vault proxy"),- )- }- };+ // `choose_connector` does not persist the chosen connector in the payment attempt for+ // this flow, so set it explicitly — the confirm update tracker reads it back.+ payment_data.set_connector_in_payment_attempt(Some(+ connector.connector_name.to_string(),+ ));- let op_ref = &operation;- let should_trigger_post_processing_flows = is_operation_confirm(&operation);+ let (+ merchant_connector_account,+ external_vault_merchant_connector_account,+ router_data,+ ) = call_connector_service_prerequisites_for_external_vault_proxy_v1(+ state,+ &platform,+ &mut payment_data,+ &connector,+ &business_profile,+ header_payload.clone(),+ )+ .await?;- let operation = Box::new(PaymentResponse);+ let router_data =+ decide_unified_connector_service_call_for_external_vault_proxy_v1(+ state,+ req_state.clone(),+ &platform,+ &operation,+ &mut payment_data,+ &connector,+ merchant_connector_account.clone(),+ external_vault_merchant_connector_account,+ router_data,+ call_connector_action.clone(),+ header_payload.clone(),+ &business_profile,+ &dimensions,+ return_raw_connector_response,+ )+ .await?;- let connector_http_status_code = router_data.connector_http_status_code;- let external_latency = router_data.external_latency;+ (connector, merchant_connector_account, router_data)+ }+ Some(ConnectorCallType::SessionMultiple(_)) => return Err(error_stack::report!(+ errors::ApiErrorResponse::InternalServerError+ )+ .attach_printable(+ "SessionMultiple connector call type is not supported for external vault proxy",+ )),+ None => {+ return Err(+ error_stack::report!(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "No eligible connector resolved for external vault proxy",+ ),+ )+ }+ };- add_connector_http_status_code_metrics(connector_http_status_code);+ let op_ref = &operation;+ let should_trigger_post_processing_flows = is_operation_confirm(&operation);- #[cfg(all(feature = "dynamic_routing", feature = "v1"))]- let routable_connectors =- convert_connector_data_to_routable_connectors(&[connector.clone().into()])- .map_err(|e| logger::error!(routable_connector_error=?e))- .unwrap_or_default();+ let operation = Box::new(PaymentResponse);- let router_data_for_pm_mandate = router_data.clone();+ let connector_http_status_code = router_data.connector_http_status_code;+ let external_latency = router_data.external_latency;- handle_pm_and_mandate_post_update(- state,- operation.as_ref(),- &router_data_for_pm_mandate,- &platform,- &mut payment_data,- &business_profile,- req.get_payment_method_data(),- &feature_config,- &dimensions.without_profile_id(),- )- .await?;+ add_connector_http_status_code_metrics(connector_http_status_code);- let mut payment_data = operation- .to_post_update_tracker()?- .update_tracker(- state,- platform.get_processor(),- payment_data,- router_data,- &locale,- #[cfg(all(feature = "dynamic_routing", feature = "v1"))]- routable_connectors,#[cfg(all(feature = "dynamic_routing", feature = "v1"))]- &business_profile,- &dimensions.without_profile_id(),- )- .await?;+ let routable_connectors =+ convert_connector_data_to_routable_connectors(&[connector.clone().into()])+ .map_err(|e| logger::error!(routable_connector_error=?e))+ .unwrap_or_default();- if should_trigger_post_processing_flows {- complete_postprocessing_steps_if_required(- state,- platform.get_processor(),- &merchant_connector_account,- &connector,- &mut payment_data,- op_ref,- Some(header_payload.clone()),- )- .await?;- }+ let router_data_for_pm_mandate = router_data.clone();- let cloned_payment_data = payment_data.clone();+ handle_pm_and_mandate_post_update(+ state,+ operation.as_ref(),+ &router_data_for_pm_mandate,+ &platform,+ &mut payment_data,+ &business_profile,+ req.get_payment_method_data(),+ &feature_config,+ &dimensions.without_profile_id(),+ )+ .await?;- utils::trigger_payments_webhook(- &platform,- business_profile,- cloned_payment_data,- state,- operation,- )- .await- .map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error))- .ok();+ let mut payment_data = operation+ .to_post_update_tracker()?+ .update_tracker(+ state,+ platform.get_processor(),+ payment_data,+ router_data,+ &locale,+ #[cfg(all(feature = "dynamic_routing", feature = "v1"))]+ routable_connectors,+ #[cfg(all(feature = "dynamic_routing", feature = "v1"))]+ &business_profile,+ &dimensions.without_profile_id(),+ )+ .await?;++ if should_trigger_post_processing_flows {+ complete_postprocessing_steps_if_required(+ state,+ platform.get_processor(),+ &merchant_connector_account,+ &connector,+ &mut payment_data,+ op_ref,+ Some(header_payload.clone()),+ )+ .await?;+ }++ utils::trigger_payments_webhook(+ &platform,+ business_profile.clone(),+ payment_data.clone(),+ state,+ operation,+ )+ .await+ .map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error))+ .ok();++ (payment_data, connector_http_status_code, external_latency)+ } else {+ let (operation, payment_data) = operation+ .to_update_tracker()?+ .update_trackers(+ state,+ req_state.clone(),+ platform.get_processor(),+ payment_data,+ None,+ header_payload.clone(),+ &dimensions.without_profile_id(),+ )+ .await?;++ utils::trigger_payments_webhook(+ &platform,+ business_profile.clone(),+ payment_data.clone(),+ state,+ operation,+ )+ .await+ .map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error))+ .ok();++ (payment_data, None, None)+ };Ok((payment_data,@@ -3320,8 +3385,15 @@ wherepayment_data.set_merchant_connector_id_in_attempt(merchant_connector_account.get_mca_id());}- // Fetch the external vault MCA from business_profile- let external_vault_mca_id = business_profile+ let provider_business_profile =+ helpers::resolve_provider_profile(state, platform, business_profile)+ .await+ .inspect_err(|err| {+ logger::error!(resolve_provider_profile_error=?err, "Failed to resolve provider profile for external-vault MCA lookup");+ })?;++ // Fetch the external vault MCA from the provider's business_profile+ let external_vault_mca_id = provider_business_profile.external_vault_details.get_vault_connector_id().ok_or_else(|| {@@ -3329,24 +3401,22 @@ where.attach_printable("external vault is not enabled for this business profile")})?;- let profile_id = payment_data- .get_payment_intent()- .profile_id- .as_ref()- .get_required_value("profile_id")- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("profile_id is not set in payment_intent")?- .clone();-- let external_vault_merchant_connector_account = helpers::get_merchant_connector_account(- state,- platform.get_processor(),- None,- &profile_id,- &connector.connector_name.to_string(),- Some(&external_vault_mca_id),- )- .await?;+ let external_vault_merchant_connector_account =+ helpers::MerchantConnectorAccountType::DbVal(Box::new(+ state+ .store+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(+ platform.get_provider().get_account().get_id(),+ &external_vault_mca_id,+ platform.get_provider().get_key_store(),+ )+ .await+ .to_not_found_response(+ errors::ApiErrorResponse::MerchantConnectorAccountNotFound {+ id: external_vault_mca_id.get_string_repr().to_string(),+ },+ )?,+ ));let router_data = payment_data.construct_router_data(@@ -5154,6 +5224,24 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {.authentication_id.ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("missing authentication_id in payment_attempt")?;+ let business_profile = state+ .store+ .find_business_profile_by_profile_id(+ platform.get_processor().get_key_store(),+ payment_intent+ .profile_id+ .as_ref()+ .ok_or(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("missing profile_id in payment_intent")?,+ )+ .await+ .change_context(errors::ApiErrorResponse::ProfileNotFound {+ id: payment_intent+ .profile_id+ .as_ref()+ .map(|profile_id| profile_id.get_string_repr().to_owned())+ .unwrap_or_default(),+ })?;// Fetching merchant_connector_account to check if pull_mechanism is enabled for 3ds connectorlet authentication_merchant_connector_account = helpers::get_merchant_connector_account(@@ -5210,9 +5298,12 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {merchant_id: req.merchant_id.clone(),feature_metadata: Some(api_models::payments::FeatureMetadata {redirect_response: Some(api_models::payments::RedirectResponse {- param: req.param.map(Secret::new),+ param: req.param.clone().map(Secret::new),json_payload: Some(- req.json_payload.unwrap_or(serde_json::json!({})).into(),+ req.json_payload+ .clone()+ .unwrap_or(serde_json::json!({}))+ .into(),),}),search_tags: None,@@ -5225,7 +5316,71 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {..Default::default()};let is_setup_mandate = payment_intent.is_setup_mandate();- if is_setup_mandate {++ let provider_business_profile = helpers::resolve_provider_profile(+ state,+ &platform,+ &business_profile,+ )+ .await+ .inspect_err(|err| {+ logger::error!(resolve_provider_profile_error=?err, "Failed to resolve provider profile for external-vault probe");+ })?;++ let is_external_vault_payment = provider_business_profile+ .external_vault_details+ .is_external_vault_enabled()+ && match payment_attempt.payment_token.as_ref() {+ Some(token) => read_external_vault_alias_from_temp_locker(+ state,+ token,+ platform.get_processor().get_key_store(),+ )+ .await+ .inspect_err(|err| {+ logger::error!(read_external_vault_alias_error=?err, "payment_token did not resolve to an external-vault alias (expected for a non-proxied card; check for a genuine Redis failure otherwise)");+ })+ .is_ok(),+ None => false,+ };+ if is_external_vault_payment {+ let payment_token = payment_attempt+ .payment_token+ .clone()+ .ok_or(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "payment_token missing on attempt for external vault 3DS redirect completion",+ )?;++ let external_vault_req = api::PaymentsRequest {+ payment_id: Some(req.resource_id.clone()),+ merchant_id: req.merchant_id.clone(),+ payment_token: Some(payment_token),+ payment_method: Some(common_enums::PaymentMethod::Card),+ payment_method_type: payment_attempt.payment_method_type,+ ..Default::default()+ };+ Box::pin(external_vault_proxy_for_payments_core::<+ api::ExternalVaultProxy,+ api::PaymentsResponse,+ _,+ _,+ _,+ PaymentData<api::ExternalVaultProxy>,+ >(+ state.clone(),+ req_state,+ platform.clone(),+ payment_intent.profile_id.clone(),+ PaymentExternalVaultProxyConfirm,+ external_vault_req,+ services::api::AuthFlow::Merchant,+ connector_action,+ HeaderPayload::with_source(enums::PaymentSource::ExternalAuthenticator),+ None,+ ))+ .await?+ } else if is_setup_mandate {Box::pin(payments_core::<api::SetupMandate,api::PaymentsResponse,@@ -6172,8 +6327,13 @@ whereexecution_path,execution_mode,};- // Update feature metadata to track Direct routing usage for stickiness- update_gateway_system_in_feature_metadata(payment_data, gateway_context.get_gateway_system())?;++ if core_utils::get_flow_name::<F>().unwrap_or_default() != "PSync" {+ update_gateway_system_in_feature_metadata(+ payment_data,+ gateway_context.get_gateway_system(),+ )?;+ }let (updated_customer, call_connector_service_response) = call_connector_service(&updated_state,processor,@@ -12925,6 +13085,127 @@ pub async fn route_connector_v1_for_payouts(Ok(ConnectorCallType::Retryable(connector_data))}+#[cfg(feature = "v1")]+pub async fn tokenize_external_vault_alias_proxy(+ state: &SessionState,+ external_vault_pmd: &hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData,+ payment_method: common_enums::PaymentMethod,+ business_profile: &domain::Profile,+ key_store: &domain::MerchantKeyStore,+) -> RouterResult<String> {+ let alias_json = serde_json::to_string(external_vault_pmd)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to serialize external_vault_pmd for temp-locker tokenization")?;+ let token = common_utils::generate_id(consts::ID_LENGTH, "token");+ let intent_fulfillment_time = business_profile+ .get_order_fulfillment_time()+ .unwrap_or(consts::DEFAULT_FULFILLMENT_TIME);+ vault::create_tokenize_with_configurable_expiry(+ state,+ alias_json,+ None,+ token.clone(),+ key_store.key.get_inner(),+ Some(intent_fulfillment_time),+ )+ .await+ .attach_printable("Failed to store external_vault alias in temp locker")?;+ let token_data = storage::PaymentTokenData::temporary_generic(token.clone());+ ParentPaymentMethodToken::create_key_for_token((&token, payment_method))+ .insert(intent_fulfillment_time, token_data, state)+ .await?;+ Ok(token)+}++/// Proxy analogue of `tokenize_in_router_when_confirm_false_or_external_authentication`: creates+/// the vault-alias temp-locker token up front when external 3DS was requested, before the+/// eligibility/pre-authentication hook runs.+#[cfg(feature = "v1")]+pub async fn tokenize_in_router_when_external_authentication_proxy<F, D>(+ state: &SessionState,+ payment_data: &mut D,+ business_profile: &domain::Profile,+ key_store: &domain::MerchantKeyStore,+) -> RouterResult<()>+where+ F: Send + Clone,+ D: OperationSessionGetters<F> + OperationSessionSetters<F>,+{+ let is_external_authentication_requested = payment_data+ .get_payment_intent()+ .request_external_three_ds_authentication+ .unwrap_or(false);+ let external_vault_pmd = is_external_authentication_requested+ .then(|| payment_data.get_external_vault_pmd().cloned())+ .flatten();++ if let Some(external_vault_pmd) = external_vault_pmd {+ let payment_method = payment_data+ .get_payment_attempt()+ .payment_method+ .unwrap_or(common_enums::PaymentMethod::Card);++ let alias_token = tokenize_external_vault_alias_proxy(+ state,+ &external_vault_pmd,+ payment_method,+ business_profile,+ key_store,+ )+ .await+ .attach_printable(+ "Failed to create external vault alias token ahead of 3DS eligibility check",+ )?;+ payment_data.set_token(alias_token);+ }+ Ok(())+}++#[cfg(feature = "v1")]+pub(crate) async fn read_external_vault_alias_from_temp_locker(+ state: &SessionState,+ token: &str,+ key_store: &domain::MerchantKeyStore,+) -> RouterResult<hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData> {+ let alias_json = vault::get_tokenized_data(state, token, false, key_store.key.get_inner())+ .await+ .attach_printable("Failed to read external_vault alias from temp locker")?+ .value1;+ serde_json::from_str(&alias_json)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse external_vault alias from temp locker")+}++#[cfg(feature = "v1")]+pub(crate) async fn resolve_external_vault_alias_from_payment_token(+ state: &SessionState,+ platform: &domain::Platform,+ payment_token: String,+ payment_method: common_enums::PaymentMethod,+) -> RouterResult<hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData> {+ let key_store = platform.get_processor().get_key_store();+ let token_data =+ helpers::retrieve_payment_token_data(state, payment_token, Some(payment_method)).await?;++ match token_data {+ storage::PaymentTokenData::TemporaryGeneric(generic) => {+ read_external_vault_alias_from_temp_locker(state, &generic.token, key_store).await+ }+ // A permanent (saved) payment method token has no CVC to recover here — the CVC-bearing+ // 3DS flow always resolves through a `TemporaryGeneric` alias instead. Fail loudly rather+ // than silently building a cvc-less card.+ storage::PaymentTokenData::Permanent(_) | storage::PaymentTokenData::PermanentCard(_) => {+ Err(errors::ApiErrorResponse::InternalServerError).attach_printable(+ "external vault alias resolution from a saved payment method token is not supported \+ (no CVC recoverable from the modular service)",+ )+ }+ other => Err(errors::ApiErrorResponse::InternalServerError).attach_printable(format!(+ "unexpected payment_token kind for external vault alias resolution: {other:?}"+ ))?,+ }+}+#[cfg(feature = "v2")]pub async fn payment_external_authentication(_state: SessionState,@@ -13053,16 +13334,6 @@ pub async fn payment_external_authentication<F: Clone + Sync>(id: profile_id.get_string_repr().to_owned(),})?;- let payment_method_details = helpers::get_payment_method_details_from_payment_token(- &state,- &payment_attempt,- &payment_intent,- &platform,- storage_scheme,- )- .await?- .ok_or(errors::ApiErrorResponse::InternalServerError)- .attach_printable("missing payment_method_details")?;let browser_info: Option<BrowserInformation> = payment_attempt.browser_info.clone()@@ -13098,66 +13369,100 @@ pub async fn payment_external_authentication<F: Clone + Sync>(.clone().get_required_value("authentication_connector_details").attach_printable("authentication_connector_details not configured by the merchant")?;- let authentication_response =- if helpers::is_merchant_eligible_authentication_service(platform.get_processor(), &state)- .await?- {- let authentication_id = payment_attempt- .authentication_id- .clone()- .ok_or(errors::ApiErrorResponse::InternalServerError)- .attach_printable("missing authentication_id in payment_attempt")?;- let authenticate_req = api_models::authentication::AuthenticationAuthenticateRequest {- authentication_id: authentication_id.clone(),- client_secret: None,- sdk_information: req.sdk_information.clone(),- device_channel: req.device_channel,- threeds_method_comp_ind: req.threeds_method_comp_ind,- };- // If micro service is enabled we do api call else do internal function call- let response = if let Some(auth_config) =- &state.conf.micro_services.authentication_service- {- let req_identifier = router_env::RequestIdentifier::new("x-request-id");- let client = crate::core::authentication_client::AuthenticationServiceClient::new(- auth_config,- &req_identifier,- )- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to create auth client")?;+ let provider_business_profile = helpers::resolve_provider_profile(&state, &platform, &business_profile)+ .await+ .inspect_err(|err| {+ logger::error!(resolve_provider_profile_error=?err, "Failed to resolve provider profile for external-vault probe");+ })?;- crate::core::authentication_client::AuthenticationAuthenticateFlow::call(- &state,- &client,- authenticate_req,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to call authentication authenticate flow")?- } else {- crate::core::unified_authentication_service::authentication_authenticate_core(- state.clone(),- platform.clone(),- authenticate_req,- services::api::AuthFlow::Client,- )- .await?- .get_json_body()- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(- "Failed to get json body from authentication authenticate response",- )?- };+ let is_external_vault_payment = if provider_business_profile+ .external_vault_details+ .is_external_vault_enabled()+ {+ match payment_attempt.payment_token.as_ref() {+ Some(token) => read_external_vault_alias_from_temp_locker(+ &state,+ token,+ platform.get_processor().get_key_store(),+ )+ .await+ .is_ok(),+ None => false,+ }+ } else {+ false+ };+ let authentication_response = if is_external_vault_payment {+ Box::pin(authentication_core::perform_authentication_proxy(+ &state,+ &platform,+ &payment_intent,+ &payment_attempt,+ &business_profile,+ amount,+ currency,+ billing_address.as_ref().map(|address| address.into()),+ shipping_address.as_ref().map(|address| address.into()),+ optional_customer.and_then(|customer| customer.email.map(pii::Email::from)),+ HeaderPayload::default(),+ req.device_channel,+ req.sdk_information,+ ))+ .await?+ } else if helpers::is_merchant_eligible_authentication_service(platform.get_processor(), &state)+ .await?+ {+ let authentication_id = payment_attempt+ .authentication_id+ .clone()+ .ok_or(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("missing authentication_id in payment_attempt")?;- let attempt_update = storage::PaymentAttemptUpdate::AuthenticationUpdate {- status: payment_attempt.status,- external_three_ds_authentication_attempted: Some(true),- external_threeds_authentication_type: response- .transaction_status- .as_ref()- .and_then(|transaction_status| {- match transaction_status {+ let authenticate_req = api_models::authentication::AuthenticationAuthenticateRequest {+ authentication_id: authentication_id.clone(),+ client_secret: None,+ sdk_information: req.sdk_information.clone(),+ device_channel: req.device_channel,+ threeds_method_comp_ind: req.threeds_method_comp_ind,+ };+ // If micro service is enabled we do api call else do internal function call+ let response = if let Some(auth_config) = &state.conf.micro_services.authentication_service+ {+ let req_identifier = router_env::RequestIdentifier::new("x-request-id");+ let client = crate::core::authentication_client::AuthenticationServiceClient::new(+ auth_config,+ &req_identifier,+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to create auth client")?;++ crate::core::authentication_client::AuthenticationAuthenticateFlow::call(+ &state,+ &client,+ authenticate_req,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to call authentication authenticate flow")?+ } else {+ crate::core::unified_authentication_service::authentication_authenticate_core(+ state.clone(),+ platform.clone(),+ authenticate_req,+ services::api::AuthFlow::Client,+ )+ .await?+ .get_json_body()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to get json body from authentication authenticate response")?+ };++ let attempt_update = storage::PaymentAttemptUpdate::AuthenticationUpdate {+ status: payment_attempt.status,+ external_three_ds_authentication_attempted: Some(true),+ external_threeds_authentication_type: response.transaction_status.as_ref().and_then(+ |transaction_status| match transaction_status {common_enums::TransactionStatus::ChallengeRequired| common_enums::TransactionStatus::ChallengeRequiredDecoupledAuthentication => {Some(common_enums::DecoupledAuthenticationType::Challenge)@@ -13166,86 +13471,96 @@ pub async fn payment_external_authentication<F: Clone + Sync>(Some(common_enums::DecoupledAuthenticationType::Frictionless)}_ => None,- }- }),- authentication_connector: response.authentication_connector.map(|c| c.to_string()),- authentication_id: Some(response.authentication_id.clone()),- updated_by: storage_scheme.to_string(),- };+ },+ ),+ authentication_connector: response.authentication_connector.map(|c| c.to_string()),+ authentication_id: Some(response.authentication_id.clone()),+ updated_by: storage_scheme.to_string(),+ };- db.update_payment_attempt_with_attempt_id(- payment_attempt.clone(),- attempt_update,- storage_scheme,+ db.update_payment_attempt_with_attempt_id(+ payment_attempt.clone(),+ attempt_update,+ storage_scheme,+ platform.get_processor().get_key_store(),+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)+ .attach_printable("Error while updating the payment_attempt")?;++ authentication::AuthenticationResponse {+ trans_status: response+ .transaction_status+ .unwrap_or(common_enums::TransactionStatus::VerificationNotPerformed),+ acs_url: response.acs_url,+ challenge_request: response.challenge_request,+ acs_reference_number: response.acs_reference_number,+ acs_trans_id: response.acs_trans_id,+ three_dsserver_trans_id: response.three_ds_server_transaction_id,+ acs_signed_content: response.acs_signed_content,+ challenge_request_key: None,+ error_message: response.error_message,+ }+ } else {+ let authentication = db+ .find_authentication_by_processor_merchant_id_authentication_id(+ processor_merchant_id,+ &payment_attempt+ .authentication_id+ .clone()+ .ok_or(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("missing authentication_id in payment_attempt")?,platform.get_processor().get_key_store(),+ key_manager_state,+ storage_scheme,).await- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)- .attach_printable("Error while updating the payment_attempt")?;-- authentication::AuthenticationResponse {- trans_status: response- .transaction_status- .unwrap_or(common_enums::TransactionStatus::VerificationNotPerformed),- acs_url: response.acs_url,- challenge_request: response.challenge_request,- acs_reference_number: response.acs_reference_number,- acs_trans_id: response.acs_trans_id,- three_dsserver_trans_id: response.three_ds_server_transaction_id,- acs_signed_content: response.acs_signed_content,- challenge_request_key: None,- error_message: response.error_message,- }- } else {- let authentication = db- .find_authentication_by_processor_merchant_id_authentication_id(- processor_merchant_id,- &payment_attempt- .authentication_id- .clone()- .ok_or(errors::ApiErrorResponse::InternalServerError)- .attach_printable("missing authentication_id in payment_attempt")?,- platform.get_processor().get_key_store(),- key_manager_state,- storage_scheme,- )- .await- .to_not_found_response(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Error while fetching authentication record")?;- Box::pin(authentication_core::perform_authentication(- &state,- business_profile.merchant_id,- authentication_connector,- payment_method_details.0,- payment_method_details.1,- billing_address- .as_ref()- .map(|address| address.into())- .ok_or(errors::ApiErrorResponse::MissingRequiredField {- field_name: "billing_address",- })?,- shipping_address.as_ref().map(|address| address.into()),- browser_info,- merchant_connector_account,- Some(amount),- Some(currency),- authentication::MessageCategory::Payment,- req.device_channel,- authentication,- return_url,- req.sdk_information,- req.threeds_method_comp_ind,- optional_customer.and_then(|customer| customer.email.map(pii::Email::from)),- webhook_url,- authentication_details.three_ds_requestor_url.clone(),- payment_intent.psd2_sca_exemption_type,- payment_intent.payment_id,- payment_intent.force_3ds_challenge_trigger.unwrap_or(false),- platform.get_processor().get_key_store(),- storage_scheme,- ))- .await?- };+ .to_not_found_response(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error while fetching authentication record")?;+ let payment_method_details = helpers::get_payment_method_details_from_payment_token(+ &state,+ &payment_attempt,+ &payment_intent,+ &platform,+ storage_scheme,+ )+ .await?+ .ok_or(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("missing payment_method_details")?;+ Box::pin(authentication_core::perform_authentication(+ &state,+ business_profile.merchant_id,+ authentication_connector,+ payment_method_details.0,+ payment_method_details.1,+ billing_address+ .as_ref()+ .map(|address| address.into())+ .ok_or(errors::ApiErrorResponse::MissingRequiredField {+ field_name: "billing_address",+ })?,+ shipping_address.as_ref().map(|address| address.into()),+ browser_info,+ merchant_connector_account,+ Some(amount),+ Some(currency),+ authentication::MessageCategory::Payment,+ req.device_channel,+ authentication,+ return_url,+ req.sdk_information,+ req.threeds_method_comp_ind,+ optional_customer.and_then(|customer| customer.email.map(pii::Email::from)),+ webhook_url,+ authentication_details.three_ds_requestor_url.clone(),+ payment_intent.psd2_sca_exemption_type,+ payment_intent.payment_id,+ payment_intent.force_3ds_challenge_trigger.unwrap_or(false),+ platform.get_processor().get_key_store(),+ storage_scheme,+ ))+ .await?+ };Ok(services::ApplicationResponse::Json(api_models::payments::PaymentsExternalAuthenticationResponse {transaction_status: authentication_response.trans_status,diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rsindex 3258b9f345..55ae3df855 100644--- a/crates/router/src/core/payments/flows/authorize_flow.rs+++ b/crates/router/src/core/payments/flows/authorize_flow.rs@@ -1694,3 +1694,145 @@ pub async fn call_unified_connector_service_pre_authenticate(.await.change_context(interface_errors::ConnectorError::ResponseHandlingFailed)}++/// External-vault-proxy variant of [`call_unified_connector_service_pre_authenticate`] above: the+/// request is built from the resolved `ExternalVaultPaymentMethodData` alias (via the+/// `(router_data, external_vault_pmd)` `ForeignTryFrom` impl) instead of a real+/// `payment_method_data`, and carries `external_vault_proxy_metadata` so the outbound call is+/// routed through the vault's proxy (e.g. VGS).+#[cfg(feature = "v1")]+#[allow(clippy::too_many_arguments)]+pub async fn call_unified_connector_service_pre_authenticate_proxy(+ router_data: &types::RouterData<+ api::PreAuthenticate,+ types::PaymentsPreAuthenticateData,+ types::PaymentsResponseData,+ >,+ external_vault_pmd: &domain::ExternalVaultPaymentMethodData,+ state: &SessionState,+ header_payload: &domain_payments::HeaderPayload,+ lineage_ids: grpc_client::LineageIds,+ merchant_connector_account: helpers::MerchantConnectorAccountType,+ external_vault_merchant_connector_account: helpers::MerchantConnectorAccountType,+ processor: &domain::Processor,+ connector: enums::connector_enums::Connector,+ unified_connector_service_execution_mode: enums::ExecutionMode,+) -> 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(interface_errors::ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to fetch Unified Connector Service client")?;++ let mut payment_pre_authenticate_request =+ payments_grpc::PaymentMethodAuthenticationServicePreAuthenticateRequest::foreign_try_from(+ (router_data, external_vault_pmd),+ )+ .change_context(interface_errors::ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to construct external-vault Payment Pre Authenticate Request")?;++ payment_pre_authenticate_request.connector_feature_data =+ unified_connector_service::build_connector_feature_data_from_auth_mca(+ &merchant_connector_account,+ None,+ None,+ None,+ None,+ )+ .change_context(interface_errors::ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to build connector_feature_data from authentication MCA")?;++ let connector_auth_metadata =+ unified_connector_service::build_unified_connector_service_auth_metadata(+ merchant_connector_account,+ processor.get_account().get_id(),+ router_data.connector.clone(),+ )+ .change_context(interface_errors::ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to construct request metadata")?;++ let external_vault_proxy_metadata =+ unified_connector_service::build_unified_connector_service_external_vault_proxy_metadata_v1(+ external_vault_merchant_connector_account,+ &state.conf.connectors,+ )+ .change_context(interface_errors::ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to construct external vault proxy metadata")?;++ let merchant_reference_id = unified_connector_service::parse_merchant_reference_id(+ header_payload+ .x_reference_id+ .as_deref()+ .unwrap_or(router_data.payment_id.as_str()),+ )+ .map(ucs_types::UcsReferenceId::Payment);+ let resource_id = id_type::PaymentResourceId::from_str(router_data.attempt_id.as_str())+ .inspect_err(+ |err| logger::warn!(error=?err, "Invalid Payment AttemptId for UCS resource id"),+ )+ .ok()+ .map(ucs_types::UcsResourceId::PaymentAttempt);+ let headers_builder = state+ .get_grpc_headers_ucs(unified_connector_service_execution_mode)+ .external_vault_proxy_metadata(Some(external_vault_proxy_metadata))+ .merchant_reference_id(merchant_reference_id)+ .resource_id(resource_id)+ .lineage_ids(lineage_ids);+ let (updated_router_data, _) =+ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(+ router_data.clone(),+ state,+ payment_pre_authenticate_request,+ headers_builder,+ unified_connector_service_execution_mode,+ |mut router_data, payment_pre_authenticate_request, grpc_headers| async move {+ let response = Box::pin(client.payment_pre_authenticate(+ payment_pre_authenticate_request,+ connector_auth_metadata,+ grpc_headers,+ ))+ .await+ .attach_printable("Failed to pre authenticate payment")?;++ let payment_pre_authenticate_response = response.into_inner();++ let (router_data_response, status_code) =+ unified_connector_service::handle_unified_connector_service_response_for_payment_pre_authenticate(+ payment_pre_authenticate_response.clone(),+ router_data.status,+ )+ .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 = match router_data_response {+ Ok(response) => Ok(transform_response_for_pre_authenticate_flow(+ connector, response,+ )?),+ Err(err) => Err(err),+ };+ router_data.response = router_data_response;+ router_data.raw_connector_response = payment_pre_authenticate_response+ .raw_connector_response+ .clone()+ .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))+ },+ ))+ .await+ .change_context(interface_errors::ConnectorError::ResponseHandlingFailed)?;++ Ok(updated_router_data)+}diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rsindex 426a556d53..2069e9bb92 100644--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs@@ -865,6 +865,154 @@ pub async fn call_unified_connector_service_authenticate(Ok(router_data)}+/// External-vault-proxy variant of [`call_unified_connector_service_authenticate`] above: the+/// request is built from the resolved `ExternalVaultPaymentMethodData` alias (via the+/// `(router_data, external_vault_pmd)` `ForeignTryFrom` impl) instead of a real+/// `payment_method_data`, carries `force_3ds_challenge`/notification-url/acquirer metadata merged+/// into `connector_feature_data`, and carries `external_vault_proxy_metadata` so the outbound+/// call is routed through the vault's proxy (e.g. VGS).+// TODO: fold proxy-vs-direct UCS dispatch into the `Gateway`/`FlowGateway` abstraction+// (gateway/authenticate_gateway.rs) instead of core/authentication.rs calling this directly.+#[cfg(feature = "v1")]+#[allow(clippy::too_many_arguments)]+pub async fn call_unified_connector_service_authenticate_proxy(+ router_data: &types::RouterData<+ api::Authenticate,+ types::PaymentsAuthenticateData,+ types::PaymentsResponseData,+ >,+ external_vault_pmd: &domain::ExternalVaultPaymentMethodData,+ state: &SessionState,+ header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ lineage_ids: grpc_client::LineageIds,+ merchant_connector_account: helpers::MerchantConnectorAccountType,+ external_vault_merchant_connector_account: helpers::MerchantConnectorAccountType,+ processor: &domain::Processor,+ unified_connector_service_execution_mode: common_enums::ExecutionMode,+ force_3ds_challenge: Option<bool>,+ notification_url: Option<common_utils::types::Url>,+ acquirer_metadata: Option<serde_json::Value>,+) -> errors::CustomResult<+ types::RouterData<+ api::Authenticate,+ types::PaymentsAuthenticateData,+ types::PaymentsResponseData,+ >,+ interface_errors::ConnectorError,+> {+ let client = state+ .grpc_client+ .unified_connector_service_client+ .clone()+ .ok_or(interface_errors::ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to fetch Unified Connector Service client")?;++ let mut payment_authenticate_request =+ payments_grpc::PaymentMethodAuthenticationServiceAuthenticateRequest::foreign_try_from((+ router_data,+ external_vault_pmd,+ ))+ .change_context(interface_errors::ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to construct external-vault Payment Authenticate Request")?;++ let results_response_notification_url = merchant_connector_account.get_mca_id().map(|mca_id| {+ helpers::create_webhook_url(+ &state.base_url,+ processor.get_account().get_id(),+ mca_id.get_string_repr(),+ )+ });++ payment_authenticate_request.connector_feature_data =+ ucs_core::build_connector_feature_data_from_auth_mca(+ &merchant_connector_account,+ force_3ds_challenge,+ results_response_notification_url,+ notification_url,+ acquirer_metadata,+ )+ .change_context(interface_errors::ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to build connector_feature_data from authentication MCA")?;++ let connector_auth_metadata = ucs_core::build_unified_connector_service_auth_metadata(+ merchant_connector_account,+ processor.get_account().get_id(),+ router_data.connector.clone(),+ )+ .change_context(interface_errors::ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to construct request metadata")?;++ let external_vault_proxy_metadata =+ ucs_core::build_unified_connector_service_external_vault_proxy_metadata_v1(+ external_vault_merchant_connector_account,+ &state.conf.connectors,+ )+ .change_context(interface_errors::ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to construct external vault proxy metadata")?;++ let merchant_reference_id = ucs_core::parse_merchant_reference_id(+ header_payload+ .x_reference_id+ .as_deref()+ .unwrap_or(router_data.payment_id.as_str()),+ )+ .map(ucs_types::UcsReferenceId::Payment);+ let resource_id = id_type::PaymentResourceId::from_str(router_data.attempt_id.as_str())+ .inspect_err(+ |err| logger::warn!(error=?err, "Invalid Payment AttemptId for UCS resource id"),+ )+ .ok()+ .map(ucs_types::UcsResourceId::PaymentAttempt);+ let headers_builder = state+ .get_grpc_headers_ucs(unified_connector_service_execution_mode)+ .external_vault_proxy_metadata(Some(external_vault_proxy_metadata))+ .merchant_reference_id(merchant_reference_id)+ .resource_id(resource_id)+ .lineage_ids(lineage_ids);+ let (updated_router_data, _) = Box::pin(ucs_core::ucs_logging_wrapper_granular(+ router_data.clone(),+ state,+ payment_authenticate_request,+ headers_builder,+ unified_connector_service_execution_mode,+ |mut router_data, payment_authenticate_request, grpc_headers| async move {+ let response = Box::pin(client.payment_authenticate(+ payment_authenticate_request,+ connector_auth_metadata,+ grpc_headers,+ ))+ .await+ .attach_printable("Failed to authenticate payment")?;++ let payment_authenticate_response = response.into_inner();++ let (router_data_response, status_code) =+ ucs_core::handle_unified_connector_service_response_for_payment_authenticate(+ payment_authenticate_response.clone(),+ router_data.status,+ )+ .attach_printable("Failed to deserialize UCS response")?;++ let router_data_response = router_data_response.map(|(response, status)| {+ router_data.status = status;+ response+ });+ router_data.response = router_data_response;+ router_data.raw_connector_response = payment_authenticate_response+ .raw_connector_response+ .clone()+ .map(|raw_connector_response| raw_connector_response.expose().into());+ router_data.connector_http_status_code = Some(status_code);++ Ok((router_data, (), payment_authenticate_response))+ },+ ))+ .await+ .change_context(interface_errors::ConnectorError::ResponseHandlingFailed)?;++ Ok(updated_router_data)+}+#[allow(dead_code, clippy::too_many_arguments)]pub async fn call_unified_connector_service_post_authenticate(router_data: &types::RouterData<@@ -979,6 +1127,141 @@ pub async fn call_unified_connector_service_post_authenticate(Ok(router_data)}+/// External-vault-proxy variant of [`call_unified_connector_service_post_authenticate`] above:+/// the request is built from the resolved `ExternalVaultPaymentMethodData` alias (via the+/// `(router_data, external_vault_pmd)` `ForeignTryFrom` impl) instead of a real+/// `payment_method_data`, and carries `external_vault_proxy_metadata` so the outbound call is+/// routed through the vault's proxy (e.g. VGS).+// TODO: fold proxy-vs-direct UCS dispatch into the `Gateway`/`FlowGateway` abstraction+// (gateway/post_authenticate_gateway.rs) instead of core/authentication.rs calling this directly.+#[cfg(feature = "v1")]+#[allow(clippy::too_many_arguments)]+pub async fn call_unified_connector_service_post_authenticate_proxy(+ router_data: &types::RouterData<+ api::PostAuthenticate,+ types::PaymentsPostAuthenticateData,+ types::PaymentsResponseData,+ >,+ external_vault_pmd: &domain::ExternalVaultPaymentMethodData,+ state: &SessionState,+ header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ lineage_ids: grpc_client::LineageIds,+ merchant_connector_account: helpers::MerchantConnectorAccountType,+ external_vault_merchant_connector_account: helpers::MerchantConnectorAccountType,+ processor: &domain::Processor,+ unified_connector_service_execution_mode: common_enums::ExecutionMode,+) -> errors::CustomResult<+ types::RouterData<+ api::PostAuthenticate,+ types::PaymentsPostAuthenticateData,+ types::PaymentsResponseData,+ >,+ interface_errors::ConnectorError,+> {+ let client = state+ .grpc_client+ .unified_connector_service_client+ .clone()+ .ok_or(interface_errors::ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to fetch Unified Connector Service client")?;++ let mut payment_post_authenticate_request =+ payments_grpc::PaymentMethodAuthenticationServicePostAuthenticateRequest::foreign_try_from(+ (router_data, external_vault_pmd),+ )+ .change_context(interface_errors::ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to construct external-vault Payment Post Authenticate Request")?;++ payment_post_authenticate_request.connector_feature_data =+ ucs_core::build_connector_feature_data_from_auth_mca(+ &merchant_connector_account,+ None,+ None,+ None,+ None,+ )+ .change_context(interface_errors::ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to build connector_feature_data from authentication MCA")?;++ let connector_auth_metadata = ucs_core::build_unified_connector_service_auth_metadata(+ merchant_connector_account,+ processor.get_account().get_id(),+ router_data.connector.clone(),+ )+ .change_context(interface_errors::ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to construct request metadata")?;++ let external_vault_proxy_metadata =+ ucs_core::build_unified_connector_service_external_vault_proxy_metadata_v1(+ external_vault_merchant_connector_account,+ &state.conf.connectors,+ )+ .change_context(interface_errors::ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to construct external vault proxy metadata")?;++ let merchant_reference_id = ucs_core::parse_merchant_reference_id(+ header_payload+ .x_reference_id+ .as_deref()+ .unwrap_or(router_data.payment_id.as_str()),+ )+ .map(ucs_types::UcsReferenceId::Payment);+ let resource_id = id_type::PaymentResourceId::from_str(router_data.attempt_id.as_str())+ .inspect_err(+ |err| logger::warn!(error=?err, "Invalid Payment AttemptId for UCS resource id"),+ )+ .ok()+ .map(ucs_types::UcsResourceId::PaymentAttempt);+ let headers_builder = state+ .get_grpc_headers_ucs(unified_connector_service_execution_mode)+ .external_vault_proxy_metadata(Some(external_vault_proxy_metadata))+ .merchant_reference_id(merchant_reference_id)+ .resource_id(resource_id)+ .lineage_ids(lineage_ids);+ let (updated_router_data, _) = Box::pin(ucs_core::ucs_logging_wrapper_granular(+ router_data.clone(),+ state,+ payment_post_authenticate_request,+ headers_builder,+ unified_connector_service_execution_mode,+ |mut router_data, payment_post_authenticate_request, grpc_headers| async move {+ let response = Box::pin(client.payment_post_authenticate(+ payment_post_authenticate_request,+ connector_auth_metadata,+ grpc_headers,+ ))+ .await+ .attach_printable("Failed to post authenticate payment")?;++ let payment_post_authenticate_response = response.into_inner();++ let (router_data_response, status_code) =+ ucs_core::handle_unified_connector_service_response_for_payment_post_authenticate(+ payment_post_authenticate_response.clone(),+ router_data.status,+ )+ .attach_printable("Failed to deserialize UCS response")?;++ let router_data_response = router_data_response.map(|(response, status)| {+ router_data.status = status;+ response+ });+ router_data.response = router_data_response;+ router_data.raw_connector_response = payment_post_authenticate_response+ .raw_connector_response+ .clone()+ .map(|raw_connector_response| raw_connector_response.expose().into());+ router_data.connector_http_status_code = Some(status_code);++ Ok((router_data, (), payment_post_authenticate_response))+ },+ ))+ .await+ .change_context(interface_errors::ConnectorError::ResponseHandlingFailed)?;++ Ok(updated_router_data)+}+impl<F>ForeignTryFrom<types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>>for types::PaymentsCaptureDatadiff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 0241eeb0e3..bf31a297c8 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -3112,11 +3112,21 @@ pub async fn resolve_provider_profile(}#[cfg(feature = "v2")]{- Err(- report!(errors::ApiErrorResponse::InternalServerError).attach_printable(- "Platform-connected provider profile resolution is not supported in v2",- ),- )+ // v2 MerchantAccount has no `default_profile`; resolve the provider's single business+ // profile (which holds provider-level config, e.g. external vault) by listing its profiles.+ let profiles = state+ .store+ .list_profile_by_merchant_id(+ provider.get_key_store(),+ provider.get_account().get_id(),+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to list provider merchant business profiles")?;+ profiles.into_iter().next().ok_or_else(|| {+ report!(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Provider merchant has no business profile configured")+ })}}}@@ -8828,6 +8838,58 @@ pub async fn get_payment_external_authentication_flow_during_confirm<F: Clone>(})}+/// External-vault-proxy analogue of `PaymentExternalAuthenticationFlow`. Variants carry no+/// card/token/acquirer_details — the proxy has no real card (that data lives on+/// `payment_data.external_vault_pmd` instead), and `perform_pre_authentication_proxy` resolves+/// the authentication connector/acquirer metadata itself. This is a deliberate, narrow+/// near-duplicate of `PaymentExternalAuthenticationFlow`/`get_payment_external_authentication_flow_during_confirm`+/// above (left untouched) rather than a shared-predicate refactor, since the card-vs-vault-alias+/// difference and the synchronous-vs-async (no MCA fetch needed here) shape don't factor cleanly.+#[cfg(feature = "v1")]+#[derive(Debug)]+pub enum PaymentExternalAuthenticationFlowProxy {+ PreAuthenticationFlow,+ PostAuthenticationFlow {+ authentication_id: id_type::AuthenticationId,+ },+}++#[cfg(feature = "v1")]+pub fn get_payment_external_authentication_flow_during_confirm_proxy<F: Clone>(+ payment_data: &PaymentData<F>,+ connector_call_type: &api::ConnectorCallType,+ mandate_type: Option<mandates::MandateTransactionType>,+) -> Option<PaymentExternalAuthenticationFlowProxy> {+ let authentication_id = payment_data.payment_attempt.authentication_id.clone();+ let is_authentication_type_3ds = payment_data.payment_attempt.authentication_type+ == Some(common_enums::AuthenticationType::ThreeDs);+ let separate_authentication_requested = payment_data+ .payment_intent+ .request_external_three_ds_authentication+ .unwrap_or(false);+ let separate_three_ds_authentication_attempted = payment_data+ .payment_attempt+ .external_three_ds_authentication_attempted+ .unwrap_or(false);+ let connector_supports_separate_authn =+ authentication::utils::get_connector_data_if_separate_authn_supported(connector_call_type);++ if separate_three_ds_authentication_attempted {+ authentication_id.map(|authentication_id| {+ PaymentExternalAuthenticationFlowProxy::PostAuthenticationFlow { authentication_id }+ })+ } else if separate_authentication_requested+ && is_authentication_type_3ds+ && mandate_type != Some(mandates::MandateTransactionType::RecurringMandateTransaction)+ && connector_supports_separate_authn.is_some()+ && payment_data.external_vault_pmd.is_some()+ {+ Some(PaymentExternalAuthenticationFlowProxy::PreAuthenticationFlow)+ } else {+ None+ }+}+pub fn get_redis_key_for_extended_card_info(merchant_id: &id_type::MerchantId,payment_id: &id_type::PaymentId,diff --git a/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs b/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rsindex 1ed9e57323..eacac75769 100644--- a/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs+++ b/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs@@ -3,27 +3,31 @@ use std::marker::PhantomData;use api_models::{enums::FrmSuggestion, payments::PaymentsRequest};use async_trait::async_trait;use common_enums;+use common_utils::ext_traits::{Encode, ValueExt};use error_stack::ResultExt;-use hyperswitch_domain_models::payment_methods::VaultPaymentMethodData;+use hyperswitch_domain_models::{+ mandates::MandateTransactionType, payment_methods::VaultPaymentMethodData,+};use hyperswitch_masking::{ExposeInterface, Secret};use router_env::{instrument, tracing};use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};use crate::{core::{+ authentication as authentication_core,configs::dimension_state,errors::{self, CustomResult, RouterResult, StorageErrorExt},payment_methods::{transformers as pm_transformers, transformers::PaymentMethodFetchData},payments::{- helpers, operations, CustomerDetails, OperationSessionSetters, PaymentAddress,- PaymentData,+ helpers, operations, read_external_vault_alias_from_temp_locker, CustomerDetails,+ OperationSessionSetters, PaymentAddress, PaymentData,},utils as core_utils,},routes::{app::ReqState, SessionState},services,types::{- api::{self, PaymentIdTypeExt},+ api::{self, ConnectorCallType, PaymentIdTypeExt},domain,storage::{self, enums as storage_enums},},@@ -33,16 +37,10 @@ use crate::{#[derive(Debug, Clone, Copy)]pub struct PaymentExternalVaultProxyConfirm;-/// Derives the external vault payment method data for the proxy flow from the confirm request-/// and the vault tokens fetched from the modular PM service:-/// - `ProxyCard`: inline vault card data carried directly on the request.-/// - `VaultCardTokenData`: a saved card referenced by `payment_token`; its vault tokens come-/// from `payment_method_wrapper.vault_payment_method_token_data`, combined with the CVC /-/// card holder name supplied on the request.-///-/// Shared by `PaymentExternalVaultProxyConfirm::get_trackers` (two-step confirm) and-/// `PaymentCreate::get_trackers` (single-call create+confirm) so both populate-/// `PaymentData::external_vault_pmd` identically.+/// Derives the external vault payment method data for the proxy flow, from either an inline+/// `ProxyCard` or a saved `VaultCardTokenData` resolved via the modular PM service. Shared by+/// `PaymentExternalVaultProxyConfirm::get_trackers` and `PaymentCreate::get_trackers` so both+/// populate `PaymentData::external_vault_pmd` identically.pub(crate) fn build_external_vault_payment_method_data(request: &PaymentsRequest,payment_method_wrapper: Option<@@ -172,7 +170,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsRequest>platform: &domain::Platform,_auth_flow: services::AuthFlow,_flow_kind: operations::PaymentFlowKind,- _header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ header_payload: &hyperswitch_domain_models::payments::HeaderPayload,payment_method_fetch_data: PaymentMethodFetchData,_dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,_payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,@@ -196,18 +194,37 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsRequest>.await.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;- helpers::validate_payment_status_against_not_allowed_statuses(- payment_intent.status,- &[- storage_enums::IntentStatus::Cancelled,- storage_enums::IntentStatus::Succeeded,- storage_enums::IntentStatus::Processing,- storage_enums::IntentStatus::RequiresCapture,- storage_enums::IntentStatus::RequiresMerchantAction,- storage_enums::IntentStatus::RequiresCustomerAction,- ],- "external_vault_proxy_confirm",- )?;+ if [+ Some(common_enums::PaymentSource::Webhook),+ Some(common_enums::PaymentSource::ExternalAuthenticator),+ ]+ .contains(&header_payload.payment_confirm_source)+ {+ helpers::validate_payment_status_against_not_allowed_statuses(+ payment_intent.status,+ &[+ storage_enums::IntentStatus::Cancelled,+ storage_enums::IntentStatus::Succeeded,+ storage_enums::IntentStatus::Processing,+ storage_enums::IntentStatus::RequiresCapture,+ storage_enums::IntentStatus::RequiresMerchantAction,+ ],+ "external_vault_proxy_confirm",+ )?;+ } else {+ helpers::validate_payment_status_against_not_allowed_statuses(+ payment_intent.status,+ &[+ storage_enums::IntentStatus::Cancelled,+ storage_enums::IntentStatus::Succeeded,+ storage_enums::IntentStatus::Processing,+ storage_enums::IntentStatus::RequiresCapture,+ storage_enums::IntentStatus::RequiresMerchantAction,+ storage_enums::IntentStatus::RequiresCustomerAction,+ ],+ "external_vault_proxy_confirm",+ )?;+ }let mut payment_attempt = db.find_payment_attempt_by_payment_id_processor_merchant_id_attempt_id(@@ -281,8 +298,25 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsRequest>// were retrieved from the modular PM service in `fetch_payment_method` (available here// as `payment_method_wrapper.vault_payment_method_token_data`). We combine those tokens// with the CVC / card holder name supplied on the request.- let external_vault_pmd =- build_external_vault_payment_method_data(request, payment_method_wrapper.as_ref())?;+ let external_vault_pmd = match build_external_vault_payment_method_data(+ request,+ payment_method_wrapper.as_ref(),+ )? {+ Some(pmd) => Some(pmd),+ // A resume confirm carries only `payment_token`, not fresh `payment_method_data` —+ // resolve the same alias the AReq step already used.+ None => match request.payment_token.as_ref() {+ Some(payment_token) => Some(+ read_external_vault_alias_from_temp_locker(+ state,+ payment_token,+ platform.get_processor().get_key_store(),+ )+ .await?,+ ),+ None => None,+ },+ };// `payment_method` / `payment_method_type` are optional on the confirm request but required// for the external vault proxy flow so the routing engine can match connectors. When the@@ -308,8 +342,41 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsRequest>payment_attempt.payment_method = Some(payment_method);payment_attempt.payment_method_type = Some(payment_method_subtype);+ payment_attempt.browser_info = request+ .browser_info+ .clone()+ .or(payment_attempt.browser_info.clone())+ .as_ref()+ .map(Encode::encode_to_value)+ .transpose()+ .change_context(errors::ApiErrorResponse::InvalidDataValue {+ field_name: "browser_info",+ })?;+let payment_method_info = payment_method_wrapper.map(|w| w.payment_method);+ payment_attempt.customer_acceptance = request+ .customer_acceptance+ .clone()+ .map(|customer_acceptance| customer_acceptance.encode_to_value())+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed while encoding customer_acceptance to value")?+ .map(Secret::new)+ .or(payment_attempt.customer_acceptance);++ let customer_acceptance = request.customer_acceptance.clone().or(payment_attempt+ .customer_acceptance+ .clone()+ .map(|customer_acceptance| {+ customer_acceptance+ .expose()+ .parse_value("CustomerAcceptance")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed while deserializing customer_acceptance")+ })+ .transpose()?);+let payment_data = PaymentData {flow: PhantomData,payment_intent,@@ -318,7 +385,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsRequest>mandate_id: None,mandate_connector: None,setup_mandate: None,- customer_acceptance: request.customer_acceptance.clone(),+ customer_acceptance,token: request.payment_token.clone(),address: PaymentAddress::new(shipping_address.as_ref().map(From::from),@@ -415,13 +482,77 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, PaymentsRequest>.connector_request_reference_id.clone();+ let (+ intent_status,+ attempt_status,+ error_code,+ error_message,+ external_three_ds_authentication_attempted,+ external_threeds_authentication_type,+ authentication_connector,+ authentication_id,+ ) = match payment_data.authentication.as_ref() {+ Some(authentication_store) => {+ let authentication = &authentication_store.authentication;+ let external_three_ds_authentication_attempted =+ Some(authentication.is_separate_authn_required());+ let external_threeds_authentication_type = authentication.authentication_type;+ let authentication_connector = authentication.authentication_connector.clone();+ let authentication_id = Some(authentication.authentication_id.clone());+ if authentication.authentication_status.is_failed() {+ (+ storage_enums::IntentStatus::Failed,+ storage_enums::AttemptStatus::Failure,+ Some(Some("EXTERNAL_AUTHENTICATION_FAILURE".to_string())),+ Some(Some("external authentication failure".to_string())),+ external_three_ds_authentication_attempted,+ external_threeds_authentication_type,+ authentication_connector,+ authentication_id,+ )+ } else if authentication.is_separate_authn_required() {+ (+ storage_enums::IntentStatus::RequiresCustomerAction,+ storage_enums::AttemptStatus::AuthenticationPending,+ None,+ None,+ external_three_ds_authentication_attempted,+ external_threeds_authentication_type,+ authentication_connector,+ authentication_id,+ )+ } else {+ (+ storage_enums::IntentStatus::Processing,+ storage_enums::AttemptStatus::Pending,+ None,+ None,+ external_three_ds_authentication_attempted,+ external_threeds_authentication_type,+ authentication_connector,+ authentication_id,+ )+ }+ }+ None => (+ storage_enums::IntentStatus::Processing,+ storage_enums::AttemptStatus::Pending,+ None,+ None,+ None,+ None,+ None,+ None,+ ),+ };+let updated_payment_attempt = state.store.update_payment_attempt_with_attempt_id(payment_data.payment_attempt.clone(),storage::PaymentAttemptUpdate::ConfirmUpdate {currency: payment_data.currency,- status: storage_enums::AttemptStatus::Pending,+ status: attempt_status,payment_method,authentication_type,capture_method: payment_data.payment_attempt.capture_method,@@ -436,14 +567,14 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, PaymentsRequest>.payment_attempt.straight_through_algorithm.clone(),- error_code: None,- error_message: None,+ error_code,+ error_message,updated_by: storage_scheme.to_string(),merchant_connector_id,- external_three_ds_authentication_attempted: None,- external_threeds_authentication_type: None,- authentication_connector: None,- authentication_id: None,+ external_three_ds_authentication_attempted,+ external_threeds_authentication_type,+ authentication_connector,+ authentication_id,payment_method_billing_address_id: payment_data.payment_attempt.payment_method_billing_address_id@@ -499,6 +630,27 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, PaymentsRequest>payment_data.payment_attempt = updated_payment_attempt;+ if payment_data.payment_intent.status != intent_status {+ let updated_payment_intent = state+ .store+ .update_payment_intent(+ payment_data.payment_intent.clone(),+ storage::PaymentIntentUpdate::PGStatusUpdate {+ status: intent_status,+ updated_by: storage_scheme.to_string(),+ incremental_authorization_allowed: payment_data+ .payment_intent+ .incremental_authorization_allowed,+ feature_metadata: payment_data.payment_intent.feature_metadata.clone(),+ },+ key_store,+ storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;+ payment_data.payment_intent = updated_payment_intent;+ }+Ok((Box::new(*self), payment_data))}}@@ -649,19 +801,36 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsRequest, PaymentData<F>>router_env::logger::info!("Skipping PM creation: customer_acceptance is None");return Ok(());}- // A repeat payment that reuses a saved card (the `VaultCardTokenData` / `payment_token`- // flow) already had its existing payment method resolved into `payment_method_info` during- // `get_trackers`. Creating again here would insert a duplicate `payment_methods` record for- // the same card on every off-session repeat, so reuse the existing one — just record its id- // on the attempt. The PM was fetched from the modular service (already `version: V2`), so the- // post-payment update still takes the modular acknowledgement path, not the legacy save path.- if let Some(existing_pm_id) = payment_data++ let existing_pm_id = payment_data.payment_method_info.as_ref().map(|existing_pm| existing_pm.get_id().clone())- {+ .or_else(|| payment_data.payment_attempt.payment_method_id.clone());+ if let Some(existing_pm_id) = existing_pm_id {+ if payment_data.payment_method_info.is_none() {+ match pm_transformers::fetch_payment_method_from_modular_service(+ state,+ platform,+ business_profile.get_id(),+ &existing_pm_id,+ None,+ false,+ )+ .await+ {+ Ok(payment_method_with_raw_data) => {+ let mut pm_info = payment_method_with_raw_data.payment_method;+ pm_info.version = common_enums::ApiVersion::V2;+ payment_data.set_payment_method_info(Some(pm_info));+ }+ Err(err) => {+ router_env::logger::error!(error=?err, "Failed to re-fetch existing PM on 3DS resume for acknowledgement path");+ }+ }+ }router_env::logger::info!(- "Reusing existing payment method resolved from payment_token; skipping duplicate PM creation"+ "Reusing existing payment method; skipping duplicate PM creation");payment_data.set_payment_method_id_in_attempt(Some(existing_pm_id));return Ok(());@@ -785,6 +954,111 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsRequest, PaymentData<F>>Ok(())}+ #[cfg(feature = "v1")]+ async fn call_external_three_ds_authentication_if_eligible<'a>(+ &'a self,+ state: &SessionState,+ payment_data: &mut PaymentData<F>,+ should_continue_confirm_transaction: &mut bool,+ connector_call_type: &ConnectorCallType,+ business_profile: &domain::Profile,+ processor: &domain::Processor,+ initiator: Option<&domain::Initiator>,+ mandate_type: Option<MandateTransactionType>,+ ) -> CustomResult<(), errors::ApiErrorResponse> {+ let external_authentication_flow =+ helpers::get_payment_external_authentication_flow_during_confirm_proxy(+ payment_data,+ connector_call_type,+ mandate_type,+ );+ router_env::logger::info!(+ debug_external_authentication_flow = ?external_authentication_flow,+ debug_authentication_id = ?payment_data.payment_attempt.authentication_id,+ debug_external_three_ds_authentication_attempted = ?payment_data.payment_attempt.external_three_ds_authentication_attempted,+ "DEBUG_PROXY_AUTH_FLOW_DECISION"+ );+ payment_data.authentication = match external_authentication_flow {+ Some(helpers::PaymentExternalAuthenticationFlowProxy::PreAuthenticationFlow) => {+ let (authentication_store, alias_token) =+ Box::pin(authentication_core::perform_pre_authentication_proxy(+ state,+ processor,+ initiator,+ business_profile,+ payment_data,+ ))+ .await?;+ if let Some(authentication_store) = authentication_store.as_ref() {+ if authentication_store+ .authentication+ .is_separate_authn_required()+ || authentication_store+ .authentication+ .authentication_status+ .is_failed()+ {+ *should_continue_confirm_transaction = false;+ let authentication_connector = authentication_store+ .authentication+ .authentication_connector+ .clone()+ .ok_or(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "authentication_connector not present in authentication record",+ )?;+ let connector = authentication_connector+ .parse::<common_enums::connector_enums::Connector>()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Invalid authentication connector name")?;+ let dimensions = dimension_state::Dimensions::new()+ .with_processor_merchant_id(processor.get_processor_merchant_id())+ .with_connector(connector);+ let poll_config = dimensions+ .get_poll_config_external_three_ds(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ Some(payment_data.payment_intent.get_id()),+ )+ .await;+ payment_data.poll_config = Some(poll_config);+ }+ }+ if let Some(token) = alias_token {+ payment_data.token = Some(token);+ }+ authentication_store+ }+ Some(helpers::PaymentExternalAuthenticationFlowProxy::PostAuthenticationFlow {+ authentication_id,+ }) => {+ let authentication_store =+ Box::pin(authentication_core::perform_post_authentication_proxy(+ state,+ processor,+ initiator,+ business_profile,+ payment_data,+ authentication_id,+ ))+ .await?;+ if authentication_store.authentication.authentication_status+ != common_enums::AuthenticationStatus::Success+ {+ *should_continue_confirm_transaction = false;+ }+ router_env::logger::info!(+ debug_authentication_status = ?authentication_store.authentication.authentication_status,+ debug_should_continue_confirm_transaction = *should_continue_confirm_transaction,+ "DEBUG_PROXY_POST_AUTH_RESULT"+ );+ Some(authentication_store)+ }+ None => None,+ };+ Ok(())+ }+#[instrument(skip_all)]async fn get_or_create_customer_details<'a>(&'a self,@@ -794,7 +1068,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsRequest, PaymentData<F>>provider: &domain::Provider,initiator: Option<&domain::Initiator>,_dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,- _mandate_type: Option<api::MandateTransactionType>,+ _mandate_type: Option<MandateTransactionType>,) -> CustomResult<(ExternalVaultProxyOperation<'a, F>, Option<domain::Customer>),errors::StorageError,diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rsindex 703080581f..0270e7a0c2 100644--- a/crates/router/src/core/payments/transformers.rs+++ b/crates/router/src/core/payments/transformers.rs@@ -893,7 +893,11 @@ pub async fn construct_external_vault_proxy_payment_router_data_v1<'a>(Some(RequestIncrementalAuthorization::True)),metadata: payment_data.payment_intent.metadata.clone(),- authentication_data: None,+ authentication_data: payment_data+ .authentication+ .as_ref()+ .map(AuthenticationData::foreign_try_from)+ .transpose()?,customer_acceptance: payment_data.customer_acceptance,split_payments: None,merchant_order_reference_id: None,diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rsindex fb6b5f3ec6..852cf01954 100644--- a/crates/router/src/core/payments/types.rs+++ b/crates/router/src/core/payments/types.rs@@ -391,6 +391,10 @@ impl ForeignTryFrom<&router_request_types::authentication::AuthenticationStore>acs_trans_id: authentication.acs_trans_id.clone(),transaction_id: authentication.connector_authentication_id.clone(),ucaf_collection_indicator: None,+ challenge_code: authentication.challenge_code.clone(),+ challenge_cancel: authentication.challenge_cancel.clone(),+ challenge_code_reason: authentication.challenge_code_reason.clone(),+ message_extension: authentication.message_extension.clone(),})} else {Err(errors::ApiErrorResponse::PaymentAuthenticationFailed { data: None }.into())diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex 85310f7f9b..390a84d140 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -1847,6 +1847,57 @@ fn get_ucs_client(})}+// The UCS proto has no first-class fields for Netcetera-style authentication-connector+// metadata (force_3ds_challenge, results/notification URLs, acquirer details), so these are+// merged into the authentication-connector MCA's metadata JSON and passed through the generic+// `connector_feature_data` string field instead.+#[cfg(feature = "v1")]+pub fn build_connector_feature_data_from_auth_mca(+ merchant_connector_account: &MerchantConnectorAccountType,+ force_3ds_challenge: Option<bool>,+ results_response_notification_url: Option<String>,+ notification_url: Option<common_utils::types::Url>,+ acquirer_metadata: Option<serde_json::Value>,+) -> CustomResult<Option<Secret<String>>, UnifiedConnectorServiceError> {+ merchant_connector_account+ .get_metadata()+ .map(|metadata| {+ let mut metadata_value = metadata.expose();+ if let Some(obj) = metadata_value.as_object_mut() {+ if let Some(force) = force_3ds_challenge {+ obj.insert(+ "force_3ds_challenge".to_string(),+ serde_json::Value::Bool(force),+ );+ }+ if let Some(url) = results_response_notification_url {+ obj.insert(+ "results_response_notification_url".to_string(),+ serde_json::Value::String(url),+ );+ }+ if let Some(url) = notification_url {+ obj.insert(+ "notification_url".to_string(),+ serde_json::Value::String(url.get_string_repr().to_string()),+ );+ }+ if let Some(serde_json::Value::Object(acquirer)) = acquirer_metadata {+ for (key, value) in acquirer {+ obj.insert(key, value);+ }+ }+ }+ serde_json::to_string(&metadata_value)+ .change_context(UnifiedConnectorServiceError::RequestEncodingFailed)+ .attach_printable(+ "Failed to serialize authentication connector MCA metadata for connector_feature_data",+ )+ .map(Secret::new)+ })+ .transpose()+}+fn as_header_value(value: &Secret<String>) -> Option<Secret<String>> {http::HeaderValue::from_str(value.peek()).is_ok()diff --git a/crates/router/src/core/unified_connector_service/connector_config.rs b/crates/router/src/core/unified_connector_service/connector_config.rsindex c2ae3f57ce..03d33d4482 100644--- a/crates/router/src/core/unified_connector_service/connector_config.rs+++ b/crates/router/src/core/unified_connector_service/connector_config.rs@@ -647,6 +647,8 @@ pub enum ConnectorSpecificConfig {},/// Givepayments connector configurationGivepayments { api_key: Secret<String> },+ /// Netcetera authentication connector configuration (no connector-specific config needed)+ Netcetera,/// Santander payout connector configurationSantander {certificates: Secret<String>,@@ -1675,6 +1677,7 @@ impl ForeignTryFrom<(Connector, &ConnectorAuthType, Option<&serde_json::Value>)>}),_ => Err(err("Givepayments requires HeaderKey auth type")),},+ Connector::Netcetera => Ok(Self::Netcetera),Connector::Santander => match auth {ConnectorAuthType::CertificateAuth {certificate,diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rsindex e15b8f5efb..dc9d93b0c6 100644--- a/crates/router/src/core/unified_connector_service/transformers.rs+++ b/crates/router/src/core/unified_connector_service/transformers.rs@@ -1240,7 +1240,126 @@ impl.transpose()?,connector_feature_data: None,capture_method: capture_method.map(|capture_method| capture_method.into()),- webhook_url: None,+ webhook_url: router_data.request.webhook_url.clone(),+ domain_data: None,+ })+ }+}++/// `PaymentMethodAuthenticationServiceAuthenticateRequest.metadata` has no typed proto field for+/// device_channel/sdk_information, so it's JSON-stuffed as a string — same convention used+/// elsewhere for UCS proto gaps (e.g. `AcquirerMetadata` in `core/authentication.rs`).+#[derive(serde::Serialize)]+struct UcsAuthenticateMetadata {+ device_channel: Option<api_models::payments::DeviceChannel>,+ sdk_information: Option<api_models::payments::SdkInformation>,+}++// External-vault-proxy variant of the Authenticate request builder above: the proxy has no+// real card in `payment_method_data` (it lives in the external vault), so the payment method+// is built from the resolved `ExternalVaultPaymentMethodData` alias instead.+impl+ transformers::ForeignTryFrom<(+ &RouterData<+ uas_flows::Authenticate,+ router_request_types::PaymentsAuthenticateData,+ PaymentsResponseData,+ >,+ &hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData,+ )> for payments_grpc::PaymentMethodAuthenticationServiceAuthenticateRequest+{+ type Error = error_stack::Report<UnifiedConnectorServiceError>;+ fn foreign_try_from(+ (router_data, external_vault_pmd): (+ &RouterData<+ uas_flows::Authenticate,+ router_request_types::PaymentsAuthenticateData,+ PaymentsResponseData,+ >,+ &hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData,+ ),+ ) -> Result<Self, Self::Error> {+ let currency = payments_grpc::Currency::foreign_try_from(+ router_data.request.currency.unwrap_or_default(),+ )?;++ let payment_method =+ unified_connector_service::build_unified_connector_service_payment_method_for_external_proxy(+ external_vault_pmd.clone(),+ router_data.request.payment_method_type,+ )?;++ let capture_method = router_data+ .request+ .capture_method+ .map(payments_grpc::CaptureMethod::foreign_try_from)+ .transpose()?;+ let address = payments_grpc::PaymentAddress::foreign_try_from(router_data.address.clone())?;++ let authentication_data = router_data+ .request+ .authentication_data+ .clone()+ .map(payments_grpc::AuthenticationData::foreign_try_from)+ .transpose()?;++ Ok(Self {+ merchant_order_id: Some(router_data.connector_request_reference_id.clone()),+ amount: router_data+ .request+ .minor_amount+ .map(|minor_amount| payments_grpc::Money {+ minor_amount: minor_amount.get_amount_as_i64(),+ currency: currency.into(),+ }),+ payment_method: Some(payment_method),+ customer: Some(payments_grpc::Customer {+ first_name: None,+ last_name: None,+ salutation: None,+ name: None,+ email: router_data+ .request+ .clone()+ .map(|e| e.expose().expose().into()),+ id: None,+ connector_customer_id: router_data.connector_customer.clone(),+ phone_number: None,+ phone_country_code: None,+ customer_document_details: to_grpc_customer_document_details(router_data),+ }),+ address: Some(address),+ authentication_data,+ metadata: Some(+ serde_json::to_string(&UcsAuthenticateMetadata {+ device_channel: router_data.request.device_channel.clone(),+ sdk_information: router_data.request.sdk_information.clone(),+ })+ .change_context(UnifiedConnectorServiceError::RequestEncodingFailed)+ .attach_printable("Failed to serialize device_channel/sdk_information metadata")?+ .into(),+ ),+ return_url: None,+ continue_redirection_url: router_data.request.complete_authorize_url.clone(),+ state: None,+ redirection_response: router_data+ .request+ .redirect_response+ .clone()+ .map(|redirection_response| {+ payments_grpc::RedirectionResponse::foreign_try_from(redirection_response)+ })+ .transpose()?,+ browser_info: router_data+ .request+ .browser_info+ .clone()+ .map(payments_grpc::BrowserInformation::foreign_try_from)+ .transpose()?,+ connector_feature_data: None,+ capture_method: capture_method.map(|capture_method| capture_method.into()),+ webhook_url: router_data.request.webhook_url.clone(),domain_data: None,})}@@ -1341,6 +1460,101 @@ impl}}+// External-vault-proxy variant of the PostAuthenticate request builder above: builds the+// payment method from the resolved `ExternalVaultPaymentMethodData` alias instead of a real+// `payment_method_data`.+impl+ transformers::ForeignTryFrom<(+ &RouterData<+ uas_flows::PostAuthenticate,+ router_request_types::PaymentsPostAuthenticateData,+ PaymentsResponseData,+ >,+ &hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData,+ )> for payments_grpc::PaymentMethodAuthenticationServicePostAuthenticateRequest+{+ type Error = error_stack::Report<UnifiedConnectorServiceError>;+ fn foreign_try_from(+ (router_data, external_vault_pmd): (+ &RouterData<+ uas_flows::PostAuthenticate,+ router_request_types::PaymentsPostAuthenticateData,+ PaymentsResponseData,+ >,+ &hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData,+ ),+ ) -> Result<Self, Self::Error> {+ let currency = payments_grpc::Currency::foreign_try_from(+ router_data.request.currency.unwrap_or_default(),+ )?;++ let address = payments_grpc::PaymentAddress::foreign_try_from(router_data.address.clone())?;++ let payment_method =+ unified_connector_service::build_unified_connector_service_payment_method_for_external_proxy(+ external_vault_pmd.clone(),+ router_data.request.payment_method_type,+ )?;++ let capture_method = router_data+ .request+ .capture_method+ .map(payments_grpc::CaptureMethod::foreign_try_from)+ .transpose()?;++ Ok(Self {+ merchant_order_id: Some(router_data.connector_request_reference_id.clone()),+ amount: router_data+ .request+ .minor_amount+ .map(|minor_amount| payments_grpc::Money {+ minor_amount: minor_amount.get_amount_as_i64(),+ currency: currency.into(),+ }),+ payment_method: Some(payment_method),+ customer: Some(payments_grpc::Customer {+ first_name: None,+ last_name: None,+ salutation: None,+ name: None,+ email: router_data+ .request+ .clone()+ .map(|e| e.expose().expose().into()),+ id: None,+ connector_customer_id: router_data.connector_customer.clone(),+ phone_number: None,+ phone_country_code: None,+ customer_document_details: to_grpc_customer_document_details(router_data),+ }),+ address: Some(address),+ authentication_data: None,+ metadata: None,+ return_url: None,+ continue_redirection_url: None,+ state: None,+ redirection_response: router_data+ .request+ .redirect_response+ .clone()+ .map(|redirection_response| {+ payments_grpc::RedirectionResponse::foreign_try_from(redirection_response)+ })+ .transpose()?,+ browser_info: router_data+ .request+ .browser_info+ .clone()+ .map(payments_grpc::BrowserInformation::foreign_try_from)+ .transpose()?,+ connector_feature_data: None,+ connector_order_reference_id: None,+ capture_method: capture_method.map(|capture_method| capture_method.into()),+ })+ }+}+impltransformers::ForeignTryFrom<&RouterData<@@ -1433,6 +1647,103 @@ impl}}+// External-vault-proxy variant of the PreAuthenticate request builder above: builds the+// payment method from the resolved `ExternalVaultPaymentMethodData` alias instead of a real+// `payment_method_data`.+impl+ transformers::ForeignTryFrom<(+ &RouterData<+ uas_flows::PreAuthenticate,+ router_request_types::PaymentsPreAuthenticateData,+ PaymentsResponseData,+ >,+ &hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData,+ )> for payments_grpc::PaymentMethodAuthenticationServicePreAuthenticateRequest+{+ type Error = error_stack::Report<UnifiedConnectorServiceError>;+ fn foreign_try_from(+ (router_data, external_vault_pmd): (+ &RouterData<+ uas_flows::PreAuthenticate,+ router_request_types::PaymentsPreAuthenticateData,+ PaymentsResponseData,+ >,+ &hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData,+ ),+ ) -> Result<Self, Self::Error> {+ let currency = payments_grpc::Currency::foreign_try_from(+ router_data.request.currency.unwrap_or_default(),+ )?;++ let payment_method =+ unified_connector_service::build_unified_connector_service_payment_method_for_external_proxy(+ external_vault_pmd.clone(),+ router_data.request.payment_method_type,+ )?;++ let capture_method = router_data+ .request+ .capture_method+ .map(payments_grpc::CaptureMethod::foreign_try_from)+ .transpose()?;++ let address = payments_grpc::PaymentAddress::foreign_try_from(router_data.address.clone())?;+ let metadata = router_data+ .request+ .metadata+ .as_ref()+ .map(serde_json::to_string)+ .transpose()+ .change_context(UnifiedConnectorServiceError::RequestEncodingFailed)?+ .map(|s| s.into());++ Ok(Self {+ merchant_order_id: Some(router_data.connector_request_reference_id.clone()),+ amount: Some(payments_grpc::Money {+ minor_amount: router_data.request.minor_amount.get_amount_as_i64(),+ currency: currency.into(),+ }),+ payment_method: Some(payment_method),+ customer: Some(payments_grpc::Customer {+ first_name: None,+ last_name: None,+ salutation: None,+ name: router_data+ .request+ .customer_name+ .clone()+ .map(|customer_name| customer_name.peek().to_owned()),+ email: router_data+ .request+ .clone()+ .map(|e| e.expose().expose().into()),+ id: None,+ connector_customer_id: router_data.connector_customer.clone(),+ phone_number: None,+ phone_country_code: None,+ customer_document_details: to_grpc_customer_document_details(router_data),+ }),+ address: Some(address),+ enrolled_for_3ds: router_data.request.enrolled_for_3ds,+ metadata,+ return_url: router_data.request.router_return_url.clone(),+ continue_redirection_url: router_data.request.complete_authorize_url.clone(),+ state: None,+ browser_info: router_data+ .request+ .browser_info+ .clone()+ .map(payments_grpc::BrowserInformation::foreign_try_from)+ .transpose()?,+ connector_feature_data: None,+ capture_method: capture_method.map(|capture_method| capture_method.into()),+ description: router_data.description.clone(),+ merchant_transaction_id: Some(router_data.connector_request_reference_id.clone()),+ })+ }+}+impl transformers::ForeignTryFrom<&RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>>for payments_grpc::PaymentServiceCaptureRequest{@@ -4794,15 +5105,23 @@ impl transformers::ForeignTryFrom<payments_grpc::AuthenticationData>acs_transaction_id,connector_transaction_id,ucaf_collection_indicator,+ challenge_code,+ challenge_cancel,+ challenge_code_reason,+ message_extension,exemption_indicator: _,network_params: _,created_at: _,- challenge_code: _,- challenge_cancel: _,- challenge_code_reason: _,- message_extension: _,authentication_type: _,} = response;+ let message_extension = message_extension+ .map(|value| {+ serde_json::from_str::<serde_json::Value>(&value)+ .change_context(UnifiedConnectorServiceError::ResponseDeserializationFailed)+ .attach_printable("Failed to deserialize message_extension as JSON")+ })+ .transpose()?+ .map(Secret::new);let trans_status = trans_status.map(payments_grpc::TransactionStatus::try_from).transpose()@@ -4826,6 +5145,10 @@ impl transformers::ForeignTryFrom<payments_grpc::AuthenticationData>acs_trans_id: acs_transaction_id,transaction_id: connector_transaction_id,ucaf_collection_indicator,+ challenge_code,+ challenge_cancel,+ challenge_code_reason,+ message_extension,})}}diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rsindex 17d1b8f7aa..0f2322516a 100644--- a/crates/router/src/core/webhooks/incoming.rs+++ b/crates/router/src/core/webhooks/incoming.rs@@ -1992,15 +1992,99 @@ async fn external_authentication_incoming_webhook_flow().await.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;+ let processor_merchant_id = platform.get_processor().get_account().get_id().clone();let payment_confirm_req = api::PaymentsRequest {payment_id: Some(api_models::payments::PaymentIdType::PaymentIntentId(payment_intent.payment_id.clone(),)),- merchant_id: Some(platform.get_processor().get_account().get_id().clone()),+ merchant_id: Some(processor_merchant_id.clone()),..Default::default()};let is_setup_mandate = payment_intent.is_setup_mandate();- let payments_response = if is_setup_mandate {+ let provider_business_profile = payments::helpers::resolve_provider_profile(+ &state,+ &platform,+ &business_profile,+ )+ .await?;+ let attempt_id = payment_intent.active_attempt.get_id().clone();+ let payment_attempt = state+ .store+ .find_payment_attempt_by_payment_id_processor_merchant_id_attempt_id(+ &payment_intent.payment_id,+ &processor_merchant_id,+ &attempt_id,+ platform.get_processor().get_account().storage_scheme,+ platform.get_processor().get_key_store(),+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;+ // A merchant with external vault enabled can still accept a plain (non-proxied)+ // card for an individual payment — probe whether this payment's payment_token+ // actually resolves to a vault alias before committing to the proxy resume path.+ let is_external_vault_payment = provider_business_profile+ .external_vault_details+ .is_external_vault_enabled()+ && match payment_attempt.payment_token.as_ref() {+ Some(token) => payments::read_external_vault_alias_from_temp_locker(+ &state,+ token,+ platform.get_processor().get_key_store(),+ )+ .await+ .is_ok(),+ None => false,+ };+ let payments_response = if is_external_vault_payment {+ // External-vault-proxy payment: resume through the same proxy confirm+ // operation the normal confirm flow used (`PaymentExternalVaultProxyConfirm`+ // via `external_vault_proxy_for_payments_core`), instead of `payments_core`'s+ // `Authorize`/`SetupMandate` — mirrors the two branches below structurally.+ let payment_token = payment_attempt+ .payment_token+ .clone()+ .get_required_value("payment_token")+ .attach_printable(+ "payment_token missing on attempt for external vault 3DS webhook authorize",+ )?;+ // No `payment_method_data` is sent: `payment_token` alone points at the+ // temp-generic vault alias minted during pre-authentication, which+ // `PaymentExternalVaultProxyConfirm::get_trackers` resolves the same way the+ // AReq step already did (`read_external_vault_alias_from_temp_locker`) — this+ // payment used the inline `vault_data_card` shape at the original confirm,+ // not a saved `VaultCardTokenData` card, so there is nothing to fetch from+ // the modular PM service here.+ let external_vault_req = api::PaymentsRequest {+ payment_id: Some(api_models::payments::PaymentIdType::PaymentIntentId(+ payment_intent.payment_id.clone(),+ )),+ merchant_id: Some(processor_merchant_id.clone()),+ payment_token: Some(payment_token),+ payment_method: Some(common_enums::PaymentMethod::Card),+ payment_method_type: payment_attempt.payment_method_type,+ ..Default::default()+ };+ Box::pin(payments::external_vault_proxy_for_payments_core::<+ api::ExternalVaultProxy,+ api::PaymentsResponse,+ _,+ _,+ _,+ payments::PaymentData<api::ExternalVaultProxy>,+ >(+ state.clone(),+ req_state,+ platform.clone(),+ payment_intent.profile_id.clone(),+ payments::PaymentExternalVaultProxyConfirm,+ external_vault_req,+ services::api::AuthFlow::Merchant,+ payments::CallConnectorAction::Trigger,+ HeaderPayload::with_source(enums::PaymentSource::ExternalAuthenticator),+ None,+ ))+ .await?+ } else if is_setup_mandate {Box::pin(payments::payments_core::<api::SetupMandate,api::PaymentsResponse,