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(migration): add generic locker's fingerprint ID migration (#12849)

Kashif5fd24f6a0e10
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs
index 5971537ad5..a1c33bd8d5 100644
--- a/crates/api_models/src/events/payment.rs
+++ b/crates/api_models/src/events/payment.rs
@@ -387,6 +387,8 @@ impl ApiEventMetric for PaymentMethodMigrateResponse {
}
}
+impl ApiEventMetric for payment_methods::ModularPaymentMethodMigrationResponse {}
+
impl ApiEventMetric for PaymentMethodUpdate {}
#[cfg(feature = "v1")]
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index a1b96241a9..618918442e 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -3734,6 +3734,15 @@ pub struct PaymentMethodId {
pub payment_method_id: String,
}
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct ModularPaymentMethodMigrationRecord {
+ pub merchant_id: id_type::MerchantId,
+ #[serde(flatten)]
+ pub payment_method_id: PaymentMethodId,
+ #[serde(skip_deserializing, default)]
+ pub line_number: Option<i64>,
+}
+
#[cfg(feature = "v1")]
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
pub struct DefaultPaymentMethod {
@@ -4019,6 +4028,28 @@ pub struct PaymentMethodMigrationResponse {
}
#[derive(Debug, Default, serde::Serialize)]
+pub struct ModularPaymentMethodMigrationResponse {
+ pub total_rows: usize,
+ pub successful_count: usize,
+ pub failed_count: usize,
+ pub results: Vec<ModularPaymentMethodMigrationRowResult>,
+}
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct ModularPaymentMethodMigrationRowResult {
+ pub row_number: usize,
+ pub merchant_id: Option<id_type::MerchantId>,
+ pub payment_method_id: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub old_fingerprint_id: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub new_fingerprint_id: Option<String>,
+ pub migration_status: MigrationStatus,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error_message: Option<String>,
+}
+
+#[derive(Debug, Clone, Default, serde::Serialize)]
pub enum MigrationStatus {
Success,
#[default]
diff --git a/crates/payment_methods/src/controller.rs b/crates/payment_methods/src/controller.rs
index 7b0d353e48..2c21f820e0 100644
--- a/crates/payment_methods/src/controller.rs
+++ b/crates/payment_methods/src/controller.rs
@@ -311,6 +311,31 @@ pub trait PaymentMethodsController {
&self,
pm: &payment_methods::PaymentMethod,
) -> errors::PmResult<api::CardDetailFromLocker>;
+
+ #[cfg(feature = "v1")]
+ async fn retrieve_payment_method_from_vault(
+ &self,
+ vault_id: &payment_methods::VaultId,
+ merchant_id: &id_type::MerchantId,
+ customer_id: &id_type::CustomerId,
+ is_v2_pm: bool,
+ ) -> errors::VaultResult<hyperswitch_domain_models::vault::PaymentMethodVaultingData>;
+
+ #[cfg(feature = "v1")]
+ async fn store_payment_method_in_vault(
+ &self,
+ merchant_id: &id_type::MerchantId,
+ vault_id: &payment_methods::VaultId,
+ data: &hyperswitch_domain_models::vault::PaymentMethodVaultingData,
+ ) -> errors::VaultResult<()>;
+
+ #[cfg(feature = "v1")]
+ async fn get_fingerprint_id_from_vault(
+ &self,
+ entity_id: &Option<String>,
+ fingerprint_data: &hyperswitch_domain_models::vault::FingerprintData,
+ fingerprint_id: String,
+ ) -> errors::VaultResult<String>;
}
pub async fn create_encrypted_data<T>(
diff --git a/crates/payment_methods/src/core/migration.rs b/crates/payment_methods/src/core/migration.rs
index e278c7da5b..73743adfa4 100644
--- a/crates/payment_methods/src/core/migration.rs
+++ b/crates/payment_methods/src/core/migration.rs
@@ -1,5 +1,6 @@
use actix_multipart::form::{self, bytes, text};
use api_models::payment_methods as pm_api;
+use common_utils::id_type;
use csv::Reader;
use error_stack::ResultExt;
#[cfg(feature = "v1")]
@@ -22,9 +23,9 @@ type PmMigrationResult<T> =
pub async fn migrate_payment_methods(
state: &state::PaymentMethodsState,
payment_methods: Vec<pm_api::PaymentMethodRecord>,
- merchant_id: &common_utils::id_type::MerchantId,
+ merchant_id: &id_type::MerchantId,
platform: &platform::Platform,
- mca_ids: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
+ mca_ids: Option<Vec<id_type::MerchantConnectorAccountId>>,
controller: &dyn pm::PaymentMethodsController,
) -> PmMigrationResult<Vec<pm_api::PaymentMethodMigrationResponse>> {
let mut result = Vec::with_capacity(payment_methods.len());
@@ -69,10 +70,9 @@ pub struct PaymentMethodsMigrateForm {
#[multipart(limit = "1MB")]
pub file: bytes::Bytes,
- pub merchant_id: text::Text<common_utils::id_type::MerchantId>,
+ pub merchant_id: text::Text<id_type::MerchantId>,
- pub merchant_connector_id:
- Option<text::Text<common_utils::id_type::MerchantConnectorAccountId>>,
+ pub merchant_connector_id: Option<text::Text<id_type::MerchantConnectorAccountId>>,
pub merchant_connector_ids: Option<text::Text<String>>,
}
@@ -82,8 +82,7 @@ pub struct MerchantConnectorValidator;
impl MerchantConnectorValidator {
pub fn parse_comma_separated_ids(
ids_string: &str,
- ) -> Result<Vec<common_utils::id_type::MerchantConnectorAccountId>, errors::ApiErrorResponse>
- {
+ ) -> Result<Vec<id_type::MerchantConnectorAccountId>, errors::ApiErrorResponse> {
// Estimate capacity based on comma count
let capacity = ids_string.matches(',').count() + 1;
let mut result = Vec::with_capacity(capacity);
@@ -91,11 +90,10 @@ impl MerchantConnectorValidator {
for id in ids_string.split(',') {
let trimmed_id = id.trim();
if !trimmed_id.is_empty() {
- let mca_id =
- common_utils::id_type::MerchantConnectorAccountId::wrap(trimmed_id.to_string())
- .map_err(|_| errors::ApiErrorResponse::InvalidRequestData {
- message: format!("Invalid merchant_connector_account_id: {trimmed_id}"),
- })?;
+ let mca_id = id_type::MerchantConnectorAccountId::wrap(trimmed_id.to_string())
+ .map_err(|_| errors::ApiErrorResponse::InvalidRequestData {
+ message: format!("Invalid merchant_connector_account_id: {trimmed_id}"),
+ })?;
result.push(mca_id);
}
}
@@ -142,9 +140,9 @@ impl MerchantConnectorValidator {
type MigrationValidationResult = Result<
(
- common_utils::id_type::MerchantId,
+ id_type::MerchantId,
Vec<pm_api::PaymentMethodRecord>,
- Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
+ Option<Vec<id_type::MerchantConnectorAccountId>>,
),
errors::ApiErrorResponse,
>;
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 6acfb2a8c8..910b84ff5c 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -1726,7 +1726,7 @@ impl LockerOperations for GenericLocker {
)
.change_context(errors::VaultError::RequestEncodingFailed)?;
- let resp = vault::call_to_vault::<pm_types::VaultRetrieve>(state, payload, None)
+ let resp = vault::call_to_vault::<pm_types::VaultRetrieve>(state, payload, None, None)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")?;
@@ -1754,7 +1754,7 @@ impl LockerOperations for GenericLocker {
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode VaultDeleteRequest")?;
- let resp = vault::call_to_vault::<pm_types::VaultDelete>(state, payload, None)
+ let resp = vault::call_to_vault::<pm_types::VaultDelete>(state, payload, None, None)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")?;
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index fe57f48e7b..63d6ac32e8 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -807,10 +807,11 @@ impl PaymentMethodsController for PmCards<'_> {
key,
)?;
- let resp = vault::call_to_vault::<pm_types::GetVaultFingerprint>(self.state, payload, None)
- .await
- .change_context(errors::VaultError::VaultAPIError)
- .attach_printable("Call to vault failed")?;
+ let resp =
+ vault::call_to_vault::<pm_types::GetVaultFingerprint>(self.state, payload, None, None)
+ .await
+ .change_context(errors::VaultError::VaultAPIError)
+ .attach_printable("Call to vault failed")?;
let fingerprint_resp: pm_types::VaultFingerprintResponse = resp
.parse_struct("VaultFingerprintResponse")
@@ -861,7 +862,7 @@ impl PaymentMethodsController for PmCards<'_> {
let query_params = Some(pm_types::VaultQueryParam::from(pm_types::WriteMode::Insert));
let resp =
- vault::call_to_vault::<pm_types::AddVault>(self.state, payload, query_params)
+ vault::call_to_vault::<pm_types::AddVault>(self.state, payload, query_params, None)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")?;
@@ -914,10 +915,11 @@ impl PaymentMethodsController for PmCards<'_> {
key,
)?;
- let resp = vault::call_to_vault::<pm_types::GetVaultFingerprint>(self.state, payload, None)
- .await
- .change_context(errors::VaultError::VaultAPIError)
- .attach_printable("Call to vault failed")?;
+ let resp =
+ vault::call_to_vault::<pm_types::GetVaultFingerprint>(self.state, payload, None, None)
+ .await
+ .change_context(errors::VaultError::VaultAPIError)
+ .attach_printable("Call to vault failed")?;
let fingerprint_resp: pm_types::VaultFingerprintResponse = resp
.parse_struct("VaultFingerprintResponse")
@@ -967,7 +969,7 @@ impl PaymentMethodsController for PmCards<'_> {
let query_params = Some(pm_types::VaultQueryParam::from(pm_types::WriteMode::Insert));
let resp =
- vault::call_to_vault::<pm_types::AddVault>(self.state, payload, query_params)
+ vault::call_to_vault::<pm_types::AddVault>(self.state, payload, query_params, None)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")?;
@@ -1384,6 +1386,126 @@ impl PaymentMethodsController for PmCards<'_> {
get_card_details_from_locker(self.state, pm).await
}
+ #[cfg(feature = "v1")]
+ async fn retrieve_payment_method_from_vault(
+ &self,
+ vault_id: &domain::VaultId,
+ merchant_id: &id_type::MerchantId,
+ customer_id: &id_type::CustomerId,
+ is_v2_pm: bool,
+ ) -> errors::CustomResult<
+ hyperswitch_domain_models::vault::PaymentMethodVaultingData,
+ errors::VaultError,
+ > {
+ let payload = if !is_v2_pm {
+ pm_types::VaultRetrieveRequest {
+ entity_id: hyperswitch_domain_models::vault::V1VaultEntityId::new(
+ merchant_id.clone(),
+ customer_id.clone(),
+ ),
+ vault_id: vault_id.clone(),
+ }
+ .encode_to_vec()
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode VaultRetrieveRequest")?
+ } else {
+ pm_types::GenericVaultRetrieveRequest {
+ entity_id: customer_id.clone(),
+ vault_id: vault_id.clone(),
+ }
+ .encode_to_vec()
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode GenericVaultRetrieveRequest")?
+ };
+
+ let resp = vault::call_to_vault::<pm_types::VaultRetrieve>(self.state, payload, None, None)
+ .await
+ .change_context(errors::VaultError::VaultAPIError)
+ .attach_printable("Call to vault failed")?;
+
+ let stored_pm_resp: pm_types::VaultRetrieveResponse = resp
+ .parse_struct("VaultRetrieveResponse")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
+ .attach_printable("Failed to parse data into VaultRetrieveResponse")?;
+
+ Ok(stored_pm_resp.data)
+ }
+
+ #[cfg(feature = "v1")]
+ async fn store_payment_method_in_vault(
+ &self,
+ merchant_id: &id_type::MerchantId,
+ vault_id: &domain::VaultId,
+ data: &hyperswitch_domain_models::vault::PaymentMethodVaultingData,
+ ) -> errors::CustomResult<(), errors::VaultError> {
+ let payload = pm_types::AddVaultRequestNew {
+ entity_id: merchant_id.clone(),
+ vault_id: vault_id.clone(),
+ data: data.clone(),
+ ttl: self.state.conf.locker.ttl_for_storage_in_secs,
+ }
+ .encode_to_vec()
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode AddVaultRequest")?;
+
+ let query_params = Some(pm_types::VaultQueryParam::from(pm_types::WriteMode::Insert));
+
+ vault::call_to_vault::<pm_types::AddVault>(self.state, payload, query_params, None)
+ .await
+ .change_context(errors::VaultError::VaultAPIError)
+ .attach_printable("Call to vault failed")?;
+
+ Ok(())
+ }
+
+ #[cfg(feature = "v1")]
+ async fn get_fingerprint_id_from_vault(
+ &self,
+ entity_id: &Option<String>,
+ fingerprint_data: &hyperswitch_domain_models::vault::FingerprintData,
+ fingerprint_id: String,
+ ) -> errors::CustomResult<String, errors::VaultError> {
+ let entity_id = entity_id
+ .to_owned()
+ .get_required_value("Customer key")
+ .change_context(errors::VaultError::MissingRequiredField {
+ field_name: "Customer key",
+ })
+ .attach_printable("entity_id is required to get fingerprint id from vault")?;
+
+ let data = serde_json::to_string(fingerprint_data)
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode fingerprint data")?;
+
+ let payload = pm_types::VaultFingerprintRequestNew {
+ key: entity_id,
+ data,
+ }
+ .encode_to_vec()
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode VaultFingerprintRequestNew")?;
+
+ let resp = vault::call_to_vault::<pm_types::GetVaultFingerprint>(
+ self.state,
+ payload,
+ None,
+ Some(HashMap::from([(
+ crate::headers::X_FINGERPRINT_ID.to_string(),
+ fingerprint_id.to_string(),
+ )])),
+ )
+ .await
+ .change_context(errors::VaultError::VaultAPIError)
+ .attach_printable("Call to vault failed")?;
+
+ let fingerprint_resp: pm_types::VaultFingerprintResponse = resp
+ .parse_struct("VaultFingerprintResponse")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
+ .attach_printable("Failed to parse VaultFingerprintResponse")?;
+
+ Ok(fingerprint_resp.fingerprint_id)
+ }
+
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn retrieve_payment_method(
@@ -6304,7 +6426,7 @@ pub async fn get_bank_debit_from_hs_locker(
token_ref,
)?;
- let resp = vault::call_to_vault::<pm_types::VaultRetrieve>(state, payload, None)
+ let resp = vault::call_to_vault::<pm_types::VaultRetrieve>(state, payload, None, None)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")
@@ -6347,7 +6469,7 @@ pub async fn get_wallet_from_hs_locker(
token_ref,
)?;
- let resp = vault::call_to_vault::<pm_types::VaultRetrieve>(state, payload, None)
+ let resp = vault::call_to_vault::<pm_types::VaultRetrieve>(state, payload, None, None)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")
diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs
index c27afdb408..0262ab55c0 100644
--- a/crates/router/src/core/payment_methods/vault.rs
+++ b/crates/router/src/core/payment_methods/vault.rs
@@ -1,3 +1,5 @@
+use std::collections::HashMap;
+
use common_enums::PaymentMethodType;
#[cfg(any(feature = "v1", feature = "v2"))]
use common_utils::encryption::Encryption;
@@ -1942,6 +1944,7 @@ async fn create_vault_request<R: pm_types::VaultingInterface>(
payload: Vec<u8>,
tenant_id: id_type::TenantId,
write_mode: Option<pm_types::VaultQueryParam>,
+ additional_headers: Option<HashMap<String, String>>,
) -> CustomResult<request::Request, errors::VaultError> {
let private_key = jwekey.vault_private_key.peek().as_bytes();
@@ -1973,6 +1976,12 @@ async fn create_vault_request<R: pm_types::VaultingInterface>(
headers::X_TENANT_ID,
tenant_id.get_string_repr().to_owned().into(),
);
+
+ if let Some(additional_headers) = additional_headers {
+ for (header_name, header_value) in additional_headers {
+ request.add_header(&header_name, header_value.into());
+ }
+ }
request.set_body(request::RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
@@ -1982,6 +1991,7 @@ pub async fn call_to_vault<V: pm_types::VaultingInterface>(
state: &routes::SessionState,
payload: Vec<u8>,
query_params: Option<pm_types::VaultQueryParam>,
+ additional_headers: Option<HashMap<String, String>>,
) -> CustomResult<String, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = state.conf.jwekey.get_inner();
@@ -1992,6 +2002,7 @@ pub async fn call_to_vault<V: pm_types::VaultingInterface>(
payload,
state.tenant.tenant_id.to_owned(),
query_params,
+ additional_headers,
)
.await?;
let response = services::call_connector_api(state, request, V::get_vaulting_flow_name())
@@ -2053,7 +2064,7 @@ async fn get_fingerprint_id_from_vault<D: serde::Serialize>(
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode VaultFingerprintRequestNew")?;
- let resp = call_to_vault::<pm_types::GetVaultFingerprint>(state, payload, None)
+ let resp = call_to_vault::<pm_types::GetVaultFingerprint>(state, payload, None, None)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")?;
@@ -2095,7 +2106,7 @@ pub async fn add_payment_method_to_vault(
let query_params = write_mode.map(pm_types::VaultQueryParam::from);
- let resp = call_to_vault::<pm_types::AddVault>(state, payload, query_params)
+ let resp = call_to_vault::<pm_types::AddVault>(state, payload, query_params, None)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")?;
@@ -2140,7 +2151,7 @@ pub async fn retrieve_value_from_vault(
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode VaultRetrieveRequest")?;
- let resp = call_to_vault::<pm_types::VaultRetrieve>(state, payload, None)
+ let resp = call_to_vault::<pm_types::VaultRetrieve>(state, payload, None, None)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")?;
diff --git a/crates/router/src/core/tokenization.rs b/crates/router/src/core/tokenization.rs
index a6451b72df..cf2a569162 100644
--- a/crates/router/src/core/tokenization.rs
+++ b/crates/router/src/core/tokenization.rs
@@ -54,10 +54,11 @@ pub async fn create_vault_token_core(
let query_params = Some(pm_types::VaultQueryParam::from(pm_types::WriteMode::Insert));
// Call the vault service
- let resp = pm_vault::call_to_vault::<pm_types::AddVault>(&state, payload.clone(), query_params)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Call to vault failed")?;
+ let resp =
+ pm_vault::call_to_vault::<pm_types::AddVault>(&state, payload.clone(), query_params, None)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Call to vault failed")?;
// Parse the response
let stored_resp: pm_types::AddVaultResponse = resp
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index d691797b3b..7beab05ffb 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -90,6 +90,7 @@ pub mod headers {
pub const X_APP_ID: &str = "x-app-id";
pub const X_REDIRECT_URI: &str = "x-redirect-uri";
pub const X_TENANT_ID: &str = "x-tenant-id";
+ pub const X_FINGERPRINT_ID: &str = "x-fingerprint-id";
pub const X_CLIENT_SECRET: &str = "X-Client-Secret";
pub const X_CUSTOMER_ID: &str = "X-Customer-Id";
pub const X_CONNECTED_MERCHANT_ID: &str = "x-connected-merchant-id";
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 7d40dbb363..980ab65053 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1728,6 +1728,10 @@ impl PaymentMethods {
web::resource("/batch")
.route(web::get().to(payment_methods::payment_methods_batch_retrieve_api)),
)
+ .service(
+ web::resource("/fingerprint/migrate-batch")
+ .route(web::post().to(payment_methods::modular_migrate_payment_methods)),
+ )
.service(
web::resource("/tokenize-card")
.route(web::post().to(payment_methods::tokenize_card_api)),
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 3756b61ba5..6d58af8a93 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -132,6 +132,7 @@ impl From<Flow> for ApiIdentifier {
Flow::MandatesRetrieve | Flow::MandatesRevoke | Flow::MandatesList => Self::Mandates,
Flow::PaymentMethodsCreate
| Flow::PaymentMethodsMigrate
+ | Flow::ModularPaymentMethodsMigrate
| Flow::PaymentMethodsBatchUpdate
| Flow::PaymentMethodsBatchRetrieve
| Flow::PaymentMethodsList
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index a1b9df63df..664d479b63 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -1,6 +1,8 @@
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
use std::collections::HashMap;
+#[cfg(feature = "v1")]
+mod migrate;
use ::payment_methods::{
controller::PaymentMethodsController,
core::{migration, migration::payment_methods::migrate_payment_method},
@@ -15,6 +17,8 @@ use hyperswitch_domain_models::{
bulk_tokenization::CardNetworkTokenizeRequest, merchant_key_store::MerchantKeyStore,
payment_methods::PaymentMethodCustomerMigrate, transformers::ForeignTryFrom,
};
+#[cfg(feature = "v1")]
+pub use migrate::modular_migrate_payment_methods;
use router_env::{instrument, logger, tracing, Flow};
use super::app::{AppState, SessionState};
diff --git a/crates/router/src/routes/payment_methods/migrate.rs b/crates/router/src/routes/payment_methods/migrate.rs
new file mode 100644
index 0000000000..a23afc345e
--- /dev/null
+++ b/crates/router/src/routes/payment_methods/migrate.rs
@@ -0,0 +1,1031 @@
+use std::{collections::HashMap, marker::PhantomData};
+
+use ::payment_methods::controller::PaymentMethodsController;
+use actix_multipart::form::{bytes::Bytes as MultipartBytes, MultipartForm};
+use actix_web::{web, HttpRequest, HttpResponse};
+use api_models::payment_methods::{
+ MigrationStatus, ModularPaymentMethodMigrationRecord, ModularPaymentMethodMigrationResponse,
+ ModularPaymentMethodMigrationRowResult, PaymentMethodId,
+};
+use common_enums::{enums, ApiVersion};
+use common_utils::id_type;
+use error_stack::{report, ResultExt};
+use futures::future;
+use hyperswitch_domain_models::platform;
+use router_env::{instrument, logger, tracing, Flow};
+
+use crate::{
+ core::{api_locking, errors, payment_methods::cards},
+ routes::{app::AppState, SessionState},
+ services::{api, authentication as auth, ApplicationResponse},
+};
+
+pub const MAX_FINGERPRINT_ID_MIGRATION_PARALLELISM: usize = 10;
+const MAX_FINGERPRINT_ID_MIGRATION_ROWS: usize = 500;
+
+type MigrationStepResult<T> = Result<T, Box<ModularPaymentMethodMigrationRowResult>>;
+
+#[derive(Debug, MultipartForm)]
+pub struct FingerprintIdMigrationForm {
+ #[multipart(limit = "1MB")]
+ pub file: MultipartBytes,
+}
+
+#[instrument(skip_all, fields(flow = ?Flow::ModularPaymentMethodsMigrate))]
+pub async fn modular_migrate_payment_methods(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ MultipartForm(form): MultipartForm<FingerprintIdMigrationForm>,
+) -> HttpResponse {
+ let flow = Flow::ModularPaymentMethodsMigrate;
+ let csv_bytes = form.file.data.to_vec();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ (),
+ |state, _, _payload, _| {
+ let csv_bytes = csv_bytes.clone();
+ async move { migrate_fingerprint_ids(state, &csv_bytes).await }
+ },
+ &auth::AdminApiAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+async fn migrate_fingerprint_ids(
+ state: SessionState,
+ csv_bytes: &[u8],
+) -> errors::RouterResponse<ModularPaymentMethodMigrationResponse> {
+ let rows = parse_csv(csv_bytes)?;
+ let total_rows = rows.len();
+ let results = rows.hydrate_merchants(&state).await.migrate(&state).await;
+
+ let successful_count = results
+ .iter()
+ .filter(|result| matches!(result.migration_status, MigrationStatus::Success))
+ .count();
+ let failed_count = total_rows - successful_count;
+
+ Ok(ApplicationResponse::Json(
+ ModularPaymentMethodMigrationResponse {
+ total_rows,
+ successful_count,
+ failed_count,
+ results,
+ },
+ ))
+}
+
+fn parse_csv(csv_bytes: &[u8]) -> errors::RouterResult<MigrationBatch<Parsed>> {
+ let mut reader = csv::ReaderBuilder::new()
+ .trim(csv::Trim::All)
+ .from_reader(csv_bytes);
+ let headers = reader
+ .headers()
+ .change_context(errors::ApiErrorResponse::InvalidRequestData {
+ message: "CSV must include header: merchant_id,payment_method_id".to_string(),
+ })?
+ .clone();
+
+ let has_valid_headers = headers.len() == 2
+ && headers.get(0) == Some("merchant_id")
+ && headers.get(1) == Some("payment_method_id");
+
+ if !has_valid_headers {
+ Err(report!(errors::ApiErrorResponse::InvalidRequestData {
+ message: "CSV must include header: merchant_id,payment_method_id".to_string(),
+ }))
+ } else {
+ let rows = reader
+ .records()
+ .enumerate()
+ .map(|(index, record)| {
+ let row_number = index + 2;
+ record
+ .map_err(|error| {
+ Box::new(invalid_row_result(
+ row_number,
+ None,
+ None,
+ format!("Invalid CSV row: {error}"),
+ ))
+ })
+ .and_then(|record| parse_record(row_number, &headers, &record))
+ })
+ .collect::<Vec<_>>();
+
+ match (rows.is_empty(), rows.len() > MAX_FINGERPRINT_ID_MIGRATION_ROWS) {
+ (true, _) => Err(report!(errors::ApiErrorResponse::InvalidRequestData {
+ message: "CSV must contain at least one payment method row".to_string(),
+ })),
+ (_, true) => Err(report!(errors::ApiErrorResponse::InvalidRequestData {
+ message: format!(
+ "CSV can contain at most {MAX_FINGERPRINT_ID_MIGRATION_ROWS} payment method rows"
+ ),
+ })),
+ (false, false) => Ok(MigrationBatch::new(rows)),
+ }
+ }
+}
+
+fn parse_record(
+ row_number: usize,
+ headers: &csv::StringRecord,
+ record: &csv::StringRecord,
+) -> MigrationStepResult<MigrationRow<Parsed>> {
+ let raw_payment_method_id = record.get(1).map(str::to_owned);
+
+ match record.len() == 2 {
+ true => record
+ .deserialize::<ModularPaymentMethodMigrationRecord>(Some(headers))
+ .map(|record| {
+ MigrationRow::new(row_number, record.merchant_id, record.payment_method_id)
+ })
+ .map_err(|_| {
+ Box::new(invalid_row_result(
+ row_number,
+ None,
+ raw_payment_method_id,
+ "CSV row must contain valid merchant_id and payment_method_id values"
+ .to_string(),
+ ))
+ }),
+ false => Err(Box::new(invalid_row_result(
+ row_number,
+ None,
+ raw_payment_method_id,
+ "CSV row must contain valid merchant_id and payment_method_id values".to_string(),
+ ))),
+ }
+}
+
+struct Parsed;
+struct MerchantsHydrated;
+struct PaymentMethodsFetched;
+struct ReadyForVaultRetrieve;
+struct VaultRetrieved;
+struct EligibilityVerified;
+
+struct MigrationBatch<State> {
+ rows: Vec<MigrationStepResult<MigrationRow<State>>>,
+ merchant_contexts: HashMap<id_type::MerchantId, platform::Platform>,
+ merchant_context_errors: HashMap<id_type::MerchantId, String>,
+ customer_cache: HashMap<(String, String), Result<String, String>>,
+ state: PhantomData<State>,
+}
+
+struct MerchantContextBatch {
+ contexts: HashMap<id_type::MerchantId, platform::Platform>,
+ errors: HashMap<id_type::MerchantId, String>,
+}
+
+struct CompletedMigrationChunk {
+ results: Vec<ModularPaymentMethodMigrationRowResult>,
+ customer_cache: HashMap<(String, String), Result<String, String>>,
+}
+
+enum CustomerCacheCandidate<'a> {
+ Ready {
+ row: &'a MigrationRow<EligibilityVerified>,
+ customer_id: &'a id_type::CustomerId,
+ key: (String, String),
+ },
+ Skipped {
+ row_number: usize,
+ merchant_id: Option<id_type::MerchantId>,
+ payment_method_id: Option<String>,
+ reason: String,
+ },
+}
+
+fn customer_cache_candidate(
+ row: &MigrationStepResult<MigrationRow<EligibilityVerified>>,
+) -> CustomerCacheCandidate<'_> {
+ match row {
+ Err(result) => CustomerCacheCandidate::Skipped {
+ row_number: result.row_number,
+ merchant_id: result.merchant_id.clone(),
+ payment_method_id: result.payment_method_id.clone(),
+ reason: result.error_message.clone().unwrap_or_else(|| {
+ "Row already failed before customer cache hydration".to_string()
+ }),
+ },
+ Ok(row) => match row.customer_id.as_ref() {
+ None => CustomerCacheCandidate::Skipped {
+ row_number: row.row_number,
+ merchant_id: Some(row.merchant_id.clone()),
+ payment_method_id: Some(row.payment_method_id.payment_method_id.clone()),
+ reason: "Payment method does not have a customer_id".to_string(),
+ },
+ Some(customer_id) => CustomerCacheCandidate::Ready {
+ row,
+ customer_id,
+ key: customer_cache_key(&row.merchant_id, customer_id),
+ },
+ },
+ }
+}
+
+impl MigrationBatch<Parsed> {
+ fn new(rows: Vec<MigrationStepResult<MigrationRow<Parsed>>>) -> Self {
+ Self {
+ rows,
+ merchant_contexts: HashMap::new(),
+ merchant_context_errors: HashMap::new(),
+ customer_cache: HashMap::new(),
+ state: PhantomData,
+ }
+ }
+
+ async fn hydrate_merchants(self, state: &SessionState) -> MigrationBatch<MerchantsHydrated> {
+ let merchant_ids = self.valid_merchant_ids();
+ let merchant_contexts = get_merchant_contexts_for_batch(state, merchant_ids).await;
+ self.transition_with_contexts::<MerchantsHydrated>(merchant_contexts)
+ }
+}
+
+impl MigrationBatch<MerchantsHydrated> {
+ async fn migrate(self, state: &SessionState) -> Vec<ModularPaymentMethodMigrationRowResult> {
+ let merchant_contexts = self.merchant_contexts;
+ let merchant_context_errors = self.merchant_context_errors;
+ let mut customer_cache = self.customer_cache;
+ let mut rows = self.rows.into_iter();
+ let mut results = Vec::new();
+
+ loop {
+ let row_chunk = rows
+ .by_ref()
+ .take(MAX_FINGERPRINT_ID_MIGRATION_PARALLELISM)
+ .collect::<Vec<_>>();
+
+ if row_chunk.is_empty() {
+ break;
+ }
+
+ let completed_chunk = Self {
+ rows: row_chunk,
+ merchant_contexts: merchant_contexts.clone(),
+ merchant_context_errors: merchant_context_errors.clone(),
+ customer_cache,
+ state: PhantomData::<MerchantsHydrated>,
+ }
+ .fetch_payment_methods(state)
+ .await
+ .prepare_rows()
+ .retrieve_vault_data(state)
+ .await
+ .cache_customers(state)
+ .await
+ .migrate_chunk(state)
+ .await;
+
+ customer_cache = completed_chunk.customer_cache;
+ results.extend(completed_chunk.results);
+ }
+
+ results.sort_by_key(|result| result.row_number);
+ results
+ }
+
+ async fn fetch_payment_methods(
+ self,
+ state: &SessionState,
+ ) -> MigrationBatch<PaymentMethodsFetched> {
+ let mut grouped_rows: HashMap<id_type::MerchantId, Vec<MigrationRow<MerchantsHydrated>>> =
+ HashMap::new();
+ let mut results = Vec::new();
+
+ for row in self.rows {
+ match row {
+ Ok(row) => grouped_rows
+ .entry(row.merchant_id.clone())
+ .or_default()
+ .push(row),
+ Err(result) => results.push(Err(result)),
+ }
+ }
+
+ let mut fetched_rows = Vec::new();
+
+ for (merchant_id, rows) in grouped_rows {
+ match self.merchant_contexts.get(&merchant_id) {
+ None => {
+ let message = self
+ .merchant_context_errors
+ .get(&merchant_id)
+ .cloned()
+ .unwrap_or_else(|| {
+ "Merchant account or key store not found for merchant_id".to_string()
+ });
+ fetched_rows.extend(
+ rows.into_iter()
+ .map(|row| Err(Box::new(row.failed(message.clone())))),
+ );
+ }
+ Some(platform) => {
+ let mut payment_method_ids = Vec::new();
+ for row in &rows {
+ if !payment_method_ids.contains(&row.payment_method_id.payment_method_id) {
+ payment_method_ids
+ .push(row.payment_method_id.payment_method_id.clone());
+ }
+ }
+
+ match state
+ .store
+ .find_payment_methods_by_merchant_id_payment_method_ids(
+ platform.get_provider().get_key_store(),
+ &merchant_id,
+ &payment_method_ids,
+ platform.get_provider().get_account().storage_scheme,
+ )
+ .await
+ {
+ Ok(payment_methods) => {
+ let payment_method_map = payment_methods
+ .into_iter()
+ .map(|payment_method| {
+ (payment_method.payment_method_id.clone(), payment_method)
+ })
+ .collect::<HashMap<_, _>>();
+
+ fetched_rows.extend(rows.into_iter().map(|row| {
+ row.attach_payment_method_or_validate_mismatch(&payment_method_map)
+ }));
+ }
+ Err(error) => {
+ fetched_rows.extend(rows.into_iter().map(|row| {
+ Err(Box::new(row.result(
+ MigrationStatus::Failed,
+ Some(format!(
+ "Failed to fetch payment method records: {error:?}"
+ )),
+ )))
+ }));
+ }
+ }
+ }
+ }
+ }
+
+ fetched_rows.extend(results);
+
+ MigrationBatch {
+ rows: fetched_rows,
+ merchant_contexts: self.merchant_contexts,
+ merchant_context_errors: self.merchant_context_errors,
+ customer_cache: self.customer_cache,
+ state: PhantomData,
+ }
+ }
+}
+
+impl MigrationBatch<PaymentMethodsFetched> {
+ fn prepare_rows(self) -> MigrationBatch<ReadyForVaultRetrieve> {
+ MigrationBatch {
+ rows: self
+ .rows
+ .into_iter()
+ .map(|row| {
+ row.and_then(|row| {
+ row.prepare_for_retrieve().and_then(
+ MigrationRow::<ReadyForVaultRetrieve>::validate_record_version,
+ )
+ })
+ })
+ .collect(),
+ merchant_contexts: self.merchant_contexts,
+ merchant_context_errors: self.merchant_context_errors,
+ customer_cache: self.customer_cache,
+ state: PhantomData,
+ }
+ }
+}
+
+impl MigrationBatch<ReadyForVaultRetrieve> {
+ async fn retrieve_vault_data(
+ self,
+ state: &SessionState,
+ ) -> MigrationBatch<EligibilityVerified> {
+ let merchant_contexts = &self.merchant_contexts;
+ let rows = future::join_all(self.rows.into_iter().map(|row| async move {
+ match row {
+ Ok(row) => match merchant_contexts.get(&row.merchant_id) {
+ Some(platform) => match row.retrieve_from_vault(state, platform).await {
+ Ok(row) => row.validate_vaulting_data(),
+ Err(result) => Err(result),
+ },
+ None => Err(Box::new(
+ row.failed("Merchant account or key store not found for merchant_id"),
+ )),
+ },
+ Err(result) => Err(result),
+ }
+ }))
+ .await;
+
+ MigrationBatch {
+ rows,
+ merchant_contexts: self.merchant_contexts,
+ merchant_context_errors: self.merchant_context_errors,
+ customer_cache: self.customer_cache,
+ state: PhantomData,
+ }
+ }
+}
+
+impl MigrationBatch<EligibilityVerified> {
+ async fn cache_customers(self, state: &SessionState) -> Self {
+ let mut customer_cache = self.customer_cache;
+
+ for row in &self.rows {
+ match customer_cache_candidate(row) {
+ CustomerCacheCandidate::Ready {
+ row,
+ customer_id,
+ key,
+ } if !customer_cache.contains_key(&key) => {
+ let result =
+ match self.merchant_contexts.get(&row.merchant_id) {
+ Some(platform) => match state
+ .store
+ .find_customer_by_customer_id_merchant_id(
+ customer_id,
+ &row.merchant_id,
+ platform.get_provider().get_key_store(),
+ platform.get_provider().get_account().storage_scheme,
+ )
+ .await
+ {
+ Ok(customer) => {
+ customer.get_global_customer_id().clone().ok_or_else(|| {
+ "Customer global id is required for fingerprint migration"
+ .to_string()
+ })
+ }
+ Err(error) => {
+ Err(format!("Failed to fetch customer record: {error:?}"))
+ }
+ },
+ None => Err("Merchant account or key store not found for merchant_id"
+ .to_string()),
+ };
+
+ customer_cache.insert(key, result);
+ }
+ CustomerCacheCandidate::Ready { row, key, .. } => {
+ logger::debug!(
+ row_number = row.row_number,
+ merchant_id = ?row.merchant_id,
+ payment_method_id = row.payment_method_id.payment_method_id,
+ customer_cache_key = ?key,
+ "customer cache hydration skipped because customer was already cached"
+ );
+ }
+ CustomerCacheCandidate::Skipped {
+ row_number,
+ merchant_id,
+ payment_method_id,
+ reason,
+ } => {
+ logger::warn!(
+ row_number,
+ merchant_id = ?merchant_id,
+ payment_method_id = ?payment_method_id,
+ reason,
+ "customer cache hydration skipped for migration row"
+ );
+ }
+ }
+ }
+
+ Self {
+ rows: self.rows,
+ merchant_contexts: self.merchant_contexts,
+ merchant_context_errors: self.merchant_context_errors,
+ customer_cache,
+ state: PhantomData,
+ }
+ }
+}
+
+impl MigrationBatch<EligibilityVerified> {
+ async fn migrate_chunk(self, state: &SessionState) -> CompletedMigrationChunk {
+ let results = future::join_all(self.rows.into_iter().map(|row| async {
+ let result = match row {
+ Ok(row) => {
+ process_row(row, state, &self.merchant_contexts, &self.customer_cache).await
+ }
+ Err(result) => *result,
+ };
+ log_row_result(&result);
+ result
+ }))
+ .await;
+
+ CompletedMigrationChunk {
+ results,
+ customer_cache: self.customer_cache,
+ }
+ }
+}
+
+impl<State> MigrationBatch<State> {
+ fn len(&self) -> usize {
+ self.rows.len()
+ }
+
+ fn valid_merchant_ids(&self) -> Vec<id_type::MerchantId> {
+ let mut merchant_ids = Vec::new();
+ for row in self.rows.iter().flatten() {
+ if !merchant_ids.contains(&row.merchant_id) {
+ merchant_ids.push(row.merchant_id.clone());
+ }
+ }
+ merchant_ids
+ }
+
+ fn transition_with_contexts<NextState>(
+ self,
+ merchant_context_batch: MerchantContextBatch,
+ ) -> MigrationBatch<NextState> {
+ MigrationBatch {
+ rows: self
+ .rows
+ .into_iter()
+ .map(|row| row.map(MigrationRow::transition))
+ .collect(),
+ merchant_contexts: merchant_context_batch.contexts,
+ merchant_context_errors: merchant_context_batch.errors,
+ customer_cache: self.customer_cache,
+ state: PhantomData,
+ }
+ }
+}
+
+struct MigrationRow<State> {
+ row_number: usize,
+ merchant_id: id_type::MerchantId,
+ payment_method_id: PaymentMethodId,
+ payment_method: Option<hyperswitch_domain_models::payment_methods::PaymentMethod>,
+ customer_id: Option<id_type::CustomerId>,
+ vault_id: Option<hyperswitch_domain_models::payment_methods::VaultId>,
+ vaulting_data: Option<hyperswitch_domain_models::vault::PaymentMethodVaultingData>,
+ old_fingerprint_id: Option<String>,
+ is_v2_pm: bool,
+ state: PhantomData<State>,
+}
+
+impl MigrationRow<Parsed> {
+ fn new(
+ row_number: usize,
+ merchant_id: id_type::MerchantId,
+ payment_method_id: PaymentMethodId,
+ ) -> Self {
+ Self {
+ row_number,
+ merchant_id,
+ payment_method_id,
+ payment_method: None,
+ customer_id: None,
+ vault_id: None,
+ vaulting_data: None,
+ old_fingerprint_id: None,
+ is_v2_pm: false,
+ state: PhantomData,
+ }
+ }
+}
+
+impl MigrationRow<MerchantsHydrated> {
+ fn attach_payment_method_or_validate_mismatch(
+ self,
+ payment_method_map: &HashMap<
+ String,
+ hyperswitch_domain_models::payment_methods::PaymentMethod,
+ >,
+ ) -> MigrationStepResult<MigrationRow<PaymentMethodsFetched>> {
+ match payment_method_map.get(&self.payment_method_id.payment_method_id) {
+ Some(payment_method) => self.attach_payment_method(payment_method.clone()),
+ None => Err(Box::new(self.failed(
+ "Payment method not found for merchant_id or belongs to another merchant",
+ ))),
+ }
+ }
+
+ fn attach_payment_method(
+ self,
+ payment_method: hyperswitch_domain_models::payment_methods::PaymentMethod,
+ ) -> MigrationStepResult<MigrationRow<PaymentMethodsFetched>> {
+ let mut next = self.transition::<PaymentMethodsFetched>();
+ next.old_fingerprint_id = payment_method.locker_fingerprint_id.clone();
+ next.payment_method = Some(payment_method);
+ Ok(next)
+ }
+}
+
+impl MigrationRow<PaymentMethodsFetched> {
+ fn prepare_for_retrieve(self) -> MigrationStepResult<MigrationRow<ReadyForVaultRetrieve>> {
+ let payment_method = self
+ .payment_method
+ .as_ref()
+ .ok_or_else(|| Box::new(self.failed("Payment method record was not available")))?;
+ let customer_id = payment_method
+ .customer_id
+ .clone()
+ .ok_or_else(|| Box::new(self.failed("Payment method must have a customer_id")))?;
+ let locker_id = payment_method
+ .locker_id
+ .clone()
+ .ok_or_else(|| Box::new(self.failed("Payment method must have a locker_id")))?;
+ let old_fingerprint_id = payment_method
+ .locker_fingerprint_id
+ .clone()
+ .ok_or_else(|| Box::new(self.failed("Payment method must have a fingerprint")))?;
+
+ let mut next = self.transition::<ReadyForVaultRetrieve>();
+ next.customer_id = Some(customer_id);
+ next.vault_id =
+ Some(hyperswitch_domain_models::payment_methods::VaultId::generate(locker_id));
+ next.old_fingerprint_id = Some(old_fingerprint_id);
+ Ok(next)
+ }
+}
+
+impl MigrationRow<ReadyForVaultRetrieve> {
+ fn validate_record_version(mut self) -> MigrationStepResult<Self> {
+ let payment_method = self
+ .payment_method
+ .as_ref()
+ .ok_or_else(|| Box::new(self.failed("Payment method record was not available")))?;
+
+ match payment_method.version {
+ ApiVersion::V1 => {
+ self.is_v2_pm = false;
+ Ok(self)
+ }
+ ApiVersion::V2 if payment_method.payment_method == Some(enums::PaymentMethod::Card) => {
+ self.is_v2_pm = true;
+ Ok(self)
+ }
+ ApiVersion::V2 => Err(Box::new(
+ self.failed("v2 records can only be card payment methods"),
+ )),
+ }
+ }
+
+ async fn retrieve_from_vault(
+ self,
+ state: &SessionState,
+ platform: &platform::Platform,
+ ) -> MigrationStepResult<MigrationRow<VaultRetrieved>> {
+ let customer_id = self
+ .customer_id
+ .as_ref()
+ .ok_or_else(|| Box::new(self.failed("Payment method must have a customer_id")))?;
+ let vault_id = self
+ .vault_id
+ .as_ref()
+ .ok_or_else(|| Box::new(self.failed("Payment method must have a locker_id")))?;
+ let controller = cards::PmCards {
+ state,
+ provider: platform.get_provider(),
+ };
+
+ match controller
+ .retrieve_payment_method_from_vault(
+ vault_id,
+ &self.merchant_id,
+ customer_id,
+ self.is_v2_pm,
+ )
+ .await
+ {
+ Ok(vaulting_data) => {
+ let mut next = self.transition::<VaultRetrieved>();
+ next.vaulting_data = Some(vaulting_data);
+ Ok(next)
+ }
+ Err(error) => Err(Box::new(self.failed(format!(
+ "Failed to retrieve payment method from vault: {error:?}"
+ )))),
+ }
+ }
+}
+
+impl MigrationRow<VaultRetrieved> {
+ fn validate_vaulting_data(self) -> MigrationStepResult<MigrationRow<EligibilityVerified>> {
+ let payment_method = self
+ .payment_method
+ .as_ref()
+ .ok_or_else(|| Box::new(self.failed("Payment method record was not available")))?;
+ let vaulting_data = self
+ .vaulting_data
+ .as_ref()
+ .ok_or_else(|| Box::new(self.failed("Vaulting data was not available")))?;
+
+ let is_bank_debit = matches!(
+ vaulting_data,
+ hyperswitch_domain_models::vault::PaymentMethodVaultingData::BankDebit(_)
+ );
+ let is_wallet = matches!(
+ vaulting_data,
+ hyperswitch_domain_models::vault::PaymentMethodVaultingData::Wallet(_)
+ );
+ let is_card = matches!(
+ vaulting_data,
+ hyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(_)
+ );
+
+ match payment_method.version {
+ ApiVersion::V1 if is_bank_debit || is_wallet => Ok(self.transition()),
+ ApiVersion::V1 => Err(Box::new(
+ self.failed("v1 records can only be wallet or bank debit"),
+ )),
+ ApiVersion::V2 if is_card => Ok(self.transition()),
+ ApiVersion::V2 => Err(Box::new(
+ self.failed("v2 records can only be card payment methods"),
+ )),
+ }
+ }
+}
+
+impl MigrationRow<EligibilityVerified> {
+ async fn migrate(
+ self,
+ state: &SessionState,
+ platform: &platform::Platform,
+ customer_cache: &HashMap<(String, String), Result<String, String>>,
+ ) -> ModularPaymentMethodMigrationRowResult {
+ match self
+ .execute_vault_migration(state, platform, customer_cache)
+ .await
+ {
+ Ok(new_fingerprint_id) => self.success_result(Some(new_fingerprint_id)),
+ Err(result) => *result,
+ }
+ }
+
+ fn customer_key(
+ &self,
+ customer_cache: &HashMap<(String, String), Result<String, String>>,
+ ) -> MigrationStepResult<String> {
+ let customer_id = self
+ .customer_id
+ .as_ref()
+ .ok_or_else(|| Box::new(self.failed("Payment method must have a customer_id")))?;
+ let key = customer_cache_key(&self.merchant_id, customer_id);
+
+ match customer_cache.get(&key) {
+ Some(Ok(customer_key)) => Ok(customer_key.clone()),
+ Some(Err(error)) => Err(Box::new(self.failed(error.clone()))),
+ None => Err(Box::new(self.failed(
+ "Customer record was not available for fingerprint migration",
+ ))),
+ }
+ }
+
+ async fn execute_vault_migration(
+ &self,
+ state: &SessionState,
+ platform: &platform::Platform,
+ customer_cache: &HashMap<(String, String), Result<String, String>>,
+ ) -> MigrationStepResult<String> {
+ let vault_id = self
+ .vault_id
+ .as_ref()
+ .ok_or_else(|| Box::new(self.failed("Payment method must have a locker_id")))?;
+ let vaulting_data = self
+ .vaulting_data
+ .as_ref()
+ .ok_or_else(|| Box::new(self.failed("Vaulting data was not available")))?;
+ let old_fingerprint_id = self
+ .old_fingerprint_id
+ .clone()
+ .ok_or_else(|| Box::new(self.failed("Payment method must have a fingerprint")))?;
+ let controller = cards::PmCards {
+ state,
+ provider: platform.get_provider(),
+ };
+ let fingerprint_data = vaulting_data.to_fingerprint_data();
+ let customer_key = Some(self.customer_key(customer_cache)?);
+
+ let new_fingerprint_id = controller
+ .get_fingerprint_id_from_vault(&customer_key, &fingerprint_data, old_fingerprint_id)
+ .await
+ .map_err(|error| {
+ Box::new(self.failed(format!(
+ "Failed to create fingerprint record in vault: {error:?}"
+ )))
+ })?;
+
+ controller
+ .store_payment_method_in_vault(&self.merchant_id, vault_id, vaulting_data)
+ .await
+ .map_err(|error| {
+ Box::new(self.failed(format!(
+ "Failed to store payment method in vault with new entity_id: {error:?}"
+ )))
+ })?;
+
+ Ok(new_fingerprint_id)
+ }
+}
+
+impl<State> MigrationRow<State> {
+ fn transition<NextState>(self) -> MigrationRow<NextState> {
+ MigrationRow {
+ row_number: self.row_number,
+ merchant_id: self.merchant_id,
+ payment_method_id: self.payment_method_id,
+ payment_method: self.payment_method,
+ customer_id: self.customer_id,
+ vault_id: self.vault_id,
+ vaulting_data: self.vaulting_data,
+ old_fingerprint_id: self.old_fingerprint_id,
+ is_v2_pm: self.is_v2_pm,
+ state: PhantomData,
+ }
+ }
+
+ fn result(
+ &self,
+ migration_status: MigrationStatus,
+ error_message: Option<String>,
+ ) -> ModularPaymentMethodMigrationRowResult {
+ ModularPaymentMethodMigrationRowResult {
+ row_number: self.row_number,
+ merchant_id: Some(self.merchant_id.clone()),
+ payment_method_id: Some(self.payment_method_id.payment_method_id.clone()),
+ old_fingerprint_id: self.old_fingerprint_id.clone(),
+ new_fingerprint_id: None,
+ migration_status,
+ error_message,
+ }
+ }
+
+ fn failed(&self, message: impl Into<String>) -> ModularPaymentMethodMigrationRowResult {
+ self.result(MigrationStatus::Failed, Some(message.into()))
+ }
+
+ fn success_result(
+ &self,
+ new_fingerprint_id: Option<String>,
+ ) -> ModularPaymentMethodMigrationRowResult {
+ ModularPaymentMethodMigrationRowResult {
+ row_number: self.row_number,
+ merchant_id: Some(self.merchant_id.clone()),
+ payment_method_id: Some(self.payment_method_id.payment_method_id.clone()),
+ old_fingerprint_id: self.old_fingerprint_id.clone(),
+ new_fingerprint_id,
+ migration_status: MigrationStatus::Success,
+ error_message: None,
+ }
+ }
+}
+
+async fn process_row(
+ row: MigrationRow<EligibilityVerified>,
+ state: &SessionState,
+ merchant_contexts: &HashMap<id_type::MerchantId, platform::Platform>,
+ customer_cache: &HashMap<(String, String), Result<String, String>>,
+) -> ModularPaymentMethodMigrationRowResult {
+ match merchant_contexts.get(&row.merchant_id) {
+ None => row.failed("Merchant account or key store not found for merchant_id"),
+ Some(platform) => row.migrate(state, platform, customer_cache).await,
+ }
+}
+
+fn customer_cache_key(
+ merchant_id: &id_type::MerchantId,
+ customer_id: &id_type::CustomerId,
+) -> (String, String) {
+ (
+ merchant_id.get_string_repr().to_owned(),
+ customer_id.get_string_repr().to_owned(),
+ )
+}
+
+fn invalid_row_result(
+ row_number: usize,
+ merchant_id: Option<id_type::MerchantId>,
+ payment_method_id: Option<String>,
+ message: String,
+) -> ModularPaymentMethodMigrationRowResult {
+ ModularPaymentMethodMigrationRowResult {
+ row_number,
+ merchant_id,
+ payment_method_id,
+ old_fingerprint_id: None,
+ new_fingerprint_id: None,
+ migration_status: MigrationStatus::Failed,
+ error_message: Some(message),
+ }
+}
+
+fn log_row_result(result: &ModularPaymentMethodMigrationRowResult) {
+ logger::info!(
+ row_number = result.row_number,
+ merchant_id = ?result.merchant_id,
+ payment_method_id = ?result.payment_method_id,
+ status = ?result.migration_status,
+ error_message = ?result.error_message,
+ "fingerprint id migration row processed"
+ );
+}
+
+async fn get_merchant_contexts_for_batch(
+ state: &SessionState,
+ merchant_ids: Vec<id_type::MerchantId>,
+) -> MerchantContextBatch {
+ match state
+ .store
+ .list_multiple_key_stores(
+ merchant_ids.clone(),
+ &state.store.get_master_key().to_vec().into(),
+ )
+ .await
+ {
+ Err(error) => {
+ logger::error!("Failed to bulk fetch merchant key stores: {:?}", error);
+ MerchantContextBatch::all_failed(
+ merchant_ids,
+ "Failed to fetch merchant key stores".to_string(),
+ )
+ }
+ Ok(key_stores) => match state
+ .store
+ .list_multiple_merchant_accounts(merchant_ids.clone())
+ .await
+ {
+ Err(error) => {
+ logger::error!("Failed to bulk fetch merchant accounts: {:?}", error);
+ MerchantContextBatch::all_failed(
+ merchant_ids,
+ "Failed to fetch merchant accounts".to_string(),
+ )
+ }
+ Ok(merchant_accounts) => {
+ let key_store_map = key_stores
+ .into_iter()
+ .map(|key_store| (key_store.merchant_id.clone(), key_store))
+ .collect::<HashMap<_, _>>();
+ let merchant_account_map = merchant_accounts
+ .into_iter()
+ .map(|merchant_account| (merchant_account.get_id().clone(), merchant_account))
+ .collect::<HashMap<_, _>>();
+ let mut contexts = HashMap::new();
+ let mut errors = HashMap::new();
+
+ for merchant_id in merchant_ids {
+ match (
+ key_store_map.get(&merchant_id),
+ merchant_account_map.get(&merchant_id),
+ ) {
+ (Some(key_store), Some(merchant_account)) => {
+ contexts.insert(
+ merchant_id,
+ platform::Platform::new(
+ merchant_account.clone(),
+ key_store.clone(),
+ merchant_account.clone(),
+ key_store.clone(),
+ None,
+ ),
+ );
+ }
+ (None, _) => {
+ errors.insert(
+ merchant_id,
+ "Failed to fetch merchant key store".to_string(),
+ );
+ }
+ (_, None) => {
+ errors.insert(
+ merchant_id,
+ "Failed to fetch merchant account".to_string(),
+ );
+ }
+ }
+ }
+
+ MerchantContextBatch { contexts, errors }
+ }
+ },
+ }
+}
+
+impl MerchantContextBatch {
+ fn all_failed(merchant_ids: Vec<id_type::MerchantId>, message: String) -> Self {
+ Self {
+ contexts: HashMap::new(),
+ errors: merchant_ids
+ .into_iter()
+ .map(|merchant_id| (merchant_id, message.clone()))
+ .collect(),
+ }
+ }
+}
diff --git a/crates/router/src/types/payment_methods.rs b/crates/router/src/types/payment_methods.rs
index c1f372519a..45c59d3e8b 100644
--- a/crates/router/src/types/payment_methods.rs
+++ b/crates/router/src/types/payment_methods.rs
@@ -33,6 +33,13 @@ pub struct VaultFingerprintRequest {
pub key: hyperswitch_domain_models::vault::V1VaultEntityId,
}
+#[cfg(feature = "v1")]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct GenericVaultRetrieveRequest {
+ pub entity_id: id_type::CustomerId,
+ pub vault_id: domain::VaultId,
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultFingerprintRequestNew {
pub data: String,
diff --git a/crates/router/src/workflows/payment_method_modular_backward_compat.rs b/crates/router/src/workflows/payment_method_modular_backward_compat.rs
index bbcbfa699d..220628d654 100644
--- a/crates/router/src/workflows/payment_method_modular_backward_compat.rs
+++ b/crates/router/src/workflows/payment_method_modular_backward_compat.rs
@@ -197,7 +197,7 @@ pub async fn backfill_legacy_locker_card(
)?;
let vault_response =
- vault::call_to_vault::<pm_types::VaultRetrieve>(state, payload, None)
+ vault::call_to_vault::<pm_types::VaultRetrieve>(state, payload, None, None)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
@@ -361,7 +361,7 @@ pub async fn backfill_legacy_locker_card(
)?;
let vault_response = vault::call_to_vault::<pm_types::VaultRetrieve>(
- state, payload, None,
+ state, payload, None, None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/workflows/payment_method_modular_forward_compat.rs b/crates/router/src/workflows/payment_method_modular_forward_compat.rs
index b6465817ce..3651eaf4ad 100644
--- a/crates/router/src/workflows/payment_method_modular_forward_compat.rs
+++ b/crates/router/src/workflows/payment_method_modular_forward_compat.rs
@@ -151,14 +151,15 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodModularForwardCompatW
let query_params =
Some(pm_types::VaultQueryParam::from(pm_types::WriteMode::Upsert));
- let resp = vault::call_to_vault::<pm_types::AddVault>(state, payload, query_params)
- .await
- .change_context(errors::VaultError::VaultAPIError)
- .attach_printable("Call to vault failed")
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "Failed to add payment method in generic locker in compatibility PT",
- )?;
+ let resp =
+ vault::call_to_vault::<pm_types::AddVault>(state, payload, query_params, None)
+ .await
+ .change_context(errors::VaultError::VaultAPIError)
+ .attach_printable("Call to vault failed")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to add payment method in generic locker in compatibility PT",
+ )?;
let _stored_pm_resp =
cards::parse_add_vault_response(should_trigger_fingerprint_migration, resp)
@@ -242,6 +243,7 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodModularForwardCompatW
state,
network_token_payload,
network_token_query_params,
+ None,
)
.await
.change_context(errors::VaultError::VaultAPIError)
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index af61c6dddf..f76f6ba2fe 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -136,6 +136,8 @@ pub enum Flow {
PaymentMethodsCreate,
/// Payment methods migrate flow.
PaymentMethodsMigrate,
+ /// Modular Payment methods migrate flow.
+ ModularPaymentMethodsMigrate,
/// Payment methods batch update flow.
PaymentMethodsBatchUpdate,
/// Payment methods batch retrieve flow.