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

feat(router): Add support for storing ACH Bank Debit Details in locker (#10614)

Anurag Thakur7f37fa6de892
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index 9ed1a5ce5b..6eebdbff7f 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -11394,6 +11394,33 @@
}
]
},
+ "BankDebitDetail": {
+ "oneOf": [
+ {
+ "type": "object",
+ "required": [
+ "ach"
+ ],
+ "properties": {
+ "ach": {
+ "type": "object",
+ "required": [
+ "account_number",
+ "routing_number"
+ ],
+ "properties": {
+ "account_number": {
+ "type": "string"
+ },
+ "routing_number": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ ]
+ },
"BankDebitResponse": {
"allOf": [
{
@@ -25851,6 +25878,17 @@
"$ref": "#/components/schemas/CardDetail"
}
}
+ },
+ {
+ "type": "object",
+ "required": [
+ "bank_debit"
+ ],
+ "properties": {
+ "bank_debit": {
+ "$ref": "#/components/schemas/BankDebitDetail"
+ }
+ }
}
]
},
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index bb25fc6b08..5e07ebdf9c 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -534,6 +534,20 @@ pub enum PaymentMethodCreateData {
#[serde(rename = "payment_method_data")]
pub enum PaymentMethodCreateData {
Card(CardDetail),
+ BankDebit(BankDebitDetail),
+}
+
+#[cfg(feature = "v1")]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+#[serde(rename_all = "snake_case")]
+pub enum BankDebitDetail {
+ Ach {
+ #[schema(value_type = String)]
+ account_number: masking::Secret<String>,
+ #[schema(value_type = String)]
+ routing_number: masking::Secret<String>,
+ },
}
#[cfg(feature = "v1")]
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index e9543da81f..4fee2d92ff 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -357,6 +357,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payment_methods::CardDetailFromLocker,
api_models::payment_methods::PaymentMethodCreateData,
api_models::payment_methods::CardDetail,
+ api_models::payment_methods::BankDebitDetail,
api_models::payment_methods::CardDetailUpdate,
api_models::payment_methods::RequestPaymentMethodTypes,
api_models::poll::PollResponse,
diff --git a/crates/payment_methods/src/controller.rs b/crates/payment_methods/src/controller.rs
index 32e3c990f7..96bc3cfc8d 100644
--- a/crates/payment_methods/src/controller.rs
+++ b/crates/payment_methods/src/controller.rs
@@ -141,6 +141,15 @@ pub trait PaymentMethodsController {
customer_id: &id_type::CustomerId,
) -> errors::VaultResult<(api::PaymentMethodResponse, Option<DataDuplicationCheck>)>;
+ #[cfg(feature = "v1")]
+ async fn add_bank_debit_to_locker(
+ &self,
+ req: api::PaymentMethodCreate,
+ 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>)>;
+
#[cfg(feature = "v1")]
async fn get_or_insert_payment_method(
&self,
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 88088b2fc8..84f24f88a1 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -46,6 +46,7 @@ use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::behaviour::Conversion;
use hyperswitch_domain_models::{
+ payment_method_data::BankDebitData,
payments::{payment_attempt::PaymentAttempt, PaymentIntent, VaultData},
router_data_v2::flow_common_types::VaultConnectorFlowData,
router_flow_types::ExternalVaultInsertFlow,
@@ -689,14 +690,95 @@ pub async fn retrieve_payment_method_with_token(
payment_method_data: None,
payment_method_id: None,
},
- // TODO: Locker support for BankDebit will be added in a future PR, currently keeping
- // these fields as None
- storage::PaymentTokenData::BankDebit(_) => storage::PaymentMethodDataWithId {
- payment_method: None,
- payment_method_data: None,
+ storage::PaymentTokenData::BankDebit(bank_debit) => {
+ let customer =
+ customer
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "customer",
+ })?;
- payment_method_id: None,
- },
+ let locker_id = bank_debit.locker_id.as_ref().ok_or(
+ errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "locker_id",
+ },
+ )?;
+
+ let bank_debit_detail = cards::get_bank_debit_from_hs_locker(
+ state,
+ merchant_key_store,
+ &customer.customer_id,
+ &merchant_key_store.merchant_id,
+ locker_id,
+ )
+ .await?;
+
+ let (account_number, routing_number) = match bank_debit_detail {
+ payment_methods::BankDebitDetail::Ach {
+ account_number,
+ routing_number,
+ } => (account_number, routing_number),
+ };
+
+ let payment_method_data = payment_method_info
+ .get_required_value("PaymentMethod")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("PaymentMethod not found")?;
+
+ let (
+ card_holder_name,
+ bank_account_holder_name,
+ bank_name,
+ bank_type,
+ bank_holder_type,
+ ) = if let Some(
+ hyperswitch_domain_models::payment_method_data::PaymentMethodsData::BankDebit(
+ bank_debit_data,
+ ),
+ ) = payment_method_data.get_payment_methods_data()
+ {
+ use hyperswitch_domain_models::payment_method_data::BankDebitDetailsPaymentMethod;
+
+ let BankDebitDetailsPaymentMethod::AchBankDebit {
+ masked_account_number: _,
+ masked_routing_number: _,
+ card_holder_name,
+ bank_account_holder_name,
+ bank_name,
+ bank_type,
+ bank_holder_type,
+ } = bank_debit_data;
+ (
+ card_holder_name.clone(),
+ bank_account_holder_name.clone(),
+ bank_name,
+ bank_type,
+ bank_holder_type,
+ )
+ } else {
+ return Err(report!(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Payment method data is not bank debit"));
+ };
+
+ storage::PaymentMethodDataWithId {
+ payment_method: Some(enums::PaymentMethod::BankDebit),
+ payment_method_data: Some(
+ hyperswitch_domain_models::payment_method_data::PaymentMethodData::BankDebit(
+ BankDebitData::AchBankDebit {
+ account_number,
+ routing_number,
+ card_holder_name,
+ bank_account_holder_name,
+ bank_name,
+ bank_type,
+ bank_holder_type,
+ },
+ ),
+ ),
+
+ payment_method_id: Some(bank_debit.payment_method_id.clone()),
+ }
+ }
};
Ok(token)
}
@@ -822,6 +904,44 @@ pub(crate) async fn get_payment_method_create_request(
};
Ok(payment_method_request)
}
+ domain::PaymentMethodData::BankDebit(BankDebitData::AchBankDebit {
+ account_number,
+ routing_number,
+ card_holder_name: _,
+ bank_account_holder_name: _,
+ bank_name: _,
+ bank_type: _,
+ bank_holder_type: _,
+ }) => {
+ let payment_method_request = payment_methods::PaymentMethodCreate {
+ payment_method: Some(payment_method),
+ payment_method_type,
+ payment_method_issuer: None,
+ payment_method_issuer_code: None,
+ #[cfg(feature = "payouts")]
+ bank_transfer: None,
+ #[cfg(feature = "payouts")]
+ wallet: None,
+ card: None,
+ metadata: None,
+ customer_id: customer_id.clone(),
+ card_network: None,
+ client_secret: None,
+ payment_method_data: Some(
+ payment_methods::PaymentMethodCreateData::BankDebit(
+ payment_methods::BankDebitDetail::Ach {
+ account_number: account_number.to_owned(),
+ routing_number: routing_number.to_owned(),
+ },
+ ),
+ ),
+ billing: payment_method_billing_address.cloned().map(From::from),
+ connector_mandate_details: None,
+ network_transaction_id: None,
+ };
+ Ok(payment_method_request)
+ }
+
_ => {
let payment_method_request = payment_methods::PaymentMethodCreate {
payment_method: Some(payment_method),
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 116f1f3935..ff61bacfe7 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -602,6 +602,73 @@ impl PaymentMethodsController for PmCards<'_> {
Ok((payment_method_resp, store_resp.duplication_check))
}
+ #[cfg(feature = "v1")]
+ async fn add_bank_debit_to_locker(
+ &self,
+ req: api::PaymentMethodCreate,
+ bank_debit_data: api_models::payment_methods::BankDebitDetail,
+ key_store: &domain::MerchantKeyStore,
+ customer_id: &id_type::CustomerId,
+ ) -> errors::CustomResult<
+ (
+ api::PaymentMethodResponse,
+ Option<payment_methods::DataDuplicationCheck>,
+ ),
+ errors::VaultError,
+ > {
+ let key = key_store.key.get_inner().peek();
+
+ 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
+ }
+ .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()))
+ })?;
+
+ 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,
+ 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))
+ }
/// The response will be the tuple of PaymentMethodResponse and the duplication check of payment_method
async fn add_card_to_locker(
&self,
@@ -1608,6 +1675,13 @@ pub async fn add_payment_method_data(
}
}
}
+ api_models::payment_methods::PaymentMethodCreateData::BankDebit(_) => {
+ Err(errors::ApiErrorResponse::NotImplemented {
+ message: errors::NotImplementedMessage::Reason(
+ "add_payment_method_data not implemented for bank-debit".to_string(),
+ ),
+ })?
+ }
}
}
@@ -4924,6 +4998,29 @@ pub async fn get_bank_from_vault(
}
}
+#[cfg(feature = "v1")]
+pub async fn get_bank_debit_from_hs_locker(
+ state: &routes::SessionState,
+ key_store: &domain::MerchantKeyStore,
+ customer_id: &id_type::CustomerId,
+ merchant_id: &id_type::MerchantId,
+ token_ref: &str,
+) -> errors::RouterResult<api_models::payment_methods::BankDebitDetail> {
+ let payment_method =
+ get_encrypted_data_from_vault(state, key_store, customer_id, merchant_id, token_ref)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error getting payment method from locker")?;
+
+ let bank_debit_create_data: api_models::payment_methods::BankDebitDetail = payment_method
+ .peek()
+ .to_string()
+ .parse_struct("BankDebitDetail")
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+
+ Ok(bank_debit_create_data)
+}
+
#[cfg(feature = "v1")]
pub struct TempLockerCardSupport;
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 148fbb60dd..9a2caeb915 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -437,6 +437,30 @@ pub fn mk_add_bank_response_hs(
}
}
+#[cfg(feature = "v1")]
+pub fn mk_add_bank_debit_response_hs(
+ bank_reference: String,
+ req: api::PaymentMethodCreate,
+ merchant_id: &id_type::MerchantId,
+) -> api::PaymentMethodResponse {
+ api::PaymentMethodResponse {
+ merchant_id: merchant_id.to_owned(),
+ customer_id: req.customer_id.to_owned(),
+ payment_method_id: bank_reference,
+ payment_method: req.payment_method,
+ payment_method_type: req.payment_method_type,
+ bank_transfer: None,
+ card: None,
+ metadata: req.metadata,
+ created: Some(common_utils::date_time::now()),
+ recurring_enabled: Some(false), // [#256]
+ installment_payment_enabled: Some(false), // #[#256]
+ payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
+ last_used_at: Some(common_utils::date_time::now()),
+ client_secret: None,
+ }
+}
+
#[cfg(all(feature = "v2", feature = "payouts"))]
pub fn mk_add_bank_response_hs(
_bank: api::BankPayout,
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index f292b5b762..8a3c36ac31 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -790,7 +790,7 @@ where
create_payment_method_metadata(None, connector_token)?;
locker_id = resp.payment_method.and_then(|pm| {
- if pm == PaymentMethod::Card {
+ if pm == PaymentMethod::Card || pm == PaymentMethod::BankDebit {
Some(resp.payment_method_id)
} else {
None
@@ -1116,8 +1116,12 @@ pub async fn save_in_locker_internal(
.customer_id
.clone()
.get_required_value("customer_id")?;
- match (payment_method_request.card.clone(), card_detail) {
- (_, Some(card)) | (Some(card), _) => Box::pin(
+ match (
+ payment_method_request.card.clone(),
+ card_detail,
+ payment_method_request.payment_method_data.clone(),
+ ) {
+ (_, Some(card), _) | (Some(card), _, _) => Box::pin(
PmCards {
state,
provider: platform.get_provider(),
@@ -1127,6 +1131,29 @@ pub async fn save_in_locker_internal(
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Card Failed"),
+
+ (
+ None,
+ None,
+ Some(api_models::payment_methods::PaymentMethodCreateData::BankDebit(
+ bank_debit_create_data,
+ )),
+ ) => Box::pin(
+ PmCards {
+ state,
+ provider: platform.get_provider(),
+ }
+ .add_bank_debit_to_locker(
+ payment_method_request,
+ bank_debit_create_data,
+ platform.get_processor().get_key_store(),
+ &customer_id,
+ ),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Add Bank Debit Failed"),
+
_ => {
let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm");
let payment_method_response = api::PaymentMethodResponse {