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
feat(migration): Add support to migrate ACH tokens (#11274)
DEEPANSHU BANSALa4acc25f5d44
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex ec531089e9..e27810fa0b 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -290,6 +290,9 @@ pub struct PaymentMethodMigrateResponse {//card data migration statuspub card_migrated: Option<bool>,+ //payment method data migration status (bank debit, wallet, etc.)+ pub payment_method_migrated: Option<bool>,+//network token data migration statuspub network_token_migrated: Option<bool>,@@ -456,6 +459,34 @@ impl PaymentMethodCreate {network_transaction_id: payment_method_migrate.network_transaction_id.clone(),}}++ pub fn get_payment_method_create_from_payment_method_data_migrate(+ payment_method_data: PaymentMethodCreateData,+ payment_method_migrate: &PaymentMethodMigrate,+ ) -> Self {+ Self {+ customer_id: payment_method_migrate.customer_id.clone(),+ payment_method: payment_method_migrate.payment_method,+ payment_method_type: payment_method_migrate.payment_method_type,+ payment_method_issuer: payment_method_migrate.payment_method_issuer.clone(),+ payment_method_issuer_code: payment_method_migrate.payment_method_issuer_code,+ metadata: payment_method_migrate.metadata.clone(),+ payment_method_data: Some(payment_method_data),+ connector_mandate_details: payment_method_migrate+ .connector_mandate_details+ .clone()+ .map(PaymentsMandateReference::from),+ client_secret: None,+ billing: payment_method_migrate.billing.clone(),+ card: None,+ card_network: None,+ #[cfg(feature = "payouts")]+ bank_transfer: None,+ #[cfg(feature = "payouts")]+ wallet: None,+ network_transaction_id: payment_method_migrate.network_transaction_id.clone(),+ }+ }}#[cfg(feature = "v2")]@@ -2994,9 +3025,14 @@ pub struct PaymentMethodRecord {pub nick_name: Option<masking::Secret<String>>,pub payment_instrument_id: Option<masking::Secret<String>>,pub connector_customer_id: Option<String>,- pub card_number_masked: masking::Secret<String>,- pub card_expiry_month: masking::Secret<String>,- pub card_expiry_year: masking::Secret<String>,+ // Card fields are optional to support non-card CSV rows (e.g., ACH bank debit).+ // For card rows these will still be populated normally from the CSV columns.+ #[serde(default)]+ pub card_number_masked: Option<masking::Secret<String>>,+ #[serde(default)]+ pub card_expiry_month: Option<masking::Secret<String>>,+ #[serde(default)]+ pub card_expiry_year: Option<masking::Secret<String>>,pub card_scheme: Option<String>,pub original_transaction_id: Option<String>,pub billing_address_zip: Option<masking::Secret<String>>,@@ -3018,6 +3054,31 @@ pub struct PaymentMethodRecord {pub network_token_expiry_month: Option<masking::Secret<String>>,pub network_token_expiry_year: Option<masking::Secret<String>>,pub network_token_requestor_ref_id: Option<String>,+ #[serde(default)]+ pub account_number: Option<masking::Secret<String>>,+ #[serde(default)]+ pub routing_number: Option<masking::Secret<String>>,+}++#[cfg(feature = "v1")]+impl PaymentMethodRecord {+ /// Constructs `PaymentMethodCreateData` from the CSV record fields.+ /// Returns `None` for card records (cards are handled via `MigrateCardDetail`).+ /// Extend the match arms here to support additional payment method types+ /// (e.g., SEPA, BACS, wallets) in the future.+ pub fn get_payment_method_data(&self) -> Option<PaymentMethodCreateData> {+ match (self.account_number.as_ref(), self.routing_number.as_ref()) {+ (Some(account_number), Some(routing_number))+ if !account_number.peek().is_empty() && !routing_number.peek().is_empty() =>+ {+ Some(PaymentMethodCreateData::BankDebit(BankDebitDetail::Ach {+ account_number: account_number.clone(),+ routing_number: routing_number.clone(),+ }))+ }+ _ => None,+ }+ }}#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]@@ -3086,6 +3147,7 @@ pub struct PaymentMethodMigrationResponse {pub migration_error: Option<String>,pub card_number_masked: Option<masking::Secret<String>>,pub card_migrated: Option<bool>,+ pub payment_method_migrated: Option<bool>,pub network_token_migrated: Option<bool>,pub connector_mandate_details_migrated: Option<bool>,pub network_transaction_id_migrated: Option<bool>,@@ -3180,18 +3242,19 @@ impl From<PaymentMethodMigrationResponseType> for PaymentMethodMigrationResponsecustomer_id: res.payment_method_response.customer_id,migration_status: MigrationStatus::Success,migration_error: None,- card_number_masked: Some(record.card_number_masked),+ card_number_masked: record.card_number_masked.clone(),line_number: record.line_number,card_migrated: res.card_migrated,+ payment_method_migrated: res.payment_method_migrated,network_token_migrated: res.network_token_migrated,connector_mandate_details_migrated: res.connector_mandate_details_migrated,network_transaction_id_migrated: res.network_transaction_id_migrated,},Err(e) => Self {- customer_id: Some(record.customer_id),+ customer_id: Some(record.customer_id.clone()),migration_status: MigrationStatus::Failed,migration_error: Some(e),- card_number_masked: Some(record.card_number_masked),+ card_number_masked: record.card_number_masked.clone(),line_number: record.line_number,..Self::default()},@@ -3227,6 +3290,7 @@ impl From<PaymentMethodUpdateResponseType> for PaymentMethodUpdateResponse {}}+#[cfg(feature = "v1")]implTryFrom<(&PaymentMethodRecord,@@ -3270,16 +3334,19 @@ implNone};- Ok(Self {- merchant_id,- customer_id: Some(record.customer_id.clone()),- card: Some(MigrateCardDetail {+ let payment_method_data = record.get_payment_method_data();+ let is_non_card = payment_method_data.is_some();++ let card = if is_non_card {+ None+ } else {+ Some(MigrateCardDetail {card_number: record.raw_card_number.clone()- .unwrap_or_else(|| record.card_number_masked.clone()),- card_exp_month: record.card_expiry_month.clone(),- card_exp_year: record.card_expiry_year.clone(),+ .unwrap_or_else(|| record.card_number_masked.clone().unwrap_or_default()),+ card_exp_month: record.card_expiry_month.clone().unwrap_or_default(),+ card_exp_year: record.card_expiry_year.clone().unwrap_or_default(),card_holder_name: record.card_holder_name.clone().or(record.name.clone()),card_network: None,card_type: None,@@ -3287,8 +3354,13 @@ implcard_issuing_country: None,card_issuing_country_code: None,nick_name: record.nick_name.clone(),- }),- network_token: Some(MigrateNetworkTokenDetail {+ })+ };++ let network_token = if is_non_card {+ None+ } else {+ Some(MigrateNetworkTokenDetail {network_token_data: MigrateNetworkTokenData {network_token_number: record.network_token_number.clone().unwrap_or_default(),network_token_exp_month: record@@ -3311,7 +3383,14 @@ impl.network_token_requestor_ref_id.clone().unwrap_or_default(),- }),+ })+ };++ Ok(Self {+ merchant_id,+ customer_id: Some(record.customer_id.clone()),+ card,+ network_token,payment_method: record.payment_method,payment_method_type: record.payment_method_type,payment_method_issuer: None,@@ -3328,7 +3407,7 @@ implbank_transfer: None,#[cfg(feature = "payouts")]wallet: None,- payment_method_data: None,+ payment_method_data,network_transaction_id: record.original_transaction_id.clone(),})}diff --git a/crates/payment_methods/src/core/migration.rs b/crates/payment_methods/src/core/migration.rsindex b1cc848ed7..bc9f5f3cef 100644--- a/crates/payment_methods/src/core/migration.rs+++ b/crates/payment_methods/src/core/migration.rs@@ -264,6 +264,7 @@ fn validate_card_exp_year(year: String) -> Result<(), errors::ValidationError> {#[derive(Debug)]pub struct RecordMigrationStatus {pub card_migrated: Option<bool>,+ pub payment_method_migrated: Option<bool>,pub network_token_migrated: Option<bool>,pub connector_mandate_details_migrated: Option<bool>,pub network_transaction_migrated: Option<bool>,@@ -272,6 +273,7 @@ pub struct RecordMigrationStatus {#[derive(Debug)]pub struct RecordMigrationStatusBuilder {pub card_migrated: Option<bool>,+ pub payment_method_migrated: Option<bool>,pub network_token_migrated: Option<bool>,pub connector_mandate_details_migrated: Option<bool>,pub network_transaction_migrated: Option<bool>,@@ -281,6 +283,7 @@ impl RecordMigrationStatusBuilder {pub fn new() -> Self {Self {card_migrated: None,+ payment_method_migrated: None,network_token_migrated: None,connector_mandate_details_migrated: None,network_transaction_migrated: None,@@ -291,6 +294,10 @@ impl RecordMigrationStatusBuilder {self.card_migrated = Some(card_migrated);}+ pub fn payment_method_migrated(&mut self, payment_method_migrated: bool) {+ self.payment_method_migrated = Some(payment_method_migrated);+ }+pub fn network_token_migrated(&mut self, network_token_migrated: Option<bool>) {self.network_token_migrated = network_token_migrated;}@@ -309,6 +316,7 @@ impl RecordMigrationStatusBuilder {pub fn build(self) -> RecordMigrationStatus {RecordMigrationStatus {card_migrated: self.card_migrated,+ payment_method_migrated: self.payment_method_migrated,network_token_migrated: self.network_token_migrated,connector_mandate_details_migrated: self.connector_mandate_details_migrated,network_transaction_migrated: self.network_transaction_migrated,diff --git a/crates/payment_methods/src/core/migration/payment_methods.rs b/crates/payment_methods/src/core/migration/payment_methods.rsindex 3b7dfc0958..5b13c3d8c4 100644--- a/crates/payment_methods/src/core/migration/payment_methods.rs+++ b/crates/payment_methods/src/core/migration/payment_methods.rs@@ -45,6 +45,24 @@ pub async fn migrate_payment_method(controller: &dyn PaymentMethodsController,) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodMigrateResponse>, errors::ApiErrorResponse>{+ // If payment_method_data contains non-card data (e.g., bank debit), use the dedicated migration flow+ if let Some(payment_method_data) = req+ .payment_method_data+ .clone()+ .filter(|data| !matches!(data, pm_api::PaymentMethodCreateData::Card(_)))+ {+ return migrate_payment_method_data(+ state,+ &req,+ payment_method_data,+ merchant_id,+ platform,+ controller,+ )+ .await;+ }++ // Existing card migration flowlet mut req = req;let card_details = &req.card.get_required_value("card")?;@@ -157,6 +175,7 @@ pub async fn migrate_payment_method(pm_api::PaymentMethodMigrateResponse {payment_method_response,card_migrated: migrate_status.card_migrated,+ payment_method_migrated: None,network_token_migrated: migrate_status.network_token_migrated,connector_mandate_details_migrated: migrate_status.connector_mandate_details_migrated,network_transaction_id_migrated: migrate_status.network_transaction_migrated,@@ -164,6 +183,88 @@ pub async fn migrate_payment_method())}+/// Migrates a payment method using payment_method_data (e.g., ACH bank debit, wallet, etc.).+/// This bypasses card-specific logic (BIN lookup, card validation, network token, etc.)+/// and stores the details directly via `controller.add_payment_method()`.+#[cfg(feature = "v1")]+#[instrument(skip_all)]+async fn migrate_payment_method_data(+ _state: &state::PaymentMethodsState,+ req: &pm_api::PaymentMethodMigrate,+ payment_method_data: pm_api::PaymentMethodCreateData,+ merchant_id: &id_type::MerchantId,+ platform: &platform::Platform,+ controller: &dyn PaymentMethodsController,+) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodMigrateResponse>, errors::ApiErrorResponse>+{+ logger::debug!("Migrating payment method via payment_method_data");++ if let Some(connector_mandate_details) = &req.connector_mandate_details {+ controller+ .validate_merchant_connector_ids_in_connector_mandate_details(+ platform.get_processor().get_key_store(),+ connector_mandate_details,+ merchant_id,+ None,+ )+ .await?;+ };++ let mut migration_status = migration::RecordMigrationStatusBuilder::new();++ let payment_method_create =+ pm_api::PaymentMethodCreate::get_payment_method_create_from_payment_method_data_migrate(+ payment_method_data,+ req,+ );++ let connector_mandate_details = payment_method_create+ .connector_mandate_details+ .clone()+ .map(serde_json::to_value)+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)?;++ let network_transaction_id = payment_method_create.network_transaction_id.clone();++ let res = controller+ .add_payment_method(&payment_method_create)+ .await?;++ let payment_method_response = match res {+ ApplicationResponse::Json(response) => response,+ _ => Err(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to fetch the payment method response")?,+ };++ migration_status.payment_method_migrated(true);+ migration_status.network_transaction_id_migrated(+ network_transaction_id.and_then(|val| (!val.is_empty_after_trim()).then_some(true)),+ );+ migration_status.connector_mandate_details_migrated(+ connector_mandate_details+ .and_then(|val| if val == json!({}) { None } else { Some(true) })+ .or_else(|| {+ payment_method_create+ .connector_mandate_details+ .and_then(|val| (!val.0.is_empty()).then_some(false))+ }),+ );++ let migrate_status = migration_status.build();++ Ok(ApplicationResponse::Json(+ pm_api::PaymentMethodMigrateResponse {+ payment_method_response,+ card_migrated: None,+ payment_method_migrated: migrate_status.payment_method_migrated,+ network_token_migrated: None,+ connector_mandate_details_migrated: migrate_status.connector_mandate_details_migrated,+ network_transaction_id_migrated: migrate_status.network_transaction_migrated,+ },+ ))+}+#[cfg(feature = "v2")]pub async fn migrate_payment_method(_state: &state::PaymentMethodsState,