Skip to content

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

fix(core): defer bank redirect payment method creation until terminal status (#14391)

Vani Gupta5dd17494a82b
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 43df6abea7..a7ee29cfc4 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -6,6 +6,8 @@ use std::{collections::HashMap, ops::Deref};
use ::payment_methods::client::{
BankDebitDetailUpdate, CardDetailUpdate, PaymentMethodUpdateData, UpdatePaymentMethodV1Payload,
};
+#[cfg(feature = "v1")]
+use ::payment_methods::controller::PaymentMethodsController;
#[cfg(feature = "dynamic_routing")]
use api_models::routing::RoutableConnectorChoice;
use async_trait::async_trait;
@@ -784,7 +786,19 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
should_avoid_saving
};
- if is_legacy_mandate {
+ let should_defer_pm_creation =
+ is_payment_method_creation_deferred(payment_data.payment_attempt.payment_method)
+ && !resp.status.is_authorization_success();
+
+ if should_defer_pm_creation {
+ logger::info!(
+ payment_id = ?payment_data.payment_attempt.payment_id,
+ payment_method = ?payment_data.payment_attempt.payment_method,
+ attempt_status = ?resp.status,
+ "Deferring payment method creation until authorization success"
+ );
+ Ok(())
+ } else if is_legacy_mandate {
// Mandate is created on the application side and at the connector.
let tokenization::SavePaymentMethodDataResponse {
payment_method_id, ..
@@ -1274,7 +1288,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSyncData> for
resp.connector_returned_payment_method_details.as_ref(),
);
- update_payment_method_status_ntid_and_additional_data(
+ Box::pin(create_or_update_payment_method_from_payment_response(
state,
platform.get_provider().get_key_store(),
payment_data,
@@ -1287,7 +1301,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSyncData> for
payment_data.payment_attempt.merchant_connector_id.clone(),
platform,
business_profile,
- )
+ ))
.await?;
Ok(())
}
@@ -2308,7 +2322,12 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::CompleteAuthorizeData
payment_data,
)?;
- update_payment_method_status_ntid_and_additional_data(
+ let additional_payment_method_data = get_additional_payment_method_data_from_psync(
+ resp.status,
+ resp.connector_returned_payment_method_details.as_ref(),
+ );
+
+ Box::pin(create_or_update_payment_method_from_payment_response(
state,
platform.get_provider().get_key_store(),
payment_data,
@@ -2317,11 +2336,11 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::CompleteAuthorizeData
platform.get_provider().get_account().storage_scheme,
&platform.get_provider().get_account().organization_id,
platform.get_initiator(),
- None,
- None,
+ additional_payment_method_data,
+ payment_data.payment_attempt.merchant_connector_id.clone(),
platform,
_business_profile,
- )
+ ))
.await?;
Ok(())
}
@@ -3454,7 +3473,7 @@ fn get_payment_intent_update_data<F: Clone, T: types::Capturable>(
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
-async fn update_payment_method_status_ntid_and_additional_data<F: Clone>(
+async fn create_or_update_payment_method_from_payment_response<F: Clone>(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
@@ -3467,9 +3486,274 @@ async fn update_payment_method_status_ntid_and_additional_data<F: Clone>(
todo!()
}
+#[cfg(feature = "v1")]
+fn is_payment_method_creation_deferred(payment_method: Option<enums::PaymentMethod>) -> bool {
+ matches!(payment_method, Some(enums::PaymentMethod::BankRedirect))
+}
+
+#[cfg(feature = "v1")]
+fn get_vaultable_payment_method_data(
+ payment_method: Option<enums::PaymentMethod>,
+ connector_returned_payment_method_data: Option<&domain::PaymentMethodData>,
+) -> Option<&domain::PaymentMethodData> {
+ match (payment_method?, connector_returned_payment_method_data?) {
+ (
+ enums::PaymentMethod::BankRedirect,
+ payment_method_data @ domain::PaymentMethodData::BankRedirect(_),
+ ) => Some(payment_method_data),
+ _ => None,
+ }
+}
+
+#[cfg(feature = "v1")]
+type DeferredVaultResponse = (
+ domain::PaymentMethodResponse,
+ Option<payment_methods::transformers::DataDuplicationCheck>,
+);
+
+#[cfg(feature = "v1")]
+async fn vault_deferred_payment_method<F: Clone>(
+ state: &SessionState,
+ payment_data: &PaymentData<F>,
+ platform: &domain::Platform,
+ business_profile: &domain::Profile,
+ customer_id: &common_utils::id_type::CustomerId,
+ additional_payment_method_data: Option<&domain::PaymentMethodData>,
+) -> RouterResult<Option<DeferredVaultResponse>> {
+ let Some(payment_method_data) = get_vaultable_payment_method_data(
+ payment_data.payment_attempt.payment_method,
+ additional_payment_method_data,
+ ) else {
+ return Ok(None);
+ };
+
+ let payment_method_create_request = payment_methods::get_payment_method_create_request(
+ Some(payment_method_data),
+ payment_data.payment_attempt.payment_method,
+ payment_data.payment_attempt.payment_method_type,
+ &Some(customer_id.clone()),
+ None,
+ None,
+ )
+ .await?;
+
+ tokenization::save_in_locker(
+ state,
+ platform,
+ payment_method_create_request,
+ None,
+ business_profile,
+ )
+ .await
+ .map(Some)
+}
+
+#[cfg(feature = "v1")]
+async fn find_deduplicated_payment_method(
+ state: &SessionState,
+ key_store: &domain::MerchantKeyStore,
+ vault_response: Option<&DeferredVaultResponse>,
+) -> Option<domain::PaymentMethod> {
+ let locker_fingerprint_id = match vault_response? {
+ (vault_response, Some(payment_methods::transformers::DataDuplicationCheck::Duplicated)) => {
+ vault_response.locker_fingerprint_id.as_ref()?
+ }
+ _ => return None,
+ };
+
+ state
+ .store
+ .find_payment_method_by_fingerprint_id(key_store, locker_fingerprint_id)
+ .await
+ .map_err(|error| {
+ logger::info!(
+ ?error,
+ "Vault reported a duplicate but no payment method matched the fingerprint"
+ );
+ })
+ .ok()
+}
+
+#[cfg(feature = "v1")]
+async fn insert_deferred_payment_method<F: Clone>(
+ state: &SessionState,
+ payment_data: &PaymentData<F>,
+ platform: &domain::Platform,
+ customer_id: &common_utils::id_type::CustomerId,
+ customer_acceptance: common_utils::pii::SecretSerdeValue,
+ vault_response: Option<DeferredVaultResponse>,
+) -> RouterResult<domain::PaymentMethod> {
+ let provider = platform.get_provider();
+ let key_manager_state: KeyManagerState = state.into();
+
+ let encrypted_payment_method_billing_address = payment_data
+ .address
+ .get_payment_method_billing()
+ .cloned()
+ .async_map(|address| {
+ core_utils::create_encrypted_data(
+ &key_manager_state,
+ provider.get_key_store(),
+ address,
+ common_utils::type_name!(diesel_models::payment_method::PaymentMethod),
+ )
+ })
+ .await
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encrypt payment method billing address")?;
+
+ let payment_method_create_request = api_models::payment_methods::PaymentMethodCreate {
+ payment_method: payment_data.payment_attempt.payment_method,
+ payment_method_type: payment_data.payment_attempt.payment_method_type,
+ payment_method_issuer: None,
+ payment_method_issuer_code: None,
+ #[cfg(feature = "payouts")]
+ bank_transfer: None,
+ #[cfg(feature = "payouts")]
+ bank_transfer_data: None,
+ #[cfg(feature = "payouts")]
+ wallet: None,
+ card: None,
+ metadata: None,
+ customer_id: Some(customer_id.clone()),
+ card_network: None,
+ client_secret: None,
+ payment_method_data: None,
+ billing: None,
+ connector_mandate_details: None,
+ network_transaction_id: None,
+ };
+
+ let (locker_id, locker_fingerprint_id) = vault_response
+ .map(|(vault_response, _)| {
+ (
+ Some(vault_response.payment_method_id),
+ vault_response.locker_fingerprint_id,
+ )
+ })
+ .unwrap_or((None, None));
+
+ let payment_method_id = common_utils::generate_id(consts::ID_LENGTH, "pm");
+ let payment_method = payment_methods::cards::PmCards { state, provider }
+ .create_payment_method(
+ &payment_method_create_request,
+ customer_id,
+ &payment_method_id,
+ locker_id,
+ provider.get_account().get_id(),
+ None,
+ Some(customer_acceptance.expose()),
+ None,
+ None,
+ Some(common_enums::PaymentMethodStatus::Active),
+ None,
+ encrypted_payment_method_billing_address,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ locker_fingerprint_id,
+ platform.get_initiator(),
+ )
+ .await?;
+
+ logger::info!(
+ payment_method_id = %payment_method_id,
+ "Created deferred payment method on terminal success"
+ );
+
+ Ok(payment_method)
+}
+
+#[cfg(feature = "v1")]
+async fn create_deferred_payment_method<F: Clone>(
+ state: &SessionState,
+ payment_data: &mut PaymentData<F>,
+ attempt_status: common_enums::AttemptStatus,
+ platform: &domain::Platform,
+ business_profile: &domain::Profile,
+ additional_payment_method_data: Option<&domain::PaymentMethodData>,
+) -> RouterResult<()> {
+ let deferred_save_details =
+ (is_payment_method_creation_deferred(payment_data.payment_attempt.payment_method)
+ && attempt_status.is_authorization_success())
+ .then(|| {
+ payment_data
+ .payment_attempt
+ .customer_acceptance
+ .clone()
+ .zip(payment_data.payment_intent.customer_id.clone())
+ })
+ .flatten();
+
+ let Some((customer_acceptance, customer_id)) = deferred_save_details else {
+ return Ok(());
+ };
+
+ let provider = platform.get_provider();
+ let key_store = provider.get_key_store();
+
+ let vault_response = vault_deferred_payment_method(
+ state,
+ payment_data,
+ platform,
+ business_profile,
+ &customer_id,
+ additional_payment_method_data,
+ )
+ .await?;
+
+ let payment_method =
+ match find_deduplicated_payment_method(state, key_store, vault_response.as_ref()).await {
+ Some(deduplicated_payment_method) => {
+ payment_methods::cards::update_last_used_at(
+ &deduplicated_payment_method,
+ state,
+ provider.get_account().storage_scheme,
+ key_store,
+ )
+ .await
+ .map_err(|error| {
+ logger::error!(?error, "Failed to update last used at");
+ })
+ .ok();
+
+ logger::info!(
+ payment_method_id = %deduplicated_payment_method.get_id(),
+ "Reusing the existing payment method the instrument was deduplicated to"
+ );
+
+ deduplicated_payment_method
+ }
+ None => {
+ insert_deferred_payment_method(
+ state,
+ payment_data,
+ platform,
+ &customer_id,
+ customer_acceptance,
+ vault_response,
+ )
+ .await?
+ }
+ };
+
+ payment_data.payment_attempt.payment_method_id = Some(payment_method.get_id().clone());
+ payment_data.payment_method_info = Some(payment_method);
+
+ Ok(())
+}
+
+/// Creates the payment method if its creation was deferred until authorization success, then
+/// updates it from the connector response: status, network transaction id and link id, and the
+/// payment method details the connector returned.
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
-async fn update_payment_method_status_ntid_and_additional_data<F: Clone>(
+async fn create_or_update_payment_method_from_payment_response<F: Clone>(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
@@ -3485,6 +3769,20 @@ async fn update_payment_method_status_ntid_and_additional_data<F: Clone>(
platform: &domain::Platform,
business_profile: &domain::Profile,
) -> RouterResult<()> {
+ if payment_data.payment_attempt.payment_method_id.is_none() {
+ if let Err(error) = create_deferred_payment_method(
+ state,
+ payment_data,
+ attempt_status,
+ platform,
+ business_profile,
+ additional_payment_method_data,
+ )
+ .await
+ {
+ logger::error!(?error, "Failed to create deferred payment method");
+ }
+ }
// If the payment_method is deleted then ignore the error related to retrieving payment method
// This should be handled when the payment method is soft deleted
if let Some(id) = &payment_data.payment_attempt.payment_method_id {
@@ -3504,7 +3802,7 @@ async fn update_payment_method_status_ntid_and_additional_data<F: Clone>(
} else {
Err(error)
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error retrieving payment method from db in update_payment_method_status_ntid_and_additional_data")?
+ .attach_printable("Error retrieving payment method from db in create_or_update_payment_method_from_payment_response")?
}
}
};
diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.js
index c9fe11af23..762ac510c6 100644
--- a/cypress-tests/cypress/support/commands.js
+++ b/cypress-tests/cypress/support/commands.js
@@ -5461,10 +5461,18 @@ Cypress.Commands.add(
const isWalletRequiresAction =
response.body.status === "requires_customer_action" &&
response.body.payment_method === "wallet";
+ const isBankRedirect =
+ response.body.payment_method === "bank_redirect";
+ const isTerminalSuccessForDeferredPm = [
+ "succeeded",
+ "requires_capture",
+ "partially_captured",
+ ].includes(response.body.status);
if (
response.body.status !== "failed" &&
!isWalletRequiresAction &&
- response.body.setup_future_usage === "off_session"
+ response.body.setup_future_usage === "off_session" &&
+ (!isBankRedirect || isTerminalSuccessForDeferredPm)
) {
expect(response.body.payment_method_id, "payment_method_id").to.not
.be.null;