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(payments): add network token MIT with vault card alias fallback (#14639)
Prasunna Soppa7ba2bd2f04b4
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex 2d47bc7669..98a7b69263 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -30092,6 +30092,81 @@}}},+ "NetworkTokenDetails": {+ "type": "object",+ "description": "Network token details for an MIT: no network transaction ID, and no cryptogram.",+ "required": [+ "network_token",+ "token_exp_month",+ "token_exp_year",+ "card_holder_name"+ ],+ "properties": {+ "network_token": {+ "type": "string",+ "description": "The Network Token",+ "example": "4604000460040787"+ },+ "token_exp_month": {+ "type": "string",+ "description": "The token's expiry month",+ "example": "05"+ },+ "token_exp_year": {+ "type": "string",+ "description": "The token's expiry year",+ "example": "24"+ },+ "card_network": {+ "allOf": [+ {+ "$ref": "#/components/schemas/CardNetwork"+ }+ ],+ "nullable": true+ },+ "card_type": {+ "type": "string",+ "description": "The type of the card such as Credit, Debit",+ "example": "CREDIT",+ "nullable": true+ },+ "card_issuing_country": {+ "type": "string",+ "description": "The country in which the card was issued",+ "example": "INDIA",+ "nullable": true+ },+ "bank_code": {+ "type": "string",+ "description": "The bank code of the bank that issued the card",+ "example": "JP_AMEX",+ "nullable": true+ },+ "card_holder_name": {+ "type": "string",+ "description": "The card holder's name",+ "example": "John Test"+ },+ "card_issuer": {+ "type": "string",+ "description": "The name of the issuer of card",+ "example": "chase",+ "nullable": true+ },+ "nick_name": {+ "type": "string",+ "description": "The card holder's nick name",+ "example": "John Test",+ "nullable": true+ },+ "eci": {+ "type": "string",+ "description": "The ECI(Electronic Commerce Indicator) value for this authentication.",+ "nullable": true+ }+ }+ },"NetworkTokenResponse": {"type": "object","properties": {@@ -30150,6 +30225,32 @@}}},+ "NetworkTokenWithVaultCardFallback": {+ "type": "object",+ "description": "Network token details for an MIT, with a vault card to fall back to on a clear-PAN eligible\ndecline. Both arms share one `network_transaction_id`.",+ "required": [+ "network_token",+ "network_transaction_id",+ "vault_card_data"+ ],+ "properties": {+ "network_token": {+ "$ref": "#/components/schemas/NetworkTokenDetails"+ },+ "network_transaction_id": {+ "type": "string",+ "description": "The network transaction ID provided by the card network during a Customer Initiated\nTransaction (CIT) when `setup_future_usage` is set to `off_session`. Shared by both arms."+ },+ "transaction_link_id": {+ "type": "string",+ "description": "The Mastercard Transaction Link Identifier (TLID) provided by the card network during a\nCIT (Customer Initiated Transaction), when `setup_future_usage` is set to `off_session`.",+ "nullable": true+ },+ "vault_card_data": {+ "$ref": "#/components/schemas/VaultCardData"+ }+ }+ },"NetworkTransactionIdAndCardDetails": {"type": "object","required": [@@ -44515,6 +44616,24 @@"$ref": "#/components/schemas/CardWithLimitedData"}}+ },+ {+ "type": "object",+ "required": [+ "type",+ "data"+ ],+ "properties": {+ "type": {+ "type": "string",+ "enum": [+ "network_token_with_vault_card_fallback"+ ]+ },+ "data": {+ "$ref": "#/components/schemas/NetworkTokenWithVaultCardFallback"+ }+ }}],"description": "Details required for recurring payment",diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex feb8e66908..c8385a227b 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -20480,6 +20480,81 @@}}},+ "NetworkTokenDetails": {+ "type": "object",+ "description": "Network token details for an MIT: no network transaction ID, and no cryptogram.",+ "required": [+ "network_token",+ "token_exp_month",+ "token_exp_year",+ "card_holder_name"+ ],+ "properties": {+ "network_token": {+ "type": "string",+ "description": "The Network Token",+ "example": "4604000460040787"+ },+ "token_exp_month": {+ "type": "string",+ "description": "The token's expiry month",+ "example": "05"+ },+ "token_exp_year": {+ "type": "string",+ "description": "The token's expiry year",+ "example": "24"+ },+ "card_network": {+ "allOf": [+ {+ "$ref": "#/components/schemas/CardNetwork"+ }+ ],+ "nullable": true+ },+ "card_type": {+ "type": "string",+ "description": "The type of the card such as Credit, Debit",+ "example": "CREDIT",+ "nullable": true+ },+ "card_issuing_country": {+ "type": "string",+ "description": "The country in which the card was issued",+ "example": "INDIA",+ "nullable": true+ },+ "bank_code": {+ "type": "string",+ "description": "The bank code of the bank that issued the card",+ "example": "JP_AMEX",+ "nullable": true+ },+ "card_holder_name": {+ "type": "string",+ "description": "The card holder's name",+ "example": "John Test"+ },+ "card_issuer": {+ "type": "string",+ "description": "The name of the issuer of card",+ "example": "chase",+ "nullable": true+ },+ "nick_name": {+ "type": "string",+ "description": "The card holder's nick name",+ "example": "John Test",+ "nullable": true+ },+ "eci": {+ "type": "string",+ "description": "The ECI(Electronic Commerce Indicator) value for this authentication.",+ "nullable": true+ }+ }+ },"NetworkTokenDetailsPaymentMethod": {"type": "object","properties": {@@ -20750,6 +20825,32 @@}}},+ "NetworkTokenWithVaultCardFallback": {+ "type": "object",+ "description": "Network token details for an MIT, with a vault card to fall back to on a clear-PAN eligible\ndecline. Both arms share one `network_transaction_id`.",+ "required": [+ "network_token",+ "network_transaction_id",+ "vault_card_data"+ ],+ "properties": {+ "network_token": {+ "$ref": "#/components/schemas/NetworkTokenDetails"+ },+ "network_transaction_id": {+ "type": "string",+ "description": "The network transaction ID provided by the card network during a Customer Initiated\nTransaction (CIT) when `setup_future_usage` is set to `off_session`. Shared by both arms."+ },+ "transaction_link_id": {+ "type": "string",+ "description": "The Mastercard Transaction Link Identifier (TLID) provided by the card network during a\nCIT (Customer Initiated Transaction), when `setup_future_usage` is set to `off_session`.",+ "nullable": true+ },+ "vault_card_data": {+ "$ref": "#/components/schemas/VaultCardData"+ }+ }+ },"NetworkTokenization": {"type": "object","description": "The network tokenization configuration for creating the payment method session",@@ -31387,6 +31488,24 @@"$ref": "#/components/schemas/CardWithLimitedData"}}+ },+ {+ "type": "object",+ "required": [+ "type",+ "data"+ ],+ "properties": {+ "type": {+ "type": "string",+ "enum": [+ "network_token_with_vault_card_fallback"+ ]+ },+ "data": {+ "$ref": "#/components/schemas/NetworkTokenWithVaultCardFallback"+ }+ }}],"description": "Details required for recurring payment",diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rsindex c981d85074..79464a9986 100644--- a/crates/api_models/src/mandates.rs+++ b/crates/api_models/src/mandates.rs@@ -196,6 +196,11 @@ pub enum RecurringDetails {/// Allows doing MIT with only Card data (no reference id)#[smithy(value_type = "CardWithLimitedData")]CardWithLimitedData(Box<CardWithLimitedData>),++ /// Network token details for an MIT, with external vault card details to fall back to when+ /// the network token attempt is declined in a way the network flags as retryable on the card.+ #[smithy(value_type = "NetworkTokenWithVaultCardFallback")]+ NetworkTokenWithVaultCardFallback(Box<NetworkTokenWithVaultCardFallback>),}/// Processor payment token for MIT payments where payment_method_data is not available@@ -412,6 +417,68 @@ pub struct NetworkTransactionIdAndNetworkTokenDetails {pub transaction_link_id: Option<String>,}+/// Network token details for an MIT: no network transaction ID, and no cryptogram.+#[derive(+ Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq, SmithyModel,+)]+#[smithy(namespace = "com.hyperswitch.smithy.types")]+pub struct NetworkTokenDetails {+ /// The Network Token+ #[schema(value_type = String, example = "4604000460040787")]+ #[smithy(value_type = "String")]+ pub network_token: cards::NetworkToken,++ /// The token's expiry month+ #[schema(value_type = String, example = "05")]+ #[smithy(value_type = "String")]+ pub token_exp_month: Secret<String>,++ /// The token's expiry year+ #[schema(value_type = String, example = "24")]+ #[smithy(value_type = "String")]+ pub token_exp_year: Secret<String>,++ /// The card network for the card+ #[schema(value_type = Option<CardNetwork>, example = "Visa")]+ #[smithy(value_type = "Option<CardNetwork>")]+ pub card_network: Option<api_enums::CardNetwork>,++ /// The type of the card such as Credit, Debit+ #[schema(example = "CREDIT")]+ #[smithy(value_type = "Option<String>")]+ pub card_type: Option<String>,++ /// The country in which the card was issued+ #[schema(example = "INDIA")]+ #[smithy(value_type = "Option<String>")]+ pub card_issuing_country: Option<String>,++ /// The bank code of the bank that issued the card+ #[schema(example = "JP_AMEX")]+ #[smithy(value_type = "Option<String>")]+ pub bank_code: Option<String>,++ /// The card holder's name+ #[schema(value_type = String, example = "John Test")]+ #[smithy(value_type = "Option<String>")]+ pub card_holder_name: Option<Secret<String>>,++ /// The name of the issuer of card+ #[schema(example = "chase")]+ #[smithy(value_type = "Option<String>")]+ pub card_issuer: Option<String>,++ /// The card holder's nick name+ #[schema(value_type = Option<String>, example = "John Test")]+ #[smithy(value_type = "Option<String>")]+ pub nick_name: Option<Secret<String>>,++ /// The ECI(Electronic Commerce Indicator) value for this authentication.+ #[schema(value_type = Option<String>)]+ #[smithy(value_type = "Option<String>")]+ pub eci: Option<String>,+}+/// Card details held in an external vault, referenced by a vault alias rather than by PAN.#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq, SmithyModel,@@ -502,6 +569,74 @@ pub struct NetworkTransactionIdAndVaultCardDetails {pub transaction_link_id: Option<String>,}+/// Network token details for an MIT, with a vault card to fall back to on a clear-PAN eligible+/// decline. Both arms share one `network_transaction_id`.+#[derive(+ Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq, SmithyModel,+)]+#[smithy(namespace = "com.hyperswitch.smithy.types")]+pub struct NetworkTokenWithVaultCardFallback {+ /// The network token to attempt first+ #[smithy(value_type = "NetworkTokenDetails")]+ pub network_token: NetworkTokenDetails,++ /// The network transaction ID provided by the card network during a Customer Initiated+ /// Transaction (CIT) when `setup_future_usage` is set to `off_session`. Shared by both arms.+ #[schema(value_type = String)]+ #[smithy(value_type = "String")]+ pub network_transaction_id: Secret<String>,++ /// The Mastercard Transaction Link Identifier (TLID) provided by the card network during a+ /// CIT (Customer Initiated Transaction), when `setup_future_usage` is set to `off_session`.+ #[schema(value_type = Option<String>)]+ #[smithy(value_type = "Option<String>")]+ pub transaction_link_id: Option<String>,++ /// The external vault card details to fall back to+ #[smithy(value_type = "VaultCardData")]+ pub vault_card_data: VaultCardData,+}++impl NetworkTokenWithVaultCardFallback {+ /// Arm 1's details, as the concrete type. Callers that need the enum use+ /// [`Self::to_network_token_arm`]; this exists so conversions over the struct stay total.+ pub fn network_token_arm_details(&self) -> NetworkTransactionIdAndNetworkTokenDetails {+ NetworkTransactionIdAndNetworkTokenDetails {+ network_token: self.network_token.network_token.clone(),+ token_exp_month: self.network_token.token_exp_month.clone(),+ token_exp_year: self.network_token.token_exp_year.clone(),+ card_network: self.network_token.card_network.clone(),+ card_type: self.network_token.card_type.clone(),+ card_issuing_country: self.network_token.card_issuing_country.clone(),+ bank_code: self.network_token.bank_code.clone(),+ card_holder_name: self.network_token.card_holder_name.clone(),+ card_issuer: self.network_token.card_issuer.clone(),+ nick_name: self.network_token.nick_name.clone(),+ eci: self.network_token.eci.clone(),+ network_transaction_id: self.network_transaction_id.clone(),+ transaction_link_id: self.transaction_link_id.clone(),+ }+ }++ /// Arm 1 — the network token attempt, in the shape the existing NTI proxy core understands.+ pub fn to_network_token_arm(&self) -> RecurringDetails {+ RecurringDetails::NetworkTransactionIdAndNetworkTokenDetails(Box::new(+ self.network_token_arm_details(),+ ))+ }++ /// Arm 2 — the vault card alias, in the shape the external vault proxy core understands.+ pub fn to_vault_card_arm(&self) -> RecurringDetails {+ RecurringDetails::NetworkTransactionIdAndVaultCardDetails(Box::new(+ NetworkTransactionIdAndVaultCardDetails {+ vault_card_data: self.vault_card_data.clone(),+ network_transaction_id: self.network_transaction_id.clone(),+ transaction_link_id: self.transaction_link_id.clone(),+ },+ ))+ }+}+impl RecurringDetails {pub fn is_network_transaction_id_and_card_details_flow(self) -> bool {matches!(self, Self::NetworkTransactionIdAndCardDetails(_))diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rsindex d18edd0e34..82d38f2089 100644--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs@@ -1026,8 +1026,10 @@ impl NetworkTokenDetailsForNetworkTransactionId {pub fn get_nti_and_network_token_details_for_mit_flow(network_transaction_id_and_network_token_details: NetworkTransactionIdAndNetworkTokenDetails,) -> (mandates::MandateReferenceId, PaymentMethodData) {+ // A network token replay carries its own mandate reference variant: connectors match on+ // it to pick the token payment source, and `NetworkMandateId` is the raw-card one.let mandate_reference_id =- mandates::MandateReferenceId::NetworkMandateId(mandates::NetworkMandateIdRef {+ mandates::MandateReferenceId::NetworkTokenWithNTI(mandates::NetworkTokenWithNTIRef {network_transaction_id: network_transaction_id_and_network_token_details.network_transaction_id.peek()@@ -1035,6 +1037,16 @@ impl NetworkTokenDetailsForNetworkTransactionId {transaction_link_id: network_transaction_id_and_network_token_details.transaction_link_id.clone(),+ token_exp_month: Some(+ network_transaction_id_and_network_token_details+ .token_exp_month+ .clone(),+ ),+ token_exp_year: Some(+ network_transaction_id_and_network_token_details+ .token_exp_year+ .clone(),+ ),});(@@ -4988,6 +5000,16 @@ impl From<api_mandates::RecurringDetails> for RecurringDetails {) => Self::NetworkTransactionIdAndVaultCardDetails(Box::new((*network_transaction_id_and_vault_card_details).into(),)),+ // The fallback variant is an orchestration-level input: the core flow decomposes it+ // into its two arms (`to_network_token_arm` / `to_vault_card_arm`) before calling a+ // payment core, so only those arm variants ever reach the domain model. Should one+ // leak through, it resolves to the arm that runs first rather than to nothing, so a+ // first attempt still carries its mandate reference.+ api_mandates::RecurringDetails::NetworkTokenWithVaultCardFallback(fallback) => {+ Self::NetworkTransactionIdAndNetworkTokenDetails(Box::new(+ fallback.network_token_arm_details().into(),+ ))+ }api_mandates::RecurringDetails::CardWithLimitedData(card_with_limited_data) => {Self::CardWithLimitedData(Box::new((*card_with_limited_data).into()))}diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex 65461f678d..cda22d4d93 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -901,6 +901,8 @@ Never share your secret api keys. Keep them guarded and secure.api_models::mandates::CardWithLimitedData,api_models::mandates::NetworkTransactionIdAndNetworkTokenDetails,api_models::mandates::NetworkTransactionIdAndVaultCardDetails,+ api_models::mandates::NetworkTokenDetails,+ api_models::mandates::NetworkTokenWithVaultCardFallback,api_models::mandates::VaultCardData,api_models::mandates::ProcessorPaymentToken,api_models::ephemeral_key::EphemeralKeyCreateResponse,diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rsindex c403e763e8..efea0fdeac 100644--- a/crates/openapi/src/openapi_v2.rs+++ b/crates/openapi/src/openapi_v2.rs@@ -679,6 +679,8 @@ Never share your secret api keys. Keep them guarded and secure.api_models::mandates::CardWithLimitedData,api_models::mandates::NetworkTransactionIdAndNetworkTokenDetails,api_models::mandates::NetworkTransactionIdAndVaultCardDetails,+ api_models::mandates::NetworkTokenDetails,+ api_models::mandates::NetworkTokenWithVaultCardFallback,api_models::mandates::VaultCardData,api_models::payments::GooglePaySessionResponse,api_models::payments::GpayShippingAddressParameters,diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex a924a235d6..cfd091dd7d 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -3927,6 +3927,234 @@ where)}+/// Whether the profile that ran the network token arm has clear-PAN retries enabled. An+/// unreadable profile counts as disabled.+#[cfg(feature = "v1")]+async fn is_clear_pan_retry_enabled_for_profile(+ state: &SessionState,+ platform: &domain::Platform,+ network_token_response: &payments_api::PaymentsResponse,+) -> bool {+ match network_token_response.profile_id.as_ref() {+ Some(profile_id) => state+ .store+ .find_business_profile_by_profile_id(+ platform.get_processor().get_key_store(),+ profile_id,+ )+ .await+ .map(|business_profile| business_profile.is_clear_pan_retries_enabled)+ .inspect_err(|error| {+ logger::error!(+ ?error,+ "could not read the profile to check is_clear_pan_retries_enabled; treating the vault card fallback as disabled"+ );+ })+ .unwrap_or(false),+ None => false,+ }+}++/// Whether a declined network-token arm may be re-run against the vault card. Mirrors the+/// clear-PAN rule in `retry.rs`: profile switch on, GSM decides `Retry` and sets+/// `clear_pan_possible`.+#[cfg(feature = "v1")]+async fn is_vault_card_fallback_eligible(+ state: &SessionState,+ platform: &domain::Platform,+ network_token_response: &payments_api::PaymentsResponse,+) -> bool {+ let issuer_details = network_token_response+ .error_details+ .as_ref()+ .and_then(|error_details| error_details.issuer_details.as_ref());+ // The response's `error_message` is `error_reason.or(error_message)`, while `retry.rs` keys+ // the GSM row on the raw connector message. Prefer the raw one so both look up the same row.+ let error_message = network_token_response+ .error_details+ .as_ref()+ .and_then(|error_details| error_details.connector_details.as_ref())+ .and_then(|connector_details| connector_details.message.clone())+ .or_else(|| network_token_response.error_message.clone());++ match (+ network_token_response.status,+ network_token_response.connector.clone(),+ ) {+ // The merchant-level switch gates this exactly as it gates the clear-PAN auto retry in+ // `retry.rs`, so a merchant that turned clear-PAN retries off does not get the fallback+ // either. Checked first, so a disabled profile costs no GSM lookup.+ (enums::IntentStatus::Failed, Some(connector)) => {+ // The vault card arm inherits arm one's gateway, and the external vault proxy has no+ // Direct implementation — a fallback that would land on Direct cannot authorize, so it+ // is not worth creating an attempt for.+ crate::core::unified_connector_service::is_ucs_execution_path_for_external_vault_proxy(+ state,+ platform.get_processor(),+ &connector,+ network_token_response+ .payment_method+ .unwrap_or(common_enums::PaymentMethod::Card),+ network_token_response.payment_method_type,+ )+ .await+ .unwrap_or(false)+ && is_clear_pan_retry_enabled_for_profile(state, platform, network_token_response)+ .await+ && helpers::get_gsm_record(+ state,+ connector.clone(),+ consts::PAYMENT_FLOW_STR,+ &core_utils::get_flow_name::<api::Authorize>().unwrap_or_default(),+ network_token_response.error_code.clone(),+ error_message,+ issuer_details.and_then(|details| details.code.clone()),+ issuer_details+ .and_then(|details| details.network_details.as_ref())+ .and_then(|network_details| network_details.name.clone()),+ )+ .await+ .and_then(|gsm| gsm.feature_data.get_retry_feature_data())+ .map(|retry_feature_data| {+ // Auto retries require the decision as well as the flag, so a row that permits a+ // clear-PAN retry but decides `DoDefault` must not trigger the fallback either.+ retry_feature_data.get_decision() == common_enums::GsmDecision::Retry+ && retry_feature_data.is_clear_pan_possible()+ })+ .unwrap_or(false)+ }+ _ => false,+ }+}++/// Recovers the payment response carried by an [`ApplicationResponse`], if it carries one.+#[cfg(feature = "v1")]+fn payment_response_from_application_response(+ application_response: &services::ApplicationResponse<payments_api::PaymentsResponse>,+) -> Option<&payments_api::PaymentsResponse> {+ match application_response {+ services::ApplicationResponse::Json(response) => Some(response),+ services::ApplicationResponse::JsonWithHeaders((response, _)) => Some(response),+ _ => None,+ }+}++/// Runs a network-token MIT and, on a clear-PAN eligible decline, re-runs it against the vault+/// card under the same network transaction ID.+///+/// The arms run on different cores (`PaymentData<Authorize>` vs `PaymentData<ExternalVaultProxy>`),+/// so they are composed at the response level. The fallback runs at most once.+#[cfg(feature = "v1")]+#[allow(clippy::too_many_arguments)]+pub async fn network_token_with_vault_card_fallback_core<Op>(+ state: SessionState,+ req_state: ReqState,+ platform: domain::Platform,+ profile_id: Option<id_type::ProfileId>,+ operation: Op,+ req: payments_api::PaymentsRequest,+ fallback: Box<api_models::mandates::NetworkTokenWithVaultCardFallback>,+ auth_flow: services::AuthFlow,+ header_payload: HeaderPayload,+) -> RouterResponse<payments_api::PaymentsResponse>+where+ Op: Debug+ + Sync+ + Clone+ + Operation<api::Authorize, payments_api::PaymentsRequest, Data = PaymentData<api::Authorize>>,+{+ let all_keys_required = req.all_keys_required;++ let network_token_request = payments_api::PaymentsRequest {+ recurring_details: Some(fallback.to_network_token_arm()),+ ..req.clone()+ };++ let network_token_outcome = Box::pin(proxy_for_payments_core::<+ api::Authorize,+ payments_api::PaymentsResponse,+ _,+ _,+ _,+ PaymentData<api::Authorize>,+ >(+ state.clone(),+ req_state.clone(),+ platform.clone(),+ profile_id.clone(),+ operation,+ network_token_request,+ auth_flow,+ CallConnectorAction::Trigger,+ header_payload.clone(),+ req.all_keys_required,+ ))+ .await?;++ let network_token_response = payment_response_from_application_response(&network_token_outcome);++ let fallback_target = match network_token_response {+ Some(response) => {+ match is_vault_card_fallback_eligible(&state, &platform, response).await {+ true => Some((+ response.payment_id.clone(),+ response.payment_method,+ response.payment_method_type,+ )),+ false => None,+ }+ }+ None => None,+ };++ match fallback_target {+ None => Ok(network_token_outcome),+ Some((payment_id, payment_method, payment_method_type)) => {+ logger::info!(+ payment_id = ?payment_id,+ "network token arm declined as clear-pan eligible, falling back to the vault card arm"+ );++ let vault_card_request = payments_api::PaymentsRequest {+ payment_id: Some(payments_api::PaymentIdType::PaymentIntentId(payment_id)),+ recurring_details: Some(fallback.to_vault_card_arm()),+ // A confirm call may omit these, having supplied them at create. Arm two creates a+ // fresh attempt, which needs them, so carry arm one's resolved values forward+ // rather than relying on the request repeating them.+ payment_method: payment_method.or(req.payment_method),+ payment_method_type: payment_method_type.or(req.payment_method_type),+ ..req+ };++ // No attempt bookkeeping here: the external vault proxy confirm operation always+ // advances the attempt count, so the vault card arm lands on its own attempt and arm+ // one's decline survives.+ Box::pin(external_vault_proxy_for_payments_core::<+ api::ExternalVaultProxy,+ payments_api::PaymentsResponse,+ _,+ _,+ _,+ PaymentData<api::ExternalVaultProxy>,+ >(+ state.clone(),+ req_state,+ platform.clone(),+ profile_id,+ // Always the confirm operation, for both endpoints: arm one has already persisted+ // the intent, including on a single-call create+confirm.+ PaymentExternalVaultProxyConfirm,+ vault_card_request,+ auth_flow,+ CallConnectorAction::Trigger,+ header_payload,+ all_keys_required,+ ))+ .await+ }+ }+}+#[cfg(feature = "v2")]#[allow(clippy::too_many_arguments)]pub async fn proxy_for_payments_core<F, Res, Req, Op, FData, D>(@@ -11507,6 +11735,7 @@ pub fn get_proxy_connector_filters(RecurringDetails::NetworkTransactionIdAndCardDetails(_)| RecurringDetails::NetworkTransactionIdAndDecryptedWalletTokenDetails(_)| RecurringDetails::NetworkTransactionIdAndVaultCardDetails(_)+ | RecurringDetails::NetworkTokenWithVaultCardFallback(_)| RecurringDetails::NetworkTransactionIdAndNetworkTokenDetails(_) => Ok(state.conf.network_transaction_id_supported_connectorsdiff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 69a0867bb1..75e5010d21 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -622,7 +622,8 @@ pub async fn get_token_pm_type_mandate_details(None,None,),- RecurringDetails::NetworkTransactionIdAndVaultCardDetails(_) => (+ RecurringDetails::NetworkTransactionIdAndVaultCardDetails(_)+ | RecurringDetails::NetworkTokenWithVaultCardFallback(_) => (None,request.payment_method,request.payment_method_type,@@ -1429,6 +1430,7 @@ fn validate_recurring_mandate(req: api::MandateValidationFields) -> RouterResult| RecurringDetails::NetworkTransactionIdAndDecryptedWalletTokenDetails(_)| RecurringDetails::NetworkTransactionIdAndNetworkTokenDetails(_)| RecurringDetails::NetworkTransactionIdAndVaultCardDetails(_)+ | RecurringDetails::NetworkTokenWithVaultCardFallback(_)| RecurringDetails::CardWithLimitedData(_) => Ok(()),_ => {req.customer_id.check_value_present("customer_id")?;diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex a58f14f2ce..6f222f190d 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -873,6 +873,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>| RecurringDetails::NetworkTransactionIdAndNetworkTokenDetails(_)| RecurringDetails::NetworkTransactionIdAndDecryptedWalletTokenDetails(_)| RecurringDetails::NetworkTransactionIdAndVaultCardDetails(_)+ | RecurringDetails::NetworkTokenWithVaultCardFallback(_)| RecurringDetails::NetworkTransactionIdAndCardDetails(_) => {Some(mandates::MandateIds {mandate_id: None,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 30992347b7..1f95c9f41a 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@@ -240,7 +240,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsRequest>)?;}- let mut payment_attempt = db+ let active_payment_attempt = db.find_payment_attempt_by_payment_id_processor_merchant_id_attempt_id(&payment_intent.payment_id,processor_merchant_id,@@ -251,6 +251,52 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsRequest>.await.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;+ // The vault card arm of a fallback follows an earlier attempt on the same intent, so it+ // needs its own attempt or that attempt's decline is overwritten. Only that case: a 3DS+ // resume reaches this operation with its authentication on the active attempt, and a new+ // attempt would drop `authentication_id` and authorize without the 3DS result.+ let needs_new_attempt =+ request+ .recurring_details+ .as_ref()+ .is_some_and(|recurring_details| {+ matches!(+ recurring_details,+ api_models::mandates::RecurringDetails::NetworkTransactionIdAndVaultCardDetails(+ _+ )+ )+ })+ && active_payment_attempt.status.is_terminal_status();++ let (payment_intent, mut payment_attempt) = match needs_new_attempt {+ true => {+ let previous_connector = active_payment_attempt.connector.clone();+ let previous_merchant_connector_id =+ active_payment_attempt.merchant_connector_id.clone();++ let (payment_intent, mut payment_attempt) = Box::pin(+ helpers::AttemptType::New.modify_payment_intent_and_payment_attempt(+ request,+ payment_intent,+ active_payment_attempt,+ state,+ platform.get_processor().get_key_store(),+ storage_scheme,+ ),+ )+ .await?;++ // The manual retry helper clears both, but the network transaction ID was issued+ // by the connector that declined, so the fallback has to stay on it.+ payment_attempt.connector = previous_connector;+ payment_attempt.merchant_connector_id = previous_merchant_connector_id;++ (payment_intent, payment_attempt)+ }+ false => (payment_intent, active_payment_attempt),+ };+let currency = payment_attempt.currency.get_required_value("currency")?;let amount = payment_attempt.get_total_amount().into();diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rsindex 4d55ee363a..f1f8707df5 100644--- a/crates/router/src/core/payments/operations/payment_create.rs+++ b/crates/router/src/core/payments/operations/payment_create.rs@@ -487,6 +487,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>| RecurringDetails::NetworkTransactionIdAndNetworkTokenDetails(_)| RecurringDetails::NetworkTransactionIdAndDecryptedWalletTokenDetails(_)| RecurringDetails::NetworkTransactionIdAndVaultCardDetails(_)+ | RecurringDetails::NetworkTokenWithVaultCardFallback(_)| RecurringDetails::NetworkTransactionIdAndCardDetails(_) => {Some(mandates::MandateIds {mandate_id: None,diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex 16f2b0417c..a6be83c9f8 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -1188,6 +1188,59 @@ fn is_kill_switch_applicable()}+/// Whether an external vault proxy authorize for `connector_name` would reach the connector over+/// UCS.+///+/// `decide_execution_path` pins a later attempt to the gateway the earlier one used, and the+/// external vault proxy has no Direct implementation. A fallback that would land on Direct cannot+/// authorize, so the caller checks this before creating an attempt for it.+#[cfg(feature = "v1")]+pub async fn is_ucs_execution_path_for_external_vault_proxy(+ state: &SessionState,+ processor: &Processor,+ connector_name: &str,+ payment_method: common_enums::PaymentMethod,+ payment_method_type: Option<PaymentMethodType>,+) -> RouterResult<bool> {+ let connector_enum = Connector::from_str(connector_name)+ .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)+ .attach_printable_lazy(|| format!("Failed to parse connector name: {connector_name}"))?;++ match check_ucs_availability(state).await {+ UcsAvailability::Disabled => Ok(false),+ UcsAvailability::Enabled => {+ let rollout_keys = build_rollout_keys_by_precedence(+ processor.get_account().get_org_id().get_string_repr(),+ processor.get_account().get_id().get_string_repr(),+ connector_name,+ // Derived the same way the live path does, so the key shapes cannot drift.+ &get_flow_name::<hyperswitch_domain_models::router_flow_types::Authorize>()?,+ payment_method,+ payment_method_type,+ );++ let rollout_result =+ should_execute_based_on_rollout_with_precedence(state, &rollout_keys).await?;++ let connector_integration_type =+ determine_connector_integration_type(state, connector_enum).await?;++ // `previous_gateway` is left unset deliberately: this asks whether the configuration+ // admits UCS at all, which is what decides whether both arms can run there.+ let (gateway_system, _execution_path) = decide_execution_path(+ connector_integration_type,+ None,+ rollout_result.execution_mode,+ )?;++ Ok(matches!(+ gateway_system,+ GatewaySystem::UnifiedConnectorService+ ))+ }+ }+}+fn decide_execution_path(connector_type: ConnectorIntegrationType,previous_gateway: Option<GatewaySystem>,@@ -2336,6 +2389,16 @@ pub fn build_unified_connector_service_payment_method(payment_method: Some(PaymentMethod::CardDetailsForNetworkTransactionId(card_details_for_nti)),})}+ // v1 only: the conversion it delegates to is v1-gated, matching the flow that produces+ // this variant.+ #[cfg(feature = "v1")]+ hyperswitch_domain_models::payment_method_data::PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(token_nti_data) => {+ let network_token = payments_grpc::NetworkTokenData::foreign_try_from(token_nti_data)?;++ Ok(payments_grpc::PaymentMethod {+ payment_method: Some(PaymentMethod::NetworkToken(network_token)),+ })+ }hyperswitch_domain_models::payment_method_data::PaymentMethodData::NetworkToken(network_token_data) => {let network_token = payments_grpc::NetworkTokenData::foreign_try_from(network_token_data)?;diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rsindex fab97ae0b6..4b08ba98ad 100644--- a/crates/router/src/core/unified_connector_service/transformers.rs+++ b/crates/router/src/core/unified_connector_service/transformers.rs@@ -4828,6 +4828,47 @@ impl transformers::ForeignTryFrom<hyperswitch_domain_models::payment_method_data}}+/// The MIT counterpart of the `NetworkTokenData` conversion: no cryptogram, since an MIT has no+/// cardholder present and authorizes on the network transaction ID.+#[cfg(feature = "v1")]+impl+ transformers::ForeignTryFrom<+ hyperswitch_domain_models::payment_method_data::NetworkTokenDetailsForNetworkTransactionId,+ > for payments_grpc::NetworkTokenData+{+ type Error = error_stack::Report<UnifiedConnectorServiceError>;++ fn foreign_try_from(+ token_nti_data: hyperswitch_domain_models::payment_method_data::NetworkTokenDetailsForNetworkTransactionId,+ ) -> Result<Self, Self::Error> {+ let card_network = token_nti_data+ .card_network+ .clone()+ .map(payments_grpc::CardNetwork::foreign_from);++ Ok(Self {+ token_number: Some(+ NetworkToken::from_str(&token_nti_data.network_token.get_card_no())+ .change_context(+ UnifiedConnectorServiceError::RequestEncodingFailedWithReason(+ "Failed to parse network token number".to_string(),+ ),+ )?,+ ),+ token_exp_month: Some(token_nti_data.token_exp_month.expose().into()),+ token_exp_year: Some(token_nti_data.token_exp_year.expose().into()),+ token_cryptogram: None,+ card_issuer: token_nti_data.card_issuer.clone(),+ card_network: card_network.map(|card_network| card_network.into()),+ card_type: token_nti_data.card_type.clone(),+ card_issuing_country: token_nti_data.card_issuing_country.clone(),+ bank_code: token_nti_data.bank_code.clone(),+ nick_name: token_nti_data.nick_name.map(|n| n.expose().into()),+ eci: token_nti_data.eci,+ })+ }+}+impl transformers::ForeignTryFrom<hyperswitch_domain_models::payment_method_data::NetworkTokenData>for payments_grpc::NetworkTokenData{diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rsindex 3c1cd3a4ae..35931ad9ee 100644--- a/crates/router/src/routes/payments.rs+++ b/crates/router/src/routes/payments.rs@@ -2860,10 +2860,31 @@ where// the operation are flow agnostic, and the flow is only required in the post_update_tracker// Thus the flow can be generated just before calling the connector instead of explicitly passing it here.+ // A network-token-with-vault-card-fallback request is not a single payment: it names a network+ // token arm and a vault-aliased card arm sharing one network transaction ID, and the two arms+ // run on different cores. Its wrapper owns that sequencing, so it is checked ahead of both+ // single-core gates.+ let network_token_with_vault_card_fallback =+ helpers::network_token_with_vault_card_fallback_details(&req);+let should_call_proxy_for_payments_core =helpers::should_call_proxy_for_payments_core(req.clone());- if should_call_proxy_for_payments_core {+ if let Some(fallback) = network_token_with_vault_card_fallback {+ logger::debug!("Authorize call for NTI with network token and vault card fallback flow");+ Box::pin(payments::network_token_with_vault_card_fallback_core(+ state,+ req_state,+ platform,+ profile_id,+ operation,+ req,+ fallback,+ auth_flow,+ header_payload,+ ))+ .await+ } else if should_call_proxy_for_payments_core {// no list of eligible connectors will be passed in the confirm calllogger::debug!("Authorize call for NTI and Card Details flow");payments::proxy_for_payments_core::<diff --git a/crates/router/src/routes/payments/helpers.rs b/crates/router/src/routes/payments/helpers.rsindex ba384763e1..6ef779cec7 100644--- a/crates/router/src/routes/payments/helpers.rs+++ b/crates/router/src/routes/payments/helpers.rs@@ -130,3 +130,19 @@ pub fn should_call_external_vault_proxy_for_payments_core(}).unwrap_or(false)}++/// The fallback payload, when the request carries one. Returns the payload rather than a bool so+/// the caller need not match twice.+#[cfg(feature = "v1")]+pub fn network_token_with_vault_card_fallback_details(+ payment_request: &api::PaymentsRequest,+) -> Option<Box<api_models::mandates::NetworkTokenWithVaultCardFallback>> {+ payment_request.recurring_details.clone().and_then(+ |recurring_details| match recurring_details {+ api_models::mandates::RecurringDetails::NetworkTokenWithVaultCardFallback(fallback) => {+ Some(fallback)+ }+ _ => None,+ },+ )+}