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
perf(payment-methods): pay then vault operations using redis (#13832)
Kashif9dc7e744c6bb
diff --git a/config/superposition_seed.toml b/config/superposition_seed.tomlindex 280caba0ff..369d08bb54 100644--- a/config/superposition_seed.toml+++ b/config/superposition_seed.toml@@ -2672,6 +2672,10 @@ pt_mapping_outgoing_connector_webhooks = { value = { default_mapping = { frequen"vaulting.save_wallet_decrypted_data" = { value = false, schema = { type = "boolean" }, description = "Whether to save wallet decrypted data", change_reason = "Initial setup" }"vaulting.fingerprint_secret" = { value = "", schema = { type = "string" }, description = "Fingerprint secret used as a migration fallback for merchant accounts", change_reason = "Retain during merchant account migration" }"payments.should_call_gsm" = { value = false, schema = { type = "boolean" }, description = "Whether to call GSM (Global Status Mapping) for auto-retries on payment failure", change_reason = "Initial setup" }+"system.payment_method_integration_type" = { value = "vault_then_pay", schema = { enum = [+ "vault_then_pay",+ "pay_then_vault",+] }, description = "When the payment method is written to durable storage: vault_then_pay vaults at session confirm, pay_then_vault vaults only after the payment is acknowledged", change_reason = "Initial setup" }"system.should_call_pm_modular_service" = { value = false, schema = { type = "boolean" }, description = "Whether to call the PM modular service for a provider merchant, with organization fallback", change_reason = "Initial setup" }"vaulting.should_disable_vault_tokenization" = { value = false, schema = { type = "boolean" }, description = "Whether to disable vault tokenization for a merchant", change_reason = "Initial setup" }"system.should_enable_authentication_service" = { value = false, schema = { type = "boolean" }, description = "Whether a merchant/org is eligible for the unified authentication service, with organization taking precedence over merchant", change_reason = "Initial setup" }diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex 90e70d8dcb..8efaea035e 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -489,6 +489,8 @@ pub mod superposition {/// Trigger PM modular backward compatibility inline configuration keypub const SHOULD_TRIGGER_BACKWARDS_COMPATIBILITY_INLINE: &str ="system.should_trigger_backwards_compatibility_inline";+ /// Payment method integration type configuration key+ pub const PAYMENT_METHOD_INTEGRATION_TYPE: &str = "system.payment_method_integration_type";/// Trigger fingerprint migration configuration keypub const SHOULD_TRIGGER_FINGERPRINT_MIGRATION: &str ="vaulting.should_trigger_fingerprint_migration";diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex 6da57fce6f..3877cacade 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -6,7 +6,10 @@ use external_services::superposition;use scheduler::consumer::types::process_data::RetryMapping;use super::{dimension_state, fetch_db_config_for_dimensions, ConfigContext, DatabaseBackedConfig};-use crate::{consts::superposition as superposition_consts, db::StorageInterface, utils::id_type};+use crate::{+ consts::superposition as superposition_consts, db::StorageInterface,+ types::payment_methods as pm_types, utils::id_type,+};/// Macro to generate config struct and superposition::Config trait implementation./// Note: Manually implement `DatabaseBackedConfig` for the config struct:@@ -423,6 +426,25 @@ impl DatabaseBackedConfig for ShouldCallPmModularService {}}+config! {+ superposition_key = PAYMENT_METHOD_INTEGRATION_TYPE,+ output = pm_types::PaymentMethodIntegrationType,+ default = pm_types::PaymentMethodIntegrationType::VaultThenPay,+ string_enum = true,+ requires = dimension_state::DimensionsWithProviderMerchantIdAndOrgId,+ targeting_key = id_type::CustomerId+}++impl DatabaseBackedConfig for PaymentMethodIntegrationType {+ const KEY: &'static str = "payment_method_integration_type";++ fn db_key(dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {+ dimensions+ .get_organization_id()+ .map(|id| format!("{}_{}", Self::KEY, id.get_string_repr()))+ }+}+config! {superposition_key = SHOULD_SCHEDULE_MODULAR_FORWARD_COMPAT,output = bool,diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex 745a90bf79..6b2da8dfee 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -1782,6 +1782,7 @@ pub async fn create_payment_method(req,platform,profile,+ None,)).await?;@@ -1795,10 +1796,19 @@ pub async fn create_payment_method_core(req: api::PaymentMethodCreate,platform: &domain::Platform,profile: &domain::Profile,+ customer_acceptance: Option<common_utils::pii::SecretSerdeValue>,) -> RouterResult<(api::PaymentMethodResponse, domain::PaymentMethod)> {match req.storage_type {common_enums::StorageType::Volatile => {- create_volatile_payment_method_core(state, _request_state, req, platform, profile).await+ create_volatile_payment_method_core(+ state,+ _request_state,+ req,+ platform,+ profile,+ customer_acceptance,+ )+ .await}common_enums::StorageType::Persistent => {create_persistent_payment_method_core(state, _request_state, req, platform, profile)@@ -1926,6 +1936,7 @@ pub async fn create_volatile_payment_method_core(req: api::PaymentMethodCreate,platform: &domain::Platform,profile: &domain::Profile,+ customer_acceptance: Option<common_utils::pii::SecretSerdeValue>,) -> RouterResult<(api::PaymentMethodResponse, domain::PaymentMethod)> {req.validate()?;@@ -1983,6 +1994,7 @@ pub async fn create_volatile_payment_method_core(&customer_id,payment_method_id,payment_method_billing_address,+ customer_acceptance,)).await}@@ -2271,22 +2283,36 @@ impl LockerOperations for GenericLocker {) -> RouterResult<PaymentMethodResolver> {let db = &*state.store;- let (fingerprint_id_result, auxiliary_fingerprint_id_result) = tokio::join!(- vault::get_fingerprint_id_for_payment_method(- state,- &payment_method_data,- customer_id.get_string_repr().to_owned(),- ),- vault::get_auxiliary_fingerprint_id_for_payment_method(- state,- &payment_method_data,- customer_id.get_string_repr().to_owned(),- ),- );+ // The auxiliary fingerprint runs as its own task so it never sits in front of the+ // primary one, and is awaited only when the primary lookup misses.+ let auxiliary_fingerprint_task = {+ use router_env::tracing::Instrument;- let fingerprint_id = fingerprint_id_result- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to get fingerprint_id from vault using generic strategy")?;+ let state = state.clone();+ let payment_method_data = payment_method_data.clone();+ let customer_id = customer_id.get_string_repr().to_owned();+ tokio::spawn(+ async move {+ vault::get_auxiliary_fingerprint_id_for_payment_method(+ &state,+ &payment_method_data,+ customer_id,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ }+ .in_current_span(),+ )+ };++ let fingerprint_id = vault::get_fingerprint_id_for_payment_method(+ state,+ &payment_method_data,+ customer_id.get_string_repr().to_owned(),+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to get fingerprint_id from vault using generic strategy")?;match db.find_payment_method_by_fingerprint_id(@@ -2338,11 +2364,12 @@ impl LockerOperations for GenericLocker {logger::debug!("Payment method not found, falling back to creation");- let auxiliary_fingerprint_id = auxiliary_fingerprint_id_result+ let auxiliary_fingerprint_id = auxiliary_fingerprint_task+ .await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to get auxiliary fingerprint_id from vault using generic strategy",- )?;+ )??;let locker_resolver = LockerTypeResolver {locker_type: LockerType::Generic,@@ -3261,8 +3288,8 @@ pub async fn create_generic_volatile_payment_method(payment_method_billing_address: Option<Encryptable<hyperswitch_domain_models::address::Address>,>,+ customer_acceptance: Option<common_utils::pii::SecretSerdeValue>,) -> RouterResult<(api::PaymentMethodResponse, domain::PaymentMethod)> {- let db = &*state.store;let keymanager_state = &(state).into();let merchant_key_store = platform.get_provider().get_key_store();@@ -3275,6 +3302,56 @@ pub async fn create_generic_volatile_payment_method(.or(req.payment_method_subtype);let payment_method_data = bin_enriched_payment_method_data.data;+ // Fingerprint only for a `PayThenVault` flow with a customer present and customer acceptance:+ // the acceptance reaches this workflow from session confirm under `PayThenVault` alone.+ let (payment_method_id, fingerprint_details) = match customer_id+ .as_ref()+ .filter(|_| customer_acceptance.is_some())+ {+ Some(customer_id) => {+ let resolution = payment_method_resolver(+ state,+ platform,+ customer_id,+ &req,+ payment_method_data.clone(),+ )+ .await+ .attach_printable("Failed to resolve volatile payment method")?;++ match resolution.0 {+ PaymentMethodResolution::Get(existing_payment_method) => (+ existing_payment_method.id.clone(),+ Some(FingerprintDetails {+ fingerprint_id: existing_payment_method.locker_fingerprint_id.clone(),+ auxiliary_fingerprint_id: existing_payment_method+ .auxiliary_fingerprint_id+ .clone(),+ }),+ ),+ PaymentMethodResolution::Update {+ fingerprint_id,+ payment_method_id: existing_payment_method_id,+ payment_method: existing_payment_method,+ ..+ } => (+ existing_payment_method_id,+ Some(FingerprintDetails {+ fingerprint_id,+ auxiliary_fingerprint_id: existing_payment_method+ .auxiliary_fingerprint_id+ .clone(),+ }),+ ),+ PaymentMethodResolution::Create {+ fingerprint_details,+ ..+ } => (payment_method_id, fingerprint_details),+ }+ }+ None => (payment_method_id, None),+ };+let vaulting_result = vault_payment_method_in_volatile_storage(state,&payment_method_data,@@ -3295,6 +3372,16 @@ pub async fn create_generic_volatile_payment_method(external_vault_source,)) => {let locker_id = Some(vault_id.clone());++ // A resolved fingerprint replaces the one the volatile vault produced.+ let (locker_fingerprint_id, auxiliary_fingerprint_id) = match fingerprint_details {+ Some(fingerprint_details) => (+ fingerprint_details.fingerprint_id,+ fingerprint_details.auxiliary_fingerprint_id,+ ),+ None => (fingerprint_id, None),+ };+let payment_method = construct_payment_method_object(req.metadata.clone(),customer_id,@@ -3307,17 +3394,21 @@ pub async fn create_generic_volatile_payment_method(Some(req.payment_method_type),payment_method_subtype,locker_id,- fingerprint_id,+ locker_fingerprint_id,+ auxiliary_fingerprint_id,external_vault_source,+ customer_acceptance,platform.get_initiator(),).await- .attach_printable("failed to construct payment method")?- .convert()- .await- .change_context(errors::StorageError::EncryptionError)- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to convert payment method")?; //Convert to storage model payment method to store in redis+ .attach_printable("failed to construct payment method")?;++ let payment_method = payment_method+ .convert()+ .await+ .change_context(errors::StorageError::EncryptionError)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to convert payment method")?; //Convert to storage model payment method to store in redislet redis_connection = state.store@@ -4686,7 +4777,9 @@ pub async fn construct_payment_method_object(payment_method_subtype: Option<common_enums::PaymentMethodType>,locker_id: Option<domain::VaultId>,locker_fingerprint_id: Option<String>,+ auxiliary_fingerprint_id: Option<String>,external_vault_source: Option<id_type::MerchantConnectorAccountId>,+ customer_acceptance: Option<common_utils::pii::SecretSerdeValue>,initiator: Option<&domain::Initiator>,) -> RouterResult<domain::PaymentMethod> {let current_time = common_utils::date_time::now();@@ -4724,7 +4817,7 @@ pub async fn construct_payment_method_object(payment_method_subtype,payment_method_data: encrypted_payment_method_data,connector_mandate_details: None,- customer_acceptance: None,+ customer_acceptance,client_secret: None,status: enums::PaymentMethodStatus::New,network_transaction_id: None,@@ -4746,7 +4839,7 @@ pub async fn construct_payment_method_object(last_modified_by: initiator.and_then(|initiator| initiator.to_created_by()),customer_details: None,network_tokenization_data: None,- auxiliary_fingerprint_id: None,+ auxiliary_fingerprint_id,compatibility_updated_at: None,})}@@ -6696,6 +6789,35 @@ pub async fn update_payment_method_core(existing_payment_method: Option<domain::PaymentMethod>,network_tokenization_resp: Option<NetworkTokenPaymentMethodDetails>,) -> RouterResult<(api::PaymentMethodResponse, domain::PaymentMethod)> {+ // `PayThenVault` defers vaulting to the acknowledgement, so this update is what writes the+ // card to the vault and the database. Both update endpoints reach this point.+ let volatile_payment_method = if request.status == Some(enums::PaymentMethodStatus::Active)+ && resolve_payment_method_integration_type(state, platform).await+ == pm_types::PaymentMethodIntegrationType::PayThenVault+ {+ fetch_volatile_payment_method_record(+ state,+ platform.get_provider().get_key_store(),+ payment_method_id.get_string_repr(),+ )+ .await+ .inspect_err(|error| {+ logger::info!(?error, "No volatile payment method found to promote");+ })+ .ok()+ // The acceptance the record was written with is what marks it for promotion, and there+ // has to be a customer to attach the card to. Without either the card was only ever meant+ // to last for this payment, whichever endpoint asks for the acknowledgement.+ .filter(|volatile_payment_method| {+ volatile_payment_method.customer_acceptance.is_some()+ && volatile_payment_method.customer_id.is_some()+ })+ } else {+ None+ };++ let is_promotion = volatile_payment_method.is_some();+let mut handler = match existing_payment_method {Some(payment_method) => {let handler = pm_types::PaymentMethodUpdateHandler {@@ -6703,6 +6825,7 @@ pub async fn update_payment_method_core(profile,request,payment_method,+ insert_promoted_record: false,state,};handler.validate()?;@@ -6714,16 +6837,38 @@ pub async fn update_payment_method_core(profile,request,payment_method_id,+ volatile_payment_method,).await.attach_printable("Failed to generate PaymentMethodUpdateHandler")?,};- Box::pin(execute_payment_method_update_handler(+ let (response, payment_method) = Box::pin(execute_payment_method_update_handler(&mut handler,network_tokenization_resp,))- .await+ .await?;++ // A volatile copy left in redis is read in preference to the row that now holds the card.+ if is_promotion {+ let deleted = state+ .store+ .get_redis_conn()+ .map_err(Into::<errors::StorageError>::into)+ .async_and_then(|redis_connection| async move {+ redis_connection+ .delete_key(&payment_method_id.get_string_repr().into())+ .await+ .map_err(Into::<errors::StorageError>::into)+ })+ .await;++ if let Err(error) = deleted {+ logger::warn!(?error, "Failed to delete the volatile payment method copy");+ }+ }++ Ok((response, payment_method))}#[cfg(feature = "v2")]@@ -6981,6 +7126,25 @@ impl EncryptableData for payment_methods::PaymentMethodsSessionUpdateRequest {}}+/// Resolves the merchant's payment-method integration type, defaulting to `VaultThenPay`.+#[cfg(feature = "v2")]+async fn resolve_payment_method_integration_type(+ state: &SessionState,+ platform: &domain::Platform,+) -> pm_types::PaymentMethodIntegrationType {+ let dimensions = dimension_state::Dimensions::new()+ .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id())+ .with_organization_id(+ platform+ .get_provider()+ .get_account()+ .organization_id+ .clone(),+ );++ utils::get_payment_method_integration_type(state, &dimensions, None).await+}+#[cfg(feature = "v2")]pub async fn payment_methods_session_create(state: SessionState,@@ -7663,6 +7827,24 @@ pub async fn payment_methods_session_confirm(common_enums::StorageType::Volatile};+ // `PayThenVault` writes the card to volatile storage instead, carrying the acceptance that+ // marks it for promotion once the payment goes through.+ let (storage_type, customer_acceptance) =+ match resolve_payment_method_integration_type(&state, &platform).await {+ pm_types::PaymentMethodIntegrationType::PayThenVault => {+ let customer_acceptance = request+ .customer_acceptance+ .as_ref()+ .map(|customer_acceptance| customer_acceptance.encode_to_value())+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to encode payment method customer acceptance")?+ .map(Secret::new);+ (common_enums::StorageType::Volatile, customer_acceptance)+ }+ pm_types::PaymentMethodIntegrationType::VaultThenPay => (storage_type, None),+ };+let create_payment_method_request = get_payment_method_create_request(request.payment_method_data@@ -7684,6 +7866,7 @@ pub async fn payment_methods_session_confirm(create_payment_method_request.clone(),&platform,&profile,+ customer_acceptance,)).await?;@@ -8012,6 +8195,7 @@ impl<'a> pm_types::PaymentMethodUpdateHandler<'a> {profile: &'a domain::Profile,request: DomainPaymentMethodUpdate,payment_method_id: &'a id_type::GlobalPaymentMethodId,+ volatile_payment_method: Option<domain::PaymentMethod>,) -> RouterResult<Self> {let payment_method = state.store@@ -8020,14 +8204,29 @@ impl<'a> pm_types::PaymentMethodUpdateHandler<'a> {payment_method_id,platform.get_provider().get_account().storage_scheme,)- .await- .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;+ .await;++ let (payment_method, insert_promoted_record) =+ match (payment_method, volatile_payment_method) {+ (Ok(payment_method), _) => (payment_method, false),+ (Err(error), Some(volatile_payment_method))+ if error.current_context().is_db_not_found() =>+ {+ (volatile_payment_method, true)+ }+ (Err(error), _) => (+ Err(error)+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?,+ false,+ ),+ };let handler = Self {platform,profile,request,payment_method,+ insert_promoted_record,state,};handler.validate()?;@@ -8195,43 +8394,130 @@ impl<'a> pm_types::PaymentMethodUpdateHandler<'a> {let db = self.state.store.as_ref();- let pm_update = create_pm_additional_data_update(- vault_request_data.as_ref(),- self.state,- self.platform.get_provider().get_key_store(),- vault_resp- .as_ref()- .map(|resp| resp.vault_id.get_string_repr().to_owned()),- vault_resp- .as_ref()- .and_then(|resp| resp.fingerprint_id.clone()),- &self.payment_method,- self.request.connector_token_details.clone(),- self.request.network_transaction_id.clone(),- network_tokenization_resp,- None,- None,- None,- pm_status,- self.platform.get_initiator(),- )- .await- .attach_printable("Unable to create Payment method data")?;+ // A promoted card has only ever been in redis: this is where it reaches the vault, and its+ // response is written with the row below rather than by a second pass over it.+ let (vault_request_data, vault_resp) = match self.insert_promoted_record {+ true => {+ let customer_id = self+ .payment_method+ .customer_id+ .clone()+ .get_required_value("GlobalCustomerId")?;- let updated_payment_method = db- .update_payment_method(- self.platform.get_provider().get_key_store(),- self.payment_method.clone(),- pm_update,- self.platform.get_provider().get_account().storage_scheme,- Some(payment_method_modular_backward_compat_action(+ let vaulting_data = vault::retrieve_volatile_payment_method_from_redis(self.state,- &self.platform.get_provider().get_account().organization_id,- )),- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to update payment method in db")?;+ self.platform.get_provider().get_key_store(),+ &self.payment_method,+ )+ .await+ .attach_printable("Failed to retrieve the volatile card from redis")?+ .data;++ let (vault_response, _external_vault_source) = Box::pin(vault_payment_method(+ self.state,+ &vaulting_data,+ self.platform,+ self.profile,+ None,+ self.payment_method.locker_fingerprint_id.clone(),+ &customer_id,+ Some(pm_types::WriteMode::Insert),+ ))+ .await+ .attach_printable("Failed to vault the payment method being promoted")?;++ (Some(vaulting_data), Some(vault_response))+ }+ false => (vault_request_data, vault_resp),+ };++ let updated_payment_method = match self.insert_promoted_record {+ // The record has only ever lived in redis, and already carries the card, the+ // fingerprints and the acceptance. Writing the vault id and the connector+ // artefacts with it is what avoids an insert followed by an update. Network+ // tokenization is scheduled separately and never arrives here.+ true => {+ let payment_method = domain::PaymentMethod {+ locker_id: vault_resp+ .as_ref()+ .map(|vault_resp| vault_resp.vault_id.clone()),+ locker_fingerprint_id: vault_resp+ .as_ref()+ .and_then(|vault_resp| vault_resp.fingerprint_id.clone())+ .or_else(|| self.payment_method.locker_fingerprint_id.clone()),+ status: pm_status.unwrap_or(self.payment_method.status),+ connector_mandate_details: self+ .request+ .connector_token_details+ .clone()+ .map(|connector_token_details| {+ create_connector_token_details_update(+ connector_token_details,+ &self.payment_method,+ )+ })+ .or_else(|| self.payment_method.connector_mandate_details.clone()),+ network_transaction_id: self+ .request+ .network_transaction_id+ .clone()+ .map(|network_transaction_id| network_transaction_id.expose())+ .or_else(|| self.payment_method.network_transaction_id.clone()),+ ..self.payment_method.clone()+ };++ db.insert_payment_method(+ self.platform.get_provider().get_key_store(),+ payment_method,+ self.platform.get_provider().get_account().storage_scheme,+ Some(payment_method_modular_backward_compat_action(+ self.state,+ &self.platform.get_provider().get_account().organization_id,+ )),+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to persist the promoted payment method in db")?+ }+ false => {+ let pm_update = create_pm_additional_data_update(+ vault_request_data.as_ref(),+ self.state,+ self.platform.get_provider().get_key_store(),+ vault_resp+ .as_ref()+ .map(|resp| resp.vault_id.get_string_repr().to_owned()),+ vault_resp+ .as_ref()+ .and_then(|resp| resp.fingerprint_id.clone()),+ &self.payment_method,+ self.request.connector_token_details.clone(),+ self.request.network_transaction_id.clone(),+ network_tokenization_resp,+ None,+ None,+ None,+ pm_status,+ self.platform.get_initiator(),+ )+ .await+ .attach_printable("Unable to create Payment method data")?;++ db.update_payment_method(+ self.platform.get_provider().get_key_store(),+ self.payment_method.clone(),+ pm_update,+ self.platform.get_provider().get_account().storage_scheme,+ Some(payment_method_modular_backward_compat_action(+ self.state,+ &self.platform.get_provider().get_account().organization_id,+ )),+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to update payment method in db")?+ }+ };self.payment_method = updated_payment_method;Ok(())diff --git a/crates/router/src/core/payment_methods/utils.rs b/crates/router/src/core/payment_methods/utils.rsindex 8198c953a7..00bbf4ea92 100644--- a/crates/router/src/core/payment_methods/utils.rs+++ b/crates/router/src/core/payment_methods/utils.rs@@ -19,7 +19,10 @@ use kgraph_utils::{error::KgraphError, transformers::IntoDirValue};use router_env::logger;use storage_impl::redis::cache::{CacheKey, PM_FILTERS_CGRAPH_CACHE};-use crate::{configs::settings, core::configs::dimension_state, routes::SessionState};+use crate::{+ configs::settings, core::configs::dimension_state, routes::SessionState,+ types::payment_methods as pm_types,+};#[cfg(feature = "v2")]use crate::{db::{@@ -829,6 +832,21 @@ pub async fn get_should_call_pm_modular_service(.await}+/// Resolves when the payment method is written to durable storage.+pub async fn get_payment_method_integration_type(+ state: &SessionState,+ dimensions: &dimension_state::DimensionsWithProviderMerchantIdAndOrgId,+ customer_id: Option<&common_utils::id_type::CustomerId>,+) -> pm_types::PaymentMethodIntegrationType {+ dimensions+ .get_payment_method_integration_type(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ customer_id,+ )+ .await+}+pub async fn get_should_perform_sdk_vaulting(state: &SessionState,dimensions: &dimension_state::DimensionsWithOrgId,diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex a72d3d9b41..4f7677c7e5 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -12188,7 +12188,11 @@ whereD: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,{let has_token_data = payment_data.get_token_data().is_some();- let is_token_data_present = has_token_data || is_payment_method_modular_allowed;+ let is_volatile_payment_method = payment_data+ .get_payment_method_info()+ .is_some_and(domain::PaymentMethod::is_pm_volatile);+ let is_token_data_present =+ has_token_data || (is_payment_method_modular_allowed && !is_volatile_payment_method);match (payment_data.get_payment_intent().setup_future_usage,diff --git a/crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs b/crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rsindex df0c80ca8f..794276614e 100644--- a/crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs+++ b/crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs@@ -392,6 +392,7 @@ impl<F: Clone + Send + Sync> Domain<F, ExternalVaultProxyPaymentsRequest, Paymenreq,platform,business_profile,+ None,)).await?;diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rsindex bcd689ce28..17bb548e65 100644--- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs+++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs@@ -653,6 +653,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsConfirmIntentRequest, PaymentConfreq,platform,business_profile,+ None,).boxed().await?;diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rsindex 09ec9fd709..ed1d140f98 100644--- a/crates/router/src/core/payments/operations/payment_response.rs+++ b/crates/router/src/core/payments/operations/payment_response.rs@@ -213,17 +213,19 @@ where);if is_eligible_pm {- let is_volatile = payment_data+ // A volatile record with no customer is a guest flow: it is never promoted out of redis,+ // so there is nothing for the modular update to acknowledge.+ let is_guest_volatile_payment_method = payment_data.get_payment_method_info()- .map(|pm| pm.is_pm_volatile());+ .is_some_and(|pm| pm.is_pm_volatile() && pm.customer_id.is_none());let payment_method_id = payment_data.payment_method_info.as_ref().map(|pm_info| pm_info.get_id().clone());- match (is_volatile, payment_method_id) {- (Some(false), Some(pm_id)) => {+ match (is_guest_volatile_payment_method, payment_method_id) {+ (false, Some(pm_id)) => {let should_update = resp.status.should_update_payment_method();let payment_method_type = payment_data@@ -393,11 +395,11 @@ where}}}- (is_volatile, payment_method_id) => {+ (is_guest_volatile_payment_method, payment_method_id) => {logger::info!(- ?is_volatile,+ ?is_guest_volatile_payment_method,?payment_method_id,- "Payment method is not eligible for modular update (volatile, or no payment method attached)"+ "Payment method is not eligible for modular update (guest volatile flow, or no payment method attached)");}}diff --git a/crates/router/src/types/payment_methods.rs b/crates/router/src/types/payment_methods.rsindex 0f47692d78..6a50b1c744 100644--- a/crates/router/src/types/payment_methods.rs+++ b/crates/router/src/types/payment_methods.rs@@ -13,12 +13,12 @@ use hyperswitch_masking::Secret;use router_env::logger;use serde::{Deserialize, Serialize};-#[cfg(feature = "v2")]-use crate::types::storage;use crate::{consts,types::{api, domain},};+#[cfg(feature = "v2")]+use crate::{routes::app::SessionState, types::storage};pub trait VaultingInterface {fn get_vaulting_request_url() -> &'static str;@@ -568,11 +568,25 @@ impl From<WriteMode> for VaultQueryParam {}}+/// Determines when a payment method is written to durable storage relative to the payment.+#[derive(+ Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize, strum::Display, strum::EnumString,+)]+#[serde(rename_all = "snake_case")]+#[strum(serialize_all = "snake_case")]+pub enum PaymentMethodIntegrationType {+ /// Vault the card at session confirm, before the payment is attempted.+ VaultThenPay,+ /// Vault the card only once the payment has been acknowledged.+ PayThenVault,+}+#[cfg(feature = "v2")]pub struct PaymentMethodUpdateHandler<'a> {pub platform: &'a hyperswitch_domain_models::platform::Platform,pub profile: &'a hyperswitch_domain_models::business_profile::Profile,pub request: hyperswitch_domain_models::payment_methods::PaymentMethodUpdate,pub payment_method: hyperswitch_domain_models::payment_methods::PaymentMethod,- pub state: &'a crate::routes::app::SessionState,+ pub insert_promoted_record: bool,+ pub state: &'a SessionState,}