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
fix(core): allow request billing to override saved payment method billing (#15059)
Tushar Shukla8c399f9347c3
diff --git a/config/superposition_seed.toml b/config/superposition_seed.tomlindex a7575ce9b9..b039b70d60 100644--- a/config/superposition_seed.toml+++ b/config/superposition_seed.toml@@ -2706,6 +2706,7 @@ pt_mapping_outgoing_connector_webhooks = { value = { default_mapping = { frequen"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" }"payments.should_enable_mit_with_limited_card_data" = { value = false, schema = { type = "boolean" }, description = "Whether to allow merchant-initiated transactions (MIT) with limited card data", change_reason = "Initial setup" }+"payments.should_prefer_request_billing_over_saved_pm_billing" = { value = false, schema = { type = "boolean" }, description = "Whether the top-level billing in a payment request overrides the billing stored on a saved payment method", change_reason = "Initial setup" }"payments.should_perform_eligibility" = { value = false, schema = { type = "boolean" }, description = "Whether the SDK should perform an eligibility check before confirming payment", change_reason = "Initial setup" }"payments.should_return_raw_payment_method_details" = { value = false, schema = { type = "boolean" }, description = "Whether to return raw payment method details (v2 only)", change_reason = "Initial setup" }"card_issuer.list_max_limit" = { value = 18000, schema = { maximum = 4294967295, minimum = 0, type = "integer" }, description = "Maximum number of card issuers the card issuer list endpoint reads", change_reason = "Initial setup" }diff --git a/crates/hyperswitch_domain_models/src/address.rs b/crates/hyperswitch_domain_models/src/address.rsindex 75a4460ed0..a992d821e9 100644--- a/crates/hyperswitch_domain_models/src/address.rs+++ b/crates/hyperswitch_domain_models/src/address.rs@@ -10,6 +10,20 @@ pub struct Address {impl hyperswitch_masking::SerializableSecret for Address {}impl Address {+ /// Whether the address has location details, and not only a name, phone or email+ pub fn has_location_details(&self) -> bool {+ self.address.as_ref().is_some_and(|details| {+ details+ .city+ .as_deref()+ .is_some_and(|city| !city.trim().is_empty())+ || [&details.line1, &details.state, &details.zip]+ .into_iter()+ .flatten()+ .any(|field| !field.peek().trim().is_empty())+ })+ }+/// Unify the address, giving priority to `self` when details are present in bothpub fn unify_address(&self, other: Option<&Self>) -> Self {let other_address_details = other.and_then(|address| address.address.as_ref());@@ -170,3 +184,38 @@ impl From<PhoneDetails> for api_models::payments::PhoneDetails {}}}++#[cfg(test)]+mod tests {+ use super::*;++ fn address_with(details: AddressDetails) -> Address {+ Address {+ address: Some(details),+ phone: None,+ email: None,+ }+ }++ #[test]+ fn has_location_details_is_true_only_for_location_fields() {+ let state_only = AddressDetails {+ state: Some(Secret::new("MB".to_string())),+ ..Default::default()+ };+ let name_only = AddressDetails {+ first_name: Some(Secret::new("Jo".to_string())),+ last_name: Some(Secret::new("Doe".to_string())),+ ..Default::default()+ };+ let blank_state = AddressDetails {+ state: Some(Secret::new(" ".to_string())),+ ..Default::default()+ };++ assert!(address_with(state_only).has_location_details());+ assert!(!address_with(name_only).has_location_details());+ assert!(!address_with(blank_state).has_location_details());+ assert!(!Address::default().has_location_details());+ }+}diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex 5529acf804..d02ef6294b 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -509,6 +509,9 @@ pub mod superposition {/// MIT with limited card data configuration keypub const SHOULD_ENABLE_MIT_WITH_LIMITED_CARD_DATA: &str ="payments.should_enable_mit_with_limited_card_data";+ /// Prefer the request's billing address over the billing stored on a saved payment method+ pub const SHOULD_PREFER_REQUEST_BILLING_OVER_SAVED_PM_BILLING: &str =+ "payments.should_prefer_request_billing_over_saved_pm_billing";/// Store eligibility check data for authentication configuration keypub const SHOULD_STORE_ELIGIBILITY_CHECK_DATA_FOR_AUTHENTICATION: &str ="payments.should_store_eligibility_check_data_for_authentication";diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex d67fa8ace5..cafa6ac852 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -697,6 +697,23 @@ impl DatabaseBackedConfig for ClientSessionValidationEnabled {}}+config! {+ superposition_key = SHOULD_PREFER_REQUEST_BILLING_OVER_SAVED_PM_BILLING,+ output = bool,+ default = false,+ requires = dimension_state::DimensionsWithProcessorAndProviderMerchantId,+ targeting_key = id_type::MerchantId+}++impl DatabaseBackedConfig for ShouldPreferRequestBillingOverSavedPmBilling {+ const KEY: &'static str = "should_prefer_request_billing_over_saved_pm_billing";+ fn db_key(dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {+ dimensions+ .get_processor_merchant_id()+ .map(|id| format!("{}_{}", Self::KEY, id.get_string_repr()))+ }+}+config! {superposition_key = MAX_AUTO_PAYOUT_RETRIES,output = u32,diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 110d9dfe69..99b82c3481 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -134,6 +134,26 @@ use crate::{core::admin as core_admin, headers, types::ConnectorAuthType};#[cfg(feature = "v1")]use crate::{core::utils::create_encrypted_data, types::storage::CustomerUpdate::Update};+/// Whether the billing stored on a saved payment method should be used for this payment.+/// When the merchant is configured to prefer the request's billing, a top-level billing with+/// location details overrides the saved payment method's billing.+#[cfg(feature = "v1")]+pub async fn should_use_saved_payment_method_billing(+ state: &SessionState,+ dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,+ merchant_id: &id_type::MerchantId,+ has_request_billing: bool,+) -> bool {+ !has_request_billing+ || !dimensions+ .get_should_prefer_request_billing_over_saved_pm_billing(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ Some(merchant_id),+ )+ .await+}+/// Use a profile-scoped lookup when authentication supplies a profile, otherwise retain merchant scope.#[cfg(feature = "v1")]pub async fn find_payment_intent(diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex edacd89b3d..3454e4904e 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -614,24 +614,49 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>.instrument(tracing::debug_span!("additional_pm_data")),);+ let use_saved_pm_billing = helpers::should_use_saved_payment_method_billing(+ state,+ dimensions,+ platform.get_processor().get_account().get_id(),+ billing_address+ .as_ref()+ .map(hyperswitch_domain_models::address::Address::from)+ .is_some_and(|billing| billing.has_location_details()),+ )+ .await;+let n_payment_method_billing_address_id =payment_attempt.payment_method_billing_address_id.clone();+ // A payment created with a saved payment method and no billing already has the saved+ // billing persisted on the attempt, so overwrite it with the request billing when that is preferred.+ let should_replace_persisted_saved_billing = !use_saved_pm_billing+ && n_payment_method_billing_address_id.is_some()+ && (request.payment_token.is_some() || payment_attempt.payment_token.is_some());+let n_request_payment_method_billing_address = request.payment_method_data.as_ref().and_then(|pmd| pmd.billing.clone())- .or(payment_method_with_raw_data.clone().and_then(|pm| {- pm.payment_method- .payment_method_billing_address- .clone()- .map(|decrypted_data| decrypted_data.into_inner().expose())- .and_then(|decrypted_value| {- decrypted_value- .parse_value("payment method billing address")- .ok()- })- }));+ .or(payment_method_with_raw_data+ .clone()+ .filter(|_| use_saved_pm_billing)+ .and_then(|pm| {+ pm.payment_method+ .payment_method_billing_address+ .clone()+ .map(|decrypted_data| decrypted_data.into_inner().expose())+ .and_then(|decrypted_value| {+ decrypted_value+ .parse_value("payment method billing address")+ .ok()+ })+ }))+ .or(billing_address+ .as_ref()+ .filter(|_| should_replace_persisted_saved_billing)+ .map(hyperswitch_domain_models::address::Address::from)+ .map(api_models::payments::Address::from));let m_payment_intent_customer_id = payment_intent.customer_id.clone();let m_payment_intent_payment_id = payment_intent.payment_id.clone();let m_key_store = platform.get_processor().get_key_store().clone();@@ -873,18 +898,21 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>payment_method_data_billing.get_billing_address()}).map(From::from);- let pm_pmd_billing = payment_method_info.as_ref().and_then(|pm| {- pm.payment_method_billing_address- .clone()- .map(|decrypted_data| decrypted_data.into_inner().expose())- .and_then(|decrypted_value| {- decrypted_value- .parse_value::<hyperswitch_domain_models::address::Address>(- "payment method billing address",- )- .ok()- })- });+ let pm_pmd_billing = payment_method_info+ .as_ref()+ .filter(|_| use_saved_pm_billing)+ .and_then(|pm| {+ pm.payment_method_billing_address+ .clone()+ .map(|decrypted_data| decrypted_data.into_inner().expose())+ .and_then(|decrypted_value| {+ decrypted_value+ .parse_value::<hyperswitch_domain_models::address::Address>(+ "payment method billing address",+ )+ .ok()+ })+ });// billing address from request body has the highest priority followed by billing address from raw pm data and then billing address from payment_attemptlet pmd_address = payment_method_data_billing.or(pm_pmd_billing);diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rsindex 768bd3e173..cf1116cc1b 100644--- a/crates/router/src/core/payments/operations/payment_create.rs+++ b/crates/router/src/core/payments/operations/payment_create.rs@@ -176,21 +176,36 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>mandate_type.as_ref(),)?;+ let use_saved_pm_billing = helpers::should_use_saved_payment_method_billing(+ state,+ dimensions,+ platform.get_processor().get_account().get_id(),+ request+ .billing+ .clone()+ .map(hyperswitch_domain_models::address::Address::from)+ .is_some_and(|billing| billing.has_location_details()),+ )+ .await;+let payment_method_data_billing = request.payment_method_data.as_ref().and_then(|pmd| pmd.billing.clone())- .or(payment_method_with_raw_data.as_ref().and_then(|pm| {- pm.payment_method- .payment_method_billing_address- .clone()- .map(|decrypted_data| decrypted_data.into_inner().expose())- .and_then(|decrypted_value| {- decrypted_value- .parse_value("payment method billing address")- .ok()- })- }));+ .or(payment_method_with_raw_data+ .as_ref()+ .filter(|_| use_saved_pm_billing)+ .and_then(|pm| {+ pm.payment_method+ .payment_method_billing_address+ .clone()+ .map(|decrypted_data| decrypted_data.into_inner().expose())+ .and_then(|decrypted_value| {+ decrypted_value+ .parse_value("payment method billing address")+ .ok()+ })+ }));// The shipping, billing and payment method billing addresses are independent of each// other, so create them concurrently rather than one after another.@@ -346,6 +361,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>.as_ref().map(|address| address.address_id.clone()),&payment_method_info,+ use_saved_pm_billing,profile_id.clone(),&customer_acceptance,payment_method_recurring_details.clone(),@@ -635,19 +651,22 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>payment_method_data_billing.get_billing_address()}).map(From::from);- let pm_pmd_billing = payment_method_with_raw_data.as_ref().and_then(|pm| {- pm.payment_method- .payment_method_billing_address- .clone()- .map(|decrypted_data| decrypted_data.into_inner().expose())- .and_then(|decrypted_value| {- decrypted_value- .parse_value::<hyperswitch_domain_models::address::Address>(- "payment method billing address",- )- .ok()- })- });+ let pm_pmd_billing = payment_method_with_raw_data+ .as_ref()+ .filter(|_| use_saved_pm_billing)+ .and_then(|pm| {+ pm.payment_method+ .payment_method_billing_address+ .clone()+ .map(|decrypted_data| decrypted_data.into_inner().expose())+ .and_then(|decrypted_value| {+ decrypted_value+ .parse_value::<hyperswitch_domain_models::address::Address>(+ "payment method billing address",+ )+ .ok()+ })+ });let add = payment_method_data_billing.or(pm_pmd_billing);@@ -1469,6 +1488,7 @@ impl PaymentCreate {state: &SessionState,optional_payment_method_billing_address_id: Option<String>,payment_method_info: &Option<domain::PaymentMethod>,+ use_saved_pm_billing: bool,profile_id: common_utils::id_type::ProfileId,customer_acceptance: &Option<common_payments_types::CustomerAcceptance>,payment_method_recurring_details: Option<domain::PaymentMethodData>,@@ -1636,6 +1656,7 @@ impl PaymentCreate {let payment_method_billing_address_id = match optional_payment_method_billing_address_id {None => payment_method_info.as_ref()+ .filter(|_| use_saved_pm_billing).and_then(|pm_info| pm_info.payment_method_billing_address.as_ref()).map(|address| {address.clone().deserialize_inner_value(|value| {