Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(vault): add runtime flag for entity_id and fingerprint data and refactor FingerprintWalletData and FingerprintBankDebitData (#12554)
Gaurav Rawat7aa380fed087
diff --git a/config/superposition_seed.toml b/config/superposition_seed.tomlindex 2aa3389856..3e7afec586 100644--- a/config/superposition_seed.toml+++ b/config/superposition_seed.toml@@ -145,6 +145,13 @@ schema = { type = "boolean" }description = "Whether to schedule PM modular forward compatibility PT for a merchant"change_reason = "Initial setup"+[default-configs.should_trigger_fingerprint_migration]+value = false+schema = { type = "boolean" }+description = "Whether to trigger fingerprint and entity_id migration for a merchant"+change_reason = "Initial setup"++[default-configs.should_schedule_modular_backward_compat]value = falseschema = { type = "boolean" }diff --git a/crates/hyperswitch_domain_models/src/platform.rs b/crates/hyperswitch_domain_models/src/platform.rsindex 5b3a610f11..8dd807a8e3 100644--- a/crates/hyperswitch_domain_models/src/platform.rs+++ b/crates/hyperswitch_domain_models/src/platform.rs@@ -40,8 +40,11 @@ impl ProviderMerchantId {pub fn inner(&self) -> &common_utils::id_type::MerchantId {&self.0}-}+ pub fn new(id: common_utils::id_type::MerchantId) -> Self {+ Self(id)+ }+}/// Processor = The merchant account whose processor credentials are used/// to execute the operation.#[derive(Clone, Debug)]diff --git a/crates/hyperswitch_domain_models/src/vault.rs b/crates/hyperswitch_domain_models/src/vault.rsindex 2c6680a06a..fd7925724b 100644--- a/crates/hyperswitch_domain_models/src/vault.rs+++ b/crates/hyperswitch_domain_models/src/vault.rs@@ -28,11 +28,14 @@ pub enum FingerprintData {Wallet(FingerprintWalletData),}-#[derive(Debug, Default, Deserialize, Serialize, Clone)]-pub struct FingerprintWalletData {- application_primary_account_number: cards::CardNumber,- expiry_month: hyperswitch_masking::Secret<String>,- expiry_year: hyperswitch_masking::Secret<String>,+#[derive(Debug, Deserialize, Serialize, Clone)]+#[serde(rename_all = "snake_case")]+pub enum FingerprintWalletData {+ ApplePayDecryptedData {+ application_primary_account_number: cards::CardNumber,+ expiry_month: hyperswitch_masking::Secret<String>,+ expiry_year: hyperswitch_masking::Secret<String>,+ },}#[derive(Debug, Deserialize, Serialize, Clone)]pub enum AuxiliaryFingerprintData {@@ -42,10 +45,13 @@ pub enum AuxiliaryFingerprintData {BankDebit(hyperswitch_masking::Secret<String>),}-#[derive(Debug, Default, Deserialize, Serialize, Clone)]-pub struct FingerprintBankDebitData {- account_number: hyperswitch_masking::Secret<String>,- routing_number: hyperswitch_masking::Secret<String>,+#[derive(Debug, Deserialize, Serialize, Clone)]+#[serde(rename_all = "snake_case")]+pub enum FingerprintBankDebitData {+ Ach {+ account_number: hyperswitch_masking::Secret<String>,+ routing_number: hyperswitch_masking::Secret<String>,+ },}#[derive(Debug, Default, Deserialize, Serialize, Clone)]@@ -236,7 +242,6 @@ impl PaymentMethodVaultingData {}}- #[cfg(feature = "v2")]pub fn to_fingerprint_data(&self) -> FingerprintData {match self {Self::Card(card) => FingerprintData::Card(FingerprintCardData {@@ -265,7 +270,7 @@ impl PaymentMethodVaultingData {expiry_year.clone(),),};- FingerprintData::Wallet(FingerprintWalletData {+ FingerprintData::Wallet(FingerprintWalletData::ApplePayDecryptedData {application_primary_account_number,expiry_month,expiry_year,@@ -299,7 +304,6 @@ impl PaymentMethodVaultingData {}}- #[cfg(feature = "v2")]pub fn get_bank_debit_fingerprint_data(bank_debit: &payment_method_data::BankDebitDetail,) -> FingerprintBankDebitData {@@ -310,7 +314,7 @@ impl PaymentMethodVaultingData {..} => (account_number.clone(), routing_number.clone()),};- FingerprintBankDebitData {+ FingerprintBankDebitData::Ach {account_number,routing_number,}diff --git a/crates/payment_methods/src/controller.rs b/crates/payment_methods/src/controller.rsindex 07f57fc09b..7b0d353e48 100644--- a/crates/payment_methods/src/controller.rs+++ b/crates/payment_methods/src/controller.rs@@ -179,6 +179,7 @@ pub trait PaymentMethodsController {bank_debit_data: api_models::payment_methods::BankDebitDetail,key_store: &merchant_key_store::MerchantKeyStore,customer_id: &id_type::CustomerId,+ key: Option<String>,) -> errors::VaultResult<(payment_methods::PaymentMethodResponse,Option<DataDuplicationCheck>,@@ -191,6 +192,7 @@ pub trait PaymentMethodsController {wallet_data: api_models::payment_methods::WalletDetail,key_store: &merchant_key_store::MerchantKeyStore,customer_id: &id_type::CustomerId,+ key: Option<String>,) -> errors::VaultResult<(payment_methods::PaymentMethodResponse,Option<DataDuplicationCheck>,diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex b04fa7072e..1dc078d1c8 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -409,6 +409,8 @@ pub mod superposition {/// Trigger PM modular backward compatibility inline configuration keypub const SHOULD_TRIGGER_BACKWARDS_COMPATIBILITY_INLINE: &str ="should_trigger_backwards_compatibility_inline";+ /// Trigger fingerprint migration configuration key+ pub const SHOULD_TRIGGER_FINGERPRINT_MIGRATION: &str = "should_trigger_fingerprint_migration";/// dynamic fields configuration key for sdk configpub const DYNAMIC_FIELDS: &str = "dynamic_fields";/// payout sync tracker configuration keydiff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex e37dbbff06..302e19cc09 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -487,6 +487,24 @@ impl DatabaseBackedConfig for ShouldTriggerBackwardsCompatibilityInline {}}+config! {+ superposition_key = SHOULD_TRIGGER_FINGERPRINT_MIGRATION,+ output = bool,+ default = false,+ requires = dimension_state::DimensionsWithProviderMerchantId,+ targeting_key = id_type::CustomerId+}++impl DatabaseBackedConfig for ShouldTriggerFingerprintMigration {+ const KEY: &'static str = "should_trigger_fingerprint_migration";++ fn db_key(dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {+ dimensions+ .get_provider_merchant_id()+ .map(|id| format!("{}_{}", Self::KEY, id.get_string_repr()))+ }+}+config! {superposition_key = PAYOUT_TRACKER_MAPPING,output = RetryMapping,diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex b7f174c007..49bced1563 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -81,7 +81,7 @@ use crate::{configs::settings,core::{configs::dimension_state, payment_methods::transformers as pm_transforms,- tokenization as tokenization_core,+ payment_methods::utils as payment_method_utils, tokenization as tokenization_core,},headers,routes::{self, payment_methods as pm_routes},@@ -1673,18 +1673,26 @@ impl LockerOperations for GenericLocker {async fn retrieve_payment_method_from_locker(&self,state: &SessionState,- _platform: &domain::Platform,+ platform: &domain::Platform,vault_id: &domain::VaultId,customer_id: &id_type::GlobalCustomerId,_payment_method_type: Option<enums::PaymentMethod>,) -> CustomResult<pm_types::VaultRetrieveResponse, errors::VaultError> {- let payload = pm_types::VaultRetrieveRequest {- entity_id: customer_id.to_owned(),- vault_id: vault_id.to_owned(),- }- .encode_to_vec()- .change_context(errors::VaultError::RequestEncodingFailed)- .attach_printable("Failed to encode VaultRetrieveRequest")?;+ let should_trigger_fingerprint_migration =+ payment_method_utils::get_should_trigger_fingerprint_migration(+ state,+ None,+ platform.get_provider().get_provider_merchant_id(),+ )+ .await;++ let payload = cards::encode_vault_retrieve_request(+ should_trigger_fingerprint_migration,+ platform.get_provider().get_account().get_id().clone(),+ customer_id,+ vault_id.get_string_repr(),+ )+ .change_context(errors::VaultError::RequestEncodingFailed)?;let resp = vault::call_to_vault::<pm_types::VaultRetrieve>(state, payload, None).await@@ -2122,7 +2130,7 @@ impl LockerOperations for LegacyLocker {.attach_printable("Card Reference not found")?;let add_vault_response = pm_types::AddVaultResponse {- entity_id: Some(customer_id.clone()),+ entity_id: None,vault_id: domain::VaultId::generate(card_reference),fingerprint_id: None,};@@ -2191,7 +2199,7 @@ impl LockerOperations for LegacyLocker {.attach_printable("Failed to add payment method to legacy locker")?;let add_vault_response = pm_types::AddVaultResponse {- entity_id: Some(customer_id.clone()),+ entity_id: None,vault_id: domain::VaultId::generate(legacy_locker_res.card_reference),fingerprint_id: None,};@@ -4846,7 +4854,7 @@ pub async fn vault_payment_method_in_volatile_storage(Ok((pm_types::AddVaultResponse {- entity_id: customer_id.clone(),+ entity_id: None,vault_id,fingerprint_id: None,},diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex 8f9acc3e9d..a7a9c8a829 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -778,6 +778,7 @@ impl PaymentMethodsController for PmCards<'_> {bank_debit_data: api_models::payment_methods::BankDebitDetail,key_store: &domain::MerchantKeyStore,customer_id: &id_type::CustomerId,+ key: Option<String>,) -> errors::CustomResult<(domain::PaymentMethodResponse,@@ -785,26 +786,26 @@ impl PaymentMethodsController for PmCards<'_> {),errors::VaultError,> {+ let should_trigger_fingerprint_migration =+ payment_method_utils::get_should_trigger_fingerprint_migration(+ self.state,+ Some(customer_id),+ self.provider.get_provider_merchant_id(),+ )+ .await;+let pmd = hyperswitch_domain_models::vault::PaymentMethodVaultingData::from(api_models::payment_methods::PaymentMethodCreateData::BankDebit(bank_debit_data).clone(),);- let data = serde_json::to_string(&pmd)- .change_context(errors::VaultError::RequestEncodingFailed)- .attach_printable("Failed to encode Vaulting data to string")?;-- let payload = pm_types::VaultFingerprintRequest {- key: hyperswitch_domain_models::vault::V1VaultEntityId::new(- // The merchant_id should belong to the Provider- key_store.merchant_id.clone(),- customer_id.to_owned(),- ),- data,- }- .encode_to_vec()- .change_context(errors::VaultError::RequestEncodingFailed)- .attach_printable("Failed to encode VaultFingerprintRequest")?;+ let payload = encode_vault_fingerprint_request(+ should_trigger_fingerprint_migration,+ key_store.merchant_id.clone(),+ customer_id.to_owned(),+ &pmd,+ key,+ )?;let resp = vault::call_to_vault::<pm_types::GetVaultFingerprint>(self.state, payload, None).await@@ -848,18 +849,13 @@ impl PaymentMethodsController for PmCards<'_> {))} else {// The merchant_id should belong to the Provider- let payload = pm_types::AddVaultRequest {- entity_id: hyperswitch_domain_models::vault::V1VaultEntityId::new(- key_store.merchant_id.clone(),- customer_id.to_owned(),- ),- vault_id: domain::VaultId::generate(uuid::Uuid::now_v7().to_string()),- data: pmd,- ttl: self.state.conf.locker.ttl_for_storage_in_secs,- }- .encode_to_vec()- .change_context(errors::VaultError::RequestEncodingFailed)- .attach_printable("Failed to encode AddVaultRequest")?;+ let payload = encode_add_vault_request(+ should_trigger_fingerprint_migration,+ key_store.merchant_id.clone(),+ customer_id,+ pmd,+ self.state.conf.locker.ttl_for_storage_in_secs,+ )?;let query_params = Some(pm_types::VaultQueryParam::from(pm_types::WriteMode::Insert));@@ -869,13 +865,10 @@ impl PaymentMethodsController for PmCards<'_> {.change_context(errors::VaultError::VaultAPIError).attach_printable("Call to vault failed")?;- let stored_pm_resp: pm_types::InternalAddVaultResponse = resp- .parse_struct("InternalAddVaultResponse")- .change_context(errors::VaultError::ResponseDeserializationFailed)- .attach_printable("Failed to parse data into AddVaultResponse")?;+ let vault_id = parse_add_vault_response(should_trigger_fingerprint_migration, resp)?;let payment_method_resp = payment_methods::mk_add_bank_debit_response_hs(- stored_pm_resp.vault_id.get_string_repr().to_owned(),+ vault_id.get_string_repr().to_owned(),req,self.provider.get_account().get_id(),fingerprint_id,@@ -892,6 +885,7 @@ impl PaymentMethodsController for PmCards<'_> {wallet_data: api_models::payment_methods::WalletDetail,key_store: &domain::MerchantKeyStore,customer_id: &id_type::CustomerId,+ key: Option<String>,) -> errors::CustomResult<(domain::PaymentMethodResponse,@@ -899,25 +893,25 @@ impl PaymentMethodsController for PmCards<'_> {),errors::VaultError,> {+ let should_trigger_fingerprint_migration =+ payment_method_utils::get_should_trigger_fingerprint_migration(+ self.state,+ Some(customer_id),+ self.provider.get_provider_merchant_id(),+ )+ .await;+let pmd = hyperswitch_domain_models::vault::PaymentMethodVaultingData::from(api_models::payment_methods::PaymentMethodCreateData::Wallet(wallet_data).clone(),);- let data = serde_json::to_string(&pmd)- .change_context(errors::VaultError::RequestEncodingFailed)- .attach_printable("Failed to encode Vaulting data to string")?;-- let payload = pm_types::VaultFingerprintRequest {- key: hyperswitch_domain_models::vault::V1VaultEntityId::new(- // The merchant_id should belong to the Provider- key_store.merchant_id.clone(),- customer_id.to_owned(),- ),- data,- }- .encode_to_vec()- .change_context(errors::VaultError::RequestEncodingFailed)- .attach_printable("Failed to encode VaultFingerprintRequest")?;+ let payload = encode_vault_fingerprint_request(+ should_trigger_fingerprint_migration,+ key_store.merchant_id.clone(),+ customer_id.to_owned(),+ &pmd,+ key,+ )?;let resp = vault::call_to_vault::<pm_types::GetVaultFingerprint>(self.state, payload, None).await@@ -960,19 +954,13 @@ impl PaymentMethodsController for PmCards<'_> {Some(payment_methods::DataDuplicationCheck::Duplicated),))} else {- // The merchant_id should belong to the Provider- let payload = pm_types::AddVaultRequest {- entity_id: hyperswitch_domain_models::vault::V1VaultEntityId::new(- key_store.merchant_id.clone(),- customer_id.to_owned(),- ),- vault_id: domain::VaultId::generate(uuid::Uuid::now_v7().to_string()),- data: pmd,- ttl: self.state.conf.locker.ttl_for_storage_in_secs,- }- .encode_to_vec()- .change_context(errors::VaultError::RequestEncodingFailed)- .attach_printable("Failed to encode AddVaultRequest")?;+ let payload = encode_add_vault_request(+ should_trigger_fingerprint_migration,+ key_store.merchant_id.clone(),+ customer_id,+ pmd,+ self.state.conf.locker.ttl_for_storage_in_secs,+ )?;let query_params = Some(pm_types::VaultQueryParam::from(pm_types::WriteMode::Insert));@@ -982,13 +970,10 @@ impl PaymentMethodsController for PmCards<'_> {.change_context(errors::VaultError::VaultAPIError).attach_printable("Call to vault failed")?;- let stored_pm_resp: pm_types::InternalAddVaultResponse = resp- .parse_struct("InternalAddVaultResponse")- .change_context(errors::VaultError::ResponseDeserializationFailed)- .attach_printable("Failed to parse data into AddVaultResponse")?;+ let vault_id = parse_add_vault_response(should_trigger_fingerprint_migration, resp)?;- let payment_method_resp = payment_methods::mk_add_bank_debit_response_hs(- stored_pm_resp.vault_id.get_string_repr().to_owned(),+ let payment_method_resp = payment_methods::mk_add_wallet_response_hs(+ vault_id.get_string_repr().to_owned(),req,self.provider.get_account().get_id(),fingerprint_id,@@ -1602,6 +1587,18 @@ impl PaymentMethodsController for PmCards<'_> {.map(serde_json::to_value).transpose().change_context(errors::ApiErrorResponse::InternalServerError)?;++ let customer_obj = db+ .find_customer_by_customer_id_merchant_id(+ &customer_id,+ merchant_id,+ self.provider.get_key_store(),+ self.provider.get_account().storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::CustomerNotFound)+ .attach_printable("Customer not found in db")?;+let response = match payment_method {#[cfg(feature = "payouts")]api_enums::PaymentMethod::BankTransfer => {@@ -1661,6 +1658,7 @@ impl PaymentMethodsController for PmCards<'_> {bank_debit_data,self.provider.get_key_store(),&customer_id,+ customer_obj.get_global_customer_id().clone(),)).await.change_context(errors::ApiErrorResponse::InternalServerError)@@ -1858,6 +1856,209 @@ impl PaymentMethodsController for PmCards<'_> {}}+// -------------------------------------------------------------------------+// Helpers for migrating between v1 entity_id (merchant_id + customer_id)+// and new-style entity_id (merchant_id only).+// -------------------------------------------------------------------------++/// Encode the appropriate `AddVaultRequest` based on the migration flag.+#[cfg(feature = "v1")]+#[instrument(skip_all)]+pub fn encode_add_vault_request(+ should_trigger_fingerprint_migration: bool,+ merchant_id: id_type::MerchantId,+ customer_id: &id_type::CustomerId,+ pmd: hyperswitch_domain_models::vault::PaymentMethodVaultingData,+ ttl: i64,+) -> errors::CustomResult<Vec<u8>, errors::VaultError> {+ if should_trigger_fingerprint_migration {+ pm_types::AddVaultRequestNew {+ entity_id: merchant_id,+ vault_id: domain::VaultId::generate(uuid::Uuid::now_v7().to_string()),+ data: pmd,+ ttl,+ }+ .encode_to_vec()+ .change_context(errors::VaultError::RequestEncodingFailed)+ .attach_printable("Failed to encode AddVaultRequestNew")+ } else {+ pm_types::AddVaultRequest {+ entity_id: hyperswitch_domain_models::vault::V1VaultEntityId::new(+ merchant_id,+ customer_id.to_owned(),+ ),+ vault_id: domain::VaultId::generate(uuid::Uuid::now_v7().to_string()),+ data: pmd,+ ttl,+ }+ .encode_to_vec()+ .change_context(errors::VaultError::RequestEncodingFailed)+ .attach_printable("Failed to encode AddVaultRequest")+ }+}++#[cfg(feature = "v1")]+#[instrument(skip_all)]+pub fn encode_vault_fingerprint_request(+ should_trigger_fingerprint_migration: bool,+ merchant_id: id_type::MerchantId,+ customer_id: id_type::CustomerId,+ pmd: &hyperswitch_domain_models::vault::PaymentMethodVaultingData,+ key: Option<String>,+) -> errors::CustomResult<Vec<u8>, errors::VaultError> {+ if should_trigger_fingerprint_migration {+ let key = key+ .get_required_value("Customer key is required")+ .change_context(errors::VaultError::MissingRequiredField {+ field_name: "Customer key",+ })?;++ let data = serde_json::to_string(&pmd.clone().to_fingerprint_data())+ .change_context(errors::VaultError::RequestEncodingFailed)+ .attach_printable("Failed to encode Vaulting data to string")?;++ pm_types::VaultFingerprintRequestNew { data, key }+ .encode_to_vec()+ .change_context(errors::VaultError::RequestEncodingFailed)+ .attach_printable("Failed to encode VaultFingerprintRequestNew")+ } else {+ let data = serde_json::to_string(&pmd)+ .change_context(errors::VaultError::RequestEncodingFailed)+ .attach_printable("Failed to encode Vaulting data to string")?;++ pm_types::VaultFingerprintRequest {+ data,+ key: hyperswitch_domain_models::vault::V1VaultEntityId::new(merchant_id, customer_id),+ }+ .encode_to_vec()+ .change_context(errors::VaultError::RequestEncodingFailed)+ .attach_printable("Failed to encode VaultFingerprintRequest")+ }+}++#[cfg(feature = "v2")]+#[instrument(skip_all)]+pub fn encode_add_vault_request(+ should_trigger_fingerprint_migration: bool,+ merchant_id: id_type::MerchantId,+ customer_id: &id_type::GlobalCustomerId,+ pmd: hyperswitch_domain_models::vault::PaymentMethodVaultingData,+ ttl: i64,+) -> errors::CustomResult<Vec<u8>, errors::VaultError> {+ if should_trigger_fingerprint_migration {+ pm_types::AddVaultRequestNew {+ entity_id: merchant_id,+ vault_id: domain::VaultId::generate(uuid::Uuid::now_v7().to_string()),+ data: pmd,+ ttl,+ }+ .encode_to_vec()+ .change_context(errors::VaultError::RequestEncodingFailed)+ .attach_printable("Failed to encode AddVaultRequestNew")+ } else {+ pm_types::AddVaultRequest {+ entity_id: customer_id.clone(),+ vault_id: domain::VaultId::generate(uuid::Uuid::now_v7().to_string()),+ data: pmd,+ ttl,+ }+ .encode_to_vec()+ .change_context(errors::VaultError::RequestEncodingFailed)+ .attach_printable("Failed to encode AddVaultRequest")+ }+}+/// Parse the vault `AddVault` response and extract the `vault_id`.+#[cfg(feature = "v1")]+#[instrument(skip_all)]+pub fn parse_add_vault_response(+ should_trigger_fingerprint_migration: bool,+ resp: String,+) -> errors::CustomResult<domain::VaultId, errors::VaultError> {+ if should_trigger_fingerprint_migration {+ let parsed: pm_types::InternalAddVaultResponseNew = resp+ .parse_struct("InternalAddVaultResponseNew")+ .change_context(errors::VaultError::ResponseDeserializationFailed)+ .attach_printable("Failed to parse data into InternalAddVaultResponseNew")?;+ Ok(parsed.vault_id)+ } else {+ let parsed: pm_types::InternalAddVaultResponse = resp+ .parse_struct("InternalAddVaultResponse")+ .change_context(errors::VaultError::ResponseDeserializationFailed)+ .attach_printable("Failed to parse data into InternalAddVaultResponse")?;+ Ok(parsed.vault_id)+ }+}++/// Encode the appropriate `VaultRetrieveRequest` based on the migration flag.+#[cfg(feature = "v1")]+#[instrument(skip_all)]+pub fn encode_vault_retrieve_request(+ should_trigger_fingerprint_migration: bool,+ merchant_id: id_type::MerchantId,+ customer_id: &id_type::CustomerId,+ token_ref: &str,+) -> errors::CustomResult<Vec<u8>, errors::ApiErrorResponse> {+ if should_trigger_fingerprint_migration {+ pm_types::VaultRetrieveRequestNew {+ entity_id: merchant_id,+ vault_id: hyperswitch_domain_models::payment_methods::VaultId::generate(+ token_ref.to_owned(),+ ),+ }+ .encode_to_vec()+ .change_context(errors::VaultError::RequestEncodingFailed)+ .attach_printable("Failed to encode VaultRetrieveRequest")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ } else {+ pm_types::VaultRetrieveRequest {+ entity_id: hyperswitch_domain_models::vault::V1VaultEntityId::new(+ merchant_id,+ customer_id.to_owned(),+ ),+ vault_id: hyperswitch_domain_models::payment_methods::VaultId::generate(+ token_ref.to_owned(),+ ),+ }+ .encode_to_vec()+ .change_context(errors::VaultError::RequestEncodingFailed)+ .attach_printable("Failed to encode VaultRetrieveRequest")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ }+}++#[cfg(feature = "v2")]+#[instrument(skip_all)]+pub fn encode_vault_retrieve_request(+ should_trigger_fingerprint_migration: bool,+ merchant_id: id_type::MerchantId,+ customer_id: &id_type::GlobalCustomerId,+ token_ref: &str,+) -> errors::CustomResult<Vec<u8>, errors::ApiErrorResponse> {+ if should_trigger_fingerprint_migration {+ pm_types::VaultRetrieveRequestNew {+ entity_id: merchant_id,+ vault_id: hyperswitch_domain_models::payment_methods::VaultId::generate(+ token_ref.to_owned(),+ ),+ }+ .encode_to_vec()+ .change_context(errors::VaultError::RequestEncodingFailed)+ .attach_printable("Failed to encode VaultRetrieveRequest")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ } else {+ pm_types::VaultRetrieveRequest {+ entity_id: customer_id.clone(),+ vault_id: hyperswitch_domain_models::payment_methods::VaultId::generate(+ token_ref.to_owned(),+ ),+ }+ .encode_to_vec()+ .change_context(errors::VaultError::RequestEncodingFailed)+ .attach_printable("Failed to encode VaultRetrieveRequest")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ }+}+#[cfg(feature = "v1")]#[instrument(skip_all)]pub async fn get_client_secret_or_add_payment_method(@@ -6047,20 +6248,20 @@ pub async fn get_bank_debit_from_hs_locker(customer_id: &id_type::CustomerId,token_ref: &str,) -> errors::RouterResult<hyperswitch_domain_models::payment_method_data::BankDebitDetail> {- let vault_request = pm_types::VaultRetrieveRequest {- entity_id: hyperswitch_domain_models::vault::V1VaultEntityId::new(- provider.get_account().get_id().clone(),- customer_id.to_owned(),- ),- vault_id: hyperswitch_domain_models::payment_methods::VaultId::generate(- token_ref.to_owned(),- ),- };- let payload = vault_request- .encode_to_vec()- .change_context(errors::VaultError::RequestEncodingFailed)- .attach_printable("Failed to encode VaultRetrieveRequest")- .change_context(errors::ApiErrorResponse::InternalServerError)?;+ let should_trigger_fingerprint_migration =+ payment_method_utils::get_should_trigger_fingerprint_migration(+ state,+ Some(customer_id),+ provider.get_provider_merchant_id(),+ )+ .await;++ let payload = encode_vault_retrieve_request(+ should_trigger_fingerprint_migration,+ provider.get_account().get_id().clone(),+ customer_id,+ token_ref,+ )?;let resp = vault::call_to_vault::<pm_types::VaultRetrieve>(state, payload, None).await@@ -6090,20 +6291,20 @@ pub async fn get_wallet_from_hs_locker(customer_id: &id_type::CustomerId,token_ref: &str,) -> errors::RouterResult<hyperswitch_domain_models::payment_method_data::WalletDetail> {- let vault_request = pm_types::VaultRetrieveRequest {- entity_id: hyperswitch_domain_models::vault::V1VaultEntityId::new(- provider.get_account().get_id().clone(),- customer_id.to_owned(),- ),- vault_id: hyperswitch_domain_models::payment_methods::VaultId::generate(- token_ref.to_owned(),- ),- };- let payload = vault_request- .encode_to_vec()- .change_context(errors::VaultError::RequestEncodingFailed)- .attach_printable("Failed to encode VaultRetrieveRequest")- .change_context(errors::ApiErrorResponse::InternalServerError)?;+ let should_trigger_fingerprint_migration =+ payment_method_utils::get_should_trigger_fingerprint_migration(+ state,+ Some(customer_id),+ provider.get_provider_merchant_id(),+ )+ .await;++ let payload = encode_vault_retrieve_request(+ should_trigger_fingerprint_migration,+ provider.get_account().get_id().clone(),+ customer_id,+ token_ref,+ )?;let resp = vault::call_to_vault::<pm_types::VaultRetrieve>(state, payload, None).awaitdiff --git a/crates/router/src/core/payment_methods/utils.rs b/crates/router/src/core/payment_methods/utils.rsindex 3a07e8180b..acc442cb0d 100644--- a/crates/router/src/core/payment_methods/utils.rs+++ b/crates/router/src/core/payment_methods/utils.rs@@ -12,8 +12,11 @@ use common_utils::ext_traits::{OptionExt, StringExt};use error_stack::ResultExt;use euclid::frontend::dir;use hyperswitch_constraint_graph as cgraph;+use hyperswitch_domain_models::platform::ProviderMerchantId;use hyperswitch_masking::ExposeInterface;use kgraph_utils::{error::KgraphError, transformers::IntoDirValue};+#[cfg(feature = "v1")]+use router_env::logger;use storage_impl::redis::cache::{CacheKey, PM_FILTERS_CGRAPH_CACHE};use crate::{configs::settings, core::configs::dimension_state, routes::SessionState};@@ -867,6 +870,30 @@ pub async fn get_should_trigger_backwards_compatibility_inline(.await}+pub async fn get_should_trigger_fingerprint_migration(+ state: &SessionState,+ customer_id: Option<&common_utils::id_type::CustomerId>,+ provider_merchant_id: ProviderMerchantId,+) -> bool {+ let dimensions =+ dimension_state::Dimensions::new().with_provider_merchant_id(provider_merchant_id);++ let should_trigger_fingerprint_migration = dimensions+ .get_should_trigger_fingerprint_migration(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ customer_id,+ )+ .await;++ logger::info!(+ "should_trigger_fingerprint_migration in get_wallet_from_hs_locker: {}",+ should_trigger_fingerprint_migration+ );++ should_trigger_fingerprint_migration+}+pub async fn get_sdk_next_action_for_payment_method_list(state: &SessionState,dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rsindex 10bbe849d2..691e209b66 100644--- a/crates/router/src/core/payment_methods/vault.rs+++ b/crates/router/src/core/payment_methods/vault.rs@@ -44,8 +44,11 @@ use crate::{#[cfg(feature = "v2")]use crate::{core::{+ configs::dimension_state,errors::StorageErrorExt,- payment_methods::{cards as pm_cards, utils, LockerOperations, LockerType},+ payment_methods::{+ cards as pm_cards, utils, utils as payment_method_utils, LockerOperations, LockerType,+ },payments::{self as payments_core, helpers as payment_helpers},utils::create_encrypted_data,},@@ -2023,10 +2026,10 @@ async fn get_fingerprint_id_from_vault<D: serde::Serialize>(.change_context(errors::VaultError::RequestEncodingFailed).attach_printable("Failed to encode Vaulting data to string")?;- let payload = pm_types::VaultFingerprintRequest { key, data }+ let payload = pm_types::VaultFingerprintRequestNew { key, data }.encode_to_vec().change_context(errors::VaultError::RequestEncodingFailed)- .attach_printable("Failed to encode VaultFingerprintRequest")?;+ .attach_printable("Failed to encode VaultFingerprintRequestNew")?;let resp = call_to_vault::<pm_types::GetVaultFingerprint>(state, payload, None).await@@ -2051,16 +2054,21 @@ pub async fn add_payment_method_to_vault(customer_id: &id_type::GlobalCustomerId,write_mode: Option<pm_types::WriteMode>,) -> CustomResult<pm_types::AddVaultResponse, errors::VaultError> {- let payload = pm_types::AddVaultRequest {- entity_id: customer_id.to_owned(),- vault_id: existing_vault_id- .unwrap_or(domain::VaultId::generate(uuid::Uuid::now_v7().to_string())),- data: pmd,- ttl: state.conf.locker.ttl_for_storage_in_secs,- }- .encode_to_vec()- .change_context(errors::VaultError::RequestEncodingFailed)- .attach_printable("Failed to encode AddVaultRequest")?;+ let should_trigger_fingerprint_migration =+ payment_method_utils::get_should_trigger_fingerprint_migration(+ state,+ None,+ platform.get_provider().get_provider_merchant_id(),+ )+ .await;++ let payload = pm_cards::encode_add_vault_request(+ should_trigger_fingerprint_migration,+ platform.get_provider().get_account().get_id().clone(),+ customer_id,+ pmd.clone(),+ state.conf.locker.ttl_for_storage_in_secs,+ )?;let query_params = write_mode.map(pm_types::VaultQueryParam::from);@@ -2069,7 +2077,7 @@ pub async fn add_payment_method_to_vault(.change_context(errors::VaultError::VaultAPIError).attach_printable("Call to vault failed")?;- let stored_pm_resp: pm_types::AddVaultResponse = resp+ let stored_pm_resp = resp.parse_struct("AddVaultResponse").change_context(errors::VaultError::ResponseDeserializationFailed).attach_printable("Failed to parse data into AddVaultResponse")?;diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex a5ed714ddd..1ac94350d1 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -1138,7 +1138,8 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for== Some(common_enums::FutureUsage::OffSession)}Some(api_models::payments::PaymentMethodData::Card(_))- | Some(api_models::payments::PaymentMethodData::BankRedirect(_)) => {+ | Some(api_models::payments::PaymentMethodData::BankRedirect(_))+ | Some(api_models::payments::PaymentMethodData::BankDebit(_)) => {true}_ => false,diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rsindex 79faa62dd3..08d7006367 100644--- a/crates/router/src/core/payments/tokenization.rs+++ b/crates/router/src/core/payments/tokenization.rs@@ -1262,11 +1262,24 @@ pub async fn save_in_locker_internal(domain::PaymentMethodResponse,Option<payment_methods::transformers::DataDuplicationCheck>,)> {+ let db = &state.store;payment_method_request.validate()?;let customer_id = payment_method_request.customer_id.clone().get_required_value("customer_id")?;++ let customer_obj = db+ .find_customer_by_customer_id_merchant_id(+ &customer_id,+ provider.get_account().get_id(),+ provider.get_key_store(),+ provider.get_account().storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::CustomerNotFound)+ .attach_printable("Customer not found in db")?;+match (payment_method_request.card.clone(),card_detail,@@ -1295,6 +1308,7 @@ pub async fn save_in_locker_internal(bank_debit_create_data,provider.get_key_store(),&customer_id,+ customer_obj.get_global_customer_id().clone(),)).await.change_context(errors::ApiErrorResponse::InternalServerError)@@ -1308,6 +1322,7 @@ pub async fn save_in_locker_internal(wallet_create_data,provider.get_key_store(),&customer_id,+ customer_obj.get_global_customer_id().clone(),)).await.change_context(errors::ApiErrorResponse::InternalServerError)diff --git a/crates/router/src/types/payment_methods.rs b/crates/router/src/types/payment_methods.rsindex 8e30a8a936..4100f0e55e 100644--- a/crates/router/src/types/payment_methods.rs+++ b/crates/router/src/types/payment_methods.rs@@ -33,9 +33,8 @@ pub struct VaultFingerprintRequest {pub key: hyperswitch_domain_models::vault::V1VaultEntityId,}-#[cfg(feature = "v2")]#[derive(Debug, serde::Deserialize, serde::Serialize)]-pub struct VaultFingerprintRequest {+pub struct VaultFingerprintRequestNew {pub data: String,pub key: String,}@@ -55,8 +54,8 @@ pub struct AddVaultRequest<D> {}#[derive(Debug, serde::Deserialize, serde::Serialize)]-pub struct AddCompatVaultRequest<D> {- pub entity_id: id_type::CustomerId,+pub struct AddVaultRequestNew<D> {+ pub entity_id: id_type::MerchantId,pub vault_id: domain::VaultId,pub data: D,pub ttl: i64,@@ -74,7 +73,7 @@ pub struct AddVaultRequest<D> {#[derive(Debug, serde::Deserialize, serde::Serialize)]pub struct AddVaultResponse {#[cfg(feature = "v2")]- pub entity_id: Option<id_type::GlobalCustomerId>,+ pub entity_id: Option<String>,#[cfg(feature = "v1")]pub entity_id: Option<id_type::CustomerId>,#[cfg(feature = "v2")]@@ -92,6 +91,14 @@ pub struct InternalAddVaultResponse {pub fingerprint_id: Option<String>,}+#[cfg(feature = "v1")]+#[derive(Debug, serde::Deserialize, serde::Serialize)]+pub struct InternalAddVaultResponseNew {+ pub entity_id: Option<id_type::MerchantId>,+ pub vault_id: domain::VaultId,+ pub fingerprint_id: Option<String>,+}+#[derive(Debug, serde::Deserialize, serde::Serialize)]pub struct AddVault;@@ -160,16 +167,16 @@ pub struct VaultRetrieveRequest {pub vault_id: domain::VaultId,}-#[cfg(feature = "v2")]#[derive(Debug, serde::Deserialize, serde::Serialize)]-pub struct VaultRetrieveRequest {- pub entity_id: id_type::GlobalCustomerId,+pub struct VaultRetrieveRequestNew {+ pub entity_id: id_type::MerchantId,pub vault_id: domain::VaultId,}+#[cfg(feature = "v2")]#[derive(Debug, serde::Deserialize, serde::Serialize)]-pub struct GenericVaultRetrieveRequest {- pub entity_id: id_type::CustomerId,+pub struct VaultRetrieveRequest {+ pub entity_id: id_type::GlobalCustomerId,pub vault_id: domain::VaultId,}diff --git a/crates/router/src/workflows/payment_method_modular_backward_compat.rs b/crates/router/src/workflows/payment_method_modular_backward_compat.rsindex bc73005bbd..bbcbfa699d 100644--- a/crates/router/src/workflows/payment_method_modular_backward_compat.rs+++ b/crates/router/src/workflows/payment_method_modular_backward_compat.rs@@ -1,6 +1,6 @@#[cfg(feature = "v1")]use api_models::payment_methods::Card;-use common_utils::ext_traits::{Encode, OptionExt, StringExt, ValueExt};+use common_utils::ext_traits::{OptionExt, StringExt, ValueExt};#[cfg(feature = "v2")]use common_utils::id_type;use error_stack::ResultExt;@@ -14,7 +14,7 @@ use crate::core::payment_methods::add_payment_method_to_legacy_locker;#[cfg(feature = "v1")]use crate::core::payment_methods::transformers;use crate::{- core::payment_methods::{cards, vault},+ core::payment_methods::{cards, utils as payment_method_utils, vault},errors,logger::{self, error},routes::{app::StorageInterface, SessionState},@@ -107,7 +107,7 @@ pub async fn backfill_legacy_db_fields(#[cfg(feature = "v1")]pub async fn backfill_legacy_locker_card(state: &SessionState,- merchant_id: &common_utils::id_type::MerchantId,+ platform: &domain::Platform,payment_method: &domain::PaymentMethod,tracking_data: &PaymentMethodModularCompatTrackingData,process_id: &str,@@ -123,6 +123,8 @@ pub async fn backfill_legacy_locker_card(_ => Some("payment method is not card"),};+ let merchant_id = platform.get_provider().get_account().get_id();+if let Some(skip_reason) = legacy_locker_skip_reason {logger::info!(process_id=%process_id,@@ -176,16 +178,24 @@ pub async fn backfill_legacy_locker_card(};if !legacy_card_exists {- let vault_request = pm_types::GenericVaultRetrieveRequest {- entity_id: customer_id.clone(),- vault_id: domain::VaultId::generate(card_reference.clone()),- };- let payload = vault_request- .encode_to_vec()- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(- "Failed to encode generic locker retrieve request in backward compatibility PT",- )?;+ let should_trigger_fingerprint_migration =+ payment_method_utils::get_should_trigger_fingerprint_migration(+ state,+ None,+ platform.get_provider().get_provider_merchant_id(),+ )+ .await;++ let payload = cards::encode_vault_retrieve_request(+ should_trigger_fingerprint_migration,+ merchant_id.clone(),+ &customer_id,+ &card_reference,+ )+ .attach_printable(+ "Failed to encode generic locker retrieve request in backward compatibility PT",+ )?;+let vault_response =vault::call_to_vault::<pm_types::VaultRetrieve>(state, payload, None).await@@ -272,6 +282,15 @@ pub async fn backfill_legacy_locker_card(_ => Some("payment method is not card"),};+ let pm_customer_id = payment_method+ .customer_id+ .clone()+ .get_required_value("customer_id")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "customer_id not found for card payment method in backward compatibility inline flow",+ )?;+if let Some(skip_reason) = legacy_locker_skip_reason {logger::info!(process_id=%process_id,@@ -280,21 +299,11 @@ pub async fn backfill_legacy_locker_card("Skipping legacy locker card backfill in modular backward compatibility inline flow");} else {- let customer_id = payment_method- .customer_id- .clone()- .get_required_value("customer_id")+ let customer_id = id_type::CustomerId::try_from(pm_customer_id.clone()).change_context(errors::ApiErrorResponse::InternalServerError).attach_printable(- "customer_id not found for card payment method in backward compatibility inline flow",- )- .and_then(|customer_id| {- id_type::CustomerId::try_from(customer_id)- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(- "Failed to convert global customer id for backward compatibility inline flow",- )- })?;+ "Failed to convert global customer id for backward compatibility inline flow",+ )?;let card_reference = payment_method.locker_id@@ -333,16 +342,24 @@ pub async fn backfill_legacy_locker_card(};if !legacy_card_exists {- let vault_request = pm_types::GenericVaultRetrieveRequest {- entity_id: customer_id.clone(),- vault_id: domain::VaultId::generate(card_reference.clone()),- };- let payload = vault_request- .encode_to_vec()- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(+ let should_trigger_fingerprint_migration =+ payment_method_utils::get_should_trigger_fingerprint_migration(+ state,+ None,+ platform.get_provider().get_provider_merchant_id(),+ )+ .await;++ let payload = cards::encode_vault_retrieve_request(+ should_trigger_fingerprint_migration,+ platform.get_provider().get_account().get_id().clone(),+ &pm_customer_id,+ &card_reference,+ )+ .attach_printable("Failed to encode generic locker retrieve request in backward compatibility inline flow",)?;+let vault_response = vault::call_to_vault::<pm_types::VaultRetrieve>(state, payload, None,)@@ -374,10 +391,7 @@ pub async fn backfill_legacy_locker_card(platform,&stored_pm_resp.data,Some(domain::VaultId::generate(card_reference.clone())),- payment_method- .customer_id- .as_ref()- .get_required_value("customer_id")?,+ &pm_customer_id,).await.change_context(errors::ApiErrorResponse::InternalServerError)@@ -447,11 +461,19 @@ pub async fn run_payment_method_modular_backward_compat_backfill().await?;+ let platform = domain::Platform::new(+ merchant_account.clone(),+ key_store.clone(),+ merchant_account,+ key_store,+ None,+ );+#[cfg(feature = "v1")]{backfill_legacy_locker_card(state,- &merchant_id,+ &platform,&payment_method,&tracking_data,process_id,@@ -461,13 +483,6 @@ pub async fn run_payment_method_modular_backward_compat_backfill(#[cfg(feature = "v2")]{- let platform = domain::Platform::new(- merchant_account.clone(),- key_store.clone(),- merchant_account,- key_store,- None,- );backfill_legacy_locker_card(state,&platform,diff --git a/crates/router/src/workflows/payment_method_modular_forward_compat.rs b/crates/router/src/workflows/payment_method_modular_forward_compat.rsindex fd4ca77026..d533ea2ea2 100644--- a/crates/router/src/workflows/payment_method_modular_forward_compat.rs+++ b/crates/router/src/workflows/payment_method_modular_forward_compat.rs@@ -8,9 +8,9 @@ use scheduler::{};#[cfg(feature = "v1")]-use crate::types::payment_methods as pm_types;+use crate::types::{domain, payment_methods as pm_types};use crate::{- core::payment_methods::{cards, vault},+ core::payment_methods::{cards, utils as payment_method_utils, vault},errors,logger::{self, error},routes::SessionState,@@ -124,15 +124,24 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodModularForwardCompatWhyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(card_detail);// Step 5: Upsert the card into generic locker via direct AddVault call.- let payload = pm_types::AddCompatVaultRequest {- entity_id: customer_id.clone(),- vault_id: crate::types::domain::VaultId::generate(card_reference),- data: &pmd,- ttl: state.conf.locker.ttl_for_storage_in_secs,- }- .encode_to_vec()- .change_context(errors::VaultError::RequestEncodingFailed)- .attach_printable("Failed to encode AddVaultRequest")++ let should_trigger_fingerprint_migration =+ payment_method_utils::get_should_trigger_fingerprint_migration(+ state,+ None,+ hyperswitch_domain_models::platform::ProviderMerchantId::new(+ merchant_id.clone(),+ ),+ )+ .await;++ let payload = cards::encode_add_vault_request(+ should_trigger_fingerprint_migration,+ merchant_id.clone(),+ &customer_id,+ pmd,+ state.conf.locker.ttl_for_storage_in_secs,+ ).change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to add payment method in generic locker in compatibility PT",@@ -150,14 +159,13 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodModularForwardCompatW"Failed to add payment method in generic locker in compatibility PT",)?;- let _stored_pm_resp: pm_types::InternalAddVaultResponse = resp- .parse_struct("InternalAddVaultResponse")- .change_context(errors::VaultError::ResponseDeserializationFailed)- .attach_printable("Failed to parse data into InternalAddVaultResponse")- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(- "Failed to add payment method in generic locker in compatibility PT",- )?;+ let _stored_pm_resp =+ cards::parse_add_vault_response(should_trigger_fingerprint_migration, resp)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to add payment method in generic locker in compatibility PT",+ )?;+logger::info!(process_id=%process.id,payment_method_id=%payment_method.payment_method_id,@@ -214,9 +222,7 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodModularForwardCompatWlet network_token_payload = pm_types::AddVaultRequest {entity_id: network_token_entity_id,- vault_id: crate::types::domain::VaultId::generate(- network_token_locker_id.clone(),- ),+ vault_id: domain::VaultId::generate(network_token_locker_id.clone()),data: &network_token_pmd,ttl: state.conf.locker.ttl_for_storage_in_secs,}