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
refactor(payment-methods): reuse customer acceptance from payment confirm for PtV integration (#14582)
Kashif997ed67df249
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex 7bfd63e5e2..e529690b60 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -25288,6 +25288,14 @@}],"nullable": true+ },+ "customer_acceptance": {+ "allOf": [+ {+ "$ref": "#/components/schemas/CustomerAcceptance"+ }+ ],+ "nullable": true}}},diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex a6f9bb921b..01950b6510 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -584,6 +584,10 @@ pub struct PaymentMethodUpdate {/// The acknowledgement status of the payment method update, this is used to determine the status of the payment method update#[schema(value_type = Option<AcknowledgementStatus>)]pub acknowledgement_status: Option<common_enums::AcknowledgementStatus>,++ /// Customer's acceptance for vaulting a payment method.+ #[schema(value_type = Option<CustomerAcceptance>)]+ pub customer_acceptance: Option<common_types::payments::CustomerAcceptance>,}#[cfg(feature = "v2")]diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rsindex 35e1ea6928..4747fb704c 100644--- a/crates/hyperswitch_domain_models/src/payment_methods.rs+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs@@ -345,6 +345,7 @@ pub struct PaymentMethodUpdate {pub connector_token_details: Option<payment_methods::ConnectorTokenDetails>,pub network_transaction_id: Option<Secret<String>>,pub acknowledgement_status: Option<common_enums::AcknowledgementStatus>,+ pub customer_acceptance: Option<common_types::payments::CustomerAcceptance>,pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,pub source_payment_method_data: Option<crate::vault::PaymentMethodVaultingData>,pub status: Option<common_enums::PaymentMethodStatus>,@@ -358,6 +359,7 @@ impl From<payment_methods::PaymentMethodUpdate> for PaymentMethodUpdate {connector_token_details: value.connector_token_details,network_transaction_id: value.network_transaction_id,acknowledgement_status: value.acknowledgement_status,+ customer_acceptance: value.customer_acceptance,network_tokenization: None,source_payment_method_data: None,status: value.acknowledgement_status.map(|ack| ack.into()),@@ -367,6 +369,17 @@ impl From<payment_methods::PaymentMethodUpdate> for PaymentMethodUpdate {#[cfg(feature = "v2")]impl PaymentMethodUpdate {+ /// A payment acknowledgement can save a volatile card only with payment-confirm consent+ /// and a customer to attach it to. Acceptance on the volatile record is not consulted.+ pub fn can_promote_volatile_payment_method(+ &self,+ customer_id: Option<&id_type::GlobalCustomerId>,+ ) -> bool {+ self.status == Some(common_enums::PaymentMethodStatus::Active)+ && self.customer_acceptance.is_some()+ && customer_id.is_some()+ }+pub fn fetch_card_cvc_update(&self) -> Option<Secret<String>> {match &self.payment_method_data {Some(payment_methods::PaymentMethodUpdateData::Card(card_update)) => {@@ -445,6 +458,7 @@ implconnector_token_details: None,network_transaction_id: None,acknowledgement_status: None,+ customer_acceptance: None,network_tokenization: req.network_tokenization.clone(),source_payment_method_data: Some(source_payment_method_data),status: None,diff --git a/crates/payment_methods/src/client/update.rs b/crates/payment_methods/src/client/update.rsindex 6b8c0b572b..1e16fbb80f 100644--- a/crates/payment_methods/src/client/update.rs+++ b/crates/payment_methods/src/client/update.rs@@ -41,6 +41,7 @@ pub struct UpdatePaymentMethodV1Payload {pub network_transaction_id: Option<Secret<String>>,pub acknowledgement_status: Option<common_enums::AcknowledgementStatus>,+ pub customer_acceptance: Option<common_types::payments::CustomerAcceptance>,}/// Modular service update request payload.@@ -54,6 +55,7 @@ pub struct ModularPMUpdateRequest {pub network_transaction_id: Option<Secret<String>>,pub acknowledgement_status: Option<common_enums::AcknowledgementStatus>,+ pub customer_acceptance: Option<common_types::payments::CustomerAcceptance>,}/// Payment method update data.@@ -128,6 +130,7 @@ impl TryFrom<&UpdatePaymentMethodV1Request> for ModularPMUpdateRequest {connector_token_details: value.payload.connector_token_details.clone(),network_transaction_id: value.payload.network_transaction_id.clone(),acknowledgement_status: value.payload.acknowledgement_status,+ customer_acceptance: value.payload.customer_acceptance.clone(),})}}diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex 318c16fb31..e6ac806bb7 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -3328,55 +3328,57 @@ 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 {+ // Resolve existing cards for PayThenVault before returning the payment method id. Consent+ // is collected during payment confirmation and does not gate fingerprint resolution.+ let should_resolve_fingerprint = customer_acceptance.is_some()+ || (customer_id.is_some()+ && resolve_payment_method_integration_type(state, platform).await+ == pm_types::PaymentMethodIntegrationType::PayThenVault);+ let (payment_method_id, fingerprint_details) =+ match customer_id.as_ref().filter(|_| should_resolve_fingerprint) {+ 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,- auxiliary_fingerprint_id: existing_payment_method- .auxiliary_fingerprint_id- .clone(),- }),- ),- PaymentMethodResolution::Create {- fingerprint_details,- ..- } => (payment_method_id, fingerprint_details),+ 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),- };+ None => (payment_method_id, None),+ };let vaulting_result = vault_payment_method_in_volatile_storage(state,@@ -6881,70 +6883,105 @@ pub async fn update_payment_method_core(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();+ // Session acceptance (including that on older Redis records) is not authorization+ // to save. The payment acknowledgement must carry acceptance and a customer.+ match volatile_payment_method {+ Some(payment_method)+ if !request+ .can_promote_volatile_payment_method(payment_method.customer_id.as_ref()) =>+ {+ let response = pm_transforms::generate_payment_method_response(+ &payment_method,+ &None,+ common_enums::StorageType::Volatile,+ None,+ payment_method.customer_id.clone(),+ None,+ payment_method+ .payment_method_billing_address+ .clone()+ .map(|billing| billing.get_inner().clone().into()),+ request.acknowledgement_status,+ )?;+ Ok((response, payment_method))+ }+ volatile_payment_method => {+ let volatile_payment_method = match volatile_payment_method {+ Some(mut payment_method) => {+ payment_method.customer_acceptance = request+ .customer_acceptance+ .as_ref()+ .map(|acceptance| acceptance.encode_to_value())+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to encode payment confirmation customer acceptance",+ )?+ .map(Secret::new);+ Some(payment_method)+ }+ None => None,+ };- let mut handler = match existing_payment_method {- Some(payment_method) => {- let handler = pm_types::PaymentMethodUpdateHandler {- platform,- profile,- request,- payment_method,- insert_promoted_record: false,- state,+ let is_promotion = volatile_payment_method.is_some();++ let mut handler = match existing_payment_method {+ Some(payment_method) => {+ let handler = pm_types::PaymentMethodUpdateHandler {+ platform,+ profile,+ request,+ payment_method,+ insert_promoted_record: false,+ state,+ };+ handler.validate()?;+ handler+ }+ None => pm_types::PaymentMethodUpdateHandler::generate(+ state,+ platform,+ profile,+ request,+ payment_method_id,+ volatile_payment_method,+ )+ .await+ .attach_printable("Failed to generate PaymentMethodUpdateHandler")?,};- handler.validate()?;- handler- }- None => pm_types::PaymentMethodUpdateHandler::generate(- state,- platform,- profile,- request,- payment_method_id,- volatile_payment_method,- )- .await- .attach_printable("Failed to generate PaymentMethodUpdateHandler")?,- };- let (response, payment_method) = Box::pin(execute_payment_method_update_handler(- &mut handler,- network_tokenization_resp,- ))- .await?;+ let (response, payment_method) = Box::pin(execute_payment_method_update_handler(+ &mut handler,+ network_tokenization_resp,+ ))+ .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+ // 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)- })- .await;+ .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");+ if let Err(error) = deleted {+ logger::warn!(?error, "Failed to delete the volatile payment method copy");+ }+ }++ Ok((response, payment_method))}}-- Ok((response, payment_method))}#[cfg(feature = "v2")]@@ -7905,23 +7942,12 @@ 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),- };+ // PayThenVault always creates a volatile record. Only acceptance supplied by payments+ // confirm, forwarded in the update request, can authorize its later promotion.+ let storage_type = match resolve_payment_method_integration_type(&state, &platform).await {+ pm_types::PaymentMethodIntegrationType::PayThenVault => common_enums::StorageType::Volatile,+ pm_types::PaymentMethodIntegrationType::VaultThenPay => storage_type,+ };let create_payment_method_request = get_payment_method_create_request(request@@ -7944,7 +7970,7 @@ pub async fn payment_methods_session_confirm(create_payment_method_request.clone(),&platform,&profile,- customer_acceptance,+ None,)).await?;diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rsindex 20151e0fde..9e63de2ca1 100644--- a/crates/router/src/core/payments/operations/payment_response.rs+++ b/crates/router/src/core/payments/operations/payment_response.rs@@ -324,6 +324,15 @@ wherenetwork_transaction_id: network_transaction_id.map(hyperswitch_masking::Secret::new),acknowledgement_status,+ customer_acceptance: payment_data+ .payment_attempt+ .customer_acceptance+ .clone()+ .map(|acceptance| acceptance.expose().parse_value("CustomerAcceptance"))+ .transpose()+ .change_context(+ ::payment_methods::errors::ModularPaymentMethodError::UpdateFailed,+ )?,};// #3 - Execute the modular payment-method update call if there is something to be updated@@ -5047,6 +5056,11 @@ impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::SetupMandateRenetwork_transaction_id: payments_response.get_network_transaction_id().map(hyperswitch_masking::Secret::new),+ customer_acceptance: payment_data+ .payment_attempt+ .customer_acceptance+ .clone()+ .map(|acceptance| acceptance.expose()),acknowledgement_status: router_data.status.should_update_payment_method()