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(router): Introduce duplication check for bank debit (#11235)
Anurag Thakurca192037ad20
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex 5ba2d81d8d..5ae4022035 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -616,7 +616,6 @@ pub enum PaymentMethodCreateData {BankDebit(BankDebitDetail),}-#[cfg(feature = "v1")]#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]#[serde(deny_unknown_fields)]#[serde(rename_all = "snake_case")]@@ -629,6 +628,42 @@ pub enum BankDebitDetail {},}+impl BankDebitDetail {+ pub fn get_masked_account_number(&self) -> String {+ match self {+ Self::Ach {+ account_number,+ routing_number: _,+ } => account_number+ .peek()+ .chars()+ .rev()+ .take(4)+ .collect::<String>()+ .chars()+ .rev()+ .collect::<String>(),+ }+ }++ pub fn get_masked_routing_number(&self) -> String {+ match self {+ Self::Ach {+ account_number: _,+ routing_number,+ } => routing_number+ .peek()+ .chars()+ .rev()+ .take(4)+ .collect::<String>()+ .chars()+ .rev()+ .collect::<String>(),+ }+ }+}+#[cfg(feature = "v1")]#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]#[serde(deny_unknown_fields)]diff --git a/crates/common_utils/src/id_type/customer.rs b/crates/common_utils/src/id_type/customer.rsindex 6b2ca23ef2..afa2d87dcd 100644--- a/crates/common_utils/src/id_type/customer.rs+++ b/crates/common_utils/src/id_type/customer.rs@@ -1,3 +1,5 @@+use crate::errors::{CustomResult, ValidationError};+crate::id_type!(CustomerId,"A type for customer_id that can be used for customer ids"@@ -22,3 +24,10 @@ impl crate::events::ApiEventMetric for CustomerId {})}}++impl CustomerId {+ /// Get a merchant id from String+ pub fn wrap(customer_id: String) -> CustomResult<Self, ValidationError> {+ Self::try_from(std::borrow::Cow::from(customer_id))+ }+}diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rsindex d5099e8683..baf5c6de6d 100644--- a/crates/diesel_models/src/payment_method.rs+++ b/crates/diesel_models/src/payment_method.rs@@ -66,6 +66,7 @@ pub struct PaymentMethod {pub created_by: Option<String>,pub last_modified_by: Option<String>,pub customer_details: Option<Encryption>,+ pub locker_fingerprint_id: Option<String>,}#[cfg(feature = "v2")]@@ -159,6 +160,7 @@ pub struct PaymentMethodNew {pub created_by: Option<String>,pub last_modified_by: Option<String>,pub customer_details: Option<Encryption>,+ pub locker_fingerprint_id: Option<String>,}#[cfg(feature = "v2")]@@ -489,6 +491,7 @@ impl PaymentMethodUpdateInternal {swift_code: source.swift_code,direct_debit_token: source.direct_debit_token,created_at: source.created_at,+ locker_fingerprint_id: source.locker_fingerprint_id,last_modified,payment_method: payment_method.or(source.payment_method),payment_method_type: payment_method_type.or(source.payment_method_type),@@ -1044,6 +1047,7 @@ impl From<&PaymentMethodNew> for PaymentMethod {created_by: payment_method_new.created_by.clone(),last_modified_by: payment_method_new.last_modified_by.clone(),customer_details: payment_method_new.customer_details.clone(),+ locker_fingerprint_id: payment_method_new.locker_fingerprint_id.clone(),}}}diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rsindex 8292d8d820..40dd1ab3c6 100644--- a/crates/diesel_models/src/query/payment_method.rs+++ b/crates/diesel_models/src/query/payment_method.rs@@ -220,6 +220,17 @@ impl PaymentMethod {result => result,}}++ pub async fn find_by_fingerprint_id(+ conn: &PgPooledConn,+ fingerprint_id: &str,+ ) -> StorageResult<Self> {+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(+ conn,+ dsl::locker_fingerprint_id.eq(fingerprint_id.to_owned()),+ )+ .await+ }}#[cfg(feature = "v2")]diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rsindex 7f2b00856d..0bd01ee32e 100644--- a/crates/diesel_models/src/schema.rs+++ b/crates/diesel_models/src/schema.rs@@ -1353,6 +1353,8 @@ diesel::table! {#[max_length = 255]last_modified_by -> Nullable<Varchar>,customer_details -> Nullable<Bytea>,+ #[max_length = 64]+ locker_fingerprint_id -> Nullable<Varchar>,}}diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rsindex 6ccdc5b680..b5c33231f9 100644--- a/crates/hyperswitch_domain_models/src/payment_methods.rs+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs@@ -94,6 +94,7 @@ pub struct PaymentMethod {pub created_by: Option<CreatedBy>,pub last_modified_by: Option<CreatedBy>,pub customer_details: OptionalEncryptableValue,+ pub locker_fingerprint_id: Option<String>,}#[cfg(feature = "v2")]@@ -369,6 +370,7 @@ impl super::behaviour::Conversion for PaymentMethod {.last_modified_by.map(|last_modified_by| last_modified_by.to_string()),customer_details: self.customer_details.map(|val| val.into()),+ locker_fingerprint_id: self.locker_fingerprint_id,})}@@ -509,6 +511,7 @@ impl super::behaviour::Conversion for PaymentMethod {.last_modified_by.and_then(|last_modified_by| last_modified_by.parse::<CreatedBy>().ok()),customer_details,+ locker_fingerprint_id: item.locker_fingerprint_id,})}@@ -560,6 +563,7 @@ impl super::behaviour::Conversion for PaymentMethod {.last_modified_by.map(|last_modified_by| last_modified_by.to_string()),customer_details: self.customer_details.map(|val| val.into()),+ locker_fingerprint_id: self.locker_fingerprint_id,})}}@@ -1012,7 +1016,6 @@ pub trait PaymentMethodInterface {payment_method: PaymentMethod,) -> CustomResult<PaymentMethod, Self::Error>;- #[cfg(feature = "v2")]async fn find_payment_method_by_fingerprint_id(&self,key_store: &MerchantKeyStore,@@ -1374,6 +1377,54 @@ impl<'a> PaymentMethodBalanceData<'a> {}}+#[cfg(feature = "v1")]+#[derive(Debug)]+pub struct PaymentMethodResponse {+ /// Unique identifier for a merchant+ pub merchant_id: id_type::MerchantId,++ /// The unique identifier of the customer.+ pub customer_id: Option<id_type::CustomerId>,++ /// The unique identifier of the Payment method+ pub payment_method_id: String,++ /// The type of payment method use for the payment.+ pub payment_method: Option<common_enums::PaymentMethod>,++ /// This is a sub-category of payment method.+ pub payment_method_type: Option<common_enums::PaymentMethodType>,++ /// Card details from card locker+ pub card: Option<payment_methods::CardDetailFromLocker>,++ /// Indicates whether the payment method supports recurring payments. Optional.+ pub recurring_enabled: Option<bool>,++ /// Indicates whether the payment method is eligible for installment payments (e.g., EMI, BNPL). Optional.+ pub installment_payment_enabled: Option<bool>,++ /// Type of payment experience enabled with the connector+ pub payment_experience: Option<Vec<common_enums::PaymentExperience>>,++ /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.+ pub metadata: Option<pii::SecretSerdeValue>,++ /// A timestamp (ISO 8601 code) that determines when the payment method was created+ pub created: Option<PrimitiveDateTime>,++ /// Payment method details from locker+ #[cfg(feature = "payouts")]+ pub bank_transfer: Option<api_models::payouts::Bank>,++ pub last_used_at: Option<PrimitiveDateTime>,++ /// For Client based calls+ pub client_secret: Option<String>,++ pub locker_fingerprint_id: Option<String>,+}+#[cfg(feature = "v1")]#[cfg(test)]mod tests {@@ -1423,6 +1474,7 @@ mod tests {created_by: None,last_modified_by: None,customer_details: None,+ locker_fingerprint_id: None,};payment_method.clone()}diff --git a/crates/hyperswitch_domain_models/src/vault.rs b/crates/hyperswitch_domain_models/src/vault.rsindex a726e7a59e..a2d8666953 100644--- a/crates/hyperswitch_domain_models/src/vault.rs+++ b/crates/hyperswitch_domain_models/src/vault.rs@@ -5,15 +5,15 @@ use common_utils::{crypto::Encryptable, errors::CustomResult, ext_traits::Optionuse error_stack::ResultExt;use serde::{Deserialize, Serialize};-#[cfg(feature = "v2")]-use crate::errors;-use crate::payment_method_data;+use crate::{errors, payment_method_data};#[derive(Debug, Deserialize, Serialize, Clone)]pub enum PaymentMethodVaultingData {Card(payment_methods::CardDetail),NetworkToken(payment_method_data::NetworkTokenDetails),CardNumber(cards::CardNumber),+ #[cfg(feature = "v1")]+ BankDebit(payment_methods::BankDebitDetail),}#[derive(Debug, Deserialize, Serialize, Clone)]pub enum FingerprintData {@@ -37,6 +37,7 @@ pub struct FingerprintNetworkTokenData {}impl PaymentMethodVaultingData {+ #[cfg(feature = "v2")]pub fn get_card(&self) -> Option<&payment_methods::CardDetail> {match self {Self::Card(card) => Some(card),@@ -45,6 +46,7 @@ impl PaymentMethodVaultingData {}}+ #[cfg(feature = "v2")]pub fn set_card_cvc(&mut self, card_cvc: masking::Secret<String>) {match self {Self::Card(card_details) => {@@ -121,6 +123,7 @@ impl PaymentMethodVaultingData {)}+ #[cfg(feature = "v2")]pub fn get_payment_methods_data(&self) -> payment_method_data::PaymentMethodsData {match self {Self::Card(card) => payment_method_data::PaymentMethodsData::Card(@@ -154,6 +157,8 @@ impl PaymentMethodVaultingData {),}}++ #[cfg(feature = "v2")]pub fn to_fingerprint_data(&self) -> FingerprintData {match self {Self::Card(card) => FingerprintData::Card(FingerprintCardData {@@ -199,10 +204,80 @@ pub struct NetworkTokenCustomData {pub cryptogram: Option<masking::Secret<String>>,}+#[cfg(feature = "v1")]+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct V1VaultEntityId {+ merchant_id: common_utils::id_type::MerchantId,+ customer_id: common_utils::id_type::CustomerId,+}++#[cfg(feature = "v1")]+impl V1VaultEntityId {+ pub fn new(+ merchant_id: common_utils::id_type::MerchantId,+ customer_id: common_utils::id_type::CustomerId,+ ) -> Self {+ Self {+ merchant_id,+ customer_id,+ }+ }++ pub fn get_string_repr(&self) -> String {+ format!(+ "{}_{}",+ self.merchant_id.get_string_repr(),+ self.customer_id.get_string_repr()+ )+ }+}++#[cfg(feature = "v1")]+impl Serialize for V1VaultEntityId {+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>+ where+ S: serde::Serializer,+ {+ serializer.serialize_str(&self.get_string_repr())+ }+}++#[cfg(feature = "v1")]+impl<'de> Deserialize<'de> for V1VaultEntityId {+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>+ where+ D: serde::Deserializer<'de>,+ {+ let s = String::deserialize(deserializer)?;+ let parts: Vec<&str> = s.splitn(2, '_').collect();++ let merchant_part = parts.first().ok_or_else(|| {+ serde::de::Error::custom(+ "Invalid V1VaultEntityId format: expected 'merchant_id_customer_id'",+ )+ })?;++ let customer_part = parts.get(1).ok_or_else(|| {+ serde::de::Error::custom(+ "Invalid V1VaultEntityId format: expected 'merchant_id_customer_id'",+ )+ })?;++ Ok(Self {+ merchant_id: common_utils::id_type::MerchantId::wrap((*merchant_part).to_string())+ .map_err(serde::de::Error::custom)?,+ customer_id: common_utils::id_type::CustomerId::wrap((*customer_part).to_string())+ .map_err(serde::de::Error::custom)?,+ })+ }+}++#[cfg(feature = "v2")]pub trait VaultingDataInterface {fn get_vaulting_data_key(&self) -> String;}+#[cfg(feature = "v2")]impl VaultingDataInterface for PaymentMethodVaultingData {fn get_vaulting_data_key(&self) -> String {match &self {@@ -212,6 +287,7 @@ impl VaultingDataInterface for PaymentMethodVaultingData {}}}+#[cfg(feature = "v2")]impl VaultingDataInterface for FingerprintData {fn get_vaulting_data_key(&self) -> String {match self {@@ -243,31 +319,58 @@ impl TryFrom<payment_methods::PaymentMethodCreateData> for PaymentMethodVaulting}}-impl From<PaymentMethodVaultingData> for PaymentMethodCustomVaultingData {- fn from(item: PaymentMethodVaultingData) -> Self {+#[cfg(feature = "v1")]+impl From<payment_methods::PaymentMethodCreateData> for PaymentMethodVaultingData {+ fn from(item: payment_methods::PaymentMethodCreateData) -> Self {match item {- PaymentMethodVaultingData::Card(card_data) => Self::CardData(CardCustomData {+ payment_methods::PaymentMethodCreateData::Card(card) => {+ Self::Card(payment_methods::CardDetail {+ card_cvc: None, // card cvc should not be used for vaulting+ ..card+ })+ }+ payment_methods::PaymentMethodCreateData::BankDebit(bank_debit_detail) => {+ Self::BankDebit(bank_debit_detail)+ }+ }+ }+}++impl TryFrom<PaymentMethodVaultingData> for PaymentMethodCustomVaultingData {+ type Error = error_stack::Report<errors::api_error_response::ApiErrorResponse>;++ fn try_from(item: PaymentMethodVaultingData) -> Result<Self, Self::Error> {+ match item {+ PaymentMethodVaultingData::Card(card_data) => Ok(Self::CardData(CardCustomData {card_number: Some(card_data.card_number),card_exp_month: Some(card_data.card_exp_month),card_exp_year: Some(card_data.card_exp_year),card_cvc: card_data.card_cvc,- }),+ })),PaymentMethodVaultingData::NetworkToken(network_token_data) => {- Self::NetworkTokenData(NetworkTokenCustomData {+ Ok(Self::NetworkTokenData(NetworkTokenCustomData {network_token: Some(network_token_data.network_token),network_token_exp_month: Some(network_token_data.network_token_exp_month),network_token_exp_year: Some(network_token_data.network_token_exp_year),cryptogram: network_token_data.cryptogram,- })+ }))}PaymentMethodVaultingData::CardNumber(card_number_data) => {- Self::CardData(CardCustomData {+ Ok(Self::CardData(CardCustomData {card_number: Some(card_number_data),card_exp_month: None,card_exp_year: None,card_cvc: None,- })+ }))}+ #[cfg(feature = "v1")]+ PaymentMethodVaultingData::BankDebit(_) => Err(+ errors::api_error_response::ApiErrorResponse::NotImplemented {+ message: errors::api_error_response::NotImplementedMessage::Reason(+ "PaymentMethodCustomVaultingData not implemented for BankDebit".to_string(),+ ),+ },+ )?,}}}diff --git a/crates/payment_methods/src/controller.rs b/crates/payment_methods/src/controller.rsindex ce7d95545c..bfeb101927 100644--- a/crates/payment_methods/src/controller.rs+++ b/crates/payment_methods/src/controller.rs@@ -58,13 +58,14 @@ pub trait PaymentMethodsController {network_token_payment_method_data: crypto::OptionalEncryptableValue,vault_source_details: Option<PaymentMethodVaultSourceDetails>,payment_method_customer_details_encrypted: crypto::OptionalEncryptableValue,+ locker_fingerprint_id: Option<String>,) -> errors::PmResult<payment_methods::PaymentMethod>;#[cfg(feature = "v1")]#[allow(clippy::too_many_arguments)]async fn insert_payment_method(&self,- resp: &api::PaymentMethodResponse,+ resp: &payment_methods::PaymentMethodResponse,req: &api::PaymentMethodCreate,key_store: &merchant_key_store::MerchantKeyStore,merchant_id: &id_type::MerchantId,@@ -116,31 +117,42 @@ pub trait PaymentMethodsController {pm_id: api::PaymentMethodId,) -> errors::PmResponse<api::PaymentMethodDeleteResponse>;+ #[cfg(feature = "v1")]async fn add_card_hs(&self,req: api::PaymentMethodCreate,card: &api::CardDetail,customer_id: &id_type::CustomerId,card_reference: Option<&str>,- ) -> errors::VaultResult<(api::PaymentMethodResponse, Option<DataDuplicationCheck>)>;+ ) -> errors::VaultResult<(+ payment_methods::PaymentMethodResponse,+ Option<DataDuplicationCheck>,+ )>;/// The response will be the tuple of PaymentMethodResponse and the duplication check of payment_method+ #[cfg(feature = "v1")]async fn add_card_to_locker(&self,req: api::PaymentMethodCreate,card: &api::CardDetail,customer_id: &id_type::CustomerId,card_reference: Option<&str>,- ) -> errors::VaultResult<(api::PaymentMethodResponse, Option<DataDuplicationCheck>)>;+ ) -> errors::VaultResult<(+ payment_methods::PaymentMethodResponse,+ Option<DataDuplicationCheck>,+ )>;- #[cfg(feature = "payouts")]+ #[cfg(all(feature = "payouts", feature = "v1"))]async fn add_bank_to_locker(&self,req: api::PaymentMethodCreate,key_store: &merchant_key_store::MerchantKeyStore,bank: &payouts::Bank,customer_id: &id_type::CustomerId,- ) -> errors::VaultResult<(api::PaymentMethodResponse, Option<DataDuplicationCheck>)>;+ ) -> errors::VaultResult<(+ payment_methods::PaymentMethodResponse,+ Option<DataDuplicationCheck>,+ )>;#[cfg(feature = "v1")]async fn add_bank_debit_to_locker(@@ -149,13 +161,16 @@ pub trait PaymentMethodsController {bank_debit_data: api_models::payment_methods::BankDebitDetail,key_store: &merchant_key_store::MerchantKeyStore,customer_id: &id_type::CustomerId,- ) -> errors::VaultResult<(api::PaymentMethodResponse, Option<DataDuplicationCheck>)>;+ ) -> errors::VaultResult<(+ payment_methods::PaymentMethodResponse,+ Option<DataDuplicationCheck>,+ )>;#[cfg(feature = "v1")]async fn get_or_insert_payment_method(&self,req: api::PaymentMethodCreate,- resp: &mut api::PaymentMethodResponse,+ resp: &mut payment_methods::PaymentMethodResponse,customer_id: &id_type::CustomerId,key_store: &merchant_key_store::MerchantKeyStore,) -> errors::PmResult<payment_methods::PaymentMethod>;@@ -196,7 +211,10 @@ pub trait PaymentMethodsController {req: &api::PaymentMethodCreate,customer_id: &id_type::CustomerId,merchant_id: &id_type::MerchantId,- ) -> (api::PaymentMethodResponse, Option<DataDuplicationCheck>);+ ) -> (+ payment_methods::PaymentMethodResponse,+ Option<DataDuplicationCheck>,+ );#[cfg(feature = "v2")]fn store_default_payment_method(diff --git a/crates/payment_methods/src/core/migration/payment_methods.rs b/crates/payment_methods/src/core/migration/payment_methods.rsindex 5b13c3d8c4..f99ebc84e1 100644--- a/crates/payment_methods/src/core/migration/payment_methods.rs+++ b/crates/payment_methods/src/core/migration/payment_methods.rs@@ -552,6 +552,7 @@ pub async fn get_client_secret_or_add_payment_method_for_migration(None,Default::default(),None,+ None,).await?;migration_status.connector_mandate_details_migrated(@@ -717,6 +718,7 @@ pub async fn skip_locker_call_and_migrate_payment_method(created_by: None,last_modified_by: None,customer_details: None,+ locker_fingerprint_id: None,},provider.get_account().storage_scheme,)diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex 28bed1ff09..50316bb1fc 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -181,40 +181,31 @@ pub const DEFAULT_PRODUCT_IMG: &str =pub const DEFAULT_SDK_LAYOUT: &str = "tabs";/// Vault Add request url-#[cfg(feature = "v2")]-pub const ADD_VAULT_REQUEST_URL: &str = "/api/v2/vault/add";+pub const V2_ADD_VAULT_REQUEST_URL: &str = "/api/v2/vault/add";/// Vault Get Fingerprint request url-#[cfg(feature = "v2")]-pub const VAULT_FINGERPRINT_REQUEST_URL: &str = "/api/v2/vault/fingerprint";+pub const V2_VAULT_FINGERPRINT_REQUEST_URL: &str = "/api/v2/vault/fingerprint";/// Vault Retrieve request url-#[cfg(feature = "v2")]-pub const VAULT_RETRIEVE_REQUEST_URL: &str = "/api/v2/vault/retrieve";+pub const V2_VAULT_RETRIEVE_REQUEST_URL: &str = "/api/v2/vault/retrieve";/// Vault Delete request url-#[cfg(feature = "v2")]-pub const VAULT_DELETE_REQUEST_URL: &str = "/api/v2/vault/delete";+pub const V2_VAULT_DELETE_REQUEST_URL: &str = "/api/v2/vault/delete";/// Vault Header content type-#[cfg(feature = "v2")]-pub const VAULT_HEADER_CONTENT_TYPE: &str = "application/json";+pub const V2_VAULT_HEADER_CONTENT_TYPE: &str = "application/json";/// Vault Add flow type-#[cfg(feature = "v2")]-pub const VAULT_ADD_FLOW_TYPE: &str = "add_to_vault";+pub const V2_VAULT_ADD_FLOW_TYPE: &str = "add_to_vault";/// Vault Retrieve flow type-#[cfg(feature = "v2")]-pub const VAULT_RETRIEVE_FLOW_TYPE: &str = "retrieve_from_vault";+pub const V2_VAULT_RETRIEVE_FLOW_TYPE: &str = "retrieve_from_vault";/// Vault Delete flow type-#[cfg(feature = "v2")]-pub const VAULT_DELETE_FLOW_TYPE: &str = "delete_from_vault";+pub const V2_VAULT_DELETE_FLOW_TYPE: &str = "delete_from_vault";/// Vault Fingerprint fetch flow type-#[cfg(feature = "v2")]-pub const VAULT_GET_FINGERPRINT_FLOW_TYPE: &str = "get_fingerprint_vault";+pub const V2_VAULT_GET_FINGERPRINT_FLOW_TYPE: &str = "get_fingerprint_vault";/// Max volume split for Dynamic routingpub const DYNAMIC_ROUTING_MAX_VOLUME: u8 = 100;diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex e1b3f616b1..a030438a34 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -587,7 +587,7 @@ pub async fn retrieve_payment_method_with_token(.unwrap_or_default()}- storage::PaymentTokenData::Permanent(card_token) => {+ storage::PaymentTokenData::Permanent(card_token) => Box::pin(payment_helpers::retrieve_payment_method_data_with_permanent_token(state,card_token.locker_id.as_ref().unwrap_or(&card_token.token),@@ -608,26 +608,26 @@ pub async fn retrieve_payment_method_with_token(payment_attempt.connector.clone(),should_retry_with_pan,vault_data,- )- .await- .map(|card| Some((card, enums::PaymentMethod::Card)))?- .map(- |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {- payment_method_data: Some(payment_method_data),- payment_method: Some(payment_method),- payment_method_id: Some(- card_token- .payment_method_id- .as_ref()- .unwrap_or(&card_token.token)- .to_string(),- ),- },- )- .unwrap_or_default()- }+ ),+ )+ .await+ .map(|card| Some((card, enums::PaymentMethod::Card)))?+ .map(+ |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {+ payment_method_data: Some(payment_method_data),+ payment_method: Some(payment_method),+ payment_method_id: Some(+ card_token+ .payment_method_id+ .as_ref()+ .unwrap_or(&card_token.token)+ .to_string(),+ ),+ },+ )+ .unwrap_or_default(),- storage::PaymentTokenData::PermanentCard(card_token) => {+ storage::PaymentTokenData::PermanentCard(card_token) => Box::pin(payment_helpers::retrieve_payment_method_data_with_permanent_token(state,card_token.locker_id.as_ref().unwrap_or(&card_token.token),@@ -648,24 +648,24 @@ pub async fn retrieve_payment_method_with_token(payment_attempt.connector.clone(),should_retry_with_pan,vault_data,- )- .await- .map(|card| Some((card, enums::PaymentMethod::Card)))?- .map(- |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {- payment_method_data: Some(payment_method_data),- payment_method: Some(payment_method),- payment_method_id: Some(- card_token- .payment_method_id- .as_ref()- .unwrap_or(&card_token.token)- .to_string(),- ),- },- )- .unwrap_or_default()- }+ ),+ )+ .await+ .map(|card| Some((card, enums::PaymentMethod::Card)))?+ .map(+ |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {+ payment_method_data: Some(payment_method_data),+ payment_method: Some(payment_method),+ payment_method_id: Some(+ card_token+ .payment_method_id+ .as_ref()+ .unwrap_or(&card_token.token)+ .to_string(),+ ),+ },+ )+ .unwrap_or_default(),storage::PaymentTokenData::AuthBankDebit(auth_token) => {pm_auth::retrieve_payment_method_from_auth_service(@@ -3159,7 +3159,7 @@ pub fn get_payment_method_custom_data(if keys_set.is_empty() {// edge case where no token to vault is present- Ok(payment_method_vaulting_data.into())+ Ok(payment_method_vaulting_data.try_into()?)} else {match payment_method_vaulting_data {hyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(card_details) => {@@ -3210,11 +3210,16 @@ pub fn get_payment_method_custom_data(Err(errors::ApiErrorResponse::InternalServerError).attach_printable("Unexpected Behaviour, Card Number variant is not supported for Custom Tokenization")?}+ #[cfg(feature = "v1")]+ hyperswitch_domain_models::vault::PaymentMethodVaultingData::BankDebit(_) => {+ Err(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unexpected Behaviour, Bank Debit variant is not supported for Custom Tokenization")?+ }}}}// default case, populate data one to one- None => Ok(payment_method_vaulting_data.into()),+ None => Ok(payment_method_vaulting_data.try_into()?),}}diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex 817929dc4c..832c479a5d 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -101,6 +101,7 @@ use crate::{types::{api::{self, routing as routing_types, PaymentMethodCreateExt},domain::{self, Profile},+ payment_methods as pm_types,storage::{self, enums, PaymentMethodListContext, PaymentTokenData},transformers::{ForeignFrom, ForeignTryFrom},},@@ -108,10 +109,7 @@ use crate::{utils::OptionExt,};#[cfg(feature = "v2")]-use crate::{- core::payment_methods as pm_core, headers, types::payment_methods as pm_types,- utils::ConnectorResponseExt,-};+use crate::{core::payment_methods as pm_core, headers, utils::ConnectorResponseExt};pub struct PmCards<'a> {pub state: &'a routes::SessionState,@@ -143,6 +141,7 @@ impl PaymentMethodsController for PmCards<'_> {network_token_payment_method_data: crypto::OptionalEncryptableValue,vault_source_details: Option<domain::PaymentMethodVaultSourceDetails>,payment_method_customer_details_encrypted: crypto::OptionalEncryptableValue,+ locker_fingerprint_id: Option<String>,) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {let db = &*self.state.store;let customer = db@@ -205,6 +204,7 @@ impl PaymentMethodsController for PmCards<'_> {created_by: None,last_modified_by: None,customer_details: payment_method_customer_details_encrypted,+ locker_fingerprint_id,},self.provider.get_account().storage_scheme,)@@ -229,11 +229,11 @@ impl PaymentMethodsController for PmCards<'_> {customer_id: &id_type::CustomerId,merchant_id: &id_type::MerchantId,) -> (- api::PaymentMethodResponse,+ domain::PaymentMethodResponse,Option<payment_methods::DataDuplicationCheck>,) {let pm_id = generate_id(consts::ID_LENGTH, "pm");- let payment_method_response = api::PaymentMethodResponse {+ let payment_method_response = domain::PaymentMethodResponse {merchant_id: merchant_id.to_owned(),customer_id: Some(customer_id.to_owned()),payment_method_id: pm_id,@@ -249,6 +249,7 @@ impl PaymentMethodsController for PmCards<'_> {payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),last_used_at: Some(common_utils::date_time::now()),client_secret: None,+ locker_fingerprint_id: None,};(payment_method_response, None)@@ -272,7 +273,7 @@ impl PaymentMethodsController for PmCards<'_> {async fn get_or_insert_payment_method(&self,req: api::PaymentMethodCreate,- resp: &mut api::PaymentMethodResponse,+ resp: &mut domain::PaymentMethodResponse,customer_id: &id_type::CustomerId,key_store: &domain::MerchantKeyStore,) -> errors::RouterResult<domain::PaymentMethod> {@@ -464,7 +465,7 @@ impl PaymentMethodsController for PmCards<'_> {#[allow(clippy::too_many_arguments)]async fn insert_payment_method(&self,- resp: &api::PaymentMethodResponse,+ resp: &domain::PaymentMethodResponse,req: &api::PaymentMethodCreate,key_store: &domain::MerchantKeyStore,merchant_id: &id_type::MerchantId,@@ -514,6 +515,7 @@ impl PaymentMethodsController for PmCards<'_> {network_token_payment_method_data,vault_source_details,None,+ None,).await}@@ -537,7 +539,7 @@ impl PaymentMethodsController for PmCards<'_> {todo!()}- #[cfg(feature = "payouts")]+ #[cfg(all(feature = "payouts", feature = "v1"))]async fn add_bank_to_locker(&self,req: api::PaymentMethodCreate,@@ -546,7 +548,7 @@ impl PaymentMethodsController for PmCards<'_> {customer_id: &id_type::CustomerId,) -> errors::CustomResult<(- api::PaymentMethodResponse,+ domain::PaymentMethodResponse,Option<payment_methods::DataDuplicationCheck>,),errors::VaultError,@@ -615,65 +617,105 @@ impl PaymentMethodsController for PmCards<'_> {customer_id: &id_type::CustomerId,) -> errors::CustomResult<(- api::PaymentMethodResponse,+ domain::PaymentMethodResponse,Option<payment_methods::DataDuplicationCheck>,),errors::VaultError,> {- let key = key_store.key.get_inner().peek();+ let pmd = hyperswitch_domain_models::vault::PaymentMethodVaultingData::from(+ api_models::payment_methods::PaymentMethodCreateData::BankDebit(bank_debit_data)+ .clone(),+ );- let key_manager_state: KeyManagerState = self.state.into();- let enc_data = async {- serde_json::to_value(bank_debit_data.to_owned())- .map_err(|err| {- logger::error!("Error while encoding bank debit data: {err:?}");- errors::VaultError::SavePaymentMethodFailed- })- .change_context(errors::VaultError::SavePaymentMethodFailed)- .attach_printable("Unable to encode bank debit data")- .ok()- .map(|v| {- let secret: Secret<String> = Secret::new(v.to_string());- secret- })- .async_lift(|inner| async {- domain::types::crypto_operation(- &key_manager_state,- type_name!(payment_method::PaymentMethod),- domain::types::CryptoOperation::EncryptOptional(inner),- Identifier::Merchant(key_store.merchant_id.clone()),- key,- )- .await- .and_then(|val| val.try_into_optionaloperation())- })- .await+ 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: customer_id.get_string_repr().to_owned(),+ data,}- .await- .change_context(errors::VaultError::SavePaymentMethodFailed)- .attach_printable("Failed to encrypt payment method data")?- .map(Encryption::from)- .map(|e| e.into_inner())- .map_or(Err(errors::VaultError::SavePaymentMethodFailed), |e| {- Ok(hex::encode(e.peek()))- })?;+ .encode_to_vec()+ .change_context(errors::VaultError::RequestEncodingFailed)+ .attach_printable("Failed to encode VaultFingerprintRequest")?;- let payload =- payment_methods::StoreLockerReq::LockerGeneric(payment_methods::StoreGenericReq {- merchant_id: self.provider.get_account().get_id().to_owned(),- merchant_customer_id: customer_id.to_owned(),- enc_data,+ let resp = vault::call_to_vault::<pm_types::GetVaultFingerprint>(self.state, payload)+ .await+ .change_context(errors::VaultError::VaultAPIError)+ .attach_printable("Call to vault failed")?;++ let fingerprint_resp: pm_types::VaultFingerprintResponse = resp+ .parse_struct("VaultFingerprintResponse")+ .change_context(errors::VaultError::ResponseDeserializationFailed)+ .attach_printable("Failed to parse data into VaultFingerprintResponse")?;++ let fingerprint_id = fingerprint_resp.fingerprint_id.clone();++ let existing_pm = self+ .state+ .store+ .find_payment_method_by_fingerprint_id(key_store, &fingerprint_id)+ .await;++ if let Ok(existing_payment_method) = existing_pm {+ let bank_debit_locker_id = existing_payment_method+ .locker_id+ .clone()+ .ok_or(errors::VaultError::MissingRequiredField {+ field_name: "locker_id",+ })+ .attach_printable(+ "Payment Method with the fingerprint already exists but is missing locker_id",+ )?;++ let payment_method_resp = payment_methods::mk_add_bank_debit_response_hs(+ bank_debit_locker_id,+ req,+ self.provider.get_account().get_id(),+ fingerprint_id,+ );++ Ok((+ payment_method_resp,+ 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,- });- let store_resp = add_card_to_vault(self.state, &payload, customer_id).await?;- let payment_method_resp = payment_methods::mk_add_bank_debit_response_hs(- store_resp.card_reference,- req,- self.provider.get_account().get_id(),- );- Ok((payment_method_resp, store_resp.duplication_check))+ }+ .encode_to_vec()+ .change_context(errors::VaultError::RequestEncodingFailed)+ .attach_printable("Failed to encode AddVaultRequest")?;++ let resp = vault::call_to_vault::<pm_types::AddVault>(self.state, payload)+ .await+ .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 payment_method_resp = payment_methods::mk_add_bank_debit_response_hs(+ stored_pm_resp.vault_id.get_string_repr().to_owned(),+ req,+ self.provider.get_account().get_id(),+ fingerprint_id,+ );++ Ok((payment_method_resp, None))+ }}/// The response will be the tuple of PaymentMethodResponse and the duplication check of payment_method+ #[cfg(feature = "v1")]async fn add_card_to_locker(&self,req: api::PaymentMethodCreate,@@ -682,7 +724,7 @@ impl PaymentMethodsController for PmCards<'_> {card_reference: Option<&str>,) -> errors::CustomResult<(- api::PaymentMethodResponse,+ domain::PaymentMethodResponse,Option<payment_methods::DataDuplicationCheck>,),errors::VaultError,@@ -740,7 +782,7 @@ impl PaymentMethodsController for PmCards<'_> {.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed while deleting card from locker")}-+ #[cfg(feature = "v1")]#[instrument(skip_all)]async fn add_card_hs(&self,@@ -750,7 +792,7 @@ impl PaymentMethodsController for PmCards<'_> {card_reference: Option<&str>,) -> errors::CustomResult<(- api::PaymentMethodResponse,+ hyperswitch_domain_models::payment_methods::PaymentMethodResponse,Option<payment_methods::DataDuplicationCheck>,),errors::VaultError,@@ -1370,7 +1412,9 @@ impl PaymentMethodsController for PmCards<'_> {}}- Ok(services::ApplicationResponse::Json(resp))+ let api_resp = api::PaymentMethodResponse::foreign_from(resp);++ Ok(services::ApplicationResponse::Json(api_resp))}}@@ -1432,6 +1476,7 @@ pub async fn get_client_secret_or_add_payment_method(None,Default::default(), //Currently this method is used for adding payment method via PaymentMethodCreate API which doesn't support external vault. hence Default i.e. InternalVault is passed for vault typeNone,+ None,).await?;@@ -1549,7 +1594,7 @@ pub async fn add_payment_method_data(.change_context(errors::ApiErrorResponse::InternalServerError);match resp {- Ok((mut pm_resp, duplication_check)) => {+ Ok((mut domain_pm_resp, duplication_check)) => {if duplication_check.is_some() {let pm_update = storage::PaymentMethodUpdate::StatusUpdate {status: Some(enums::PaymentMethodStatus::Inactive),@@ -1569,17 +1614,19 @@ pub async fn add_payment_method_data(cards.get_or_insert_payment_method(req.clone(),- &mut pm_resp,+ &mut domain_pm_resp,&customer_id,provider.get_key_store(),).await?;+ let pm_resp = api::PaymentMethodResponse::foreign_from(domain_pm_resp);+return Ok(services::ApplicationResponse::Json(pm_resp));} else {- let locker_id = pm_resp.payment_method_id.clone();- pm_resp.payment_method_id.clone_from(&pm_id);- pm_resp.client_secret = Some(client_secret.clone());+ let locker_id = domain_pm_resp.payment_method_id.clone();+ domain_pm_resp.payment_method_id.clone_from(&pm_id);+ domain_pm_resp.client_secret = Some(client_secret.clone());let card_isin = card.card_number.get_card_isin();@@ -1656,6 +1703,7 @@ pub async fn add_payment_method_data()});}+ let pm_resp = api::PaymentMethodResponse::foreign_from(domain_pm_resp);return Ok(services::ApplicationResponse::Json(pm_resp));}@@ -5000,24 +5048,40 @@ pub async fn get_bank_debit_from_hs_locker(customer_id: &id_type::CustomerId,token_ref: &str,) -> errors::RouterResult<api_models::payment_methods::BankDebitDetail> {- let payment_method = get_encrypted_data_from_vault(- state,- provider.get_key_store(),- customer_id,- provider.get_account().get_id(),- token_ref,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Error getting payment method from locker")?;+ 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 bank_debit_create_data: api_models::payment_methods::BankDebitDetail = payment_method- .peek()- .to_string()- .parse_struct("BankDebitDetail")+ let resp = vault::call_to_vault::<pm_types::VaultRetrieve>(state, payload)+ .await+ .change_context(errors::VaultError::VaultAPIError)+ .attach_printable("Call to vault failed")+ .change_context(errors::ApiErrorResponse::InternalServerError)?;++ let stored_pm_resp: pm_types::VaultRetrieveResponse = resp+ .parse_struct("VaultRetrieveResponse")+ .change_context(errors::VaultError::ResponseDeserializationFailed)+ .attach_printable("Failed to parse data into VaultRetrieveResponse").change_context(errors::ApiErrorResponse::InternalServerError)?;- Ok(bank_debit_create_data)+ match stored_pm_resp.data {+ hyperswitch_domain_models::vault::PaymentMethodVaultingData::BankDebit(+ bank_debit_detail,+ ) => Ok(bank_debit_detail),+ _ => Err(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Invalid payment method data found")?,+ }}#[cfg(feature = "v1")]diff --git a/crates/router/src/core/payment_methods/tokenize/card_executor.rs b/crates/router/src/core/payment_methods/tokenize/card_executor.rsindex 7366947123..8398fabbd5 100644--- a/crates/router/src/core/payment_methods/tokenize/card_executor.rs+++ b/crates/router/src/core/payment_methods/tokenize/card_executor.rs@@ -608,6 +608,7 @@ impl CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest> {Some(enc_token_data),Default::default(), // this method is used only for card bulk tokenization, and currently external vault is not supported for this hence passing Default i.e. InternalVaultNone,+ None,).await}diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rsindex 6bea2bfee5..1529587f12 100644--- a/crates/router/src/core/payment_methods/transformers.rs+++ b/crates/router/src/core/payment_methods/transformers.rs@@ -291,7 +291,6 @@ pub async fn get_decrypted_vault_response_payload(.attach_printable("Jws Decryption failed for JwsBody for vault")}-#[cfg(feature = "v2")]pub async fn create_jwe_body_for_vault(jwekey: &settings::Jwekey,jws: &str,@@ -432,8 +431,8 @@ pub fn mk_add_bank_response_hs(bank_reference: String,req: api::PaymentMethodCreate,merchant_id: &id_type::MerchantId,-) -> api::PaymentMethodResponse {- api::PaymentMethodResponse {+) -> domain::PaymentMethodResponse {+ domain::PaymentMethodResponse {merchant_id: merchant_id.to_owned(),customer_id: req.customer_id,payment_method_id: bank_reference,@@ -448,6 +447,7 @@ pub fn mk_add_bank_response_hs(payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),last_used_at: Some(common_utils::date_time::now()),client_secret: None,+ locker_fingerprint_id: None,}}@@ -456,8 +456,9 @@ pub fn mk_add_bank_debit_response_hs(bank_reference: String,req: api::PaymentMethodCreate,merchant_id: &id_type::MerchantId,-) -> api::PaymentMethodResponse {- api::PaymentMethodResponse {+ locker_fingerprint_id: String,+) -> domain::PaymentMethodResponse {+ domain::PaymentMethodResponse {merchant_id: merchant_id.to_owned(),customer_id: req.customer_id.to_owned(),payment_method_id: bank_reference,@@ -472,6 +473,7 @@ pub fn mk_add_bank_debit_response_hs(payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),last_used_at: Some(common_utils::date_time::now()),client_secret: None,+ locker_fingerprint_id: Some(locker_fingerprint_id),}}@@ -491,7 +493,7 @@ pub fn mk_add_card_response_hs(card_reference: String,req: api::PaymentMethodCreate,merchant_id: &id_type::MerchantId,-) -> api::PaymentMethodResponse {+) -> domain::PaymentMethodResponse {let card_number = card.card_number.clone();let last4_digits = card_number.get_last4();let card_isin = card_number.get_card_isin();@@ -517,7 +519,7 @@ pub fn mk_add_card_response_hs(card_type: card.card_type,saved_to_locker: true,};- api::PaymentMethodResponse {+ domain::PaymentMethodResponse {merchant_id: merchant_id.to_owned(),customer_id: req.customer_id,payment_method_id: card_reference,@@ -533,6 +535,7 @@ pub fn mk_add_card_response_hs(payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),last_used_at: Some(common_utils::date_time::now()), // [#256]client_secret: req.client_secret,+ locker_fingerprint_id: None,}}@@ -1324,6 +1327,7 @@ impl DomainPaymentMethodWrapper {created_by: None,last_modified_by: None,customer_details: None,+ locker_fingerprint_id: None,}))}@@ -1451,6 +1455,7 @@ impl DomainPaymentMethodWrapper {created_by: None,last_modified_by: None,customer_details: None,+ locker_fingerprint_id: None,}))}}@@ -1555,6 +1560,7 @@ impl TryFrom<CreatePaymentMethodResponse> for DomainPaymentMethodWrapper {created_by: None,last_modified_by: None,customer_details: None,+ locker_fingerprint_id: None,}))}}diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rsindex 584bea687d..018c98c2f0 100644--- a/crates/router/src/core/payment_methods/vault.rs+++ b/crates/router/src/core/payment_methods/vault.rs@@ -1,12 +1,13 @@use common_enums::PaymentMethodType;+#[cfg(feature = "v2")]+use common_utils::encryption::Encryption;use common_utils::{crypto::{DecodeMessage, EncodeMessage, GcmAes256},ext_traits::{BytesExt, Encode},generate_id_with_default_len, id_type,pii::Email,+ request,};-#[cfg(feature = "v2")]-use common_utils::{encryption::Encryption, request};use error_stack::{report, ResultExt};#[cfg(feature = "v2")]use hyperswitch_domain_models::router_flow_types::{@@ -25,27 +26,27 @@ use crate::{consts,core::{errors::{self, ConnectorErrorExt, CustomResult, RouterResult},+ payment_methods::transformers as pm_transforms,payments, utils as core_utils,},- db, logger,+ db, headers, logger,routes::{self, metrics},services::{self, connector_integration_interface::RouterDataConversion},+ settings,types::{- self, api, domain,+ self, api, domain, payment_methods as pm_types,storage::{self, enums},},- utils::StringExt,+ utils::{ConnectorResponseExt, StringExt},};#[cfg(feature = "v2")]use crate::{core::{errors::StorageErrorExt,- payment_methods::{cards as pm_cards, transformers as pm_transforms, utils},+ payment_methods::{cards as pm_cards, utils},payments::{self as payments_core, helpers as payment_helpers},},- headers, settings,- types::payment_methods as pm_types,- utils::{ext_traits::OptionExt, ConnectorResponseExt},+ utils::ext_traits::OptionExt,};const VAULT_SERVICE_NAME: &str = "CARD";@@ -1469,7 +1470,6 @@ pub async fn delete_tokenized_data(}}-#[cfg(feature = "v2")]async fn create_vault_request<R: pm_types::VaultingInterface>(jwekey: &settings::Jwekey,locker: &settings::Locker,@@ -1493,7 +1493,7 @@ async fn create_vault_request<R: pm_types::VaultingInterface>(let mut request = request::Request::new(services::Method::Post, &url);request.add_header(headers::CONTENT_TYPE,- consts::VAULT_HEADER_CONTENT_TYPE.into(),+ consts::V2_VAULT_HEADER_CONTENT_TYPE.into(),);request.add_header(headers::X_TENANT_ID,@@ -1503,7 +1503,6 @@ async fn create_vault_request<R: pm_types::VaultingInterface>(Ok(request)}-#[cfg(feature = "v2")]#[instrument(skip_all)]pub async fn call_to_vault<V: pm_types::VaultingInterface>(state: &routes::SessionState,diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex ed14ec3062..fc6362f97c 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -2949,7 +2949,11 @@ pub async fn fetch_card_details_from_external_vault(}hyperswitch_domain_models::vault::PaymentMethodVaultingData::NetworkToken(_) => {Err(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Network Token not supproted")+ .attach_printable("Network Token not supported")+ }+ hyperswitch_domain_models::vault::PaymentMethodVaultingData::BankDebit(_) => {+ Err(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Bank Debit not supported")}}}diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rsindex 982530cd35..b3b726459c 100644--- a/crates/router/src/core/payments/tokenization.rs+++ b/crates/router/src/core/payments/tokenization.rs@@ -63,7 +63,7 @@ async fn save_in_locker(card_detail: Option<api::CardDetail>,business_profile: &domain::Profile,) -> RouterResult<(- api_models::payment_methods::PaymentMethodResponse,+ domain::PaymentMethodResponse,Option<payment_methods::transformers::DataDuplicationCheck>,)> {match &business_profile.external_vault_details {@@ -495,6 +495,7 @@ wherepm_network_token_data_encrypted,Some(vault_source_details),payment_method_customer_details_encrypted,+ resp.locker_fingerprint_id,).await} else {@@ -614,6 +615,7 @@ wherepm_network_token_data_encrypted,Some(vault_source_details),payment_method_customer_details_encrypted,+ resp.locker_fingerprint_id,).await} else {@@ -838,6 +840,7 @@ wherepm_network_token_data_encrypted,Some(vault_source_details),payment_method_customer_details_encrypted,+ resp.locker_fingerprint_id,).await?;@@ -1022,7 +1025,7 @@ async fn skip_saving_card_in_locker(platform: &domain::Platform,payment_method_request: api::PaymentMethodCreate,) -> RouterResult<(- api_models::payment_methods::PaymentMethodResponse,+ domain::PaymentMethodResponse,Option<payment_methods::transformers::DataDuplicationCheck>,)> {let customer_id = payment_method_request@@ -1062,7 +1065,7 @@ async fn skip_saving_card_in_locker(card_type: card.card_type.clone(),saved_to_locker: false,};- let pm_resp = api::PaymentMethodResponse {+ let pm_resp = domain::PaymentMethodResponse {merchant_id: platform.get_provider().get_account().get_id().to_owned(),customer_id: Some(customer_id),payment_method_id,@@ -1078,13 +1081,14 @@ async fn skip_saving_card_in_locker(bank_transfer: None,last_used_at: Some(common_utils::date_time::now()),client_secret: None,+ locker_fingerprint_id: None,};Ok((pm_resp, None))}None => {let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm");- let payment_method_response = api::PaymentMethodResponse {+ let payment_method_response = domain::PaymentMethodResponse {merchant_id: platform.get_provider().get_account().get_id().to_owned(),customer_id: Some(customer_id),payment_method_id: pm_id,@@ -1100,6 +1104,7 @@ async fn skip_saving_card_in_locker(bank_transfer: None,last_used_at: Some(common_utils::date_time::now()),client_secret: None,+ locker_fingerprint_id: None,};Ok((payment_method_response, None))}@@ -1124,7 +1129,7 @@ pub async fn save_in_locker_internal(payment_method_request: api::PaymentMethodCreate,card_detail: Option<api::CardDetail>,) -> RouterResult<(- api_models::payment_methods::PaymentMethodResponse,+ domain::PaymentMethodResponse,Option<payment_methods::transformers::DataDuplicationCheck>,)> {payment_method_request.validate()?;@@ -1172,7 +1177,7 @@ pub async fn save_in_locker_internal(_ => {let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm");- let payment_method_response = api::PaymentMethodResponse {+ let payment_method_response = domain::PaymentMethodResponse {merchant_id: platform.get_provider().get_account().get_id().clone(),customer_id: Some(customer_id),payment_method_id: pm_id,@@ -1188,6 +1193,7 @@ pub async fn save_in_locker_internal(payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219]last_used_at: Some(common_utils::date_time::now()),client_secret: None,+ locker_fingerprint_id: None,};Ok((payment_method_response, None))}@@ -1202,7 +1208,7 @@ pub async fn save_in_locker_external(card_detail: Option<api::CardDetail>,external_vault_connector_details: &ExternalVaultConnectorDetails,) -> RouterResult<(- api_models::payment_methods::PaymentMethodResponse,+ domain::PaymentMethodResponse,Option<payment_methods::transformers::DataDuplicationCheck>,)> {let customer_id = payment_method_request@@ -1245,7 +1251,7 @@ pub async fn save_in_locker_external(let payment_method_id = vault_response.vault_id.get_single_vault_id()?;let card_detail = CardDetailFromLocker::from(card);- let pm_resp = api::PaymentMethodResponse {+ let pm_resp = domain::PaymentMethodResponse {merchant_id: platform.get_processor().get_account().get_id().to_owned(),customer_id: Some(customer_id),payment_method_id,@@ -1261,13 +1267,14 @@ pub async fn save_in_locker_external(bank_transfer: None,last_used_at: Some(common_utils::date_time::now()),client_secret: None,+ locker_fingerprint_id: None,};Ok((pm_resp, None))} else {//Similar implementation is done for save in locker internallet pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm");- let payment_method_response = api::PaymentMethodResponse {+ let payment_method_response = domain::PaymentMethodResponse {merchant_id: platform.get_processor().get_account().get_id().to_owned(),customer_id: Some(customer_id),payment_method_id: pm_id,@@ -1283,6 +1290,7 @@ pub async fn save_in_locker_external(payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219]last_used_at: Some(common_utils::date_time::now()),client_secret: None,+ locker_fingerprint_id: None,};Ok((payment_method_response, None))}@@ -1322,7 +1330,7 @@ pub async fn save_network_token_in_locker(network_token_data: Option<api::CardDetail>,payment_method_request: api::PaymentMethodCreate,) -> RouterResult<(- Option<api_models::payment_methods::PaymentMethodResponse>,+ Option<domain::PaymentMethodResponse>,Option<payment_methods::transformers::DataDuplicationCheck>,Option<String>,)> {@@ -1801,11 +1809,11 @@ pub async fn save_card_and_network_token_in_locker(business_profile: &domain::Profile,) -> RouterResult<((- api_models::payment_methods::PaymentMethodResponse,+ domain::PaymentMethodResponse,Option<payment_methods::transformers::DataDuplicationCheck>,Option<String>,),- Option<api_models::payment_methods::PaymentMethodResponse>,+ Option<domain::PaymentMethodResponse>,)> {let network_token_requestor_reference_id = payment_method_info.and_then(|pm_info| pm_info.network_token_requestor_reference_id.clone());diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rsindex c7e9190785..7596804f5f 100644--- a/crates/router/src/core/payouts/helpers.rs+++ b/crates/router/src/core/payouts/helpers.rs@@ -653,6 +653,7 @@ pub async fn save_payout_data_to_locker(None,Default::default(),None,+ None,).await?,);diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rsindex 711a42be23..0915027da9 100644--- a/crates/router/src/core/pm_auth.rs+++ b/crates/router/src/core/pm_auth.rs@@ -531,6 +531,7 @@ async fn store_bank_details_in_payment_methods(created_by: None,last_modified_by: None,customer_details: None,+ locker_fingerprint_id: None,};new_entries.push(pm_new);diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex 4201409688..7b024652c2 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -2294,7 +2294,6 @@ impl PaymentMethodInterface for KafkaStore {.await}- #[cfg(feature = "v2")]async fn find_payment_method_by_fingerprint_id(&self,key_store: &domain::MerchantKeyStore,diff --git a/crates/router/src/types/payment_methods.rs b/crates/router/src/types/payment_methods.rsindex 6d337b1cf5..9626d62163 100644--- a/crates/router/src/types/payment_methods.rs+++ b/crates/router/src/types/payment_methods.rs@@ -12,34 +12,40 @@ use hyperswitch_domain_models::payment_method_data::NetworkTokenDetails;use masking::Secret;use serde::{Deserialize, Serialize};-use crate::types::api;#[cfg(feature = "v2")]+use crate::types::storage;use crate::{consts,- types::{domain, storage},+ types::{api, domain},};-#[cfg(feature = "v2")]pub trait VaultingInterface {fn get_vaulting_request_url() -> &'static str;fn get_vaulting_flow_name() -> &'static str;}-#[cfg(feature = "v2")]#[derive(Debug, serde::Deserialize, serde::Serialize)]pub struct VaultFingerprintRequest {pub data: String,pub key: String,}-#[cfg(feature = "v2")]#[derive(Debug, serde::Deserialize, serde::Serialize)]pub struct VaultFingerprintResponse {pub fingerprint_id: String,}-#[cfg(any(feature = "v2", feature = "tokenization_v2"))]+#[cfg(feature = "v1")]+#[derive(Debug, serde::Deserialize, serde::Serialize)]+pub struct AddVaultRequest<D> {+ pub entity_id: hyperswitch_domain_models::vault::V1VaultEntityId,+ pub vault_id: domain::VaultId,+ pub data: D,+ pub ttl: i64,+}++#[cfg(feature = "v2")]#[derive(Debug, serde::Deserialize, serde::Serialize)]pub struct AddVaultRequest<D> {pub entity_id: id_type::GlobalCustomerId,@@ -61,63 +67,63 @@ pub struct AddVaultResponse {pub fingerprint_id: Option<String>,}-#[cfg(feature = "v2")]+#[cfg(feature = "v1")]+#[derive(Debug, serde::Deserialize, serde::Serialize)]+pub struct InternalAddVaultResponse {+ pub entity_id: Option<hyperswitch_domain_models::vault::V1VaultEntityId>,+ pub vault_id: domain::VaultId,+ pub fingerprint_id: Option<String>,+}+#[derive(Debug, serde::Deserialize, serde::Serialize)]pub struct AddVault;-#[cfg(feature = "v2")]#[derive(Debug, serde::Deserialize, serde::Serialize)]pub struct GetVaultFingerprint;-#[cfg(feature = "v2")]#[derive(Debug, serde::Deserialize, serde::Serialize)]pub struct VaultRetrieve;-#[cfg(feature = "v2")]#[derive(Debug, serde::Deserialize, serde::Serialize)]pub struct VaultDelete;-#[cfg(feature = "v2")]impl VaultingInterface for AddVault {fn get_vaulting_request_url() -> &'static str {- consts::ADD_VAULT_REQUEST_URL+ consts::V2_ADD_VAULT_REQUEST_URL}fn get_vaulting_flow_name() -> &'static str {- consts::VAULT_ADD_FLOW_TYPE+ consts::V2_VAULT_ADD_FLOW_TYPE}}-#[cfg(feature = "v2")]impl VaultingInterface for GetVaultFingerprint {fn get_vaulting_request_url() -> &'static str {- consts::VAULT_FINGERPRINT_REQUEST_URL+ consts::V2_VAULT_FINGERPRINT_REQUEST_URL}fn get_vaulting_flow_name() -> &'static str {- consts::VAULT_GET_FINGERPRINT_FLOW_TYPE+ consts::V2_VAULT_GET_FINGERPRINT_FLOW_TYPE}}-#[cfg(feature = "v2")]impl VaultingInterface for VaultRetrieve {fn get_vaulting_request_url() -> &'static str {- consts::VAULT_RETRIEVE_REQUEST_URL+ consts::V2_VAULT_RETRIEVE_REQUEST_URL}fn get_vaulting_flow_name() -> &'static str {- consts::VAULT_RETRIEVE_FLOW_TYPE+ consts::V2_VAULT_RETRIEVE_FLOW_TYPE}}-#[cfg(feature = "v2")]impl VaultingInterface for VaultDelete {fn get_vaulting_request_url() -> &'static str {- consts::VAULT_DELETE_REQUEST_URL+ consts::V2_VAULT_DELETE_REQUEST_URL}fn get_vaulting_flow_name() -> &'static str {- consts::VAULT_DELETE_FLOW_TYPE+ consts::V2_VAULT_DELETE_FLOW_TYPE}}@@ -130,6 +136,13 @@ pub struct SavedPMLPaymentsInfo {pub is_connector_agnostic_mit_enabled: bool,}+#[cfg(feature = "v1")]+#[derive(Debug, serde::Deserialize, serde::Serialize)]+pub struct VaultRetrieveRequest {+ pub entity_id: hyperswitch_domain_models::vault::V1VaultEntityId,+ pub vault_id: domain::VaultId,+}+#[cfg(feature = "v2")]#[derive(Debug, serde::Deserialize, serde::Serialize)]pub struct VaultRetrieveRequest {@@ -137,10 +150,9 @@ pub struct VaultRetrieveRequest {pub vault_id: domain::VaultId,}-#[cfg(feature = "v2")]#[derive(Debug, serde::Deserialize, serde::Serialize)]pub struct VaultRetrieveResponse {- pub data: domain::PaymentMethodVaultingData,+ pub data: hyperswitch_domain_models::vault::PaymentMethodVaultingData,}#[cfg(feature = "v2")]diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rsindex 441d8cc8ff..a7fa3e50aa 100644--- a/crates/router/src/types/transformers.rs+++ b/crates/router/src/types/transformers.rs@@ -117,6 +117,29 @@ impl}}+#[cfg(feature = "v1")]+impl ForeignFrom<domain::PaymentMethodResponse> for payment_methods::PaymentMethodResponse {+ fn foreign_from(domain_payment_method_response: domain::PaymentMethodResponse) -> Self {+ Self {+ merchant_id: domain_payment_method_response.merchant_id,+ customer_id: domain_payment_method_response.customer_id,+ payment_method_id: domain_payment_method_response.payment_method_id,+ payment_method: domain_payment_method_response.payment_method,+ payment_method_type: domain_payment_method_response.payment_method_type,+ card: domain_payment_method_response.card,+ recurring_enabled: domain_payment_method_response.recurring_enabled,+ installment_payment_enabled: domain_payment_method_response.installment_payment_enabled,+ payment_experience: domain_payment_method_response.payment_experience,+ metadata: domain_payment_method_response.metadata,+ created: domain_payment_method_response.created,+ #[cfg(feature = "payouts")]+ bank_transfer: domain_payment_method_response.bank_transfer,+ last_used_at: domain_payment_method_response.last_used_at,+ client_secret: domain_payment_method_response.client_secret,+ }+ }+}+#[cfg(feature = "v2")]implForeignFrom<(diff --git a/crates/storage_impl/src/payment_method.rs b/crates/storage_impl/src/payment_method.rsindex c3c03a0df8..33c0d68c0a 100644--- a/crates/storage_impl/src/payment_method.rs+++ b/crates/storage_impl/src/payment_method.rs@@ -383,7 +383,6 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {}// Check if KV stuff is needed here- #[cfg(feature = "v2")]async fn find_payment_method_by_fingerprint_id(&self,key_store: &MerchantKeyStore,@@ -686,7 +685,6 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {.await}- #[cfg(feature = "v2")]async fn find_payment_method_by_fingerprint_id(&self,key_store: &MerchantKeyStore,@@ -977,7 +975,6 @@ impl PaymentMethodInterface for MockDb {.await}- #[cfg(feature = "v2")]async fn find_payment_method_by_fingerprint_id(&self,key_store: &MerchantKeyStore,diff --git a/migrations/2026-02-04-074421-0000_add_locker_fingerprint_id_to_payment_methods/down.sql b/migrations/2026-02-04-074421-0000_add_locker_fingerprint_id_to_payment_methods/down.sqlnew file mode 100644index 0000000000..961b45daad--- /dev/null+++ b/migrations/2026-02-04-074421-0000_add_locker_fingerprint_id_to_payment_methods/down.sql@@ -0,0 +1,3 @@+-- This file should undo anything in `up.sql`+ALTER TABLE payment_methods+ DROP COLUMN IF EXISTS locker_fingerprint_id;\ No newline at end of filediff --git a/migrations/2026-02-04-074421-0000_add_locker_fingerprint_id_to_payment_methods/up.sql b/migrations/2026-02-04-074421-0000_add_locker_fingerprint_id_to_payment_methods/up.sqlnew file mode 100644index 0000000000..0c4a5ed073--- /dev/null+++ b/migrations/2026-02-04-074421-0000_add_locker_fingerprint_id_to_payment_methods/up.sql@@ -0,0 +1,2 @@+ALTER TABLE payment_methods+ ADD COLUMN IF NOT EXISTS locker_fingerprint_id VARCHAR(64);\ No newline at end of file