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 support for fetch payment in external vault proxy (#12651)

Prasunna Soppaa5aa54b3ea35
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index 5555447d08..98b57a1fbb 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -29137,6 +29137,18 @@
"$ref": "#/components/schemas/ProxyCardData"
}
}
+ },
+ {
+ "type": "object",
+ "title": "VaultCardTokenData",
+ "required": [
+ "vault_card_token_data"
+ ],
+ "properties": {
+ "vault_card_token_data": {
+ "$ref": "#/components/schemas/CardToken"
+ }
+ }
}
]
},
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index 103cdba7ae..9dfbd85bd4 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -21891,6 +21891,18 @@
"$ref": "#/components/schemas/ProxyCardData"
}
}
+ },
+ {
+ "type": "object",
+ "title": "VaultCardTokenData",
+ "required": [
+ "vault_card_token_data"
+ ],
+ "properties": {
+ "vault_card_token_data": {
+ "$ref": "#/components/schemas/CardToken"
+ }
+ }
}
]
},
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index ddd5a42ae2..39d7886afe 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -3155,6 +3155,7 @@ mod payment_method_data_serde {
| PaymentMethodData::Card(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::ProxyCard(_)
+ | PaymentMethodData::VaultCardTokenData(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::Wallet(_) => {
@@ -3496,6 +3497,12 @@ pub enum PaymentMethodData {
/// When this variant is used, the payment will be routed through the external vault proxy flow.
#[schema(title = "ProxyCard")]
ProxyCard(Box<ProxyCardData>),
+ /// Vault card token data used for external vault proxy payments with an already-saved card.
+ /// The top-level `payment_token` resolves to a stored payment method whose external vault
+ /// tokens are retrieved from the modular PM service; this variant carries the CVC / card
+ /// holder name to combine with those tokens. Routed through the external vault proxy flow.
+ #[schema(title = "VaultCardTokenData")]
+ VaultCardTokenData(CardToken),
}
pub trait GetAddressFromPaymentMethodData {
@@ -3523,7 +3530,8 @@ impl GetAddressFromPaymentMethodData for PaymentMethodData {
| Self::MandatePayment
| Self::MobilePayment(_)
| Self::NetworkToken(_)
- | Self::ProxyCard(_) => None,
+ | Self::ProxyCard(_)
+ | Self::VaultCardTokenData(_) => None,
}
}
}
@@ -3548,7 +3556,9 @@ 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),
+ Self::ProxyCard(_) | Self::VaultCardTokenData(_) => {
+ Some(api_enums::PaymentMethod::Card)
+ }
}
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/hyperswitch_vault/transformers.rs b/crates/hyperswitch_connectors/src/connectors/hyperswitch_vault/transformers.rs
index 39e2eae64a..e1af871c08 100644
--- a/crates/hyperswitch_connectors/src/connectors/hyperswitch_vault/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/hyperswitch_vault/transformers.rs
@@ -12,26 +12,21 @@ use hyperswitch_interfaces::errors;
use hyperswitch_masking::Secret;
use serde::{Deserialize, Serialize};
-use crate::{types::ResponseRouterData, utils};
+use crate::types::ResponseRouterData;
#[derive(Default, Debug, Serialize)]
pub struct HyperswitchVaultCreateRequest {
- customer_id: String,
+ // Optional so the guest flow (no customer) can send `customer_id: null`.
+ customer_id: Option<String>,
storage_type: common_enums::StorageType,
}
impl TryFrom<&VaultRouterData<ExternalVaultCreateFlow>> for HyperswitchVaultCreateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &VaultRouterData<ExternalVaultCreateFlow>) -> Result<Self, Self::Error> {
- let customer_id = item
- .request
- .connector_customer_id
- .clone()
- .ok_or_else(utils::missing_field_err("connector_customer"))?;
-
Ok(Self {
- customer_id,
- storage_type: common_enums::StorageType::Persistent,
+ customer_id: item.request.connector_customer_id.clone(),
+ storage_type: item.request.storage_type.unwrap_or_default(),
})
}
}
diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs
index 37fcd17d15..7747341a8e 100644
--- a/crates/hyperswitch_domain_models/src/business_profile.rs
+++ b/crates/hyperswitch_domain_models/src/business_profile.rs
@@ -123,6 +123,15 @@ impl ExternalVaultDetails {
Self::Skip => None,
}
}
+
+ /// Returns true when the configured external vault is the hyperswitch vault (`HyperswitchSdk`).
+ pub fn is_hyperswitch_vault(&self) -> bool {
+ matches!(
+ self,
+ Self::ExternalVaultEnabled(details)
+ if details.vault_sdk == Some(common_enums::VaultSdk::HyperswitchSdk)
+ )
+ }
}
#[cfg(feature = "v1")]
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index 8d2a4f3c1e..f88f630298 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -1919,11 +1919,12 @@ 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.
+ // ProxyCard / VaultCardTokenData are handled before reaching domain conversion
+ // (routed to external_vault_proxy_for_payments_core). These branches should not be
+ // reached in normal flow, but we handle them gracefully.
+ api_models::payments::PaymentMethodData::ProxyCard(_)
+ | api_models::payments::PaymentMethodData::VaultCardTokenData(_) => {
+ // These variants are intercepted at the routing layer and should not reach here.
// Falling back to MandatePayment as a safe no-op sentinel value.
Self::MandatePayment
}
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index 7f4153172d..867b97d1e9 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -1927,6 +1927,9 @@ pub struct VaultRequestData {
pub connector_vault_id: Option<String>,
pub connector_customer_id: Option<String>,
pub should_generate_multiple_tokens: Option<bool>,
+ /// Storage type (persistent/volatile) for the vault session. `None` lets the connector apply
+ /// its default. Used by the external vault (e.g. Hyperswitch Vault) session create flow.
+ pub storage_type: Option<common_enums::StorageType>,
}
#[derive(Debug, Serialize, Clone)]
diff --git a/crates/injector/src/injector.rs b/crates/injector/src/injector.rs
index ae13f4b5e0..e50510318c 100644
--- a/crates/injector/src/injector.rs
+++ b/crates/injector/src/injector.rs
@@ -833,7 +833,16 @@ pub mod core {
);
// Proxy priority: vault metadata -> backup_proxy_url -> none
- let final_proxy_url = vault_proxy_url.or_else(|| config.backup_proxy_url.clone());
+ // Proxy priority: vault metadata -> proxy_url -> backup_proxy_url -> none
+ //if vault proxy url is not present, we should use our config proxy url,
+ //where outbound proxy has the context of the proxy endpoint
+ let final_proxy_url = vault_proxy_url
+ .or_else(|| config.proxy_url.clone())
+ .or_else(|| config.backup_proxy_url.clone());
+ logger::info!(
+ proxy_attached = final_proxy_url.is_some(),
+ "Resolved outgoing proxy for injector request"
+ );
let proxy = Proxy::from_optional_url(final_proxy_url);
metrics::INJECTOR_OUTGOING_CALLS_COUNT.add(
diff --git a/crates/payment_methods/src/types.rs b/crates/payment_methods/src/types.rs
index 09d96467cc..b49cb0e993 100644
--- a/crates/payment_methods/src/types.rs
+++ b/crates/payment_methods/src/types.rs
@@ -35,7 +35,6 @@ pub struct PaymentMethodResponseItemV1 {
pub is_default: bool,
pub billing: Option<api_models::payments::Address>,
pub network_tokenization: Option<NetworkTokenResponse>,
- pub psp_tokenization_enabled: bool,
pub connector_tokens: Option<Vec<ConnectorTokenDetails>>,
pub network_transaction_id: Option<String>,
}
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index de5849078d..b7f174c007 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -4479,6 +4479,7 @@ pub async fn vault_payment_method_external(
None,
None,
None,
+ None,
)
.await?;
@@ -4633,6 +4634,7 @@ pub async fn vault_payment_method_external_v1(
None,
None,
should_generate_multiple_tokens,
+ None,
)
.await?;
@@ -6113,7 +6115,11 @@ pub async fn payment_methods_session_create(
.attach_printable("Failed to insert payment methods session in db")?;
let external_vault_details = payments_core::vault_session::fetch_external_vault_details(
- &state, &platform, &profile, &customer,
+ &state,
+ &platform,
+ &profile,
+ &customer,
+ payment_method_session_domain_model.storage_type,
)
.await
.unwrap_or_else(|err| {
@@ -6126,13 +6132,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.clone(),
- profile_id: profile.get_id().clone(),
publishable_key: platform
.get_processor()
.get_account()
.publishable_key
.clone(),
+ platform: platform.clone(),
+ profile_id: profile.get_id().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 9359528ba8..689ed2e5de 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -7,14 +7,20 @@ use api_models::{
};
use common_enums::CardNetwork;
#[cfg(feature = "v1")]
-use common_utils::{crypto::Encryptable, request::Headers, types::keymanager::KeyManagerState};
+use common_utils::{
+ crypto::Encryptable,
+ request::{Headers, RequestBuilder},
+ types::keymanager::KeyManagerState,
+};
use common_utils::{
ext_traits::{AsyncExt, Encode, StringExt},
id_type,
pii::{Email, SecretSerdeValue},
- request::RequestContent,
+ request::{Method, RequestContent},
};
use error_stack::ResultExt;
+#[cfg(feature = "v1")]
+use external_services::http_client;
use hyperswitch_domain_models::mandates;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::payment_methods::{
@@ -445,7 +451,7 @@ where
let url = locker.get_host(endpoint_path);
- let mut request = services::Request::new(services::Method::Post, &url);
+ let mut request = services::Request::new(Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(headers::X_TENANT_ID, tenant_id.get_string_repr().into());
@@ -788,7 +794,7 @@ pub fn mk_get_card_request(
let mut url = locker.host.to_owned();
url.push_str("/card/getCard");
- let mut request = services::Request::new(services::Method::Post, &url);
+ let mut request = services::Request::new(Method::Post, &url);
request.set_body(RequestContent::FormUrlEncoded(Box::new(get_card_req)));
Ok(request)
}
@@ -1923,12 +1929,17 @@ pub async fn fetch_payment_method_from_modular_service(
profile_id: &id_type::ProfileId,
payment_method_id: &str, //Currently PM id is string in v1
pmd_card_token: Option<domain::CardToken>,
+ // Whether to ask the modular service for the raw card detail (decrypted PAN from the internal
+ // vault). This must be `false` for the external vault proxy flow — those cards are not stored in
+ // the internal vault, so requesting raw detail yields an "Invalid Vault Response" error; the
+ // external vault token reference is returned regardless. The normal confirm flow uses `true`.
+ fetch_raw_detail: bool,
) -> CustomResult<PaymentMethodWithRawData, errors::ApiErrorResponse> {
let payment_method_fetch_req = RetrievePaymentMethodV1Request {
payment_method_id: api_models::payment_methods::PaymentMethodId {
payment_method_id: payment_method_id.to_owned(),
},
- fetch_raw_detail: true,
+ fetch_raw_detail,
modular_service_prefix: state.conf.micro_services.payment_methods_prefix.0.clone(),
};
@@ -1950,6 +1961,15 @@ pub async fn fetch_payment_method_from_modular_service(
.await
.attach_printable("Failed to transform payment method retrieve response")?;
+ // The external vault proxy card response may not carry the expiry month/year. In that case fall
+ // back to the additional payment method data stored in the payment methods table (`payment_method_data`) expiry returned in the same response.
+ let (fallback_exp_month, fallback_exp_year) = match &pm_response.payment_method_data {
+ Some(payment_methods::types::PaymentMethodResponseData::Card(card)) => {
+ (card.expiry_month.clone(), card.expiry_year.clone())
+ }
+ _ => (None, None),
+ };
+
// 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)
@@ -1958,8 +1978,8 @@ pub async fn fetch_payment_method_from_modular_service(
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,
+ card_exp_year: proxy_card.card_exp_year.or(fallback_exp_year),
+ card_exp_month: proxy_card.card_exp_month.or(fallback_exp_month),
});
(None, Some(vault_data))
}
@@ -2117,6 +2137,69 @@ pub async fn create_proxy_card_payment_method_in_modular_service(
Ok(payment_method_with_raw_data.0)
}
+/// Response shape for the external hyperswitch vault token-details endpoint
+/// (`GET {hyperswitch_vault_base_url}/payment-methods/token/{token}/details`). Only the permanent
+/// payment method id is consumed; other fields are ignored.
+#[cfg(feature = "v1")]
+#[derive(Debug, Deserialize)]
+struct VaultTokenDetailsResponse {
+ /// The permanent payment method id associated with the temporary token.
+ id: String,
+}
+
+/// Resolve a temporary vault token to the permanent payment method id by calling the external
+/// (SaaS) hyperswitch vault directly.
+///
+/// Used by the external vault proxy flow when the external vault is the hyperswitch vault — the
+/// request carries a temporary token that must be exchanged for the permanent id before it is
+/// persisted in the payment method entry. The vault is configured as a connector, so the call
+/// targets `connectors.hyperswitch_vault.base_url` (which already includes the `/v2` prefix) and is
+/// authenticated as the merchant using the external vault connector account's credentials
+/// (`api-key` + profile id) — not the pay server's internal API key.
+#[cfg(feature = "v1")]
+pub async fn get_permanent_pm_id_from_temporary_token(
+ state: &routes::SessionState,
+ api_key: Secret<String>,
+ vault_profile_id: Secret<String>,
+ temporary_token: String,
+) -> CustomResult<String, errors::ApiErrorResponse> {
+ let url = format!(
+ "{}/payment-methods/token/{}/details",
+ state.conf.connectors.hyperswitch_vault.base_url, temporary_token
+ );
+
+ let request = RequestBuilder::new()
+ .method(Method::Get)
+ .url(&url)
+ .attach_default_headers()
+ .headers(vec![
+ // The external vault authenticates via V2 api-key auth, which reads the api key from the
+ // `Authorization` header in the `api-key=<key>` format.
+ (
+ headers::AUTHORIZATION.to_string(),
+ format!("api-key={}", api_key.expose()).into_masked(),
+ ),
+ (
+ headers::X_PROFILE_ID.to_string(),
+ vault_profile_id.expose().into_masked(),
+ ),
+ ])
+ .build();
+
+ let response = http_client::send_request(&state.conf.proxy, request, None)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to call hyperswitch vault token details endpoint")?;
+
+ let token_details = response
+ .json::<VaultTokenDetailsResponse>()
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to parse hyperswitch vault token details response")?;
+
+ Ok(token_details.id)
+}
+
#[cfg(feature = "v1")]
pub async fn list_customer_payment_methods_from_modular_service(
state: &routes::SessionState,
diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs
index c719ecd3a2..10bbe849d2 100644
--- a/crates/router/src/core/payment_methods/vault.rs
+++ b/crates/router/src/core/payment_methods/vault.rs
@@ -2153,6 +2153,7 @@ pub async fn retrieve_payment_method_from_vault_external(
connector_vault_id,
None,
None,
+ None,
)
.await?;
@@ -2627,6 +2628,7 @@ pub async fn delete_payment_method_data_from_vault_external(
Some(connector_vault_id),
None,
None,
+ None,
)
.await?;
@@ -2767,6 +2769,7 @@ pub async fn retrieve_payment_method_from_vault_external_v1(
connector_vault_id,
None,
None,
+ None,
)
.await?;
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index d0536dda37..e5dc9a8fba 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -9441,6 +9441,7 @@ impl PaymentEligibilityData {
profile_id,
payment_token.clone().expose().as_str(),
None, // CVC token data is not passed in create api
+ true, // fetch raw card detail from the internal vault
)
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 88e6c90ffb..ccf7cf145f 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -2337,6 +2337,7 @@ impl PaymentConfirm {
&profile_id,
payment_method_ref,
card_token_data,
+ true, // fetch raw card detail from the internal vault
)
.await?;
logger::info!("Payment method fetched from PM Modular Service.");
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
index 579c165c9f..4f9eaa42e8 100644
--- a/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs
@@ -4,6 +4,8 @@ use api_models::{enums::FrmSuggestion, payments::PaymentsRequest};
use async_trait::async_trait;
use common_enums;
use error_stack::ResultExt;
+use hyperswitch_domain_models::payment_methods::VaultPaymentMethodData;
+use hyperswitch_masking::{ExposeInterface, Secret};
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
@@ -191,33 +193,95 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsRequest>
..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
+ // The external vault proxy flow is non-PCI. Derive the external vault payment method data:
+ // - `VaultDataCard`: inline vault card data carried directly on the confirm request.
+ // - `VaultCardTokenData`: a saved card referenced by `payment_token`; its vault tokens
+ // were retrieved from the modular PM service in `fetch_payment_method` (available here
+ // as `payment_method_wrapper.vault_payment_method_token_data`). We combine those tokens
+ // with the CVC / card holder name supplied on the request.
+ let external_vault_pmd = match 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(),
- ),
+ {
+ Some(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,
- });
+ ),
+ Some(api_models::payments::PaymentMethodData::VaultCardTokenData(token_data)) => {
+ match payment_method_wrapper
+ .as_ref()
+ .and_then(|wrapper| wrapper.vault_payment_method_token_data.as_ref())
+ {
+ Some(VaultPaymentMethodData::VaultCardData(vault_card)) => {
+ // Card expiry is carried on the vault tokens and the CVC on the request.
+ // Both are required to authorize through the external vault proxy, so error
+ // out explicitly rather than forwarding empty strings that fail downstream
+ // connector validation.
+ let card_exp_month = vault_card
+ .card_exp_month
+ .clone()
+ .get_required_value("card_exp_month")?;
+ let card_exp_year = vault_card
+ .card_exp_year
+ .clone()
+ .get_required_value("card_exp_year")?;
+ let card_cvc = token_data
+ .card_cvc
+ .clone()
+ .get_required_value("card_cvc")?;
+
+ Some(
+ hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::Card(
+ Box::new(hyperswitch_domain_models::payment_method_data::ExternalVaultCard {
+ card_number: vault_card.card_number.clone(),
+ card_exp_month,
+ card_exp_year,
+ card_cvc,
+ bin_number: None,
+ last_four: None,
+ card_issuer: None,
+ card_network: None,
+ card_type: None,
+ card_issuing_country: None,
+ bank_code: None,
+ nick_name: None,
+ card_holder_name: token_data.card_holder_name.clone(),
+ co_badged_card_data: None,
+ }),
+ ),
+ )
+ }
+ None => None,
+ }
+ }
+ _ => None,
+ };
- // `payment_method` / `payment_method_type` are optional on the confirm request but
- // required for the external vault proxy flow so the routing engine can match connectors.
+ // `payment_method` / `payment_method_type` are optional on the confirm request but required
+ // for the external vault proxy flow so the routing engine can match connectors. When the
+ // request omits them, fall back to the stored payment method fetched from the modular PM
+ // service (`payment_method_wrapper`).
let payment_method = request
.payment_method
+ .or_else(|| {
+ payment_method_wrapper
+ .as_ref()
+ .and_then(|wrapper| wrapper.payment_method.payment_method)
+ })
.get_required_value("payment_method")?;
let payment_method_subtype = request
.payment_method_type
+ .or_else(|| {
+ payment_method_wrapper
+ .as_ref()
+ .and_then(|wrapper| wrapper.payment_method.payment_method_type)
+ })
.get_required_value("payment_method_type")?;
payment_attempt.payment_method = Some(payment_method);
@@ -449,15 +513,95 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsRequest, PaymentData<F>>
#[instrument(skip_all)]
async fn fetch_payment_method(
&self,
- _state: &SessionState,
- _req: &PaymentsRequest,
- _platform: &domain::Platform,
- _feature_config: &core_utils::FeatureConfig,
+ 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())
+ // Only the saved-card token flow (`VaultCardTokenData`) needs an up-front fetch. The inline
+ // `VaultDataCard` flow carries the card on the request and is parsed in `get_trackers`.
+ let card_token = req
+ .payment_method_data
+ .as_ref()
+ .and_then(|pmd| pmd.payment_method_data.as_ref())
+ .and_then(|pmd| match pmd {
+ api_models::payments::PaymentMethodData::VaultCardTokenData(token_data) => {
+ Some(domain::CardToken {
+ card_cvc: token_data.card_cvc.clone(),
+ card_holder_name: token_data.card_holder_name.clone(),
+ })
+ }
+ _ => None,
+ });
+
+ // A fetch is only needed for the saved-card token flow, and only when the org is eligible
+ // for the modular PM service. Every other case has nothing to fetch up front.
+ let fetch_data = match card_token {
+ Some(card_token) if feature_config.is_payment_method_modular_allowed => {
+ // 1. Resolve the payment_token to the actual stored payment_method_id via Redis.
+ // This uses the same key construction as the regular Confirm flow's
+ // fetch_payment_method (`pm_token_{token}_{payment_method}_hyperswitch`).
+ let payment_token = req
+ .payment_token
+ .clone()
+ .get_required_value("payment_token")
+ .attach_printable("payment_token is required for the vault card token flow")?;
+
+ let token_data =
+ helpers::retrieve_payment_token_data(state, payment_token, req.payment_method)
+ .await?;
+
+ let payment_method_id = match token_data {
+ storage::PaymentTokenData::Permanent(card_token_data)
+ | storage::PaymentTokenData::PermanentCard(card_token_data) => {
+ card_token_data.payment_method_id
+ }
+ _ => None,
+ }
+ .get_required_value("payment_method_id")
+ .attach_printable("could not resolve a payment_method_id from the payment_token")?;
+
+ // 2. Retrieve the external vault tokens for that payment method from the modular PM
+ // service.
+ let profile_id = platform
+ .get_processor()
+ .get_account()
+ .get_default_profile()
+ .clone()
+ .get_required_value("profile_id")
+ .attach_printable(
+ "profile_id is required to fetch external vault tokens from the modular service",
+ )?;
+
+ let payment_method_with_raw_data =
+ pm_transformers::fetch_payment_method_from_modular_service(
+ state,
+ platform,
+ &profile_id,
+ &payment_method_id,
+ Some(card_token),
+ // External vault proxy cards are not in the internal vault; requesting raw
+ // detail fails. The external vault token reference is returned without it.
+ false,
+ )
+ .await
+ .attach_printable(
+ "Failed to fetch external vault token data from the modular PM service",
+ )?;
+
+ PaymentMethodFetchData::from_modular(payment_method_with_raw_data)
+ }
+ Some(_) => {
+ router_env::logger::info!(
+ "Organization is not eligible for PM Modular Service; skipping external vault token fetch."
+ );
+ PaymentMethodFetchData::default()
+ }
+ // Not a token flow — nothing to fetch up front.
+ None => PaymentMethodFetchData::default(),
+ };
+
+ Ok(fetch_data)
}
#[cfg(feature = "v1")]
@@ -477,7 +621,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsRequest, PaymentData<F>>
return Ok(());
}
// Only create for ExternalVaultCard (proxy card flow)
- let vault_card = match payment_data.external_vault_pmd.clone() {
+ let mut vault_card = match payment_data.external_vault_pmd.clone() {
Some(
hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::Card(
card,
@@ -503,6 +647,64 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsRequest, PaymentData<F>>
.unwrap_or(common_enums::PaymentMethod::Card);
let payment_method_type = payment_data.payment_attempt.payment_method_type;
+ // When the external vault is the hyperswitch vault, the `card_number` carried on the request
+ // is a *temporary* vault token. Exchange it for the permanent payment method id (served by
+ // the external SaaS PM service) and persist that as the token in the PM entry. The external
+ // service is a separate deployment, so authenticate with the external vault connector
+ // account's credentials (api-key + profile id) fetched from the profile's vault MCA. For any
+ // other vault, the request token is stored as-is.
+ if business_profile
+ .external_vault_details
+ .is_hyperswitch_vault()
+ {
+ let vault_connector_id = business_profile
+ .external_vault_details
+ .get_vault_connector_id()
+ .get_required_value("external vault connector id")?;
+
+ let vault_mca = state
+ .store
+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(
+ platform.get_processor().get_account().get_id(),
+ &vault_connector_id,
+ platform.get_processor().get_key_store(),
+ )
+ .await
+ .to_not_found_response(
+ errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ id: vault_connector_id.get_string_repr().to_string(),
+ },
+ )?;
+
+ let (api_key, vault_profile_id) = match vault_mca
+ .get_connector_account_details()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to parse external vault connector auth")?
+ {
+ hyperswitch_domain_models::router_data::ConnectorAuthType::SignatureKey {
+ api_key,
+ api_secret,
+ ..
+ } => Ok((api_key, api_secret)),
+ _ => Err(error_stack::report!(
+ errors::ApiErrorResponse::InternalServerError
+ )
+ .attach_printable(
+ "Unexpected auth type for hyperswitch external vault connector; expected SignatureKey",
+ )),
+ }?;
+
+ let temporary_token = vault_card.card_number.clone().expose();
+ let permanent_pm_id = pm_transformers::get_permanent_pm_id_from_temporary_token(
+ state,
+ api_key,
+ vault_profile_id,
+ temporary_token,
+ )
+ .await?;
+ vault_card.card_number = Secret::new(permanent_pm_id);
+ }
+
match pm_transformers::create_proxy_card_payment_method_in_modular_service(
state,
platform.get_provider().get_account().get_id(),
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 8bd78aa037..dc5a92955f 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -1348,6 +1348,7 @@ impl PaymentCreate {
&profile_id,
payment_method_ref,
None, // CVC token data is not passed in create api
+ true, // fetch raw card detail from the internal vault
)
.await?;
logger::info!("Payment method fetched from PM Modular Service.");
diff --git a/crates/router/src/core/payments/vault_session.rs b/crates/router/src/core/payments/vault_session.rs
index 5ed9461a70..feacfb2c6f 100644
--- a/crates/router/src/core/payments/vault_session.rs
+++ b/crates/router/src/core/payments/vault_session.rs
@@ -79,8 +79,14 @@ where
let is_external_vault_sdk_enabled = profile.is_vault_sdk_enabled();
if is_external_vault_sdk_enabled {
+ // Guest flow (no customer) uses volatile storage; a known customer uses persistent.
+ let storage_type = if customer.is_some() {
+ common_enums::StorageType::Persistent
+ } else {
+ common_enums::StorageType::Volatile
+ };
let external_vault_details =
- fetch_external_vault_details(state, platform, profile, customer).await?;
+ fetch_external_vault_details(state, platform, profile, customer, storage_type).await?;
let vault_details = external_vault_details.map(|evd| api::VaultDetails {
internal_vault: None,
external_vault_details: Some(evd),
@@ -134,10 +140,18 @@ async fn call_internal_pm_session_create_for_vault(
&state.conf.trace_header.header_name,
);
+ // Guest flow (no customer) uses volatile storage; a known customer uses persistent. This is
+ // forwarded to the modular PM service, which in turn drives the external vault session create.
+ let storage_type = if customer_id.is_some() {
+ common_enums::StorageType::Persistent
+ } else {
+ common_enums::StorageType::Volatile
+ };
+
let request = CreatePaymentMethodSessionV1Request {
customer_id: customer_id.cloned(),
modular_service_prefix: state.conf.micro_services.payment_methods_prefix.0.clone(),
- storage_type: common_enums::StorageType::Persistent,
+ storage_type,
};
let response = CreatePaymentMethodSession::call(state, &client, request)
@@ -316,6 +330,7 @@ pub async fn generate_vault_session_details(
platform: &domain::Platform,
merchant_connector_account_type: &domain::MerchantConnectorAccountTypeDetails,
connector_customer_id: Option<String>,
+ storage_type: common_enums::StorageType,
) -> RouterResult<Option<api::VaultSessionDetails>> {
let connector = VaultConnectors::try_from(merchant_connector_account_type.get_connector_name())
.map_err(|error| {
@@ -369,6 +384,7 @@ pub async fn generate_vault_session_details(
.to_string(),
key1,
api_secret,
+ storage_type,
)
.await
}
@@ -383,6 +399,7 @@ pub async fn generate_vault_session_details(
}
#[cfg(feature = "v2")]
+#[allow(clippy::too_many_arguments)]
async fn generate_hyperswitch_vault_session_details(
state: &SessionState,
platform: &domain::Platform,
@@ -391,6 +408,7 @@ async fn generate_hyperswitch_vault_session_details(
connector_name: String,
vault_publishable_key: hyperswitch_masking::Secret<String>,
vault_profile_id: hyperswitch_masking::Secret<String>,
+ storage_type: common_enums::StorageType,
) -> RouterResult<Option<api::VaultSessionDetails>> {
let connector_response = call_external_vault_create(
state,
@@ -398,6 +416,7 @@ async fn generate_hyperswitch_vault_session_details(
connector_name,
merchant_connector_account_type,
connector_customer_id.clone(),
+ storage_type,
)
.await?;
@@ -469,6 +488,7 @@ async fn call_external_vault_create(
connector_name: String,
merchant_connector_account_type: &domain::MerchantConnectorAccountTypeDetails,
connector_customer_id: Option<String>,
+ storage_type: common_enums::StorageType,
) -> RouterResult<VaultRouterData<ExternalVaultCreateFlow>>
where
dyn ConnectorTrait + Sync: services::api::ConnectorIntegration<
@@ -507,6 +527,7 @@ where
None,
connector_customer_id,
None,
+ Some(storage_type),
)
.await?;
@@ -539,6 +560,7 @@ pub async fn fetch_external_vault_details(
platform: &domain::Platform,
profile: &domain::Profile,
customer: &Option<domain::Customer>,
+ storage_type: common_enums::StorageType,
) -> RouterResult<Option<api::VaultSessionDetails>> {
let external_vault_source = profile
.external_vault_connector_details
@@ -555,26 +577,36 @@ pub async fn fetch_external_vault_details(
.await?,
));
- // Retrieve the existing connector_customer_id from the customer record for this vault MCA.
- // If none exists, create a connector customer at the vault connector.
- let connector_customer_id = get_or_create_vault_connector_customer(
- state,
- platform,
- customer,
- &merchant_connector_account,
- profile.get_id(),
- )
- .await
- .map_err(|err| {
- router_env::logger::error!(?err, "Failed to get or create vault connector customer");
- err
- })?;
+ // Connector-customer creation is optional. For the guest flow (no customer) we skip it
+ // entirely and call the external vault with a `null` customer id. When a customer is present,
+ // reuse the existing connector customer or create one at the vault connector.
+ let connector_customer_id = match customer {
+ Some(_) => get_or_create_vault_connector_customer(
+ state,
+ platform,
+ customer,
+ &merchant_connector_account,
+ profile.get_id(),
+ )
+ .await
+ .map_err(|err| {
+ router_env::logger::error!(?err, "Failed to get or create vault connector customer");
+ err
+ })?,
+ None => {
+ router_env::logger::info!(
+ "No customer present for external vault session; skipping connector customer creation (guest flow)"
+ );
+ None
+ }
+ };
generate_vault_session_details(
state,
platform,
&merchant_connector_account,
connector_customer_id,
+ storage_type,
)
.await
}
@@ -658,6 +690,7 @@ async fn get_or_create_vault_connector_customer(
None,
None,
None,
+ None,
)
.await?;
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index 866fecdff4..650c7cb10b 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -2697,6 +2697,7 @@ pub(crate) fn validate_profile_id_from_auth_layer<T: GetProfileId + std::fmt::De
}
}
+#[allow(clippy::too_many_arguments)]
pub async fn construct_vault_router_data<F>(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
@@ -2707,6 +2708,7 @@ pub async fn construct_vault_router_data<F>(
connector_vault_id: Option<String>,
connector_customer_id: Option<String>,
should_generate_multiple_tokens: Option<bool>,
+ storage_type: Option<common_enums::StorageType>,
) -> RouterResult<VaultRouterDataV2<F>> {
let connector_auth_type = merchant_connector_account
.get_connector_account_details()
@@ -2726,6 +2728,7 @@ pub async fn construct_vault_router_data<F>(
connector_vault_id,
connector_customer_id,
should_generate_multiple_tokens,
+ storage_type,
},
response: Ok(types::VaultResponseData::default()),
};
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index a2f9413d7c..605d72bd50 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -2438,20 +2438,27 @@ where
| api_models::enums::PaymentType::RecurringMandate
| api_models::enums::PaymentType::NewMandate
| api_models::enums::PaymentType::Installment => {
- // 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
+ // The external vault proxy flow is non-PCI: the card is vaulted in an external
+ // vault. Two confirm shapes route here:
+ // - `VaultDataCard`: inline vault card data.
+ // - `VaultCardTokenData`: a saved card referenced by the top-level
+ // `payment_token`; its vault tokens are retrieved from the modular PM service.
+ // In both cases the confirm request itself is used to call the proxy core
+ // directly — no conversion to a dedicated proxy request.
+ let should_call_external_vault_proxy = req
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.as_ref())
.map(|data| {
- matches!(data, api_models::payments::PaymentMethodData::ProxyCard(_))
+ matches!(
+ data,
+ api_models::payments::PaymentMethodData::ProxyCard(_)
+ | api_models::payments::PaymentMethodData::VaultCardTokenData(_)
+ )
})
.unwrap_or(false);
- if is_proxy_card {
+ if should_call_external_vault_proxy {
Box::pin(payments::external_vault_proxy_for_payments_core::<
api_types::ExternalVaultProxy,
payment_types::PaymentsResponse,
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index f71fb862b0..72681f8621 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -448,7 +448,8 @@ impl ForeignTryFrom<payments::PaymentMethodData> for api_enums::PaymentMethod {
})
}
payments::PaymentMethodData::NetworkToken(..) => Ok(Self::NetworkToken),
- payments::PaymentMethodData::ProxyCard(..) => Ok(Self::Card),
+ payments::PaymentMethodData::ProxyCard(..)
+ | payments::PaymentMethodData::VaultCardTokenData(..) => Ok(Self::Card),
}
}
}