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(payments): support hyperswitch self-hosted vault for repeat-customer payments (#12922)

Shankar Singh Cbb30ffa120af
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index 336069f3d2..1865b7887b 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -16522,6 +16522,11 @@
"type": "string",
"description": "The CVC number for the card",
"nullable": true
+ },
+ "card_cvc_token": {
+ "type": "string",
+ "description": "Token referencing a CVC vaulted in the hyperswitch (self-hosted) vault. Used by the\nself-hosted default-vault repeat-customer flow, where the card is referenced by the\ntop-level `payment_token` and the freshly-tokenized CVC arrives as this token; the server\nresolves it to the raw CVC. Not used by the external vault proxy flow.",
+ "nullable": true
}
}
},
@@ -29975,7 +29980,7 @@
],
"properties": {
"vault_card_token_data": {
- "$ref": "#/components/schemas/CardToken"
+ "$ref": "#/components/schemas/VaultCardToken"
}
}
}
@@ -44610,6 +44615,25 @@
"propertyName": "type"
}
},
+ "VaultCardToken": {
+ "type": "object",
+ "description": "Card token data carried by the external vault proxy `vault_card_token_data` variant. Its\n`card_cvc` is a vault token detokenized on the wire by the external vault (e.g. VGS). Kept as a\ndistinct type from [`CardToken`] so the self-hosted `card_cvc_token` field does not leak into\nthe proxy contract.",
+ "required": [
+ "card_holder_name"
+ ],
+ "properties": {
+ "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 (a vault token for the external vault proxy flow)",
+ "nullable": true
+ }
+ }
+ },
"VaultDetails": {
"type": "object",
"description": "Top-level vault details returned in the session-tokens response.\nFor v1: contains both internal vault (SDK authorization) and external vault details.\nFor v2: contains only external vault details.",
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index 0055b4a444..6b3a278cfa 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -10871,6 +10871,11 @@
"type": "string",
"description": "The CVC number for the card",
"nullable": true
+ },
+ "card_cvc_token": {
+ "type": "string",
+ "description": "Token referencing a CVC vaulted in the hyperswitch (self-hosted) vault. Used by the\nself-hosted default-vault repeat-customer flow, where the card is referenced by the\ntop-level `payment_token` and the freshly-tokenized CVC arrives as this token; the server\nresolves it to the raw CVC. Not used by the external vault proxy flow.",
+ "nullable": true
}
}
},
@@ -22019,7 +22024,7 @@
],
"properties": {
"vault_card_token_data": {
- "$ref": "#/components/schemas/CardToken"
+ "$ref": "#/components/schemas/VaultCardToken"
}
}
}
@@ -32507,6 +32512,25 @@
"propertyName": "type"
}
},
+ "VaultCardToken": {
+ "type": "object",
+ "description": "Card token data carried by the external vault proxy `vault_card_token_data` variant. Its\n`card_cvc` is a vault token detokenized on the wire by the external vault (e.g. VGS). Kept as a\ndistinct type from [`CardToken`] so the self-hosted `card_cvc_token` field does not leak into\nthe proxy contract.",
+ "required": [
+ "card_holder_name"
+ ],
+ "properties": {
+ "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 (a vault token for the external vault proxy flow)",
+ "nullable": true
+ }
+ }
+ },
"VaultDetails": {
"type": "object",
"description": "Top-level vault details returned in the session-tokens response.\nFor v1: contains both internal vault (SDK authorization) and external vault details.\nFor v2: contains only external vault details.",
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index a48e63424d..61c2c491b0 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -2701,6 +2701,43 @@ pub struct CardToken {
#[schema(value_type = Option<String>)]
#[smithy(value_type = "Option<String>")]
pub card_cvc: Option<Secret<String>>,
+
+ /// Token referencing a CVC vaulted in the hyperswitch (self-hosted) vault. Used by the
+ /// self-hosted default-vault repeat-customer flow, where the card is referenced by the
+ /// top-level `payment_token` and the freshly-tokenized CVC arrives as this token; the server
+ /// resolves it to the raw CVC. Not used by the external vault proxy flow.
+ #[schema(value_type = Option<String>)]
+ #[smithy(value_type = "Option<String>")]
+ pub card_cvc_token: Option<Secret<String>>,
+}
+
+/// Card token data carried by the external vault proxy `vault_card_token_data` variant. Its
+/// `card_cvc` is a vault token detokenized on the wire by the external vault (e.g. VGS). Kept as a
+/// distinct type from [`CardToken`] so the self-hosted `card_cvc_token` field does not leak into
+/// the proxy contract.
+#[derive(
+ Eq,
+ PartialEq,
+ Debug,
+ serde::Deserialize,
+ serde::Serialize,
+ Clone,
+ ToSchema,
+ Default,
+ SmithyModel,
+)]
+#[serde(rename_all = "snake_case")]
+#[smithy(namespace = "com.hyperswitch.smithy.types")]
+pub struct VaultCardToken {
+ /// The card holder's name
+ #[schema(value_type = String, example = "John Test")]
+ #[smithy(value_type = "Option<String>")]
+ pub card_holder_name: Option<Secret<String>>,
+
+ /// The CVC number for the card (a vault token for the external vault proxy flow)
+ #[schema(value_type = Option<String>)]
+ #[smithy(value_type = "Option<String>")]
+ pub card_cvc: Option<Secret<String>>,
}
#[derive(
@@ -3499,14 +3536,15 @@ pub enum PaymentMethodData {
/// 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 = "VaultDataCard")]
- #[serde(rename = "vault_data_card")]
+ #[serde(rename = "vault_data_card", alias = "vault_card")]
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),
+ #[serde(rename = "vault_card_token_data", alias = "vault_card_token")]
+ VaultCardTokenData(VaultCardToken),
}
pub trait GetAddressFromPaymentMethodData {
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index d8910968ea..57dbaabee1 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -1435,6 +1435,10 @@ pub struct CardToken {
/// The CVC number for the card
pub card_cvc: Option<Secret<String>>,
+
+ /// Token referencing a CVC vaulted in the hyperswitch (self-hosted) vault, resolved by the
+ /// server to the raw CVC for the self-hosted default-vault repeat-customer flow.
+ pub card_cvc_token: Option<Secret<String>>,
}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
@@ -2856,10 +2860,12 @@ impl From<api_models::payments::CardToken> for CardToken {
let api_models::payments::CardToken {
card_holder_name,
card_cvc,
+ card_cvc_token,
} = value;
Self {
card_holder_name,
card_cvc,
+ card_cvc_token,
}
}
}
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index d797d9bfd9..209e9dea0b 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -627,6 +627,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::Card,
api_models::payments::CardRedirectData,
api_models::payments::CardToken,
+ api_models::payments::VaultCardToken,
api_models::payments::PaymentsRequest,
api_models::payments::PaymentsCreateRequest,
api_models::payments::PaymentsUpdateRequest,
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 7ae5d70120..d5e58e2e66 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -532,6 +532,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::Card,
api_models::payments::CardRedirectData,
api_models::payments::CardToken,
+ api_models::payments::VaultCardToken,
api_models::payments::ConnectorTokenDetails,
api_models::payments::PaymentsRequest,
api_models::payments::PaymentsResponse,
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index bb91ddb27a..6acfb2a8c8 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -2406,7 +2406,7 @@ impl PaymentMethodResolver {
Some(
vault::insert_cvc_using_payment_token(
state,
- &existing_pm.id,
+ existing_pm.id.get_string_repr(),
cvc,
intent_fulfillment_time,
platform.get_provider().get_key_store(),
@@ -2658,7 +2658,7 @@ async fn execute_payment_method_create(
.async_map(|cvc| {
vault::insert_cvc_using_payment_token(
state,
- &payment_method.id,
+ payment_method.id.get_string_repr(),
cvc,
intent_fulfillment_time,
platform.get_provider().get_key_store(),
@@ -2829,7 +2829,7 @@ pub async fn create_generic_volatile_payment_method(
.async_map(|cvc| {
vault::insert_cvc_using_payment_token(
state,
- &domain_payment_method.id,
+ domain_payment_method.id.get_string_repr(),
cvc,
intent_fulfillment_time,
platform.get_provider().get_key_store(),
@@ -6357,20 +6357,28 @@ pub async fn payment_methods_session_retrieve(
Ok(services::ApplicationResponse::Json(response))
}
-/// Stores `card_cvc` and `card_holder_name` as a `TemporaryCardToken` in Redis under `token`.
+/// Stores `card_cvc` as an encrypted CVC under `pm_token_{token}_hyperswitch_cvc` — the same
+/// `_hyperswitch_cvc` mechanism used by the first-time flow — so CVC retrieval (router-side
+/// `retrieve_and_delete_cvc_from_payment_token`) resolves it consistently. The card holder name is
+/// not vaulted with the CVC token; it is carried by the saved payment method itself.
#[cfg(feature = "v2")]
async fn store_cvc_and_card_holder_name_as_payment_token_in_redis(
state: &SessionState,
token: &str,
card_cvc: Option<Secret<String>>,
- card_holder_name: Option<Secret<String>>,
+ _card_holder_name: Option<Secret<String>>,
+ key_store: &domain::MerchantKeyStore,
) -> RouterResult<()> {
- let redis_token_data =
- storage::PaymentTokenData::temporary_card_token(card_cvc, card_holder_name);
- let intent_fulfillment_time = common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME;
- pm_routes::ParentPaymentMethodToken::create_key_for_token(&token.to_string())
- .insert(intent_fulfillment_time, redis_token_data, state)
+ if let Some(card_cvc) = card_cvc {
+ vault::insert_cvc_using_payment_token(
+ state,
+ token,
+ card_cvc,
+ common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME,
+ key_store,
+ )
.await?;
+ }
Ok(())
}
@@ -6480,6 +6488,7 @@ pub async fn payment_methods_session_update_payment_method(
&parent_payment_method_token,
card_cvc,
card_holder_name,
+ platform.get_provider().get_key_store(),
)
.await?;
@@ -6541,6 +6550,7 @@ pub async fn payment_methods_session_update_payment_method(
&pm_token,
card_cvc,
card_holder_name,
+ platform.get_provider().get_key_store(),
)
.await?;
}
@@ -7174,7 +7184,7 @@ impl<'a> pm_types::PaymentMethodUpdateHandler<'a> {
.async_map(|cvc| {
vault::insert_cvc_using_payment_token(
self.state,
- self.payment_method.get_id(),
+ self.payment_method.get_id().get_string_repr(),
cvc,
common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME,
self.platform.get_provider().get_key_store(),
diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs
index 8abfdc94fb..c27afdb408 100644
--- a/crates/router/src/core/payment_methods/vault.rs
+++ b/crates/router/src/core/payment_methods/vault.rs
@@ -1,5 +1,5 @@
use common_enums::PaymentMethodType;
-#[cfg(feature = "v2")]
+#[cfg(any(feature = "v1", feature = "v2"))]
use common_utils::encryption::Encryption;
use common_utils::{
crypto::{DecodeMessage, EncodeMessage, GcmAes256},
@@ -41,6 +41,10 @@ use crate::{
},
utils::{ConnectorResponseExt, StringExt},
};
+// `pm_cards` and `OptionExt` are imported for v2 via the larger v2-only `use` block below; the v1
+// build needs them for `retrieve_and_delete_cvc_from_payment_token` (self-hosted vault CVC retrieval).
+#[cfg(feature = "v1")]
+use crate::{core::payment_methods::cards as pm_cards, utils::ext_traits::OptionExt};
#[cfg(feature = "v2")]
use crate::{
core::{
@@ -2329,7 +2333,7 @@ pub struct TemporaryVaultCvc {
#[instrument(skip_all)]
pub async fn insert_cvc_using_payment_token(
state: &routes::SessionState,
- payment_method_id: &id_type::GlobalPaymentMethodId,
+ token: &str,
card_cvc: hyperswitch_masking::Secret<String>,
fulfillment_time: i64,
key_store: &domain::MerchantKeyStore,
@@ -2340,10 +2344,7 @@ pub async fn insert_cvc_using_payment_token(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
- let key = format!(
- "pm_token_{}_hyperswitch_cvc",
- payment_method_id.get_string_repr()
- );
+ let key = format!("pm_token_{token}_hyperswitch_cvc");
let payload_to_be_encrypted = TemporaryVaultCvc { card_cvc };
@@ -2378,7 +2379,7 @@ pub async fn insert_cvc_using_payment_token(
Ok(card_token_cvc_storage)
}
-#[cfg(feature = "v2")]
+#[cfg(any(feature = "v1", feature = "v2"))]
#[instrument(skip_all)]
pub async fn retrieve_and_delete_cvc_from_payment_token(
state: &routes::SessionState,
@@ -2412,7 +2413,7 @@ pub async fn retrieve_and_delete_cvc_from_payment_token(
);
// delete key after retrieving the cvc
- redis_conn.delete_key(&key.into()).await.map_err(|err| {
+ let _ = redis_conn.delete_key(&key.into()).await.map_err(|err| {
logger::error!("Failed to delete token from redis: {:?}", err);
});
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 50b332f08a..267146c9e9 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -1243,16 +1243,20 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
if let Some(payment_method_ref) = self.get_payment_method_reference(req) {
let payment_method_ref_to_use = match req.payment_token.as_deref() {
Some(payment_token) if payment_token == payment_method_ref => {
- let token_data = helpers::retrieve_payment_token_data(
+ // Best-effort: resolve the token to its stored payment_method_id. A
+ // self-hosted vault token minted by the modular PM service is not present in
+ // the legacy redis token store (different key), so a miss/error here is not
+ // fatal — fall back to using the reference as-is and let the modular fetch
+ // resolve it, instead of failing the payment with "token invalid or expired".
+ match helpers::retrieve_payment_token_data(
state,
payment_method_ref.to_string(),
req.payment_method,
)
- .await?;
-
- match token_data {
- storage::PaymentTokenData::Permanent(card_token_data)
- | storage::PaymentTokenData::PermanentCard(card_token_data) => {
+ .await
+ {
+ Ok(storage::PaymentTokenData::Permanent(card_token_data))
+ | Ok(storage::PaymentTokenData::PermanentCard(card_token_data)) => {
card_token_data
.payment_method_id
.as_deref()
@@ -2359,6 +2363,23 @@ impl PaymentConfirm {
Some(domain::PaymentMethodData::CardToken(token)) => Some(token),
_ => None,
};
+ // Self-hosted (default) vault repeat-customer flow: the saved card is referenced by the
+ // top-level `payment_token`, while the freshly-tokenized CVC arrives as `card_cvc_token`
+ // (minted by the modular PM service and stored in redis keyed by that token). Resolve it to
+ // the raw CVC here so the modular fetch below receives a usable card. `take()` consumes the
+ // token so it is not carried any further.
+ if let Some(token) = card_token_data.as_mut() {
+ if let Some(card_cvc_token) = token.card_cvc_token.take() {
+ let resolved_cvc =
+ crate::core::payment_methods::vault::retrieve_and_delete_cvc_from_payment_token(
+ state,
+ card_cvc_token.peek(),
+ platform.get_provider().get_key_store(),
+ )
+ .await?;
+ token.card_cvc = Some(resolved_cvc);
+ }
+ }
if let Some(card_cvc) = req.card_cvc.clone() {
if let Some(card_token_data) = card_token_data.as_mut() {
card_token_data.card_cvc = Some(card_cvc);
@@ -2366,6 +2387,7 @@ impl PaymentConfirm {
card_token_data = Some(domain::CardToken {
card_holder_name: None,
card_cvc: Some(card_cvc),
+ card_cvc_token: None,
});
}
}
diff --git a/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs b/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs
index d703655190..75ef8f104b 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
@@ -555,6 +555,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsRequest, PaymentData<F>>
Some(domain::CardToken {
card_cvc: token_data.card_cvc.clone(),
card_holder_name: token_data.card_holder_name.clone(),
+ card_cvc_token: None,
})
}
_ => None,