Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

feat(router): add External vault proxy support in v1 confirm flow (#12037)

Prasunna Soppa9deb071a4ba5
diff --git a/.github/workflows/cypress-tests-runner.yml b/.github/workflows/cypress-tests-runner.yml
index 3e2b0387bc..559cbae3c7 100644
--- a/.github/workflows/cypress-tests-runner.yml
+++ b/.github/workflows/cypress-tests-runner.yml
@@ -33,7 +33,7 @@ env:
RUSTUP_MAX_RETRIES: 10
RUN_TESTS: ${{ ((github.event_name == 'pull_request') && (github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name)) || (github.event_name == 'merge_group')}}
DEBUG: cypress:cli
- RUST_MIN_STACK: 11534336
+ RUST_MIN_STACK: 16777216
jobs:
formatter:
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index 4cee2a821b..58dcd7f3b9 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -22689,27 +22689,12 @@
"HyperswitchVaultSessionDetails": {
"type": "object",
"required": [
- "payment_method_session_id",
- "client_secret",
- "publishable_key",
- "profile_id"
+ "sdk_authorization"
],
"properties": {
- "payment_method_session_id": {
- "type": "string",
- "description": "Session ID for Hyperswitch Vault"
- },
- "client_secret": {
- "type": "string",
- "description": "Client secret for Hyperswitch Vault"
- },
- "publishable_key": {
- "type": "string",
- "description": "Publishable key for Hyperswitch Vault"
- },
- "profile_id": {
+ "sdk_authorization": {
"type": "string",
- "description": "Profile ID for Hyperswitch Vault"
+ "description": "Base64-encoded SDK authorization token for the Hyperswitch Vault session"
}
}
},
@@ -29024,6 +29009,18 @@
"$ref": "#/components/schemas/NetworkTokenData"
}
}
+ },
+ {
+ "type": "object",
+ "title": "ProxyCard",
+ "required": [
+ "proxy_card"
+ ],
+ "properties": {
+ "proxy_card": {
+ "$ref": "#/components/schemas/ProxyCardData"
+ }
+ }
}
]
},
@@ -38346,6 +38343,90 @@
"contract_default"
]
},
+ "ProxyCardData": {
+ "type": "object",
+ "required": [
+ "card_number",
+ "card_exp_month",
+ "card_exp_year",
+ "card_holder_name",
+ "card_cvc",
+ "bin_number",
+ "last_four"
+ ],
+ "properties": {
+ "card_number": {
+ "type": "string",
+ "description": "The token which refers to the card number",
+ "example": "token_card_number"
+ },
+ "card_exp_month": {
+ "type": "string",
+ "description": "The card's expiry month",
+ "example": "24"
+ },
+ "card_exp_year": {
+ "type": "string",
+ "description": "The card's expiry year",
+ "example": "24"
+ },
+ "card_holder_name": {
+ "type": "string",
+ "description": "The card holder's name",
+ "example": "John Test"
+ },
+ "card_cvc": {
+ "type": "string",
+ "description": "The CVC number for the card",
+ "example": "242"
+ },
+ "card_issuer": {
+ "type": "string",
+ "description": "The name of the issuer of card",
+ "example": "chase",
+ "nullable": true
+ },
+ "card_network": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CardNetwork"
+ }
+ ],
+ "nullable": true
+ },
+ "card_type": {
+ "type": "string",
+ "example": "CREDIT",
+ "nullable": true
+ },
+ "card_issuing_country": {
+ "type": "string",
+ "example": "INDIA",
+ "nullable": true
+ },
+ "bank_code": {
+ "type": "string",
+ "example": "JP_AMEX",
+ "nullable": true
+ },
+ "nick_name": {
+ "type": "string",
+ "description": "The card holder's nick name",
+ "example": "John Test",
+ "nullable": true
+ },
+ "bin_number": {
+ "type": "string",
+ "description": "The first six digit of the card number",
+ "example": "424242"
+ },
+ "last_four": {
+ "type": "string",
+ "description": "The last four digit of the card number",
+ "example": "4242"
+ }
+ }
+ },
"RankingAlgorithm": {
"type": "string",
"enum": [
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index 7a8e9a9f2f..848c9a3141 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -16345,27 +16345,12 @@
"HyperswitchVaultSessionDetails": {
"type": "object",
"required": [
- "payment_method_session_id",
- "client_secret",
- "publishable_key",
- "profile_id"
+ "sdk_authorization"
],
"properties": {
- "payment_method_session_id": {
- "type": "string",
- "description": "Session ID for Hyperswitch Vault"
- },
- "client_secret": {
- "type": "string",
- "description": "Client secret for Hyperswitch Vault"
- },
- "publishable_key": {
- "type": "string",
- "description": "Publishable key for Hyperswitch Vault"
- },
- "profile_id": {
+ "sdk_authorization": {
"type": "string",
- "description": "Profile ID for Hyperswitch Vault"
+ "description": "Base64-encoded SDK authorization token for the Hyperswitch Vault session"
}
}
},
@@ -21892,6 +21877,18 @@
"$ref": "#/components/schemas/NetworkTokenData"
}
}
+ },
+ {
+ "type": "object",
+ "title": "ProxyCard",
+ "required": [
+ "proxy_card"
+ ],
+ "properties": {
+ "proxy_card": {
+ "$ref": "#/components/schemas/ProxyCardData"
+ }
+ }
}
]
},
@@ -27842,6 +27839,90 @@
"contract_default"
]
},
+ "ProxyCardData": {
+ "type": "object",
+ "required": [
+ "card_number",
+ "card_exp_month",
+ "card_exp_year",
+ "card_holder_name",
+ "card_cvc",
+ "bin_number",
+ "last_four"
+ ],
+ "properties": {
+ "card_number": {
+ "type": "string",
+ "description": "The token which refers to the card number",
+ "example": "token_card_number"
+ },
+ "card_exp_month": {
+ "type": "string",
+ "description": "The card's expiry month",
+ "example": "24"
+ },
+ "card_exp_year": {
+ "type": "string",
+ "description": "The card's expiry year",
+ "example": "24"
+ },
+ "card_holder_name": {
+ "type": "string",
+ "description": "The card holder's name",
+ "example": "John Test"
+ },
+ "card_cvc": {
+ "type": "string",
+ "description": "The CVC number for the card",
+ "example": "242"
+ },
+ "card_issuer": {
+ "type": "string",
+ "description": "The name of the issuer of card",
+ "example": "chase",
+ "nullable": true
+ },
+ "card_network": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CardNetwork"
+ }
+ ],
+ "nullable": true
+ },
+ "card_type": {
+ "type": "string",
+ "example": "CREDIT",
+ "nullable": true
+ },
+ "card_issuing_country": {
+ "type": "string",
+ "example": "INDIA",
+ "nullable": true
+ },
+ "bank_code": {
+ "type": "string",
+ "example": "JP_AMEX",
+ "nullable": true
+ },
+ "nick_name": {
+ "type": "string",
+ "description": "The card holder's nick name",
+ "example": "John Test",
+ "nullable": true
+ },
+ "bin_number": {
+ "type": "string",
+ "description": "The first six digit of the card number",
+ "example": "424242"
+ },
+ "last_four": {
+ "type": "string",
+ "description": "The last four digit of the card number",
+ "example": "4242"
+ }
+ }
+ },
"ProxyCardDetails": {
"type": "object",
"required": [
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 878aa153c3..932359ca12 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -3150,6 +3150,7 @@ mod payment_method_data_serde {
| PaymentMethodData::Voucher(_)
| PaymentMethodData::Card(_)
| PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::ProxyCard(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::Wallet(_) => {
@@ -3229,7 +3230,7 @@ pub struct ProxyPaymentMethodDataRequest {
#[serde(rename_all = "snake_case")]
pub enum ProxyPaymentMethodData {
#[schema(title = "ProxyCardData")]
- VaultDataCard(Box<ProxyCardData>),
+ ProxyCard(Box<ProxyCardData>),
VaultToken(VaultToken),
}
@@ -3487,6 +3488,10 @@ pub enum PaymentMethodData {
MobilePayment(MobilePaymentData),
#[schema(title = "NetworkToken")]
NetworkToken(NetworkTokenData),
+ /// Vault card data used for external vault proxy payments.
+ /// When this variant is used, the payment will be routed through the external vault proxy flow.
+ #[schema(title = "ProxyCard")]
+ ProxyCard(Box<ProxyCardData>),
}
pub trait GetAddressFromPaymentMethodData {
@@ -3513,7 +3518,8 @@ impl GetAddressFromPaymentMethodData for PaymentMethodData {
| Self::OpenBanking(_)
| Self::MandatePayment
| Self::MobilePayment(_)
- | Self::NetworkToken(_) => None,
+ | Self::NetworkToken(_)
+ | Self::ProxyCard(_) => None,
}
}
}
@@ -3538,6 +3544,7 @@ impl PaymentMethodData {
Self::MobilePayment(_) => Some(api_enums::PaymentMethod::MobilePayment),
Self::NetworkToken(_) => Some(api_enums::PaymentMethod::NetworkToken),
Self::CardToken(_) | Self::MandatePayment => None,
+ Self::ProxyCard(_) => Some(api_enums::PaymentMethod::Card),
}
}
}
@@ -10178,18 +10185,9 @@ pub struct VgsSessionDetails {
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
pub struct HyperswitchVaultSessionDetails {
- /// Session ID for Hyperswitch Vault
+ /// Base64-encoded SDK authorization token for the Hyperswitch Vault session
#[schema(value_type = String)]
- pub payment_method_session_id: Secret<String>,
- /// Client secret for Hyperswitch Vault
- #[schema(value_type = String)]
- pub client_secret: Secret<String>,
- /// Publishable key for Hyperswitch Vault
- #[schema(value_type = String)]
- pub publishable_key: Secret<String>,
- /// Profile ID for Hyperswitch Vault
- #[schema(value_type = String)]
- pub profile_id: Secret<String>,
+ pub sdk_authorization: Secret<String>,
}
#[derive(
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index db78dade1f..d3c66dd339 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -225,6 +225,7 @@ pub struct PaymentMethodNew {
pub last_modified_by: Option<String>,
pub customer_details: Option<Encryption>,
pub compatibility_updated_at: Option<PrimitiveDateTime>,
+ pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
impl PaymentMethodNew {
@@ -1441,7 +1442,6 @@ impl From<&PaymentMethodNew> for PaymentMethod {
network_token_payment_method_data: payment_method_new
.network_token_payment_method_data
.clone(),
- external_vault_source: None,
external_vault_token_data: payment_method_new.external_vault_token_data.clone(),
vault_type: payment_method_new.vault_type,
created_by: payment_method_new.created_by.clone(),
@@ -1449,6 +1449,7 @@ impl From<&PaymentMethodNew> for PaymentMethod {
customer_details: payment_method_new.customer_details.clone(),
network_tokenization_data: None,
compatibility_updated_at: payment_method_new.compatibility_updated_at,
+ external_vault_source: payment_method_new.external_vault_source.clone(),
}
}
}
diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs
index 76ccef6a0f..37fcd17d15 100644
--- a/crates/hyperswitch_domain_models/src/business_profile.rs
+++ b/crates/hyperswitch_domain_models/src/business_profile.rs
@@ -113,6 +113,16 @@ impl ExternalVaultDetails {
Self::Skip => false,
}
}
+
+ /// Returns the external vault connector account id when external vault is enabled.
+ pub fn get_vault_connector_id(
+ &self,
+ ) -> Option<common_utils::id_type::MerchantConnectorAccountId> {
+ match self {
+ Self::ExternalVaultEnabled(details) => Some(details.vault_connector_id.clone()),
+ Self::Skip => None,
+ }
+ }
}
#[cfg(feature = "v1")]
diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
index d7bf5d0488..ab6e2932f1 100644
--- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
@@ -361,7 +361,6 @@ pub struct RevenueRecoveryMetadata {
pub mca_reference: AccountReferenceMap,
}
-#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Deserialize)]
pub struct ExternalVaultConnectorMetadata {
pub proxy_url: common_utils::types::Url,
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index 59ffd6e372..25e8fb9a5e 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -1912,6 +1912,14 @@ impl From<api_models::payments::PaymentMethodData> for PaymentMethodData {
api_models::payments::PaymentMethodData::NetworkToken(network_token_data) => {
Self::NetworkToken(From::from(network_token_data))
}
+ // ProxyCard is handled before reaching domain conversion (routed to
+ // external_vault_proxy_for_payments_core). This branch should not be reached
+ // in normal flow, but we handle it gracefully.
+ api_models::payments::PaymentMethodData::ProxyCard(_) => {
+ // This variant is intercepted at the routing layer and should not reach here.
+ // Falling back to MandatePayment as a safe no-op sentinel value.
+ Self::MandatePayment
+ }
}
}
}
@@ -1919,7 +1927,7 @@ impl From<api_models::payments::PaymentMethodData> for PaymentMethodData {
impl From<api_models::payments::ProxyPaymentMethodData> for ExternalVaultPaymentMethodData {
fn from(api_model_payment_method_data: api_models::payments::ProxyPaymentMethodData) -> Self {
match api_model_payment_method_data {
- api_models::payments::ProxyPaymentMethodData::VaultDataCard(card_data) => {
+ api_models::payments::ProxyPaymentMethodData::ProxyCard(card_data) => {
Self::Card(Box::new(ExternalVaultCard::from(*card_data)))
}
api_models::payments::ProxyPaymentMethodData::VaultToken(vault_data) => {
diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs
index cf5f1a1564..a0d44552d7 100644
--- a/crates/hyperswitch_domain_models/src/payment_methods.rs
+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs
@@ -992,6 +992,7 @@ impl super::behaviour::Conversion for PaymentMethod {
customer_details: self.customer_details.map(|val| val.into()),
auxiliary_fingerprint_id: self.auxiliary_fingerprint_id,
compatibility_updated_at: self.compatibility_updated_at,
+ external_vault_source: self.external_vault_source,
})
}
}
@@ -1119,11 +1120,28 @@ impl super::behaviour::Conversion for PaymentMethodSession {
}
}
+#[cfg(feature = "v1")]
+#[derive(Clone, Debug)]
+pub struct VaultCardData {
+ pub card_number: Secret<String>,
+ pub card_exp_year: Option<Secret<String>>,
+ pub card_exp_month: Option<Secret<String>>,
+}
+
+/// Domain-level vault payment method token data (populated only for the repeat CIT / proxy-card
+/// path where the PM service returns vault token references instead of real card data).
+#[cfg(feature = "v1")]
+#[derive(Clone, Debug)]
+pub enum VaultPaymentMethodData {
+ VaultCardData(VaultCardData),
+}
+
#[cfg(feature = "v1")]
#[derive(Clone, Debug)]
pub struct PaymentMethodWithRawData {
pub payment_method: PaymentMethod,
pub raw_payment_method_data: Option<domain_payment_method_data::PaymentMethodData>,
+ pub vault_payment_method_token_data: Option<VaultPaymentMethodData>,
}
#[async_trait::async_trait]
diff --git a/crates/hyperswitch_domain_models/src/sdk_auth.rs b/crates/hyperswitch_domain_models/src/sdk_auth.rs
index 621abed211..340b6bc833 100644
--- a/crates/hyperswitch_domain_models/src/sdk_auth.rs
+++ b/crates/hyperswitch_domain_models/src/sdk_auth.rs
@@ -15,6 +15,7 @@ use crate::platform::Initiator;
pub struct SdkAuthorizationContext {
pub platform: crate::platform::Platform,
pub profile_id: id_type::ProfileId,
+ pub publishable_key: String,
pub client_secret: String,
pub customer_id: Option<id_type::GlobalCustomerId>,
pub payment_method_session_id: Option<id_type::GlobalPaymentMethodSessionId>,
@@ -39,12 +40,7 @@ impl From<SdkAuthorizationContext> for Option<SdkAuthorization> {
};
Some(SdkAuthorization {
profile_id: input.profile_id,
- publishable_key: input
- .platform
- .get_processor()
- .get_account()
- .publishable_key
- .clone(),
+ publishable_key: input.publishable_key,
platform_publishable_key,
client_secret: input.client_secret,
customer_id: input.customer_id,
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 99d1cedc74..8072ec1e3c 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -768,6 +768,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::AmazonPayShippingMethod,
api_models::payments::VaultDetails,
api_models::payments::InternalVaultSessionDetails,
+ api_models::payments::ProxyCardData,
api_models::payment_methods::RequiredFieldInfo,
api_models::payment_methods::DefaultPaymentMethod,
api_models::payment_methods::MaskedBankDetails,
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index c59e17d6c4..dd28e6762b 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -710,6 +710,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payment_methods::TokenizePaymentMethodRequest,
api_models::payment_methods::CardCVCTokenStorageDetails,
api_models::payment_methods::RawProxyCardDataResponse,
+ api_models::payments::ProxyCardData,
api_models::payment_methods::PaymentMethodDeleteSessionResponse,
api_models::payment_methods::CustomerDefaultPaymentMethodResponse,
api_models::refunds::RefundListRequest,
diff --git a/crates/payment_methods/src/client/create.rs b/crates/payment_methods/src/client/create.rs
index ed05fff059..a991494c65 100644
--- a/crates/payment_methods/src/client/create.rs
+++ b/crates/payment_methods/src/client/create.rs
@@ -27,11 +27,15 @@ pub struct CreatePaymentMethodV1Request {
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub metadata: Option<pii::SecretSerdeValue>,
pub customer_id: id_type::CustomerId, // Payment method data will be saved when customer acceptance is given, hence customer id will always be present
- pub payment_method_data: PaymentMethodData,
+ /// The payment method data for the normal create flow. `None` for the external vault proxy
+ /// flow, where `proxy_card_data` is set instead.
+ pub payment_method_data: Option<PaymentMethodData>,
pub billing: Option<hyperswitch_domain_models::address::Address>,
pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,
pub storage_type: Option<common_enums::StorageType>,
pub modular_service_prefix: String,
+ /// When set, overrides `payment_method_data` and creates a ProxyCard payment method.
+ pub proxy_card_data: Option<hyperswitch_domain_models::payment_method_data::ExternalVaultCard>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
@@ -74,11 +78,28 @@ pub enum WalletPaymentMethodData {
#[serde(rename_all = "snake_case")]
pub enum PaymentMethodCreateData {
Card(CardDetail),
+ ProxyCard(ProxyCardDetail),
BankDebit(BankDebitDetail),
Wallet(WalletPaymentMethodData),
BankRedirect(BankRedirectDetail),
}
+/// Tokenized card data for external vault proxy PM creation
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ProxyCardDetail {
+ pub card_number: Secret<String>,
+ pub card_exp_month: Secret<String>,
+ pub card_exp_year: Secret<String>,
+ pub bin_number: Option<String>,
+ pub last_four: Option<String>,
+ pub card_issuer: Option<String>,
+ pub card_network: Option<common_enums::CardNetwork>,
+ pub card_type: Option<common_enums::CardType>,
+ pub card_issuing_country: Option<String>,
+ pub nick_name: Option<Secret<String>>,
+ pub card_holder_name: Option<Secret<String>>,
+}
+
#[derive(Clone, Debug, Deserialize)]
pub struct ModularPaymentMethodResponse {
//payment method id
@@ -261,12 +282,47 @@ impl TryFrom<PaymentMethodData> for PaymentMethodCreateData {
}
}
+impl From<hyperswitch_domain_models::payment_method_data::ExternalVaultCard>
+ for PaymentMethodCreateData
+{
+ fn from(vault_card: hyperswitch_domain_models::payment_method_data::ExternalVaultCard) -> Self {
+ Self::ProxyCard(ProxyCardDetail {
+ card_number: vault_card.card_number,
+ card_exp_month: vault_card.card_exp_month,
+ card_exp_year: vault_card.card_exp_year,
+ bin_number: vault_card.bin_number,
+ last_four: vault_card.last_four,
+ card_issuer: vault_card.card_issuer,
+ card_network: vault_card.card_network,
+ card_type: None,
+ card_issuing_country: vault_card.card_issuing_country,
+ nick_name: vault_card.nick_name,
+ card_holder_name: vault_card.card_holder_name,
+ })
+ }
+}
+
impl TryFrom<&CreatePaymentMethodV1Request> for ModularPMCreateRequest {
type Error = MicroserviceClientError;
fn try_from(request: &CreatePaymentMethodV1Request) -> Result<Self, Self::Error> {
- let payment_method_data =
- PaymentMethodCreateData::try_from(request.payment_method_data.clone())?;
+ let payment_method_data = if let Some(proxy_card) = request.proxy_card_data.clone() {
+ PaymentMethodCreateData::from(proxy_card)
+ } else {
+ let payment_method_data =
+ request
+ .payment_method_data
+ .clone()
+ .ok_or_else(|| MicroserviceClientError {
+ operation: "CreatePaymentMethodV1Request to ModularPMCreateRequest"
+ .to_string(),
+ kind: MicroserviceClientErrorKind::InvalidRequest(
+ "payment_method_data is required when proxy_card_data is not provided"
+ .to_string(),
+ ),
+ })?;
+ PaymentMethodCreateData::try_from(payment_method_data)?
+ };
Ok(Self {
payment_method_type: request.payment_method,
payment_method_subtype: request.payment_method_type,
diff --git a/crates/payment_methods/src/client/session.rs b/crates/payment_methods/src/client/session.rs
index 66f5459065..3c891da83f 100644
--- a/crates/payment_methods/src/client/session.rs
+++ b/crates/payment_methods/src/client/session.rs
@@ -41,10 +41,7 @@ pub struct VgsSessionDetailsResponse {
/// Local deserializable mirror of `api_models::payments::HyperswitchVaultSessionDetails`.
#[derive(Debug, Clone, Deserialize)]
pub struct HyperswitchVaultSessionDetailsResponse {
- pub payment_method_session_id: Secret<String>,
- pub client_secret: Secret<String>,
- pub publishable_key: Secret<String>,
- pub profile_id: Secret<String>,
+ pub sdk_authorization: Secret<String>,
}
/// Local deserializable mirror of `api_models::payments::VaultSessionDetails`.
@@ -66,10 +63,7 @@ impl From<VaultSessionDetailsResponse> for api_models::payments::VaultSessionDet
}
VaultSessionDetailsResponse::HyperswitchVault(hsv) => {
Self::HyperswitchVault(api_models::payments::HyperswitchVaultSessionDetails {
- payment_method_session_id: hsv.payment_method_session_id,
- client_secret: hsv.client_secret,
- publishable_key: hsv.publishable_key,
- profile_id: hsv.profile_id,
+ sdk_authorization: hsv.sdk_authorization,
})
}
}
diff --git a/crates/payment_methods/src/types.rs b/crates/payment_methods/src/types.rs
index be57ba71fe..09d96467cc 100644
--- a/crates/payment_methods/src/types.rs
+++ b/crates/payment_methods/src/types.rs
@@ -119,6 +119,15 @@ pub enum RawPaymentMethodData {
Card(CardDetail),
CardWithNT(RawCardWithNTDetails),
BankDebit(BankDebitDetail),
+ ProxyCard(RawProxyCardDataResponse),
+}
+
+/// Proxy card data returned in retrieve response (vault token reference)
+#[derive(Clone, Debug, Deserialize)]
+pub struct RawProxyCardDataResponse {
+ pub card_number: Secret<String>,
+ pub card_exp_year: Option<Secret<String>>,
+ pub card_exp_month: Option<Secret<String>>,
}
#[derive(Clone, Debug, Deserialize)]
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 2b13a783ac..de5849078d 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -2952,10 +2952,19 @@ pub async fn create_payment_method_proxy_card_core(
let key_manager_state = &(state).into();
- let external_vault_source = profile
- .external_vault_connector_details
- .clone()
- .map(|details| details.vault_connector_id);
+ // A proxy card is, by definition, vaulted in an external vault, so the external vault
+ // connector must be configured on the profile. Fetch it from the profile and require it —
+ // otherwise the payment method would be persisted with a `None` external vault source.
+ let external_vault_source = Some(
+ profile
+ .external_vault_connector_details
+ .clone()
+ .map(|details| details.vault_connector_id)
+ .ok_or_else(|| report!(errors::ApiErrorResponse::InternalServerError))
+ .attach_printable(
+ "external_vault_connector_details must be configured on the profile to create a proxy card payment method",
+ )?,
+ );
let bin_enriched_payment_method_data = req
.payment_method_data
@@ -6117,8 +6126,13 @@ pub async fn payment_methods_session_create(
let sdk_authorization = Option::<hyperswitch_domain_models::sdk_auth::SdkAuthorization>::from(
hyperswitch_domain_models::sdk_auth::SdkAuthorizationContext {
- platform,
+ platform: platform.clone(),
profile_id: profile.get_id().clone(),
+ publishable_key: platform
+ .get_processor()
+ .get_account()
+ .publishable_key
+ .clone(),
client_secret: client_secret.secret.clone().expose(),
customer_id: payment_method_session_domain_model.customer_id.clone(),
payment_method_session_id: Some(payment_method_session_domain_model.id.clone()),
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index d6f88d25a3..9359528ba8 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -17,7 +17,9 @@ use common_utils::{
use error_stack::ResultExt;
use hyperswitch_domain_models::mandates;
#[cfg(feature = "v1")]
-use hyperswitch_domain_models::payment_methods::PaymentMethodWithRawData;
+use hyperswitch_domain_models::payment_methods::{
+ PaymentMethodWithRawData, VaultCardData, VaultPaymentMethodData,
+};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::{payment_method_data, sdk_auth::SdkAuthorization};
#[cfg(feature = "v1")]
@@ -1411,6 +1413,8 @@ pub struct DomainPaymentMethodWrapper(pub domain::PaymentMethod);
#[cfg(feature = "v1")]
pub struct DomainPaymentMethodDataWrapper(pub domain::PaymentMethodData);
+/// Vault token data returned by the internal PM service for a proxy card (repeat CIT flow).
+/// Fields are vault token references (opaque strings), not real card data.
#[cfg(feature = "v1")]
impl DomainPaymentMethodWrapper {
pub async fn transform_pm_mod_retrieve_response(
@@ -1779,6 +1783,12 @@ impl
))),
}
}
+ payment_methods::types::RawPaymentMethodData::ProxyCard(_proxy_card_data) => {
+ // ProxyCard (vault token reference) should not be converted to domain PaymentMethodData.
+ // It is handled separately via VaultPaymentMethodData in fetch_payment_method_from_modular_service.
+ Err(error_stack::report!(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("ProxyCard should not be converted via DomainPaymentMethodDataWrapper; use vault_payment_method_token_data instead"))
+ }
}
}
}
@@ -1940,15 +1950,32 @@ pub async fn fetch_payment_method_from_modular_service(
.await
.attach_printable("Failed to transform payment method retrieve response")?;
- let raw_payment_method_data = pm_response
- .raw_payment_method_data
- .map(|raw_data| DomainPaymentMethodDataWrapper::try_from((raw_data, pmd_card_token)))
- .transpose()
- .attach_printable("Failed to convert raw payment method data")?;
+ // Split raw data based on variant:
+ // - ProxyCard → vault_payment_method_token_data (raw_payment_method_data stays None)
+ // - Card / CardWithNT / BankDebit → raw_payment_method_data (vault_payment_method_token_data stays None)
+ let (raw_payment_method_data, vault_payment_method_token_data) =
+ match pm_response.raw_payment_method_data {
+ Some(payment_methods::types::RawPaymentMethodData::ProxyCard(proxy_card)) => {
+ let vault_data = VaultPaymentMethodData::VaultCardData(VaultCardData {
+ card_number: proxy_card.card_number,
+ card_exp_year: proxy_card.card_exp_year,
+ card_exp_month: proxy_card.card_exp_month,
+ });
+ (None, Some(vault_data))
+ }
+ Some(other_raw) => {
+ let domain_wrapper =
+ DomainPaymentMethodDataWrapper::try_from((other_raw, pmd_card_token))
+ .attach_printable("Failed to convert raw payment method data")?;
+ (Some(domain_wrapper.0), None)
+ }
+ None => (None, None),
+ };
let pm_wrapper = PaymentMethodWithRawData {
payment_method: payment_method.0,
- raw_payment_method_data: raw_payment_method_data.map(|wrapper| wrapper.0),
+ raw_payment_method_data,
+ vault_payment_method_token_data,
};
Ok(pm_wrapper)
}
@@ -2022,7 +2049,7 @@ pub async fn create_payment_method_in_modular_service(
payment_method_type,
metadata: None,
customer_id,
- payment_method_data,
+ payment_method_data: Some(payment_method_data),
billing: billing_address,
network_tokenization: is_network_tokenization_enabled.then_some(
common_types::payment_methods::NetworkTokenization {
@@ -2031,6 +2058,7 @@ pub async fn create_payment_method_in_modular_service(
),
storage_type: Some(common_enums::StorageType::Persistent),
modular_service_prefix: state.conf.micro_services.payment_methods_prefix.0.clone(),
+ proxy_card_data: None,
};
//Create modular service call
@@ -2048,6 +2076,47 @@ pub async fn create_payment_method_in_modular_service(
Ok(payment_method_with_raw_data.0)
}
+#[cfg(feature = "v1")]
+#[allow(clippy::too_many_arguments)]
+pub async fn create_proxy_card_payment_method_in_modular_service(
+ state: &routes::SessionState,
+ provider_merchant_id: &id_type::MerchantId,
+ processor_merchant_id: &id_type::MerchantId,
+ profile_id: &id_type::ProfileId,
+ payment_method: common_enums::PaymentMethod,
+ payment_method_type: Option<common_enums::PaymentMethodType>,
+ vault_card: hyperswitch_domain_models::payment_method_data::ExternalVaultCard,
+ billing_address: Option<hyperswitch_domain_models::address::Address>,
+ customer_id: id_type::CustomerId,
+) -> CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {
+ // Proxy flow: the card comes from `proxy_card_data`, so `payment_method_data` is None.
+ let payment_method_request = CreatePaymentMethodV1Request {
+ merchant_id: provider_merchant_id.clone(),
+ payment_method,
+ payment_method_type,
+ metadata: None,
+ customer_id,
+ payment_method_data: None,
+ billing: billing_address,
+ network_tokenization: None,
+ storage_type: Some(common_enums::StorageType::Persistent),
+ modular_service_prefix: state.conf.micro_services.payment_methods_prefix.0.clone(),
+ proxy_card_data: Some(vault_card),
+ };
+
+ let pm_response = create_pm_modular_service_call(
+ state,
+ processor_merchant_id,
+ profile_id,
+ payment_method_request,
+ )
+ .await?;
+
+ let payment_method_with_raw_data = DomainPaymentMethodWrapper::try_from(pm_response)?;
+
+ Ok(payment_method_with_raw_data.0)
+}
+
#[cfg(feature = "v1")]
pub async fn list_customer_payment_methods_from_modular_service(
state: &routes::SessionState,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 83eaa7ed58..8e417bdfd7 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -91,9 +91,9 @@ use strum::IntoEnumIterator;
#[cfg(feature = "v1")]
pub use self::operations::{
PaymentApprove, PaymentCancel, PaymentCancelPostCapture, PaymentCapture, PaymentConfirm,
- PaymentCreate, PaymentExtendAuthorization, PaymentIncrementalAuthorization,
- PaymentPostSessionTokens, PaymentReject, PaymentSession, PaymentSessionUpdate, PaymentStatus,
- PaymentUpdate, PaymentUpdateMetadata,
+ PaymentCreate, PaymentExtendAuthorization, PaymentExternalVaultProxyConfirm,
+ PaymentIncrementalAuthorization, PaymentPostSessionTokens, PaymentReject, PaymentSession,
+ PaymentSessionUpdate, PaymentStatus, PaymentUpdate, PaymentUpdateMetadata,
};
use self::{
conditional_configs::perform_decision_management,
@@ -1929,7 +1929,7 @@ where
let payment_data = match connector {
ConnectorCallType::PreDetermined(connector_data) => {
- let (mca_type_details, external_vault_mca_type_details, updated_customer, router_data) =
+ let (mca_type_details, external_vault_mca_type_details, _updated_customer, router_data) =
call_connector_service_prerequisites_for_external_vault_proxy(
state,
req_state.clone(),
@@ -1953,23 +1953,15 @@ where
state,
req_state.clone(),
platform.get_processor(),
- connector_data.connector_data.clone(),
&operation,
&mut payment_data,
- &customer,
- call_connector_action.clone(),
- None, // schedule_time is not used in PreDetermined ConnectorCallType
header_payload.clone(),
#[cfg(feature = "frm")]
None,
&profile,
- false,
- false, //should_retry_with_pan is set to false in case of PreDetermined ConnectorCallType
- req.should_return_raw_response(),
mca_type_details,
external_vault_mca_type_details,
router_data,
- updated_customer,
&dimensions,
)
.await?;
@@ -2648,22 +2640,667 @@ where
)
.await?;
- Res::generate_response(
- payment_data,
- auth_flow,
- &state.base_url,
- operation,
- &state.conf.connector_request_reference_id_config,
- connector_http_status_code,
- external_latency,
- header_payload.x_hs_latency,
- &platform,
- )
+ Res::generate_response(
+ payment_data,
+ auth_flow,
+ &state.base_url,
+ operation,
+ &state.conf.connector_request_reference_id_config,
+ connector_http_status_code,
+ external_latency,
+ header_payload.x_hs_latency,
+ &platform,
+ )
+}
+
+#[cfg(feature = "v1")]
+#[allow(clippy::too_many_arguments)]
+pub async fn proxy_for_payments_core<F, Res, Req, Op, FData, D>(
+ state: SessionState,
+ req_state: ReqState,
+ platform: domain::Platform,
+ profile_id: Option<id_type::ProfileId>,
+ operation: Op,
+ req: Req,
+ auth_flow: services::AuthFlow,
+ call_connector_action: CallConnectorAction,
+ header_payload: HeaderPayload,
+ return_raw_connector_response: Option<bool>,
+) -> RouterResponse<Res>
+where
+ F: Send + Clone + Sync,
+ FData: Send + Sync + Clone,
+ Op: Operation<F, Req, Data = D> + Send + Sync + Clone,
+ Req: Debug + Authenticate + Clone,
+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
+ Res: transformers::ToResponse<F, D, Op>,
+ // To create connector flow specific interface data
+ D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
+ RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
+
+ // To construct connector flow specific api
+ dyn api::Connector:
+ services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
+
+ // To perform router related operation for PaymentResponse
+ PaymentResponse: Operation<F, FData, Data = D>,
+{
+ let dimensions = Dimensions::new()
+ .with_processor_merchant_id(platform.get_processor().get_processor_merchant_id())
+ .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id());
+ let (payment_data, _req, connector_http_status_code, external_latency) =
+ proxy_for_payments_operation_core::<_, _, _, _, _>(
+ &state,
+ req_state,
+ platform.clone(),
+ profile_id,
+ operation.clone(),
+ req,
+ call_connector_action,
+ auth_flow,
+ header_payload.clone(),
+ return_raw_connector_response,
+ &dimensions,
+ )
+ .await?;
+
+ Res::generate_response(
+ payment_data,
+ auth_flow,
+ &state.base_url,
+ operation,
+ &state.conf.connector_request_reference_id_config,
+ connector_http_status_code,
+ external_latency,
+ header_payload.x_hs_latency,
+ &platform,
+ )
+}
+
+#[cfg(feature = "v1")]
+#[allow(clippy::too_many_arguments, clippy::type_complexity)]
+#[instrument(skip_all, fields(payment_id, merchant_id))]
+pub async fn external_vault_proxy_for_payments_operation_core<F, Req, Op, FData, D>(
+ state: &SessionState,
+ req_state: ReqState,
+ platform: domain::Platform,
+ profile_id_from_auth_layer: Option<id_type::ProfileId>,
+ operation: Op,
+ req: Req,
+ call_connector_action: CallConnectorAction,
+ auth_flow: services::AuthFlow,
+ header_payload: HeaderPayload,
+ return_raw_connector_response: Option<bool>,
+ dimensions: DimensionsWithProcessorAndProviderMerchantId,
+) -> RouterResult<(D, Req, Option<u16>, Option<u128>)>
+where
+ F: Send + Clone + Sync,
+ Req: Authenticate + Clone,
+ Op: Operation<F, Req, Data = D> + Send + Sync,
+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
+
+ // To create connector flow specific interface data
+ D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
+ RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
+
+ // To construct connector flow specific api
+ dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>
+ + Send
+ + Sync,
+
+ // To perform router related operation for PaymentResponse
+ PaymentResponse: Operation<F, FData, Data = D>,
+ FData: Send + Sync + Clone,
+{
+ let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation);
+
+ tracing::Span::current().record(
+ "merchant_id",
+ platform
+ .get_processor()
+ .get_account()
+ .get_id()
+ .get_string_repr(),
+ );
+ let (operation, validate_result) = operation
+ .to_validate_request()?
+ .validate_request(&req, platform.get_processor())?;
+
+ tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id));
+
+ // #[cfg(feature = "pm_modular")]
+ let feature_config = core_utils::get_feature_config(state, &platform, &dimensions).await;
+
+ let payment_method_info = operation
+ .to_domain()?
+ .fetch_payment_method(state, &req, &platform, &feature_config)
+ .await?;
+
+ let operations::GetTrackerResponse {
+ operation,
+ customer_details,
+ mut payment_data,
+ business_profile,
+ mandate_type,
+ } = operation
+ .to_get_tracker()?
+ .get_trackers(
+ state,
+ &validate_result.payment_id,
+ &req,
+ &platform,
+ auth_flow,
+ &header_payload,
+ payment_method_info,
+ &dimensions,
+ )
+ .await?;
+ let dimensions = dimensions.with_profile_id(business_profile.get_id().clone());
+
+ core_utils::validate_profile_id_from_auth_layer(
+ profile_id_from_auth_layer,
+ &payment_data.get_payment_intent().clone(),
+ )?;
+
+ // Routing parity with `payments_operation_core` (minus debit routing): resolve the connector
+ // call type via `choose_connector` instead of the proxy-specific eligibility helper.
+ let connector = choose_connector(
+ &operation,
+ state,
+ &req,
+ platform.get_processor(),
+ &business_profile,
+ &feature_config,
+ &mut payment_data,
+ None,
+ mandate_type,
+ &dimensions,
+ call_connector_action.clone(),
+ )
+ .await?;
+
+ let locale = header_payload.locale.clone();
+
+ let (operation, _customer) = operation
+ .to_domain()?
+ .get_or_create_customer_details(
+ state,
+ &mut payment_data,
+ customer_details,
+ platform.get_provider(),
+ platform.get_initiator(),
+ &dimensions,
+ None,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
+ .attach_printable("Failed while fetching/creating customer")?;
+
+ operation
+ .to_domain()?
+ .create_payment_method(
+ state,
+ &req,
+ &platform,
+ &mut payment_data,
+ &business_profile,
+ &feature_config,
+ )
+ .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()));
+
+ 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?;
+
+ (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()));
+
+ 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?;
+
+ (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"),
+ )
+ }
+ };
+
+ let op_ref = &operation;
+ let should_trigger_post_processing_flows = is_operation_confirm(&operation);
+
+ let operation = Box::new(PaymentResponse);
+
+ let connector_http_status_code = router_data.connector_http_status_code;
+ let external_latency = router_data.external_latency;
+
+ add_connector_http_status_code_metrics(connector_http_status_code);
+
+ #[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 router_data_for_pm_mandate = router_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,
+ )
+ .await?;
+
+ 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,
+ )
+ .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?;
+ }
+
+ let cloned_payment_data = payment_data.clone();
+
+ utils::trigger_payments_webhook(
+ &platform,
+ business_profile,
+ cloned_payment_data,
+ state,
+ operation,
+ )
+ .await
+ .map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error))
+ .ok();
+
+ Ok((
+ payment_data,
+ req,
+ connector_http_status_code,
+ external_latency,
+ ))
+}
+
+/// Prerequisites for the external vault proxy connector call (v1): resolve the payment MCA and the
+/// external vault MCA, and construct the connector router data. Mirrors the v2
+/// `call_connector_service_prerequisites_for_external_vault_proxy`.
+#[cfg(feature = "v1")]
+#[allow(clippy::too_many_arguments)]
+pub async fn call_connector_service_prerequisites_for_external_vault_proxy_v1<F, FData, D>(
+ state: &SessionState,
+ platform: &domain::Platform,
+ payment_data: &mut D,
+ connector: &api::ConnectorData,
+ business_profile: &domain::Profile,
+ header_payload: HeaderPayload,
+) -> RouterResult<(
+ helpers::MerchantConnectorAccountType,
+ helpers::MerchantConnectorAccountType,
+ RouterData<F, FData, router_types::PaymentsResponseData>,
+)>
+where
+ F: Send + Clone + Sync,
+ FData: Send + Sync + Clone,
+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
+ D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
+ RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
+ dyn api::Connector:
+ services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
+{
+ // Fetch the payment MCA
+ let merchant_connector_account = construct_profile_id_and_get_mca(
+ state,
+ platform.get_processor(),
+ payment_data,
+ &connector.connector_name.to_string(),
+ connector.merchant_connector_id.as_ref(),
+ false,
+ )
+ .await?;
+
+ if payment_data
+ .get_payment_attempt()
+ .merchant_connector_id
+ .is_none()
+ {
+ payment_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
+ .external_vault_details
+ .get_vault_connector_id()
+ .ok_or_else(|| {
+ error_stack::report!(errors::ApiErrorResponse::InternalServerError)
+ .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 router_data = payment_data
+ .construct_router_data(
+ state,
+ connector.connector.id(),
+ platform.get_processor(),
+ &merchant_connector_account,
+ None,
+ Some(header_payload),
+ payment_data.get_payment_attempt().payment_method,
+ payment_data.get_payment_attempt().payment_method_type,
+ )
+ .await?;
+
+ Ok((
+ merchant_connector_account,
+ external_vault_merchant_connector_account,
+ router_data,
+ ))
+}
+
+/// Decide and perform the external vault proxy connector call (v1): pick the execution path
+/// (UCS vs direct), update trackers, and invoke the connector. Mirrors the v2
+/// `call_unified_connector_service_for_external_proxy`.
+#[cfg(feature = "v1")]
+#[allow(clippy::too_many_arguments)]
+pub async fn decide_unified_connector_service_call_for_external_vault_proxy_v1<F, Req, FData, D>(
+ state: &SessionState,
+ req_state: ReqState,
+ platform: &domain::Platform,
+ operation: &BoxedOperation<'_, F, Req, D>,
+ payment_data: &mut D,
+ connector: &api::ConnectorData,
+ merchant_connector_account: helpers::MerchantConnectorAccountType,
+ external_vault_merchant_connector_account: helpers::MerchantConnectorAccountType,
+ mut router_data: RouterData<F, FData, router_types::PaymentsResponseData>,
+ call_connector_action: CallConnectorAction,
+ header_payload: HeaderPayload,
+ business_profile: &domain::Profile,
+ dimensions: &DimensionsWithProcessorAndProviderMerchantIdAndProfileId,
+ return_raw_connector_response: Option<bool>,
+) -> RouterResult<RouterData<F, FData, router_types::PaymentsResponseData>>
+where
+ F: Send + Clone + Sync,
+ FData: Send + Sync + Clone,
+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
+ D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
+ RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData> + Send,
+ dyn api::Connector:
+ services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
+{
+ let previous_gateway = extract_gateway_system_from_payment_intent(payment_data);
+
+ let (execution_path, updated_state) = should_call_unified_connector_service(
+ state,
+ platform.get_processor(),
+ &router_data,
+ previous_gateway,
+ call_connector_action.clone(),
+ None,
+ common_enums::TransactionType::Payment,
+ )
+ .await?;
+
+ let lineage_ids = grpc_client::LineageIds::new(
+ business_profile.merchant_id.clone(),
+ business_profile.get_id().clone(),
+ );
+
+ let execution_mode = match execution_path {
+ ExecutionPath::UnifiedConnectorService => ExecutionMode::Primary,
+ ExecutionPath::ShadowUnifiedConnectorService => ExecutionMode::Shadow,
+ ExecutionPath::Direct => ExecutionMode::NotApplicable,
+ };
+
+ update_gateway_system_in_feature_metadata(
+ payment_data,
+ match execution_path {
+ ExecutionPath::UnifiedConnectorService => GatewaySystem::UnifiedConnectorService,
+ ExecutionPath::ShadowUnifiedConnectorService | ExecutionPath::Direct => {
+ GatewaySystem::Direct
+ }
+ },
+ )?;
+
+ // Update trackers before calling connector
+ (_, *payment_data) = operation
+ .to_update_tracker()?
+ .update_trackers(
+ &updated_state,
+ req_state,
+ platform.get_processor(),
+ payment_data.clone(),
+ None,
+ header_payload.clone(),
+ &dimensions.without_profile_id(),
+ )
+ .await?;
+
+ let router_data = match execution_path {
+ ExecutionPath::UnifiedConnectorService => {
+ router_data
+ .call_unified_connector_service_with_external_vault_proxy_v1(
+ &updated_state,
+ &header_payload,
+ lineage_ids,
+ &merchant_connector_account,
+ &external_vault_merchant_connector_account,
+ platform.get_processor(),
+ execution_mode,
+ )
+ .await?;
+ router_data
+ }
+ ExecutionPath::Direct | ExecutionPath::ShadowUnifiedConnectorService => {
+ // Fallback: direct connector call via decide_flows
+ let add_access_token_result = router_data
+ .add_access_token(
+ &updated_state,
+ connector,
+ platform.get_processor(),
+ payment_data.get_creds_identifier(),
+ &gateway_context::RouterGatewayContext {
+ creds_identifier: payment_data
+ .get_creds_identifier()
+ .map(|id| id.to_string()),
+ processor: platform.get_processor().clone(),
+ header_payload: header_payload.clone(),
+ lineage_ids: lineage_ids.clone(),
+ merchant_connector_account: merchant_connector_account.clone(),
+ execution_path,
+ execution_mode,
+ },
+ )
+ .await?;
+
+ let should_continue_further = access_token::update_router_data_with_access_token_result(
+ &add_access_token_result,
+ &mut router_data,
+ &call_connector_action,
+ );
+
+ let gateway_ctx = gateway_context::RouterGatewayContext {
+ creds_identifier: payment_data.get_creds_identifier().map(|id| id.to_string()),
+ processor: platform.get_processor().clone(),
+ header_payload: header_payload.clone(),
+ lineage_ids,
+ merchant_connector_account: merchant_connector_account.clone(),
+ execution_path,
+ execution_mode,
+ };
+
+ let (connector_request, should_continue) = if should_continue_further {
+ router_data
+ .build_flow_specific_connector_request(
+ &updated_state,
+ connector,
+ call_connector_action.clone(),
+ )
+ .await?
+ } else {
+ (None, false)
+ };
+
+ if should_continue {
+ router_data.status = payment_data.get_payment_attempt().status;
+ router_data
+ .decide_flows(
+ &updated_state,
+ connector,
+ call_connector_action,
+ connector_request,
+ business_profile,
+ header_payload.clone(),
+ return_raw_connector_response,
+ gateway_ctx,
+ )
+ .await?
+ } else {
+ router_data
+ }
+ }
+ };
+
+ Ok(router_data)
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
-pub async fn proxy_for_payments_core<F, Res, Req, Op, FData, D>(
+pub async fn external_vault_proxy_for_payments_core<F, Res, Req, Op, FData, D>(
state: SessionState,
req_state: ReqState,
platform: domain::Platform,
@@ -2697,7 +3334,7 @@ where
.with_processor_merchant_id(platform.get_processor().get_processor_merchant_id())
.with_provider_merchant_id(platform.get_provider().get_provider_merchant_id());
let (payment_data, _req, connector_http_status_code, external_latency) =
- proxy_for_payments_operation_core::<_, _, _, _, _>(
+ external_vault_proxy_for_payments_operation_core::<_, _, _, _, _>(
&state,
req_state,
platform.clone(),
@@ -2708,7 +3345,7 @@ where
auth_flow,
header_payload.clone(),
return_raw_connector_response,
- &dimensions,
+ dimensions,
)
.await?;
@@ -5970,22 +6607,14 @@ pub async fn call_unified_connector_service_for_external_proxy<F, RouterDReq, Ap
state: &SessionState,
req_state: ReqState,
processor: &domain::Processor,
- _connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
- customer: &Option<domain::Customer>,
- _call_connector_action: CallConnectorAction,
- _schedule_time: Option<time::PrimitiveDateTime>,
header_payload: HeaderPayload,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
business_profile: &domain::Profile,
- _is_retry_payment: bool,
- _should_retry_with_pan: bool,
- _return_raw_connector_response: Option<bool>,
merchant_connector_account_type_details: domain::MerchantConnectorAccountTypeDetails,
external_vault_merchant_connector_account_type_details: domain::MerchantConnectorAccountTypeDetails,
mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
- _updated_customer: Option<storage::CustomerUpdate>,
dimensions: &DimensionsWithProcessorAndProviderMerchantId,
) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
where
@@ -6380,141 +7009,6 @@ where
Ok(router_data)
}
-#[cfg(feature = "v2")]
-#[allow(clippy::too_many_arguments)]
-#[instrument(skip_all)]
-pub async fn call_connector_service_for_external_vault_proxy<F, RouterDReq, ApiRequest, D>(
- state: &SessionState,
- req_state: ReqState,
- platform: &domain::Platform,
- connector: api::ConnectorData,
- operation: &BoxedOperation<'_, F, ApiRequest, D>,
- payment_data: &mut D,
- call_connector_action: CallConnectorAction,
- header_payload: HeaderPayload,
- business_profile: &domain::Profile,
- return_raw_connector_response: Option<bool>,
-) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
-where
- F: Send + Clone + Sync,
- RouterDReq: Send + Sync,
-
- // To create connector flow specific interface data
- D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
- D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
- RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send,
- // To construct connector flow specific api
- dyn api::Connector:
- services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
-{
- let stime_connector = Instant::now();
-
- let dimensions = Dimensions::new()
- .with_processor_merchant_id(platform.get_processor().get_processor_merchant_id())
- .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id());
-
- let merchant_connector_account =
- domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
- helpers::get_merchant_connector_account_v2(
- state,
- platform.get_processor(),
- connector.merchant_connector_id.as_ref(),
- )
- .await?,
- ));
- operation
- .to_domain()?
- .populate_payment_data(
- state,
- payment_data,
- platform.get_processor(),
- business_profile,
- &connector,
- )
- .await?;
-
- let mut router_data = payment_data
- .construct_router_data(
- state,
- connector.connector.id(),
- platform.get_processor(),
- &None,
- &merchant_connector_account,
- None,
- Some(header_payload.clone()),
- )
- .await?;
-
- // let add_access_token_result = router_data
- // .add_access_token(
- // state,
- // &connector,
- // platform,
- // payment_data.get_creds_identifier(),
- // )
- // .await?;
-
- // router_data = router_data.add_session_token(state, &connector).await?;
-
- // let mut should_continue_further = access_token::update_router_data_with_access_token_result(
- // &add_access_token_result,
- // &mut router_data,
- // &call_connector_action,
- // );
- let should_continue_further = true;
-
- let (connector_request, should_continue_further) = if should_continue_further {
- router_data
- .build_flow_specific_connector_request(state, &connector, call_connector_action.clone())
- .await?
- } else {
- (None, false)
- };
-
- (_, *payment_data) = operation
- .to_update_tracker()?
- .update_trackers(
- state,
- req_state,
- platform.get_processor(),
- payment_data.clone(),
- None,
- header_payload.clone(),
- &dimensions,
- )
- .await?;
-
- let gateway_context = gateway_context::RouterGatewayContext::direct(
- platform.get_processor().clone(),
- merchant_connector_account.clone(),
- business_profile.merchant_id.clone(),
- business_profile.get_id().clone(),
- payment_data.get_creds_identifier().map(|id| id.to_string()),
- );
-
- let router_data = if should_continue_further {
- router_data
- .decide_flows(
- state,
- &connector,
- call_connector_action,
- connector_request,
- business_profile,
- header_payload.clone(),
- return_raw_connector_response,
- gateway_context,
- )
- .await
- } else {
- Ok(router_data)
- }?;
-
- let etime_connector = Instant::now();
- let duration_connector = etime_connector.saturating_duration_since(stime_connector);
- tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis()));
-
- Ok(router_data)
-}
struct ApplePayWallet;
struct PazeWallet;
struct GooglePayWallet;
@@ -8781,6 +9275,8 @@ where
pub is_l2_l3_enabled: bool,
pub external_authentication_data: Option<api_models::payments::ExternalThreeDsData>,
pub client_session_id: Option<id_type::ClientSessionId>,
+ pub external_vault_pmd:
+ Option<hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData>,
}
#[cfg(feature = "v1")]
@@ -9121,6 +9617,7 @@ where
{
match format!("{operation:?}").as_str() {
"PaymentConfirm" => true,
+ "PaymentExternalVaultProxyConfirm" => true,
"PaymentStart" => {
!matches!(
payment_data.get_payment_intent().status,
@@ -10100,6 +10597,44 @@ pub fn get_proxy_connector_filters(
}
}
+async fn get_eligible_connector_for_vault_card_proxy<
+ T: core_routing::GetRoutableConnectorsForChoice,
+ F,
+ D,
+>(
+ state: &SessionState,
+ key_store: &domain::MerchantKeyStore,
+ payment_data: &mut D,
+ connector_choice: T,
+ dimensions: &DimensionsWithProcessorAndProviderMerchantIdAndProfileId,
+ business_profile: &domain::Profile,
+) -> RouterResult<api::ConnectorData>
+where
+ F: Send + Clone,
+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
+{
+ // Vault-card proxy flow: no recurring/NTI details, skip the MIT-specific proxy filter
+ // and use standard routing eligibility analysis.
+ let eligible_connector_data_list = connector_choice
+ .get_routable_connectors(state, dimensions, business_profile, payment_data)
+ .await?
+ .construct_dsl_and_perform_eligibility_analysis(
+ state,
+ key_store,
+ payment_data,
+ business_profile,
+ )
+ .await
+ .attach_printable("Failed to fetch eligible connector data for vault card proxy")?;
+
+ let eligible_connector_data = eligible_connector_data_list
+ .first()
+ .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
+ .attach_printable("No eligible connector found for the vault card proxy flow")?;
+
+ Ok(eligible_connector_data.clone())
+}
+
pub async fn set_eligible_connector_for_proxy_in_payment_data<F, D>(
state: &SessionState,
business_profile: &domain::Profile,
@@ -10112,28 +10647,56 @@ where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
+ // If there are no recurring details this is a direct vault-card proxy payment
+ // (not an MIT flow), so skip the NTI/recurring-based connector filter.
+ let is_vault_card_flow = payment_data.get_recurring_details().is_none();
+
let eligible_connector_data = match connector_choice {
api::ConnectorChoice::StraightThrough(straight_through) => {
- get_eligible_connector_for_proxy(
- state,
- key_store,
- payment_data,
- core_routing::StraightThroughAlgorithmTypeSingle(straight_through),
- dimensions,
- business_profile,
- )
- .await?
+ if is_vault_card_flow {
+ get_eligible_connector_for_vault_card_proxy(
+ state,
+ key_store,
+ payment_data,
+ core_routing::StraightThroughAlgorithmTypeSingle(straight_through),
+ dimensions,
+ business_profile,
+ )
+ .await?
+ } else {
+ get_eligible_connector_for_proxy(
+ state,
+ key_store,
+ payment_data,
+ core_routing::StraightThroughAlgorithmTypeSingle(straight_through),
+ dimensions,
+ business_profile,
+ )
+ .await?
+ }
}
api::ConnectorChoice::Decide => {
- get_eligible_connector_for_proxy(
- state,
- key_store,
- payment_data,
- core_routing::DecideConnector,
- dimensions,
- business_profile,
- )
- .await?
+ if is_vault_card_flow {
+ get_eligible_connector_for_vault_card_proxy(
+ state,
+ key_store,
+ payment_data,
+ core_routing::DecideConnector,
+ dimensions,
+ business_profile,
+ )
+ .await?
+ } else {
+ get_eligible_connector_for_proxy(
+ state,
+ key_store,
+ payment_data,
+ core_routing::DecideConnector,
+ dimensions,
+ business_profile,
+ )
+ .await?
+ }
}
api::ConnectorChoice::SessionMultiple(_) => {
Err(errors::ApiErrorResponse::InternalServerError).attach_printable(
@@ -12701,6 +13264,11 @@ pub trait OperationSessionGetters<F> {
#[cfg(feature = "v1")]
fn get_installment_details(&self) -> Option<&common_types::payments::InstallmentData>;
+
+ #[cfg(feature = "v1")]
+ fn get_external_vault_pmd(
+ &self,
+ ) -> Option<&hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData>;
}
pub trait OperationSessionSetters<F> {
@@ -12784,6 +13352,14 @@ pub trait OperationSessionSetters<F> {
);
#[cfg(feature = "v2")]
fn set_cancellation_reason(&mut self, cancellation_reason: Option<String>);
+
+ #[cfg(feature = "v1")]
+ fn set_external_vault_pmd(
+ &mut self,
+ external_vault_pmd: Option<
+ hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData,
+ >,
+ );
}
#[cfg(feature = "v1")]
@@ -12960,15 +13536,12 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentData<F> {
self.vault_session_details.clone()
}
- // #[cfg(feature = "v2")]
- // fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
- // Some(self.payment_intent.capture_method)
- // }
-
- // #[cfg(feature = "v2")]
- // fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> {
- // todo!();
- // }
+ fn get_external_vault_pmd(
+ &self,
+ ) -> Option<&hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData>
+ {
+ self.external_vault_pmd.as_ref()
+ }
}
#[cfg(feature = "v1")]
@@ -13156,6 +13729,15 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentData<F> {
) {
self.payment_attempt.connector_request_reference_id = Some(connector_request_reference_id);
}
+
+ fn set_external_vault_pmd(
+ &mut self,
+ external_vault_pmd: Option<
+ hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData,
+ >,
+ ) {
+ self.external_vault_pmd = external_vault_pmd;
+ }
}
#[cfg(feature = "v2")]
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index b662ef142e..e8ff364786 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -5,7 +5,6 @@ pub mod cancel_post_capture_flow;
pub mod capture_flow;
pub mod complete_authorize_flow;
pub mod extend_authorization_flow;
-#[cfg(feature = "v2")]
pub mod external_proxy_flow;
pub mod incremental_authorization_flow;
pub mod post_session_tokens_flow;
@@ -19,7 +18,6 @@ pub mod update_metadata_flow;
use async_trait::async_trait;
use common_enums;
use common_types::payments::CustomerAcceptance;
-#[cfg(feature = "v2")]
use external_services::grpc_client;
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
use hyperswitch_domain_models::router_flow_types::{
@@ -330,6 +328,25 @@ pub trait Feature<F, T> {
{
Ok(())
}
+
+ #[cfg(feature = "v1")]
+ async fn call_unified_connector_service_with_external_vault_proxy_v1<'a>(
+ &mut self,
+ _state: &SessionState,
+ _header_payload: &domain_payments::HeaderPayload,
+ _lineage_ids: grpc_client::LineageIds,
+ _merchant_connector_account: &'a helpers::MerchantConnectorAccountType,
+ _external_vault_merchant_connector_account: &'a helpers::MerchantConnectorAccountType,
+ _processor: &domain::Processor,
+ _unified_connector_service_execution_mode: common_enums::ExecutionMode,
+ ) -> RouterResult<()>
+ where
+ F: Clone,
+ Self: Sized,
+ dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>,
+ {
+ Ok(())
+ }
}
/// Determines whether a capture API call should be made for a payment attempt
diff --git a/crates/router/src/core/payments/flows/external_proxy_flow.rs b/crates/router/src/core/payments/flows/external_proxy_flow.rs
index d4a3af5fee..d13fbee232 100644
--- a/crates/router/src/core/payments/flows/external_proxy_flow.rs
+++ b/crates/router/src/core/payments/flows/external_proxy_flow.rs
@@ -2,7 +2,7 @@ use std::str::FromStr;
use async_trait::async_trait;
use common_enums as enums;
-use common_utils::{id_type, ucs_types, ucs_types::UcsReferenceId};
+use common_utils::{id_type, ucs_types};
use error_stack::ResultExt;
use external_services::grpc_client;
#[cfg(feature = "v2")]
@@ -11,14 +11,13 @@ use hyperswitch_domain_models::{
errors::api_error_response::ApiErrorResponse, payments as domain_payments,
};
use hyperswitch_interfaces::api::gateway;
-use hyperswitch_masking::{ExposeInterface, ExposeInterface as UcsMaskingExposeInterface};
+use hyperswitch_masking::ExposeInterface;
use unified_connector_service_client::payments as payments_grpc;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
- mandate,
payments::{
self, access_token, customers, gateway::context as gateway_context, helpers,
session_token, tokenization, transformers, PaymentData,
@@ -28,13 +27,50 @@ use crate::{
logger,
routes::{metrics, SessionState},
services::{self, api::ConnectorValidation},
- types::{
- self, api, domain,
- transformers::{ForeignFrom, ForeignTryFrom},
- },
- utils::OptionExt,
+ types::{self, api, domain, transformers::ForeignTryFrom},
};
+#[cfg(feature = "v1")]
+#[async_trait]
+impl
+ ConstructFlowSpecificData<
+ api::ExternalVaultProxy,
+ types::ExternalVaultProxyPaymentsData,
+ types::PaymentsResponseData,
+ > for PaymentData<api::ExternalVaultProxy>
+{
+ async fn construct_router_data<'a>(
+ &self,
+ state: &SessionState,
+ connector_id: &str,
+ processor: &domain::Processor,
+ merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ merchant_recipient_data: Option<types::MerchantRecipientData>,
+ header_payload: Option<domain_payments::HeaderPayload>,
+ _payment_method: Option<common_enums::enums::PaymentMethod>,
+ _payment_method_type: Option<common_enums::enums::PaymentMethodType>,
+ ) -> RouterResult<
+ types::RouterData<
+ api::ExternalVaultProxy,
+ types::ExternalVaultProxyPaymentsData,
+ types::PaymentsResponseData,
+ >,
+ > {
+ Box::pin(
+ transformers::construct_external_vault_proxy_payment_router_data_v1(
+ state,
+ self.clone(),
+ connector_id,
+ processor,
+ merchant_connector_account,
+ merchant_recipient_data,
+ header_payload,
+ ),
+ )
+ .await
+ }
+}
+
#[cfg(feature = "v2")]
#[async_trait]
impl
@@ -86,10 +122,10 @@ impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
- business_profile: &domain::Profile,
- header_payload: domain_payments::HeaderPayload,
+ _business_profile: &domain::Profile,
+ _header_payload: domain_payments::HeaderPayload,
return_raw_connector_response: Option<bool>,
- gateway_context: gateway_context::RouterGatewayContext,
+ _gateway_context: gateway_context::RouterGatewayContext,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::ExternalVaultProxy,
@@ -178,8 +214,8 @@ impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>
async fn postprocessing_steps<'a>(
self,
- state: &SessionState,
- connector: &api::ConnectorData,
+ _state: &SessionState,
+ _connector: &api::ConnectorData,
) -> RouterResult<Self> {
todo!()
}
@@ -466,4 +502,111 @@ impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>
*self = updated_router_data;
Ok(())
}
+
+ #[cfg(feature = "v1")]
+ async fn call_unified_connector_service_with_external_vault_proxy_v1<'a>(
+ &mut self,
+ state: &SessionState,
+ header_payload: &domain_payments::HeaderPayload,
+ lineage_ids: grpc_client::LineageIds,
+ merchant_connector_account: &'a helpers::MerchantConnectorAccountType,
+ external_vault_merchant_connector_account: &'a helpers::MerchantConnectorAccountType,
+ processor: &domain::Processor,
+ unified_connector_service_execution_mode: enums::ExecutionMode,
+ ) -> RouterResult<()> {
+ let client = state
+ .grpc_client
+ .unified_connector_service_client
+ .clone()
+ .ok_or(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to fetch Unified Connector Service client")?;
+
+ let payment_authorize_request =
+ payments_grpc::PaymentServiceAuthorizeRequest::foreign_try_from(&*self)
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to construct Payment Authorize Request")?;
+
+ let connector_auth_metadata =
+ unified_connector_service::build_unified_connector_service_auth_metadata(
+ merchant_connector_account.clone(),
+ processor,
+ self.connector.clone(),
+ )
+ .change_context(ApiErrorResponse::InternalServerError)
+ .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.clone(),
+ &state.conf.connectors,
+ )
+ .change_context(ApiErrorResponse::InternalServerError)
+ .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(self.payment_id.as_str()),
+ )
+ .map(ucs_types::UcsReferenceId::Payment);
+ let resource_id = id_type::PaymentResourceId::from_str(self.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_logging_wrapper(
+ self.clone(),
+ state,
+ payment_authorize_request.clone(),
+ headers_builder,
+ unified_connector_service_execution_mode,
+ |mut router_data, payment_authorize_request, grpc_headers| async move {
+ let response = Box::pin(client
+ .payment_authorize(
+ payment_authorize_request,
+ connector_auth_metadata,
+ grpc_headers,
+ ))
+ .await
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to authorize payment")?;
+
+ let payment_authorize_response = response.into_inner();
+
+ let ucs_data =
+ unified_connector_service::handle_unified_connector_service_response_for_payment_authorize(
+ payment_authorize_response.clone(),
+ router_data.status,
+ )
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to deserialize UCS response")?;
+
+ let router_data_response = ucs_data.router_data_response.map(|(response, status)| {
+ router_data.status = status;
+ response
+ });
+ router_data.response = router_data_response;
+ router_data.raw_connector_response = payment_authorize_response
+ .raw_connector_response
+ .clone()
+ .map(|raw_connector_response| raw_connector_response.expose().into());
+ router_data.connector_http_status_code = Some(ucs_data.status_code);
+
+ Ok((router_data, (), payment_authorize_response))
+ }
+ )).await?;
+
+ *self = updated_router_data;
+ Ok(())
+ }
}
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index ef73b2d6ab..9ff07e0568 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -12,6 +12,8 @@ pub mod payment_complete_authorize;
#[cfg(feature = "v1")]
pub mod payment_confirm;
#[cfg(feature = "v1")]
+pub mod payment_confirm_external_vault_proxy;
+#[cfg(feature = "v1")]
pub mod payment_create;
#[cfg(feature = "v1")]
pub mod payment_post_session_tokens;
@@ -88,10 +90,12 @@ pub use self::payment_update_intent::PaymentUpdateIntent;
pub use self::{
payment_approve::PaymentApprove, payment_cancel::PaymentCancel,
payment_cancel_post_capture::PaymentCancelPostCapture, payment_capture::PaymentCapture,
- payment_confirm::PaymentConfirm, payment_create::PaymentCreate,
- payment_post_session_tokens::PaymentPostSessionTokens, payment_reject::PaymentReject,
- payment_session::PaymentSession, payment_start::PaymentStart, payment_status::PaymentStatus,
- payment_update::PaymentUpdate, payment_update_metadata::PaymentUpdateMetadata,
+ payment_confirm::PaymentConfirm,
+ payment_confirm_external_vault_proxy::PaymentExternalVaultProxyConfirm,
+ payment_create::PaymentCreate, payment_post_session_tokens::PaymentPostSessionTokens,
+ payment_reject::PaymentReject, payment_session::PaymentSession, payment_start::PaymentStart,
+ payment_status::PaymentStatus, payment_update::PaymentUpdate,
+ payment_update_metadata::PaymentUpdateMetadata,
payments_extend_authorization::PaymentExtendAuthorization,
payments_incremental_authorization::PaymentIncrementalAuthorization,
tax_calculation::PaymentSessionUpdate,
diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs
index 6c6fadae90..58b4fe5479 100644
--- a/crates/router/src/core/payments/operations/payment_approve.rs
+++ b/crates/router/src/core/payments/operations/payment_approve.rs
@@ -210,6 +210,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCaptureR
external_authentication_data: None,
client_session_id: None,
vault_session_details: None,
+ external_vault_pmd: None,
};
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs
index 7edaaab610..5542f9058d 100644
--- a/crates/router/src/core/payments/operations/payment_cancel.rs
+++ b/crates/router/src/core/payments/operations/payment_cancel.rs
@@ -219,6 +219,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelRe
external_authentication_data: None,
client_session_id: None,
vault_session_details: None,
+ external_vault_pmd: None,
};
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs b/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs
index 926c7bce2a..b81daeae88 100644
--- a/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs
@@ -201,6 +201,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelPo
external_authentication_data: None,
client_session_id: None,
vault_session_details: None,
+ external_vault_pmd: None,
};
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs
index aa6594eed9..d89c63cee1 100644
--- a/crates/router/src/core/payments/operations/payment_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_capture.rs
@@ -274,6 +274,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, api::Paymen
external_authentication_data: None,
client_session_id: None,
vault_session_details: None,
+ external_vault_pmd: None,
};
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
index 67ddcb3652..146ba273fb 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -396,6 +396,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
external_authentication_data: None,
client_session_id: None,
vault_session_details: None,
+ external_vault_pmd: None,
};
let customer_details = Some(CustomerDetails {
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 25a7637ee3..66f2569baf 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -943,6 +943,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
external_authentication_data: request.three_ds_data.clone(),
client_session_id: None,
vault_session_details: None,
+ external_vault_pmd: None,
};
let get_trackers_response = operations::GetTrackerResponse {
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.rs
new file mode 100644
index 0000000000..579c165c9f
--- /dev/null
+++ b/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs
@@ -0,0 +1,594 @@
+use std::marker::PhantomData;
+
+use api_models::{enums::FrmSuggestion, payments::PaymentsRequest};
+use async_trait::async_trait;
+use common_enums;
+use error_stack::ResultExt;
+use router_env::{instrument, tracing};
+
+use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
+use crate::{
+ core::{
+ configs::dimension_state,
+ errors::{self, CustomResult, RouterResult, StorageErrorExt},
+ payment_methods::{transformers as pm_transformers, transformers::PaymentMethodFetchData},
+ payments::{
+ helpers, operations, CustomerDetails, OperationSessionSetters, PaymentAddress,
+ PaymentData,
+ },
+ utils as core_utils,
+ },
+ routes::{app::ReqState, SessionState},
+ services,
+ types::{
+ api::{self, PaymentIdTypeExt},
+ domain,
+ storage::{self, enums as storage_enums},
+ },
+ utils::OptionExt,
+};
+
+#[derive(Debug, Clone, Copy)]
+pub struct PaymentExternalVaultProxyConfirm;
+
+impl<F: Send + Clone + Sync> Operation<F, PaymentsRequest> for PaymentExternalVaultProxyConfirm {
+ type Data = PaymentData<F>;
+ fn to_validate_request(
+ &self,
+ ) -> RouterResult<&(dyn ValidateRequest<F, PaymentsRequest, Self::Data> + Send + Sync)> {
+ Ok(self)
+ }
+ fn to_get_tracker(
+ &self,
+ ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsRequest> + Send + Sync)> {
+ Ok(self)
+ }
+ fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsRequest, Self::Data>> {
+ Ok(self)
+ }
+ fn to_update_tracker(
+ &self,
+ ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsRequest> + Send + Sync)> {
+ Ok(self)
+ }
+}
+
+impl<F: Send + Clone + Sync> Operation<F, PaymentsRequest> for &PaymentExternalVaultProxyConfirm {
+ type Data = PaymentData<F>;
+ fn to_validate_request(
+ &self,
+ ) -> RouterResult<&(dyn ValidateRequest<F, PaymentsRequest, Self::Data> + Send + Sync)> {
+ Ok(*self)
+ }
+ fn to_get_tracker(
+ &self,
+ ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsRequest> + Send + Sync)> {
+ Ok(*self)
+ }
+ fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsRequest, Self::Data>> {
+ Ok(*self)
+ }
+ fn to_update_tracker(
+ &self,
+ ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsRequest> + Send + Sync)> {
+ Ok(*self)
+ }
+}
+
+type ExternalVaultProxyOperation<'b, F> = BoxedOperation<'b, F, PaymentsRequest, PaymentData<F>>;
+
+#[async_trait]
+impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsRequest>
+ for PaymentExternalVaultProxyConfirm
+{
+ #[instrument(skip_all)]
+ async fn get_trackers<'a>(
+ &'a self,
+ state: &'a SessionState,
+ payment_id: &api::PaymentIdType,
+ request: &PaymentsRequest,
+ platform: &domain::Platform,
+ _auth_flow: services::AuthFlow,
+ _header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
+ payment_method_fetch_data: PaymentMethodFetchData,
+ _dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,
+ ) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsRequest, PaymentData<F>>> {
+ let db = &*state.store;
+ let payment_method_wrapper = payment_method_fetch_data.payment_method_with_raw_data;
+ let processor_merchant_id = platform.get_processor().get_account().get_id();
+ let storage_scheme = platform.get_processor().get_account().storage_scheme;
+
+ let payment_id = payment_id
+ .get_payment_intent_id()
+ .change_context(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ let payment_intent = db
+ .find_payment_intent_by_payment_id_processor_merchant_id(
+ &payment_id,
+ processor_merchant_id,
+ platform.get_processor().get_key_store(),
+ storage_scheme,
+ )
+ .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",
+ )?;
+
+ let mut payment_attempt = db
+ .find_payment_attempt_by_payment_id_processor_merchant_id_attempt_id(
+ &payment_intent.payment_id,
+ processor_merchant_id,
+ payment_intent.active_attempt.get_id().as_str(),
+ storage_scheme,
+ platform.get_processor().get_key_store(),
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ let currency = payment_attempt.currency.get_required_value("currency")?;
+ let amount = payment_attempt.get_total_amount().into();
+
+ let shipping_address = helpers::get_address_by_id(
+ state,
+ payment_intent.shipping_address_id.clone(),
+ platform.get_processor().get_key_store(),
+ &payment_intent.payment_id,
+ processor_merchant_id,
+ storage_scheme,
+ )
+ .await?;
+
+ let billing_address = helpers::get_address_by_id(
+ state,
+ payment_intent.billing_address_id.clone(),
+ platform.get_processor().get_key_store(),
+ &payment_intent.payment_id,
+ processor_merchant_id,
+ storage_scheme,
+ )
+ .await?;
+
+ let payment_method_billing = helpers::get_address_by_id(
+ state,
+ payment_attempt.payment_method_billing_address_id.clone(),
+ platform.get_processor().get_key_store(),
+ &payment_intent.payment_id,
+ processor_merchant_id,
+ storage_scheme,
+ )
+ .await?;
+
+ let profile_id = payment_intent
+ .profile_id
+ .as_ref()
+ .get_required_value("profile_id")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("'profile_id' not set in payment intent")?;
+
+ let business_profile = db
+ .find_business_profile_by_profile_id(
+ platform.get_processor().get_key_store(),
+ profile_id,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
+ id: profile_id.get_string_repr().to_owned(),
+ })?;
+
+ let customer_details = CustomerDetails {
+ customer_id: payment_intent.customer_id.clone(),
+ ..CustomerDetails::default()
+ };
+
+ // The external vault proxy flow is non-PCI: the confirm request carries vault card data
+ // as `PaymentMethodData::ProxyCard`. Derive the external vault payment method data
+ // from it. Any other payment method data variant is not routed here (see the route layer).
+ let external_vault_pmd = request
+ .payment_method_data
+ .as_ref()
+ .and_then(|pmd| pmd.payment_method_data.as_ref())
+ .and_then(|pmd| match pmd {
+ api_models::payments::PaymentMethodData::ProxyCard(card) => Some(
+ hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::Card(
+ Box::new(
+ hyperswitch_domain_models::payment_method_data::ExternalVaultCard::from(
+ (**card).clone(),
+ ),
+ ),
+ ),
+ ),
+ _ => 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.
+ let payment_method = request
+ .payment_method
+ .get_required_value("payment_method")?;
+ let payment_method_subtype = request
+ .payment_method_type
+ .get_required_value("payment_method_type")?;
+
+ payment_attempt.payment_method = Some(payment_method);
+ payment_attempt.payment_method_type = Some(payment_method_subtype);
+
+ let payment_method_info = payment_method_wrapper.map(|w| w.payment_method);
+
+ let payment_data = PaymentData {
+ flow: PhantomData,
+ payment_intent,
+ currency,
+ amount,
+ mandate_id: None,
+ mandate_connector: None,
+ setup_mandate: None,
+ customer_acceptance: request.customer_acceptance.clone(),
+ token: request.payment_token.clone(),
+ address: PaymentAddress::new(
+ shipping_address.as_ref().map(From::from),
+ billing_address.as_ref().map(From::from),
+ payment_method_billing.as_ref().map(From::from),
+ business_profile.use_billing_as_payment_method_billing,
+ ),
+ token_data: None,
+ confirm: Some(true),
+ payment_attempt,
+ payment_method_data: None,
+ payment_method_token: None,
+ payment_method_info,
+ force_sync: None,
+ all_keys_required: None,
+ refunds: vec![],
+ disputes: vec![],
+ attempts: None,
+ sessions_token: vec![],
+ card_cvc: None,
+ creds_identifier: None,
+ pm_token: None,
+ connector_customer_id: None,
+ recurring_mandate_payment_data: None,
+ multiple_capture_data: None,
+ redirect_response: None,
+ surcharge_details: None,
+ frm_message: None,
+ payment_link_data: None,
+ incremental_authorization_details: None,
+ authorizations: vec![],
+ authentication: None,
+ recurring_details: None,
+ poll_config: None,
+ tax_data: None,
+ session_id: None,
+ service_details: None,
+ card_testing_guard_data: None,
+ vault_operation: None,
+ threeds_method_comp_ind: None,
+ whole_connector_response: None,
+ is_manual_retry_enabled: business_profile.is_manual_retry_enabled,
+ is_l2_l3_enabled: business_profile.is_l2_l3_enabled,
+ external_authentication_data: None,
+ vault_session_details: None,
+ external_vault_pmd,
+ client_session_id: None,
+ };
+
+ let get_trackers_response = operations::GetTrackerResponse {
+ operation: Box::new(*self),
+ customer_details: Some(customer_details),
+ payment_data,
+ business_profile,
+ mandate_type: None,
+ };
+
+ Ok(get_trackers_response)
+ }
+}
+
+#[async_trait]
+impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, PaymentsRequest>
+ for PaymentExternalVaultProxyConfirm
+{
+ #[instrument(skip_all)]
+ async fn update_trackers<'b>(
+ &'b self,
+ state: &'b SessionState,
+ _req_state: ReqState,
+ processor: &domain::Processor,
+ mut payment_data: PaymentData<F>,
+ _frm_suggestion: Option<FrmSuggestion>,
+ _header_payload: hyperswitch_domain_models::payments::HeaderPayload,
+ _dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,
+ ) -> RouterResult<(
+ BoxedOperation<'b, F, PaymentsRequest, PaymentData<F>>,
+ PaymentData<F>,
+ )>
+ where
+ F: 'b + Send,
+ {
+ let storage_scheme = processor.get_account().storage_scheme;
+ let key_store = processor.get_key_store();
+
+ let connector = payment_data.payment_attempt.connector.clone();
+ let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone();
+
+ let payment_method = payment_data.payment_attempt.payment_method;
+ let authentication_type = payment_data.payment_attempt.authentication_type;
+ let connector_request_reference_id = payment_data
+ .payment_attempt
+ .connector_request_reference_id
+ .clone();
+
+ 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,
+ payment_method,
+ authentication_type,
+ capture_method: payment_data.payment_attempt.capture_method,
+ browser_info: payment_data.payment_attempt.browser_info.clone(),
+ connector,
+ payment_token: payment_data.token.clone(),
+ payment_method_data: None,
+ payment_method_type: payment_data.payment_attempt.payment_method_type,
+ payment_experience: payment_data.payment_attempt.payment_experience,
+ business_sub_label: payment_data.payment_attempt.business_sub_label.clone(),
+ straight_through_algorithm: payment_data
+ .payment_attempt
+ .straight_through_algorithm
+ .clone(),
+ error_code: None,
+ error_message: None,
+ updated_by: storage_scheme.to_string(),
+ merchant_connector_id,
+ external_three_ds_authentication_attempted: None,
+ authentication_connector: None,
+ authentication_id: None,
+ payment_method_billing_address_id: payment_data
+ .payment_attempt
+ .payment_method_billing_address_id
+ .clone(),
+ fingerprint_id: payment_data.payment_attempt.fingerprint_id.clone(),
+ payment_method_id: payment_data.payment_attempt.payment_method_id.clone(),
+ client_source: None,
+ client_version: None,
+ customer_acceptance: payment_data.payment_attempt.customer_acceptance.clone(),
+ net_amount:
+ hyperswitch_domain_models::payments::payment_attempt::NetAmount::new(
+ payment_data.payment_attempt.net_amount.get_order_amount(),
+ payment_data.payment_intent.shipping_cost,
+ payment_data
+ .payment_attempt
+ .net_amount
+ .get_order_tax_amount(),
+ None,
+ None,
+ payment_data
+ .payment_attempt
+ .net_amount
+ .get_installment_interest(),
+ ),
+ connector_mandate_detail: payment_data
+ .payment_attempt
+ .connector_mandate_detail
+ .clone(),
+ card_discovery: None,
+ routing_approach: payment_data.payment_attempt.routing_approach.clone(),
+ connector_request_reference_id,
+ network_transaction_id: payment_data
+ .payment_attempt
+ .network_transaction_id
+ .clone(),
+ is_stored_credential: payment_data.payment_attempt.is_stored_credential,
+ request_extended_authorization: payment_data
+ .payment_attempt
+ .request_extended_authorization,
+ tokenization: payment_data.payment_attempt.get_tokenization_strategy(),
+ installment_data: None,
+ network_transaction_link_id: None,
+ },
+ storage_scheme,
+ key_store,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ payment_data.payment_attempt = updated_payment_attempt;
+
+ Ok((Box::new(*self), payment_data))
+ }
+}
+
+impl<F: Send + Clone + Sync> ValidateRequest<F, PaymentsRequest, PaymentData<F>>
+ for PaymentExternalVaultProxyConfirm
+{
+ #[instrument(skip_all)]
+ fn validate_request<'a, 'b>(
+ &'b self,
+ request: &PaymentsRequest,
+ processor: &'a domain::Processor,
+ ) -> RouterResult<(
+ ExternalVaultProxyOperation<'b, F>,
+ operations::ValidateResult,
+ )> {
+ let payment_id = request
+ .payment_id
+ .clone()
+ .ok_or(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ Ok((
+ Box::new(*self),
+ operations::ValidateResult {
+ merchant_id: processor.get_account().get_id().to_owned(),
+ payment_id,
+ storage_scheme: processor.get_account().storage_scheme,
+ requeue: false,
+ },
+ ))
+ }
+}
+
+#[async_trait]
+impl<F: Clone + Send + Sync> Domain<F, PaymentsRequest, PaymentData<F>>
+ for PaymentExternalVaultProxyConfirm
+{
+ #[cfg(feature = "v1")]
+ #[instrument(skip_all)]
+ async fn fetch_payment_method(
+ &self,
+ _state: &SessionState,
+ _req: &PaymentsRequest,
+ _platform: &domain::Platform,
+ _feature_config: &core_utils::FeatureConfig,
+ ) -> RouterResult<PaymentMethodFetchData> {
+ // The external vault proxy flow only supports inline `ProxyCard`, so there is no
+ // stored payment method to fetch up front. The vault card is parsed from the request
+ // in `get_trackers`.
+ Ok(PaymentMethodFetchData::default())
+ }
+
+ #[cfg(feature = "v1")]
+ #[instrument(skip_all)]
+ async fn create_payment_method(
+ &self,
+ state: &SessionState,
+ _req: &PaymentsRequest,
+ platform: &domain::Platform,
+ payment_data: &mut PaymentData<F>,
+ business_profile: &domain::Profile,
+ _feature_config: &core_utils::FeatureConfig,
+ ) -> RouterResult<()> {
+ // Only create if customer has given acceptance
+ if payment_data.customer_acceptance.is_none() {
+ router_env::logger::info!("Skipping PM creation: customer_acceptance is None");
+ return Ok(());
+ }
+ // Only create for ExternalVaultCard (proxy card flow)
+ let vault_card = match payment_data.external_vault_pmd.clone() {
+ Some(
+ hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::Card(
+ card,
+ ),
+ ) => *card,
+ Some(other) => {
+ router_env::logger::info!(?other, "Skipping PM creation: external_vault_pmd is not a Card variant");
+ return Ok(());
+ }
+ None => {
+ router_env::logger::info!("Skipping PM creation: external_vault_pmd is None");
+ return Ok(());
+ }
+ };
+ let customer_id = payment_data
+ .payment_intent
+ .customer_id
+ .clone()
+ .get_required_value("customer_id")?;
+ let payment_method = payment_data
+ .payment_attempt
+ .payment_method
+ .unwrap_or(common_enums::PaymentMethod::Card);
+ let payment_method_type = payment_data.payment_attempt.payment_method_type;
+
+ match pm_transformers::create_proxy_card_payment_method_in_modular_service(
+ state,
+ platform.get_provider().get_account().get_id(),
+ platform.get_processor().get_account().get_id(),
+ business_profile.get_id(),
+ payment_method,
+ payment_method_type,
+ vault_card,
+ payment_data.address.get_payment_method_billing().cloned(),
+ customer_id,
+ )
+ .await
+ {
+ Ok(mut pm_info) => {
+ router_env::logger::info!(
+ "Proxy card payment method created in modular service successfully"
+ );
+ // The payment method is created in the modular (V2) payment method service.
+ // Mark it as such so the post-payment acknowledgement path
+ // (`handle_pm_and_mandate_post_update` -> `should_use_modular_pm_path`) is taken
+ // and the modular PM status is acknowledged (new -> active). Without this the PM
+ // defaults to `version: V1`, the gate falls back to the legacy `save_pm_and_mandate`
+ // path, and the acknowledgement call is never made.
+ pm_info.version = common_enums::ApiVersion::V2;
+ payment_data.set_payment_method_id_in_attempt(Some(pm_info.get_id().clone()));
+ payment_data.set_payment_method_info(Some(pm_info));
+ }
+ Err(err) => {
+ router_env::logger::error!(error=?err, "Failed to create proxy card PM in modular service for external vault proxy");
+ }
+ }
+ Ok(())
+ }
+
+ #[instrument(skip_all)]
+ async fn get_or_create_customer_details<'a>(
+ &'a self,
+ state: &SessionState,
+ payment_data: &mut PaymentData<F>,
+ request: Option<CustomerDetails>,
+ provider: &domain::Provider,
+ initiator: Option<&domain::Initiator>,
+ _dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,
+ _mandate_type: Option<api::MandateTransactionType>,
+ ) -> CustomResult<
+ (ExternalVaultProxyOperation<'a, F>, Option<domain::Customer>),
+ errors::StorageError,
+ > {
+ helpers::create_customer_if_not_exist(
+ state,
+ Box::new(*self),
+ payment_data,
+ request,
+ provider,
+ initiator,
+ _dimensions,
+ )
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn make_pm_data<'a>(
+ &'a self,
+ _state: &'a SessionState,
+ _payment_data: &mut PaymentData<F>,
+ _storage_scheme: storage_enums::MerchantStorageScheme,
+ _platform: &domain::Platform,
+ _business_profile: &domain::Profile,
+ _should_retry_with_pan: bool,
+ ) -> RouterResult<(
+ ExternalVaultProxyOperation<'a, F>,
+ Option<domain::PaymentMethodData>,
+ Option<String>,
+ )> {
+ // The payment method data comes from external_vault_pmd, not pm_data
+ // Return None here; the transformer will extract from external_vault_pmd
+ Ok((Box::new(*self), None, None))
+ }
+
+ async fn get_connector<'a>(
+ &'a self,
+ _processor: &domain::Processor,
+ state: &SessionState,
+ _request: &PaymentsRequest,
+ _payment_intent: &storage::PaymentIntent,
+ ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
+ helpers::get_connector_default(state, None).await
+ }
+}
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index a93beeb18d..cfeddc3eea 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -730,6 +730,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
external_authentication_data: request.three_ds_data.clone(),
client_session_id,
vault_session_details: None,
+ external_vault_pmd: None,
};
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs
index 0f3d309e6b..d57c7ee3ba 100644
--- a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs
+++ b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs
@@ -186,6 +186,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsPostSess
external_authentication_data: None,
client_session_id: None,
vault_session_details: None,
+ external_vault_pmd: None,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
diff --git a/crates/router/src/core/payments/operations/payment_recurrence.rs b/crates/router/src/core/payments/operations/payment_recurrence.rs
index 6dea53615b..0c9e3b6ac2 100644
--- a/crates/router/src/core/payments/operations/payment_recurrence.rs
+++ b/crates/router/src/core/payments/operations/payment_recurrence.rs
@@ -385,6 +385,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
external_authentication_data: None,
client_session_id: None,
vault_session_details: None,
+ external_vault_pmd: None,
};
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs
index e8b90e8192..e3485dcd7b 100644
--- a/crates/router/src/core/payments/operations/payment_reject.rs
+++ b/crates/router/src/core/payments/operations/payment_reject.rs
@@ -206,6 +206,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest
external_authentication_data: None,
client_session_id: None,
vault_session_details: None,
+ external_vault_pmd: None,
};
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 7f1e2a0d6f..24599e5668 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -3536,6 +3536,118 @@ impl<F: Send + Clone> Operation<F, types::SetupMandateRequestData> for &PaymentR
}
}
+#[cfg(feature = "v1")]
+impl
+ Operation<
+ hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
+ types::ExternalVaultProxyPaymentsData,
+ > for &PaymentResponse
+{
+ type Data = PaymentData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>;
+ fn to_post_update_tracker(
+ &self,
+ ) -> RouterResult<
+ &(dyn PostUpdateTracker<
+ hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
+ Self::Data,
+ types::ExternalVaultProxyPaymentsData,
+ > + Send
+ + Sync),
+ > {
+ Ok(*self)
+ }
+}
+
+#[cfg(feature = "v1")]
+impl
+ Operation<
+ hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
+ types::ExternalVaultProxyPaymentsData,
+ > for PaymentResponse
+{
+ type Data = PaymentData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>;
+ fn to_post_update_tracker(
+ &self,
+ ) -> RouterResult<
+ &(dyn PostUpdateTracker<
+ hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
+ Self::Data,
+ types::ExternalVaultProxyPaymentsData,
+ > + Send
+ + Sync),
+ > {
+ Ok(self)
+ }
+}
+
+#[cfg(feature = "v1")]
+#[async_trait]
+impl
+ PostUpdateTracker<
+ hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
+ PaymentData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>,
+ types::ExternalVaultProxyPaymentsData,
+ > for PaymentResponse
+{
+ async fn update_tracker<'b>(
+ &'b self,
+ state: &'b SessionState,
+ processor: &domain::Processor,
+ payment_data: PaymentData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>,
+ router_data: types::RouterData<
+ hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
+ types::ExternalVaultProxyPaymentsData,
+ types::PaymentsResponseData,
+ >,
+ locale: &Option<String>,
+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec<
+ RoutableConnectorChoice,
+ >,
+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,
+ ) -> RouterResult<PaymentData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>>
+ where
+ hyperswitch_domain_models::router_flow_types::ExternalVaultProxy: 'b + Send + Sync,
+ {
+ Box::pin(payment_response_update_tracker(
+ state,
+ payment_data,
+ router_data,
+ processor,
+ locale,
+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+ routable_connector,
+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+ business_profile,
+ ))
+ .await
+ }
+
+ #[cfg(feature = "v1")]
+ async fn update_modular_pm_and_mandate<'b>(
+ &self,
+ state: &SessionState,
+ resp: &types::RouterData<
+ hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
+ types::ExternalVaultProxyPaymentsData,
+ types::PaymentsResponseData,
+ >,
+ _platform: &domain::Platform,
+ payment_data: &mut PaymentData<
+ hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
+ >,
+ _business_profile: &domain::Profile,
+ request_payment_method_data: Option<&domain::PaymentMethodData>,
+ ) -> CustomResult<(), errors::ApiErrorResponse>
+ where
+ hyperswitch_domain_models::router_flow_types::ExternalVaultProxy: 'b + Clone + Send + Sync,
+ {
+ update_modular_pm_and_mandate_impl(state, resp, request_payment_method_data, payment_data)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update modular payment method and mandate")
+ }
+}
+
#[cfg(feature = "v2")]
impl<F: Send + Clone> Operation<F, types::SetupMandateRequestData> for PaymentResponse {
type Data = PaymentConfirmData<F>;
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index b4a15c84b9..83d94ac7b6 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -232,6 +232,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsSessionR
is_l2_l3_enabled: false,
external_authentication_data: None,
client_session_id: None,
+ external_vault_pmd: None,
};
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index 7e7dd71b3e..ee23a0bc66 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -235,6 +235,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsStartReq
external_authentication_data: None,
client_session_id: None,
vault_session_details: None,
+ external_vault_pmd: None,
};
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index b8c1c0a3df..27a17fd973 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -575,6 +575,7 @@ async fn get_tracker_for_sync<
external_authentication_data: None,
client_session_id: None,
vault_session_details: None,
+ external_vault_pmd: None,
};
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 88d5d0c264..2138024810 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -581,6 +581,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
external_authentication_data: None,
client_session_id: None,
vault_session_details: None,
+ external_vault_pmd: None,
};
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/core/payments/operations/payment_update_metadata.rs b/crates/router/src/core/payments/operations/payment_update_metadata.rs
index dbfbe86fd8..680f90135f 100644
--- a/crates/router/src/core/payments/operations/payment_update_metadata.rs
+++ b/crates/router/src/core/payments/operations/payment_update_metadata.rs
@@ -192,6 +192,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsUpdateMe
external_authentication_data: None,
client_session_id: None,
vault_session_details: None,
+ external_vault_pmd: None,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
diff --git a/crates/router/src/core/payments/operations/payments_extend_authorization.rs b/crates/router/src/core/payments/operations/payments_extend_authorization.rs
index 42f131a12f..17d605e42c 100644
--- a/crates/router/src/core/payments/operations/payments_extend_authorization.rs
+++ b/crates/router/src/core/payments/operations/payments_extend_authorization.rs
@@ -207,6 +207,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsExtendAu
external_authentication_data: None,
client_session_id: None,
vault_session_details: None,
+ external_vault_pmd: None,
};
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
index b98d42cbb8..44f9401bba 100644
--- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
+++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
@@ -186,6 +186,7 @@ impl<F: Send + Clone + Sync>
external_authentication_data: None,
client_session_id: None,
vault_session_details: None,
+ external_vault_pmd: None,
};
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/core/payments/operations/tax_calculation.rs b/crates/router/src/core/payments/operations/tax_calculation.rs
index 64e7fc63ec..1256235755 100644
--- a/crates/router/src/core/payments/operations/tax_calculation.rs
+++ b/crates/router/src/core/payments/operations/tax_calculation.rs
@@ -202,6 +202,7 @@ impl<F: Send + Clone + Sync>
external_authentication_data: None,
client_session_id: None,
vault_session_details: None,
+ external_vault_pmd: None,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 2f7ca6e8c9..eea905bcf0 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -770,6 +770,249 @@ pub async fn construct_external_vault_proxy_payment_router_data<'a>(
Ok(router_data)
}
+
+#[cfg(feature = "v1")]
+#[instrument(skip_all)]
+#[allow(clippy::too_many_arguments)]
+pub async fn construct_external_vault_proxy_payment_router_data_v1<'a>(
+ state: &'a SessionState,
+ payment_data: PaymentData<api::ExternalVaultProxy>,
+ connector_id: &str,
+ processor: &domain::Processor,
+ merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ _merchant_recipient_data: Option<types::MerchantRecipientData>,
+ header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+) -> RouterResult<types::ExternalVaultProxyPaymentsRouterData> {
+ fp_utils::when(merchant_connector_account.is_disabled(), || {
+ Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled)
+ })?;
+
+ let test_mode = merchant_connector_account.is_test_mode_on();
+
+ let auth_type: types::ConnectorAuthType = merchant_connector_account
+ .get_connector_account_details()
+ .parse_value("ConnectorAuthType")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while parsing value for ConnectorAuthType")?;
+
+ let attempt = &payment_data.payment_attempt;
+
+ let merchant_connector_account_id_or_connector_name = attempt
+ .merchant_connector_id
+ .as_ref()
+ .map(|mca_id| mca_id.get_string_repr().to_owned())
+ .unwrap_or_else(|| connector_id.to_owned());
+
+ let complete_authorize_url = Some(helpers::create_complete_authorize_url(
+ &state.base_url,
+ attempt,
+ connector_id,
+ None,
+ ));
+
+ let webhook_url = Some(helpers::create_webhook_url(
+ &state.base_url,
+ &attempt.merchant_id,
+ &merchant_connector_account_id_or_connector_name,
+ ));
+
+ let router_return_url = Some(helpers::create_redirect_url(
+ &state.base_url,
+ attempt,
+ connector_id,
+ payment_data.creds_identifier.as_deref(),
+ ));
+
+ let amount = payment_data.payment_attempt.get_total_amount();
+
+ let browser_info: Option<types::BrowserInformation> = attempt
+ .browser_info
+ .clone()
+ .map(|b| b.parse_value("BrowserInformation"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "browser_info",
+ })?;
+
+ let customer_details = payment_data
+ .payment_intent
+ .customer_details
+ .clone()
+ .map(|customer_details_encrypted| {
+ customer_details_encrypted
+ .into_inner()
+ .expose()
+ .parse_value::<CustomerData>("CustomerData")
+ })
+ .transpose()
+ .change_context(errors::StorageError::DeserializationFailed)
+ .attach_printable("Failed to parse customer data from payment intent")
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+
+ let email = customer_details.as_ref().and_then(|cd| cd.email.clone());
+
+ let customer_id = payment_data.payment_intent.customer_id.clone();
+
+ let request = types::ExternalVaultProxyPaymentsData {
+ payment_method_data: payment_data
+ .external_vault_pmd
+ .clone()
+ .get_required_value("external vault proxy payment_method_data")?,
+ setup_future_usage: payment_data
+ .payment_attempt
+ .setup_future_usage_applied
+ .or(payment_data.payment_intent.setup_future_usage),
+ mandate_id: payment_data.mandate_id.clone(),
+ off_session: None,
+ setup_mandate_details: None,
+ confirm: true,
+ statement_descriptor_suffix: None,
+ statement_descriptor: None,
+ capture_method: payment_data.payment_attempt.capture_method,
+ amount: amount.get_amount_as_i64(),
+ minor_amount: amount,
+ order_tax_amount: payment_data
+ .payment_attempt
+ .net_amount
+ .get_order_tax_amount(),
+ currency: payment_data.currency,
+ browser_info,
+ email,
+ customer_name: customer_details.and_then(|customer| customer.name.clone()),
+ payment_experience: None,
+ order_details: None,
+ order_category: None,
+ session_token: None,
+ enrolled_for_3ds: true,
+ related_transaction_id: None,
+ payment_method_type: payment_data.payment_attempt.payment_method_type,
+ router_return_url,
+ webhook_url,
+ complete_authorize_url,
+ customer_id: customer_id.clone(),
+ surcharge_details: None,
+ request_extended_authorization: None,
+ request_incremental_authorization: matches!(
+ payment_data
+ .payment_intent
+ .request_incremental_authorization,
+ Some(RequestIncrementalAuthorization::True)
+ ),
+ metadata: payment_data.payment_intent.metadata.clone(),
+ authentication_data: None,
+ customer_acceptance: payment_data.customer_acceptance,
+ split_payments: None,
+ merchant_order_reference_id: None,
+ integrity_object: None,
+ shipping_cost: payment_data.payment_intent.shipping_cost,
+ additional_payment_method_data: None,
+ merchant_account_id: None,
+ merchant_config_currency: None,
+ connector_testing_data: None,
+ order_id: None,
+ };
+
+ let connector_mandate_request_reference_id = payment_data
+ .payment_attempt
+ .connector_mandate_detail
+ .as_ref()
+ .and_then(|detail| detail.get_connector_mandate_request_reference_id());
+
+ let router_data = types::RouterData {
+ flow: PhantomData,
+ merchant_id: processor.get_account().get_id().clone(),
+ customer_id,
+ tenant_id: state.tenant.tenant_id.clone(),
+ connector: connector_id.to_owned(),
+ payment_id: payment_data
+ .payment_attempt
+ .payment_id
+ .get_string_repr()
+ .to_owned(),
+ attempt_id: payment_data.payment_attempt.attempt_id.clone(),
+ status: payment_data.payment_attempt.status,
+ payment_method: payment_data
+ .payment_attempt
+ .payment_method
+ .unwrap_or_default(),
+ payment_method_type: payment_data.payment_attempt.payment_method_type,
+ connector_auth_type: auth_type,
+ description: payment_data.payment_intent.description.clone(),
+ address: payment_data.address.clone(),
+ auth_type: payment_data
+ .payment_attempt
+ .authentication_type
+ .unwrap_or_default(),
+ connector_meta_data: merchant_connector_account.get_metadata(),
+ connector_wallets_details: None,
+ request,
+ response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()),
+ amount_captured: payment_data
+ .payment_intent
+ .amount_captured
+ .map(|amt| amt.get_amount_as_i64()),
+ minor_amount_captured: payment_data.payment_intent.amount_captured,
+ access_token: None,
+ session_token: None,
+ reference_id: None,
+ payment_method_status: payment_data
+ .payment_method_info
+ .clone()
+ .map(|info| info.status),
+ payment_method_token: payment_data
+ .pm_token
+ .map(|token| types::PaymentMethodToken::Token(Secret::new(token))),
+ connector_customer: core_utils::get_connector_customer_id(
+ &state.conf,
+ connector_id,
+ payment_data.connector_customer_id.clone(),
+ &payment_data.payment_intent.customer_id,
+ &payment_data.payment_method_info,
+ &payment_data.payment_attempt,
+ )?,
+ recurring_mandate_payment_data: payment_data.recurring_mandate_payment_data,
+ connector_request_reference_id: core_utils::get_connector_request_reference_id(
+ &state.conf,
+ processor,
+ &payment_data.payment_intent,
+ &payment_data.payment_attempt,
+ connector_id,
+ )?,
+ preprocessing_id: payment_data.payment_attempt.preprocessing_step_id,
+ #[cfg(feature = "payouts")]
+ payout_method_data: None,
+ #[cfg(feature = "payouts")]
+ quote_id: None,
+ test_mode,
+ payment_method_balance: None,
+ connector_api_version: None,
+ connector_http_status_code: None,
+ external_latency: None,
+ apple_pay_flow: None,
+ frm_metadata: None,
+ refund_id: None,
+ dispute_id: None,
+ payout_id: None,
+ connector_response: None,
+ integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload,
+ connector_mandate_request_reference_id,
+ authentication_id: None,
+ psd2_sca_exemption_type: payment_data.payment_intent.psd2_sca_exemption_type,
+ raw_connector_response: None,
+ is_payment_id_from_merchant: payment_data.payment_intent.is_payment_id_from_merchant,
+ l2_l3_data: None,
+ minor_amount_capturable: None,
+ authorized_amount: None,
+ customer_document_details: None,
+ feature_data: None,
+ sender_payment_instrument_id: None,
+ };
+
+ Ok(router_data)
+}
+
#[cfg(feature = "v2")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
diff --git a/crates/router/src/core/payments/vault_session.rs b/crates/router/src/core/payments/vault_session.rs
index 40802cce19..5ed9461a70 100644
--- a/crates/router/src/core/payments/vault_session.rs
+++ b/crates/router/src/core/payments/vault_session.rs
@@ -1,6 +1,10 @@
+#[cfg(feature = "v2")]
+use api_models::enums::VaultConnectors;
pub use common_enums::enums::CallConnectorAction;
use common_utils::id_type;
-use error_stack::{report, ResultExt};
+#[cfg(feature = "v2")]
+use error_stack::report;
+use error_stack::ResultExt;
#[cfg(feature = "v2")]
pub use hyperswitch_domain_models::payments::PaymentIntentData;
pub use hyperswitch_domain_models::{
@@ -13,15 +17,22 @@ pub use hyperswitch_domain_models::{
router_request_types::CustomerDetails,
types::{VaultRouterData, VaultRouterDataV2},
};
-use hyperswitch_interfaces::api::Connector as ConnectorTrait;
#[cfg(feature = "v2")]
-use hyperswitch_interfaces::connector_integration_v2::{ConnectorIntegrationV2, ConnectorV2};
+use hyperswitch_interfaces::{
+ api::Connector as ConnectorTrait,
+ connector_integration_interface::RouterDataConversion,
+ connector_integration_v2::{ConnectorIntegrationV2, ConnectorV2},
+};
+use hyperswitch_masking::ExposeInterface;
#[cfg(feature = "v1")]
-use hyperswitch_masking::{ExposeInterface, Mask};
-use router_env::env::Env;
+use hyperswitch_masking::Mask;
#[cfg(feature = "v2")]
-use crate::core::payments::{customers, gateway::context as gateway_context, helpers};
+use crate::core::{
+ errors::utils::ConnectorErrorExt,
+ payments::{customers, gateway::context as gateway_context, helpers},
+ utils as core_utils,
+};
use crate::{
core::{
errors::{self, RouterResult},
@@ -30,16 +41,10 @@ use crate::{
operations::BoxedOperation,
OperationSessionGetters, OperationSessionSetters,
},
- utils as core_utils,
},
- db::errors::ConnectorErrorExt,
routes::{app::ReqState, SessionState},
- services::{self, connector_integration_interface::RouterDataConversion},
- types::{
- self as router_types,
- api::{self, enums as api_enums},
- domain,
- },
+ services,
+ types::{self as router_types, api, domain},
};
#[cfg(feature = "v2")]
use crate::{
@@ -312,14 +317,13 @@ pub async fn generate_vault_session_details(
merchant_connector_account_type: &domain::MerchantConnectorAccountTypeDetails,
connector_customer_id: Option<String>,
) -> RouterResult<Option<api::VaultSessionDetails>> {
- let connector =
- api_enums::VaultConnectors::try_from(merchant_connector_account_type.get_connector_name())
- .map_err(|error| {
- report!(errors::ApiErrorResponse::InternalServerError).attach_printable(format!(
- "Failed to convert connector to vault connector: {}",
- error
- ))
- })?;
+ let connector = VaultConnectors::try_from(merchant_connector_account_type.get_connector_name())
+ .map_err(|error| {
+ report!(errors::ApiErrorResponse::InternalServerError).attach_printable(format!(
+ "Failed to convert connector to vault connector: {}",
+ error
+ ))
+ })?;
let connector_auth_type: router_types::ConnectorAuthType = merchant_connector_account_type
.get_connector_account_details()
@@ -331,12 +335,14 @@ pub async fn generate_vault_session_details(
match (connector, connector_auth_type) {
// create session for vgs vault
(
- api_enums::VaultConnectors::Vgs,
+ VaultConnectors::Vgs,
router_types::ConnectorAuthType::SignatureKey { api_secret, .. },
) => {
let sdk_env = match state.conf.env {
- Env::Sandbox | Env::Development | Env::Integ => "sandbox",
- Env::Production => "live",
+ router_env::Env::Sandbox
+ | router_env::Env::Development
+ | router_env::Env::Integ => "sandbox",
+ router_env::Env::Production => "live",
}
.to_string();
Ok(Some(api::VaultSessionDetails::Vgs(
@@ -348,7 +354,7 @@ pub async fn generate_vault_session_details(
}
// create session for hyperswitch vault
(
- api_enums::VaultConnectors::HyperswitchVault,
+ VaultConnectors::HyperswitchVault,
router_types::ConnectorAuthType::SignatureKey {
key1, api_secret, ..
},
@@ -376,148 +382,6 @@ pub async fn generate_vault_session_details(
}
}
-#[cfg(feature = "v1")]
-pub async fn generate_vault_session_details_v1(
- state: &SessionState,
- processor: &domain::Processor,
- vault_mca: &domain::MerchantConnectorAccount,
- connector_customer_id: Option<String>,
-) -> RouterResult<Option<api::VaultSessionDetails>> {
- let connector_name_str = vault_mca.get_connector_name_as_string();
- let connector =
- api_enums::VaultConnectors::from_connector_name(&connector_name_str).map_err(|error| {
- report!(errors::ApiErrorResponse::InternalServerError).attach_printable(error)
- })?;
-
- let connector_auth_type: router_types::ConnectorAuthType = vault_mca
- .get_connector_account_details()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to parse connector auth type")?;
-
- match (connector, connector_auth_type) {
- // create session for vgs vault
- (
- api_enums::VaultConnectors::Vgs,
- router_types::ConnectorAuthType::SignatureKey { api_secret, .. },
- ) => {
- let sdk_env = match state.conf.env {
- Env::Sandbox | Env::Development | Env::Integ => {
- common_enums::enums::VaultEnv::Sandbox.to_string()
- }
- Env::Production => common_enums::enums::VaultEnv::Live.to_string(),
- };
- Ok(Some(api::VaultSessionDetails::Vgs(
- api::VgsSessionDetails {
- external_vault_id: api_secret,
- sdk_env,
- },
- )))
- }
- // create session for hyperswitch vault
- (
- api_enums::VaultConnectors::HyperswitchVault,
- router_types::ConnectorAuthType::SignatureKey {
- key1, api_secret, ..
- },
- ) => {
- let connector_response = call_external_vault_create_v1(
- state,
- processor,
- connector_name_str,
- vault_mca,
- connector_customer_id,
- )
- .await?;
-
- match connector_response.response {
- Ok(router_types::VaultResponseData::ExternalVaultCreateResponse {
- session_id,
- client_secret,
- }) => Ok(Some(api::VaultSessionDetails::HyperswitchVault(
- api::HyperswitchVaultSessionDetails {
- payment_method_session_id: session_id,
- client_secret,
- publishable_key: key1,
- profile_id: api_secret,
- },
- ))),
- Ok(_) => {
- router_env::logger::warn!("Unexpected response from external vault create API");
- Err(errors::ApiErrorResponse::InternalServerError.into())
- }
- Err(err) => {
- router_env::logger::error!(error_response_from_external_vault_create=?err);
- Err(errors::ApiErrorResponse::InternalServerError.into())
- }
- }
- }
- _ => {
- router_env::logger::warn!(
- "External vault session creation is not supported for connector: {:?}",
- connector
- );
- Ok(None)
- }
- }
-}
-
-#[cfg(feature = "v1")]
-async fn call_external_vault_create_v1(
- state: &SessionState,
- processor: &domain::Processor,
- connector_name: String,
- vault_mca: &domain::MerchantConnectorAccount,
- connector_customer_id: Option<String>,
-) -> RouterResult<VaultRouterData<ExternalVaultCreateFlow>>
-where
- dyn ConnectorTrait + Sync: services::api::ConnectorIntegration<
- ExternalVaultCreateFlow,
- router_types::VaultRequestData,
- router_types::VaultResponseData,
- >,
-{
- let mca_id = vault_mca.get_id();
- let connector_data: api::ConnectorData = api::ConnectorData::get_connector_by_name(
- &state.conf.connectors,
- &connector_name,
- api::GetToken::Connector,
- Some(mca_id),
- )?;
-
- let router_data = core_utils::construct_vault_router_data(
- state,
- processor.get_account().get_id(),
- vault_mca,
- None,
- None,
- connector_customer_id,
- None,
- )
- .await?;
-
- let old_router_data = VaultConnectorFlowData::to_old_router_data(router_data)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "Cannot construct router data for making the external vault create api call",
- )?;
-
- let connector_integration: services::BoxedVaultConnectorIntegrationInterface<
- ExternalVaultCreateFlow,
- router_types::VaultRequestData,
- router_types::VaultResponseData,
- > = connector_data.connector.get_connector_integration();
- services::execute_connector_processing_step(
- state,
- connector_integration,
- &old_router_data,
- CallConnectorAction::Trigger,
- None,
- None,
- )
- .await
- .to_vault_failed_response()
-}
-
#[cfg(feature = "v2")]
async fn generate_hyperswitch_vault_session_details(
state: &SessionState,
@@ -533,7 +397,7 @@ async fn generate_hyperswitch_vault_session_details(
platform,
connector_name,
merchant_connector_account_type,
- connector_customer_id,
+ connector_customer_id.clone(),
)
.await?;
@@ -541,14 +405,52 @@ async fn generate_hyperswitch_vault_session_details(
Ok(router_types::VaultResponseData::ExternalVaultCreateResponse {
session_id,
client_secret,
- }) => Ok(Some(api::VaultSessionDetails::HyperswitchVault(
- api::HyperswitchVaultSessionDetails {
- payment_method_session_id: session_id,
- client_secret,
- publishable_key: vault_publishable_key,
- profile_id: vault_profile_id,
- },
- ))),
+ }) => {
+ // Build the base64-encoded SDK authorization for the Hyperswitch Vault session,
+ // mirroring the payment-method-session-create response, instead of exposing the
+ // individual vault keys.
+ let sdk_authorization =
+ Option::<hyperswitch_domain_models::sdk_auth::SdkAuthorization>::from(
+ hyperswitch_domain_models::sdk_auth::SdkAuthorizationContext {
+ platform: platform.to_owned(),
+ publishable_key: vault_publishable_key.expose(),
+ profile_id: id_type::ProfileId::try_from(std::borrow::Cow::from(
+ vault_profile_id.expose(),
+ ))
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Invalid profile_id in Hyperswitch Vault connector auth",
+ )?,
+ client_secret: client_secret.expose(),
+ customer_id: connector_customer_id
+ .map(id_type::GlobalCustomerId::new_unchecked),
+ payment_method_session_id: Some(
+ id_type::GlobalPaymentMethodSessionId::new_unchecked(
+ session_id.clone().expose(),
+ ),
+ ),
+ },
+ )
+ .map(|auth| auth.encode())
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to encode Hyperswitch Vault SDK authorization")?;
+
+ match sdk_authorization {
+ Some(sdk_authorization) => Ok(Some(api::VaultSessionDetails::HyperswitchVault(
+ api::HyperswitchVaultSessionDetails {
+ sdk_authorization: sdk_authorization.into(),
+ },
+ ))),
+ None => {
+ router_env::logger::warn!(
+ "No SDK authorization generated for Hyperswitch Vault session (non-API initiator)"
+ );
+ Ok(None)
+ }
+ }
+ }
+
Ok(_) => {
router_env::logger::warn!("Unexpected response from external vault create API");
Err(errors::ApiErrorResponse::InternalServerError.into())
diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs
index 80ef196477..1d6a1ac9dd 100644
--- a/crates/router/src/core/unified_connector_service.rs
+++ b/crates/router/src/core/unified_connector_service.rs
@@ -2,15 +2,13 @@ use std::{borrow::Cow, str::FromStr, time::Instant};
use actix_web::ResponseError;
use api_models::admin;
-#[cfg(feature = "v2")]
use base64::Engine;
use common_enums::{
connector_enums::Connector, AttemptStatus, CallConnectorAction, ConnectorIntegrationType,
ExecutionMode, ExecutionPath, GatewaySystem, PaymentMethodType, UcsAvailability,
};
-#[cfg(feature = "v2")]
-use common_utils::consts::BASE64_ENGINE;
use common_utils::{
+ consts::BASE64_ENGINE,
errors::{CustomResult, ErrorSwitch},
ext_traits::ValueExt,
id_type,
@@ -25,10 +23,9 @@ use external_services::grpc_client::{
};
use hyperswitch_connectors::utils::CardData;
#[cfg(feature = "v2")]
-use hyperswitch_domain_models::merchant_connector_account::{
- ExternalVaultConnectorMetadata, MerchantConnectorAccountTypeDetails,
-};
+use hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccountTypeDetails;
use hyperswitch_domain_models::{
+ merchant_connector_account::ExternalVaultConnectorMetadata,
platform::Processor,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData},
router_flow_types::refunds,
@@ -43,8 +40,6 @@ use unified_connector_service_client::payments::{
CryptoCurrency, EVoucher, OpenBanking, PaymentServiceAuthorizeResponse,
};
-#[cfg(feature = "v2")]
-use crate::types::api::enums as api_enums;
use crate::{
consts,
core::{
@@ -61,6 +56,7 @@ use crate::{
events::connector_api_logs::ConnectorEvent,
routes::SessionState,
types::{
+ api::enums as api_enums,
transformers::{ForeignFrom, ForeignTryFrom},
UcsPaymentAuthorizeResponseData, UcsPaymentSetupRecurringResponseData,
UcsRecurringPaymentChargeResponseData,
@@ -1866,6 +1862,107 @@ pub fn parse_merchant_payout_reference_id(id: &str) -> Option<id_type::PayoutRef
.ok()
}
+#[cfg(feature = "v1")]
+pub fn build_unified_connector_service_external_vault_proxy_metadata_v1(
+ external_vault_merchant_connector_account: MerchantConnectorAccountType,
+ connectors: &hyperswitch_domain_models::connector_endpoints::Connectors,
+) -> CustomResult<String, UnifiedConnectorServiceError> {
+ let connector_name = external_vault_merchant_connector_account
+ .get_connector_name()
+ .ok_or(UnifiedConnectorServiceError::InvalidConnectorName)
+ .attach_printable("Connector name not found in MerchantConnectorAccountType")?;
+
+ let external_vault_connector = api_enums::VaultConnectors::try_from(connector_name.clone())
+ .map_err(|err| {
+ error_stack::report!(UnifiedConnectorServiceError::InvalidConnectorName)
+ .attach_printable(format!("Failed to parse Vault connector: {err}"))
+ })?;
+
+ let external_vault_proxy_config = match external_vault_connector {
+ api_enums::VaultConnectors::Vgs => {
+ let external_vault_metadata = external_vault_merchant_connector_account
+ .get_metadata()
+ .ok_or(UnifiedConnectorServiceError::ParsingFailed)
+ .attach_printable("Metadata is required for VGS vault connector")?;
+
+ let external_vault_metadata_parsed: ExternalVaultConnectorMetadata =
+ external_vault_metadata
+ .expose()
+ .parse_value("ExternalVaultConnectorMetadata")
+ .change_context(UnifiedConnectorServiceError::ParsingFailed)
+ .attach_printable("Failed to parse external vault connector metadata")?;
+
+ external_services::grpc_client::unified_connector_service::ExternalVaultProxyConfig {
+ vault_connector_type:
+ external_services::grpc_client::unified_connector_service::VaultConnectorType::Proxy,
+ vault_connector_id: Some("vgs".to_string()),
+ metadata: external_services::grpc_client::unified_connector_service::ExternalVaultProxyMetadata::VgsMetadata(
+ external_services::grpc_client::unified_connector_service::VgsMetadata {
+ proxy_url: external_vault_metadata_parsed.proxy_url,
+ certificate: external_vault_metadata_parsed.certificate,
+ },
+ ),
+ }
+ }
+ api_enums::VaultConnectors::HyperswitchVault => {
+ let base = &connectors.hyperswitch_vault.base_url;
+ let vault_endpoint_url = format!("{}/proxy", base)
+ .parse::<url::Url>()
+ .map(common_utils::types::Url::wrap)
+ .change_context(UnifiedConnectorServiceError::ParsingFailed)
+ .attach_printable("Failed to parse hyperswitch_vault endpoint URL")?;
+
+ let auth_type: ConnectorAuthType = external_vault_merchant_connector_account
+ .get_connector_account_details()
+ .parse_value("ConnectorAuthType")
+ .change_context(UnifiedConnectorServiceError::FailedToObtainAuthType)
+ .attach_printable("Failed to obtain ConnectorAuthType for HyperswitchVault")?;
+
+ let (api_key, profile_id) = match &auth_type {
+ ConnectorAuthType::SignatureKey {
+ api_key,
+ api_secret,
+ ..
+ } => (api_key.clone(), api_secret.clone()),
+ _ => {
+ return Err(error_stack::report!(
+ UnifiedConnectorServiceError::FailedToObtainAuthType
+ )
+ .attach_printable("HyperswitchVault requires SignatureKey auth type"))
+ }
+ };
+
+ external_services::grpc_client::unified_connector_service::ExternalVaultProxyConfig {
+ vault_connector_type:
+ external_services::grpc_client::unified_connector_service::VaultConnectorType::Transformation,
+ vault_connector_id: Some("hyperswitch_vault".to_string()),
+ metadata: external_services::grpc_client::unified_connector_service::ExternalVaultProxyMetadata::HyperswitchVaultMetadata(
+ external_services::grpc_client::unified_connector_service::HyperswitchVaultMetadata {
+ vault_endpoint: vault_endpoint_url,
+ vault_auth_data: external_services::grpc_client::unified_connector_service::VaultConnectorAuth {
+ api_key,
+ profile_id,
+ },
+ },
+ ),
+ }
+ }
+ api_enums::VaultConnectors::Tokenex => Err(error_stack::report!(
+ UnifiedConnectorServiceError::NotImplemented(
+ "External vault proxy metadata is not supported for Tokenex".to_string(),
+ )
+ ))?,
+ };
+
+ logger::info!(external_vault_proxy_config = ?external_vault_proxy_config, "Built ExternalVaultProxyConfig (v1)");
+
+ let external_vault_config_bytes = serde_json::to_vec(&external_vault_proxy_config)
+ .change_context(UnifiedConnectorServiceError::ParsingFailed)
+ .attach_printable("Failed to serialize ExternalVaultProxyConfig to bytes")?;
+
+ Ok(BASE64_ENGINE.encode(&external_vault_config_bytes))
+}
+
#[cfg(feature = "v2")]
pub fn build_unified_connector_service_external_vault_proxy_metadata(
external_vault_merchant_connector_account: MerchantConnectorAccountTypeDetails,
@@ -1907,7 +2004,7 @@ pub fn build_unified_connector_service_external_vault_proxy_metadata(
}
api_enums::VaultConnectors::HyperswitchVault => {
let base = &connectors.hyperswitch_vault.base_url;
- let vault_endpoint_url = format!("{}/v2/proxy", base)
+ let vault_endpoint_url = format!("{}/proxy", base)
.parse::<url::Url>()
.map(common_utils::types::Url::wrap)
.change_context(UnifiedConnectorServiceError::ParsingFailed)
@@ -1954,6 +2051,8 @@ pub fn build_unified_connector_service_external_vault_proxy_metadata(
))?,
};
+ logger::info!(external_vault_proxy_config = ?external_vault_proxy_config, "Built ExternalVaultProxyConfig (v2)");
+
let external_vault_config_bytes = serde_json::to_vec(&external_vault_proxy_config)
.change_context(UnifiedConnectorServiceError::ParsingFailed)
.attach_printable("Failed to serialize ExternalVaultProxyConfig to bytes")?;
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index 1c12c6a6ca..82562bf5aa 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -2389,102 +2389,138 @@ where
| api_models::enums::PaymentType::RecurringMandate
| api_models::enums::PaymentType::NewMandate
| api_models::enums::PaymentType::Installment => {
- let (payment_data, _req, connector_http_status_code, external_latency) =
- Box::pin(payments::payments_operation_core::<
- api_types::Authorize,
+ // The external vault proxy flow is non-PCI: only vault card data
+ // (`PaymentMethodData::ProxyCard`) is allowed at the connector. When the
+ // confirm request carries it, route to the external vault proxy core directly
+ // using the confirm request itself — no conversion to a dedicated proxy request.
+ let is_proxy_card = req
+ .payment_method_data
+ .as_ref()
+ .and_then(|pmd| pmd.payment_method_data.as_ref())
+ .map(|data| {
+ matches!(data, api_models::payments::PaymentMethodData::ProxyCard(_))
+ })
+ .unwrap_or(false);
+
+ if is_proxy_card {
+ Box::pin(payments::external_vault_proxy_for_payments_core::<
+ api_types::ExternalVaultProxy,
+ payment_types::PaymentsResponse,
_,
_,
_,
- payments::PaymentData<api_types::Authorize>,
+ payments::PaymentData<api_types::ExternalVaultProxy>,
>(
- &state,
- req_state.clone(),
- &platform,
- profile_id.clone(),
- operation.clone(),
- req.clone(),
+ state,
+ req_state,
+ platform,
+ profile_id,
+ payments::PaymentExternalVaultProxyConfirm,
+ req,
+ auth_flow,
payments::CallConnectorAction::Trigger,
+ header_payload,
None,
- auth_flow,
- eligible_routable_connectors.clone(),
- header_payload.clone(),
- &dimensions,
))
- .await?;
-
- let connector = payment_data.get_payment_attempt_connector();
-
- if let Some(connector_name) = connector {
- let connector_data = api_types::ConnectorData::get_connector_by_name(
- &state.conf.connectors,
- connector_name,
- api_types::GetToken::Connector,
- None,
- )?;
- let should_continue_further = connector_data
- .connector
- .is_payment_recurrence_operation_needed(
- &payment_data.payment_intent.clone(),
- )
- .unwrap_or(false);
- if should_continue_further {
- logger::info!(
+ .await
+ } else {
+ let (payment_data, _req, connector_http_status_code, external_latency) =
+ Box::pin(payments::payments_operation_core::<
+ api_types::Authorize,
+ _,
+ _,
+ _,
+ payments::PaymentData<api_types::Authorize>,
+ >(
+ &state,
+ req_state.clone(),
+ &platform,
+ profile_id.clone(),
+ operation.clone(),
+ req.clone(),
+ payments::CallConnectorAction::Trigger,
+ None,
+ auth_flow,
+ eligible_routable_connectors.clone(),
+ header_payload.clone(),
+ &dimensions,
+ ))
+ .await?;
+
+ let connector = payment_data.get_payment_attempt_connector();
+
+ if let Some(connector_name) = connector {
+ let connector_data = api_types::ConnectorData::get_connector_by_name(
+ &state.conf.connectors,
+ connector_name,
+ api_types::GetToken::Connector,
+ None,
+ )?;
+ let should_continue_further = connector_data
+ .connector
+ .is_payment_recurrence_operation_needed(
+ &payment_data.payment_intent.clone(),
+ )
+ .unwrap_or(false);
+ if should_continue_further {
+ logger::info!(
"Re-invoking payments_operation_core | should_continue_further: {} | payment_id: {:?}",
should_continue_further,
payment_data.get_payment_intent().payment_id,
);
- let (pd, _req, connector_status_code, ext_latency) =
- Box::pin(payments::payments_operation_core::<
- api_types::SetupMandate,
- _,
- _,
- _,
- payments::PaymentData<api_types::SetupMandate>,
- >(
- &state,
- req_state,
- &platform,
- profile_id,
- PaymentRecurrence,
- req,
- payments::CallConnectorAction::Trigger,
- None,
+ let (pd, _req, connector_status_code, ext_latency) =
+ Box::pin(payments::payments_operation_core::<
+ api_types::SetupMandate,
+ _,
+ _,
+ _,
+ payments::PaymentData<api_types::SetupMandate>,
+ >(
+ &state,
+ req_state,
+ &platform,
+ profile_id,
+ PaymentRecurrence,
+ req,
+ payments::CallConnectorAction::Trigger,
+ None,
+ auth_flow,
+ eligible_routable_connectors,
+ header_payload.clone(),
+ &dimensions,
+ ))
+ .await?;
+ let total_ext_latency = match (external_latency, ext_latency) {
+ (Some(l1), Some(l2)) => Some(l1 + l2),
+ (Some(l), None) | (None, Some(l)) => Some(l),
+ (None, None) => None,
+ };
+ return payment_types::PaymentsResponse::generate_response(
+ pd,
auth_flow,
- eligible_routable_connectors,
- header_payload.clone(),
- &dimensions,
- ))
- .await?;
- let total_ext_latency = match (external_latency, ext_latency) {
- (Some(l1), Some(l2)) => Some(l1 + l2),
- (Some(l), None) | (None, Some(l)) => Some(l),
- (None, None) => None,
- };
- return payment_types::PaymentsResponse::generate_response(
- pd,
- auth_flow,
- &state.base_url,
- operation,
- &state.conf.connector_request_reference_id_config,
- connector_status_code,
- total_ext_latency,
- header_payload.x_hs_latency,
- &platform,
- );
+ &state.base_url,
+ operation,
+ &state.conf.connector_request_reference_id_config,
+ connector_status_code,
+ total_ext_latency,
+ header_payload.x_hs_latency,
+ &platform,
+ );
+ }
}
- }
- payment_types::PaymentsResponse::generate_response(
- payment_data,
- auth_flow,
- &state.base_url,
- operation,
- &state.conf.connector_request_reference_id_config,
- connector_http_status_code,
- external_latency,
- header_payload.x_hs_latency,
- &platform,
- )
+ payment_types::PaymentsResponse::generate_response(
+ payment_data,
+ auth_flow,
+ &state.base_url,
+ operation,
+ &state.conf.connector_request_reference_id_config,
+ connector_http_status_code,
+ external_latency,
+ header_payload.x_hs_latency,
+ &platform,
+ )
+ }
}
api_models::enums::PaymentType::SetupMandate => {
payments::payments_core::<
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 12b6036f22..0acada5233 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -726,6 +726,8 @@ impl Capturable for PaymentsExtendAuthorizationData {
}
}
+impl Capturable for ExternalVaultProxyPaymentsData {}
+
pub struct AddAccessTokenResult {
pub access_token_result: Result<Option<AccessToken>, ErrorResponse>,
pub connector_supports_access_token: bool,
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index 7bea5dfd1a..2e0bc3f8a3 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -30,8 +30,9 @@ pub use api_models::{
PaymentsRequest, PaymentsResponse, PaymentsResponseForm, PaymentsRetrieveRequest,
PaymentsSessionRequest, PaymentsSessionResponse, PaymentsStartRequest,
PaymentsUpdateMetadataRequest, PaymentsUpdateMetadataResponse, PgRedirectResponse,
- PhoneDetails, RedirectionResponse, SessionToken, UrlDetails, VaultDetails,
- VaultSessionDetails, VerifyRequest, VerifyResponse, VgsSessionDetails, WalletData,
+ PhoneDetails, ProxyPaymentMethodData, ProxyPaymentMethodDataRequest, RedirectionResponse,
+ SessionToken, UrlDetails, VaultDetails, VaultSessionDetails, VerifyRequest, VerifyResponse,
+ VgsSessionDetails, WalletData,
},
};
pub use common_types::payments::{AcceptanceType, CustomerAcceptance, OnlineMandate};
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index e957db5424..f71fb862b0 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -448,6 +448,7 @@ impl ForeignTryFrom<payments::PaymentMethodData> for api_enums::PaymentMethod {
})
}
payments::PaymentMethodData::NetworkToken(..) => Ok(Self::NetworkToken),
+ payments::PaymentMethodData::ProxyCard(..) => Ok(Self::Card),
}
}
}