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(payment-methods): add forward compatibility for PM modular service (#11942)

Kashif2b441d15cd15
diff --git a/config/superposition_seed.toml b/config/superposition_seed.toml
index acb4dd4311..48d1b89943 100644
--- a/config/superposition_seed.toml
+++ b/config/superposition_seed.toml
@@ -127,6 +127,12 @@ schema = { type = "boolean" }
description = "Whether to call the PM modular service for an organization"
change_reason = "Initial setup"
+[default-configs.should_schedule_modular_forward_compat]
+value = false
+schema = { type = "boolean" }
+description = "Whether to schedule PM modular forward compatibility PT for a merchant"
+change_reason = "Initial setup"
+
[default-configs.should_return_raw_payment_method_details]
value = false
schema = { type = "boolean" }
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index f6a9e11c85..0511055fbc 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -10697,6 +10697,7 @@ pub enum ProcessTrackerRunner {
OutgoingWebhookRetryWorkflow,
AttachPayoutAccountWorkflow,
PaymentMethodStatusUpdateWorkflow,
+ PaymentMethodModularForwardCompatWorkflow,
PassiveRecoveryWorkflow,
ProcessDisputeWorkflow,
DisputeListWorkflow,
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index 2ea45b0801..c12b9340dd 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -68,6 +68,15 @@ pub struct PaymentMethod {
pub customer_details: Option<Encryption>,
pub locker_fingerprint_id: Option<String>,
pub network_tokenization_data: Option<Encryption>,
+ // Compatibility-only field: backfilled by modular-compat PT to align with v2 identifier semantics.
+ // Do not use this column in v1 business logic.
+ pub id: Option<String>,
+ // Compatibility-only field: backfilled by modular-compat PT for v2 interoperability.
+ // Do not use this column in v1 business logic.
+ pub payment_method_type_v2: Option<storage_enums::PaymentMethod>,
+ // Compatibility-only field: backfilled by modular-compat PT for v2 interoperability.
+ // Do not use this column in v1 business logic.
+ pub payment_method_subtype: Option<storage_enums::PaymentMethodType>,
}
#[cfg(feature = "v2")]
@@ -101,9 +110,9 @@ pub struct PaymentMethod {
pub customer_details: Option<Encryption>,
pub locker_fingerprint_id: Option<String>,
pub network_tokenization_data: Option<Encryption>,
+ pub id: common_utils::id_type::GlobalPaymentMethodId,
pub payment_method_type_v2: Option<storage_enums::PaymentMethod>,
pub payment_method_subtype: Option<storage_enums::PaymentMethodType>,
- pub id: common_utils::id_type::GlobalPaymentMethodId,
pub external_vault_token_data: Option<Encryption>,
}
@@ -166,6 +175,7 @@ pub struct PaymentMethodNew {
pub customer_details: Option<Encryption>,
pub locker_fingerprint_id: Option<String>,
pub network_tokenization_data: Option<Encryption>,
+ pub id: Option<String>,
}
#[cfg(feature = "v2")]
@@ -292,6 +302,14 @@ pub enum PaymentMethodUpdate {
payment_method_data: Option<Encryption>,
last_modified_by: Option<String>,
},
+ // Compatibility-only update used by modular-compat PT.
+ // Do not use this for normal v1 payment method updates.
+ PopulateModularCompatFields {
+ id: String,
+ payment_method_type_v2: Option<storage_enums::PaymentMethod>,
+ payment_method_subtype: Option<storage_enums::PaymentMethodType>,
+ last_modified_by: Option<String>,
+ },
}
#[cfg(feature = "v2")]
@@ -441,7 +459,12 @@ impl PaymentMethodUpdateInternal {
#[cfg(feature = "v1")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)]
+// Diesel derive assumes `id` as primary key unless explicitly configured.
+// This changeset must update the nullable `payment_methods.id` column, so we
+// pin the actual primary key to `payment_method_id`.
+// Ref: https://diesel.rs/guides/all-about-updates/
#[diesel(table_name = payment_methods)]
+#[diesel(primary_key(payment_method_id))]
pub struct PaymentMethodUpdateInternal {
metadata: Option<serde_json::Value>,
payment_method_data: Option<Encryption>,
@@ -462,6 +485,9 @@ pub struct PaymentMethodUpdateInternal {
last_modified_by: Option<String>,
customer_details: Option<Encryption>,
network_tokenization_data: Option<Encryption>,
+ payment_method_type_v2: Option<storage_enums::PaymentMethod>,
+ payment_method_subtype: Option<storage_enums::PaymentMethodType>,
+ id: Option<String>,
}
#[cfg(feature = "v1")]
@@ -487,6 +513,9 @@ impl PaymentMethodUpdateInternal {
last_modified_by,
customer_details,
network_tokenization_data,
+ payment_method_type_v2,
+ payment_method_subtype,
+ id,
} = self;
PaymentMethod {
@@ -535,6 +564,9 @@ impl PaymentMethodUpdateInternal {
customer_details: customer_details.or(source.customer_details),
network_tokenization_data: network_tokenization_data
.or(source.network_tokenization_data),
+ payment_method_type_v2: payment_method_type_v2.or(source.payment_method_type_v2),
+ payment_method_subtype: payment_method_subtype.or(source.payment_method_subtype),
+ id: id.or(source.id),
}
}
}
@@ -567,6 +599,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_modified_by,
customer_details: None,
network_tokenization_data: None,
+ id: None,
+ payment_method_type_v2: None,
+ payment_method_subtype: None,
},
PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data,
@@ -591,6 +626,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_modified_by,
customer_details: None,
network_tokenization_data: None,
+ id: None,
+ payment_method_type_v2: None,
+ payment_method_subtype: None,
},
PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self {
metadata: None,
@@ -612,6 +650,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_modified_by: None,
customer_details: None,
network_tokenization_data: None,
+ id: None,
+ payment_method_type_v2: None,
+ payment_method_subtype: None,
},
PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed {
payment_method_data,
@@ -638,6 +679,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_modified_by,
customer_details: None,
network_tokenization_data: None,
+ id: None,
+ payment_method_type_v2: None,
+ payment_method_subtype: None,
},
PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
network_transaction_id,
@@ -663,6 +707,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_modified_by,
customer_details: None,
network_tokenization_data: None,
+ id: None,
+ payment_method_type_v2: None,
+ payment_method_subtype: None,
},
PaymentMethodUpdate::StatusUpdate {
status,
@@ -687,6 +734,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_modified_by,
customer_details: None,
network_tokenization_data: None,
+ id: None,
+ payment_method_type_v2: None,
+ payment_method_subtype: None,
},
PaymentMethodUpdate::AdditionalDataUpdate {
payment_method_data,
@@ -724,6 +774,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_modified_by,
customer_details: None,
network_tokenization_data,
+ id: None,
+ payment_method_type_v2: None,
+ payment_method_subtype: None,
},
PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
connector_mandate_details,
@@ -748,6 +801,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_modified_by,
customer_details: None,
network_tokenization_data: None,
+ id: None,
+ payment_method_type_v2: None,
+ payment_method_subtype: None,
},
PaymentMethodUpdate::NetworkTokenDataUpdate {
network_token_requestor_reference_id,
@@ -775,6 +831,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_modified_by,
customer_details: None,
network_tokenization_data,
+ id: None,
+ payment_method_type_v2: None,
+ payment_method_subtype: None,
},
PaymentMethodUpdate::ConnectorNetworkTransactionIdAndMandateDetailsUpdate {
connector_mandate_details,
@@ -801,6 +860,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_modified_by,
customer_details: None,
network_tokenization_data: None,
+ id: None,
+ payment_method_type_v2: None,
+ payment_method_subtype: None,
},
PaymentMethodUpdate::PaymentMethodBatchUpdate {
connector_mandate_details,
@@ -829,6 +891,38 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_modified_by,
customer_details: None,
network_tokenization_data: None,
+ id: None,
+ payment_method_type_v2: None,
+ payment_method_subtype: None,
+ },
+ PaymentMethodUpdate::PopulateModularCompatFields {
+ id,
+ payment_method_type_v2,
+ payment_method_subtype,
+ last_modified_by,
+ } => Self {
+ metadata: None,
+ payment_method_data: None,
+ last_used_at: None,
+ network_transaction_id: None,
+ status: None,
+ locker_id: None,
+ network_token_requestor_reference_id: None,
+ payment_method: None,
+ connector_mandate_details: None,
+ updated_by: None,
+ payment_method_issuer: None,
+ payment_method_type: None,
+ last_modified: common_utils::date_time::now(),
+ network_token_locker_id: None,
+ network_token_payment_method_data: None,
+ scheme: None,
+ last_modified_by,
+ customer_details: None,
+ network_tokenization_data: None,
+ payment_method_type_v2,
+ payment_method_subtype,
+ id: Some(id),
},
}
}
@@ -1081,6 +1175,9 @@ impl From<&PaymentMethodNew> for PaymentMethod {
customer_details: payment_method_new.customer_details.clone(),
locker_fingerprint_id: payment_method_new.locker_fingerprint_id.clone(),
network_tokenization_data: payment_method_new.network_tokenization_data.clone(),
+ payment_method_type_v2: None,
+ payment_method_subtype: None,
+ id: payment_method_new.id.clone(),
}
}
}
@@ -1131,7 +1228,6 @@ impl From<&PaymentMethodNew> for PaymentMethod {
}
}
-#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentsMandateReferenceRecord {
pub connector_mandate_id: String,
@@ -1157,14 +1253,12 @@ pub struct ConnectorTokenReferenceRecord {
pub connector_customer_id: Option<String>,
}
-#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct PaymentsMandateReference(
pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>,
);
-#[cfg(feature = "v1")]
impl std::ops::Deref for PaymentsMandateReference {
type Target =
HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>;
@@ -1174,7 +1268,6 @@ impl std::ops::Deref for PaymentsMandateReference {
}
}
-#[cfg(feature = "v1")]
impl std::ops::DerefMut for PaymentsMandateReference {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
@@ -1205,6 +1298,46 @@ impl std::ops::DerefMut for PaymentsTokenReference {
}
}
+#[cfg(feature = "v2")]
+impl From<PaymentsMandateReference> for PaymentsTokenReference {
+ fn from(payments_mandate_reference: PaymentsMandateReference) -> Self {
+ let mapped_records = payments_mandate_reference
+ .0
+ .into_iter()
+ .map(|(mca_id, record)| {
+ let token_status = match record.connector_mandate_status {
+ Some(common_enums::ConnectorMandateStatus::Active) => {
+ common_enums::ConnectorTokenStatus::Active
+ }
+ Some(common_enums::ConnectorMandateStatus::Inactive) => {
+ common_enums::ConnectorTokenStatus::Inactive
+ }
+ None => common_enums::ConnectorTokenStatus::Inactive,
+ };
+
+ let token_record = ConnectorTokenReferenceRecord {
+ connector_token: record.connector_mandate_id,
+ payment_method_subtype: record.payment_method_type,
+ original_payment_authorized_amount: record
+ .original_payment_authorized_amount
+ .map(common_utils::types::MinorUnit::new),
+ original_payment_authorized_currency: record
+ .original_payment_authorized_currency,
+ metadata: record.mandate_metadata,
+ connector_token_status: token_status,
+ connector_token_request_reference_id: record
+ .connector_mandate_request_reference_id,
+ connector_customer_id: record.connector_customer_id,
+ };
+
+ (mca_id, token_record)
+ })
+ .collect();
+
+ Self(mapped_records)
+ }
+}
+
#[cfg(feature = "v1")]
common_utils::impl_to_sql_from_sql_json!(PaymentsMandateReference);
@@ -1277,6 +1410,39 @@ impl CommonMandateReference {
Ok(payments)
}
+ #[cfg(feature = "v2")]
+ fn parse_payments_reference_with_legacy_fallback(
+ payments_json: serde_json::Value,
+ ) -> CustomResult<PaymentsTokenReference, ParsingError> {
+ match serde_json::from_value::<PaymentsTokenReference>(payments_json.clone()) {
+ Ok(token_reference) => Ok(token_reference),
+ Err(token_err) => {
+ router_env::logger::warn!(
+ "Failed to parse connector_mandate_details as PaymentsTokenReference: {}. Falling back to PaymentsMandateReference parser",
+ token_err
+ );
+
+ let legacy_reference =
+ serde_json::from_value::<PaymentsMandateReference>(payments_json)
+ .inspect_err(|legacy_err| {
+ router_env::logger::error!(
+ "Failed to parse connector_mandate_details as PaymentsMandateReference: {}",
+ legacy_err
+ );
+ })
+ .change_context(ParsingError::StructParseFailure(
+ "Failed to parse payments data",
+ ))?;
+
+ router_env::logger::info!(
+ "Parsed connector_mandate_details using legacy mandate shape fallback"
+ );
+
+ Ok(PaymentsTokenReference::from(legacy_reference))
+ }
+ }
+ }
+
#[cfg(feature = "v2")]
/// Insert a new payment token reference for the given connector_id
pub fn insert_payment_token_reference_record(
@@ -1378,15 +1544,9 @@ where
.map(|obj| {
obj.remove("payouts");
- serde_json::from_value::<PaymentsTokenReference>(serde_json::Value::Object(
+ Self::parse_payments_reference_with_legacy_fallback(serde_json::Value::Object(
obj.clone(),
))
- .inspect_err(|err| {
- router_env::logger::error!("Failed to parse payments data: {}", err);
- })
- .change_context(ParsingError::StructParseFailure(
- "Failed to parse payments data",
- ))
})
.transpose()?;
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index f6fd4a1351..4e5bece420 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1389,6 +1389,12 @@ diesel::table! {
#[max_length = 64]
locker_fingerprint_id -> Nullable<Varchar>,
network_tokenization_data -> Nullable<Bytea>,
+ #[max_length = 64]
+ id -> Nullable<Varchar>,
+ #[max_length = 64]
+ payment_method_type_v2 -> Nullable<Varchar>,
+ #[max_length = 64]
+ payment_method_subtype -> Nullable<Varchar>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index f129f0195f..c8f51990f9 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -1325,11 +1325,11 @@ diesel::table! {
locker_fingerprint_id -> Nullable<Varchar>,
network_tokenization_data -> Nullable<Bytea>,
#[max_length = 64]
+ id -> Varchar,
+ #[max_length = 64]
payment_method_type_v2 -> Nullable<Varchar>,
#[max_length = 64]
payment_method_subtype -> Nullable<Varchar>,
- #[max_length = 64]
- id -> Varchar,
external_vault_token_data -> Nullable<Bytea>,
}
}
diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs
index 36df49150d..1760e18775 100644
--- a/crates/hyperswitch_domain_models/src/payment_methods.rs
+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs
@@ -495,6 +495,9 @@ impl super::behaviour::Conversion for PaymentMethod {
customer_details: self.customer_details.map(|val| val.into()),
locker_fingerprint_id: self.locker_fingerprint_id,
network_tokenization_data: self.network_tokenization_data.map(|val| val.into()),
+ payment_method_type_v2: None,
+ payment_method_subtype: None,
+ id: None,
})
}
@@ -710,6 +713,7 @@ impl super::behaviour::Conversion for PaymentMethod {
customer_details: self.customer_details.map(|val| val.into()),
locker_fingerprint_id: self.locker_fingerprint_id,
network_tokenization_data: self.network_tokenization_data.map(|val| val.into()),
+ id: None,
})
}
}
diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs
index 57332532fd..511f5e3bd6 100644
--- a/crates/router/src/bin/scheduler.rs
+++ b/crates/router/src/bin/scheduler.rs
@@ -330,6 +330,9 @@ impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner {
storage::ProcessTrackerRunner::PaymentMethodStatusUpdateWorkflow => Ok(Box::new(
workflows::payment_method_status_update::PaymentMethodStatusUpdateWorkflow,
)),
+ storage::ProcessTrackerRunner::PaymentMethodModularForwardCompatWorkflow => Ok(Box::new(
+ workflows::payment_method_modular_forward_compat::PaymentMethodModularForwardCompatWorkflow,
+ )),
storage::ProcessTrackerRunner::PassiveRecoveryWorkflow => {
Ok(Box::new(workflows::revenue_recovery::ExecutePcrWorkflow))
}
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 71feae848d..8c948a3682 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -380,6 +380,9 @@ pub mod superposition {
"should_return_raw_payment_method_details";
/// Call PM modular service configuration key
pub const SHOULD_CALL_PM_MODULAR_SERVICE: &str = "should_call_pm_modular_service";
+ /// Schedule PM modular forward compatibility PT configuration key
+ pub const SHOULD_SCHEDULE_MODULAR_FORWARD_COMPAT: &str =
+ "should_schedule_modular_forward_compat";
/// dynamic fields configuration key for sdk config
pub const DYNAMIC_FIELDS: &str = "dynamic_fields";
/// payout sync tracker configuration key
diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rs
index 7bc8383346..b5bcc0d4e9 100644
--- a/crates/router/src/core/configs/dimension_config.rs
+++ b/crates/router/src/core/configs/dimension_config.rs
@@ -327,6 +327,24 @@ impl DatabaseBackedConfig for ShouldCallPmModularService {
}
}
+config! {
+ superposition_key = SHOULD_SCHEDULE_MODULAR_FORWARD_COMPAT,
+ output = bool,
+ default = false,
+ requires = dimension_state::DimensionsWithProviderMerchantId,
+ targeting_key = id_type::CustomerId
+}
+
+impl DatabaseBackedConfig for ShouldScheduleModularForwardCompat {
+ const KEY: &'static str = "should_schedule_modular_forward_compat";
+
+ fn db_key(dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {
+ dimensions
+ .get_provider_merchant_id()
+ .map(|id| format!("{}_{}", Self::KEY, id.get_string_repr()))
+ }
+}
+
config! {
superposition_key = PAYOUT_TRACKER_MAPPING,
output = RetryMapping,
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 18f9b26db0..c8e81b73c1 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -105,6 +105,8 @@ use crate::{
const PAYMENT_METHOD_STATUS_UPDATE_TASK: &str = "PAYMENT_METHOD_STATUS_UPDATE";
const PAYMENT_METHOD_STATUS_TAG: &str = "PAYMENT_METHOD_STATUS";
+const PAYMENT_METHOD_MODULAR_FORWARD_COMPAT_TASK: &str = "PAYMENT_METHOD_MODULAR_FORWARD_COMPAT";
+const PAYMENT_METHOD_MODULAR_FORWARD_COMPAT_TAG: &str = "PAYMENT_METHOD_MODULAR_FORWARD_COMPAT";
#[cfg(feature = "v2")]
const PAYMENT_METHOD_REDACTED_FINGERPRINT_ID: &str = "FINGERPRINT_ID_REDACTED";
@@ -522,6 +524,60 @@ pub async fn add_payment_method_status_update_task(
Ok(())
}
+#[cfg(feature = "v1")]
+pub async fn add_payment_method_modular_forward_compat_task(
+ db: &dyn StorageInterface,
+ payment_method: &domain::PaymentMethod,
+ merchant_id: &id_type::MerchantId,
+ application_source: common_enums::ApplicationSource,
+ initiator: Option<&hyperswitch_domain_models::platform::Initiator>,
+) -> Result<(), ProcessTrackerError> {
+ let tracking_data = storage::PaymentMethodModularCompatTrackingData {
+ payment_method_id: payment_method.payment_method_id.clone(),
+ merchant_id: merchant_id.to_owned(),
+ last_modified_by: initiator
+ .and_then(|initiator| initiator.to_created_by())
+ .map(|last_modified_by| last_modified_by.to_string()),
+ };
+
+ let runner = storage::ProcessTrackerRunner::PaymentMethodModularForwardCompatWorkflow;
+ let task = PAYMENT_METHOD_MODULAR_FORWARD_COMPAT_TASK;
+ let tag = [PAYMENT_METHOD_MODULAR_FORWARD_COMPAT_TAG];
+ let process_tracker_id = generate_task_id_for_payment_method_status_update_workflow(
+ payment_method.payment_method_id.as_str(),
+ runner,
+ task,
+ );
+
+ let process_tracker_entry = storage::ProcessTrackerNew::new(
+ process_tracker_id,
+ task,
+ runner,
+ tag,
+ tracking_data,
+ None,
+ common_utils::date_time::now(),
+ common_types::consts::API_VERSION,
+ application_source,
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to construct PAYMENT_METHOD_MODULAR_FORWARD_COMPAT process tracker task",
+ )?;
+
+ db.insert_process(process_tracker_entry)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable_lazy(|| {
+ format!(
+ "Failed while inserting PAYMENT_METHOD_MODULAR_FORWARD_COMPAT task to process_tracker for payment_method_id: {}",
+ payment_method.payment_method_id
+ )
+ })?;
+
+ Ok(())
+}
+
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
@@ -4258,11 +4314,9 @@ pub async fn fetch_payment_method_by_storage(
}
Some(_) => Err(report!(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Unexpected token data variant for payment method fetch")),
- None => id_type::GlobalPaymentMethodId::generate_from_string(
+ None => Ok(id_type::GlobalPaymentMethodId::new_unchecked(
pm_incoming.payment_method_id.clone(),
- )
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to generate GlobalPaymentMethodId"),
+ )),
}?;
fetch_payment_method_with_fallback(state, provider, &pm_id, storage_type)
@@ -4710,9 +4764,7 @@ pub async fn delete_payment_method(
platform: domain::Platform,
profile: domain::Profile,
) -> RouterResponse<api::PaymentMethodDeleteResponse> {
- let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(pm_id.payment_method_id)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to generate GlobalPaymentMethodId")?;
+ let pm_id = id_type::GlobalPaymentMethodId::new_unchecked(pm_id.payment_method_id);
let response = Box::pin(delete_payment_method_core(
&state, pm_id, &platform, &profile,
))
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index f469a44df6..721eecceb1 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -213,6 +213,45 @@ impl PaymentMethodsController for PmCards<'_> {
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
+ let should_schedule_modular_forward_compat =
+ payment_method_utils::get_should_schedule_modular_forward_compat(
+ self.state,
+ &dimension_state::Dimensions::new()
+ .with_provider_merchant_id(self.provider.get_provider_merchant_id()),
+ Some(customer_id),
+ )
+ .await;
+
+ if should_schedule_modular_forward_compat {
+ let res = super::add_payment_method_modular_forward_compat_task(
+ &*self.state.store,
+ &response,
+ merchant_id,
+ self.state.conf.application_source,
+ initiator,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to add payment method modular compatibility task in process tracker",
+ );
+
+ if let Err(err) = res {
+ logger::error!(
+ ?err,
+ payment_method_id=%response.payment_method_id,
+ merchant_id=%merchant_id.get_string_repr(),
+ "Failed to schedule modular forward compatibility PT; continuing payment method create flow"
+ );
+ }
+ } else {
+ logger::debug!(
+ payment_method_id=%response.payment_method_id,
+ merchant_id=%merchant_id.get_string_repr(),
+ "Skipping modular forward compatibility PT scheduling by config"
+ );
+ }
+
if customer.default_payment_method_id.is_none() && req.payment_method.is_some() {
let _ = self
.set_default_payment_method(
diff --git a/crates/router/src/core/payment_methods/utils.rs b/crates/router/src/core/payment_methods/utils.rs
index 4b5813f2b6..6be1a4329f 100644
--- a/crates/router/src/core/payment_methods/utils.rs
+++ b/crates/router/src/core/payment_methods/utils.rs
@@ -825,6 +825,20 @@ pub async fn get_organization_eligibility_config_for_pm_modular_service(
.await
}
+pub async fn get_should_schedule_modular_forward_compat(
+ state: &SessionState,
+ dimensions: &dimension_state::DimensionsWithProviderMerchantId,
+ customer_id: Option<&common_utils::id_type::CustomerId>,
+) -> bool {
+ dimensions
+ .get_should_schedule_modular_forward_compat(
+ state.store.as_ref(),
+ state.superposition_service.as_ref(),
+ customer_id,
+ )
+ .await
+}
+
pub async fn get_sdk_next_action_for_payment_method_list(
state: &SessionState,
dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,
diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs
index a7b6392798..ccf137cac3 100644
--- a/crates/router/src/types/storage/payment_method.rs
+++ b/crates/router/src/types/storage/payment_method.rs
@@ -207,3 +207,10 @@ pub struct PaymentMethodStatusTrackingData {
pub merchant_id: common_utils::id_type::MerchantId,
pub last_modified_by: Option<String>,
}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
+pub struct PaymentMethodModularCompatTrackingData {
+ pub payment_method_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
+ pub last_modified_by: Option<String>,
+}
diff --git a/crates/router/src/workflows.rs b/crates/router/src/workflows.rs
index e8e2e15ecc..093d6d1ba6 100644
--- a/crates/router/src/workflows.rs
+++ b/crates/router/src/workflows.rs
@@ -3,6 +3,7 @@ pub mod api_key_expiry;
#[cfg(feature = "payouts")]
pub mod attach_payout_account_workflow;
pub mod outgoing_webhook_retry;
+pub mod payment_method_modular_forward_compat;
pub mod payment_method_status_update;
pub mod payment_sync;
diff --git a/crates/router/src/workflows/payment_method_modular_forward_compat.rs b/crates/router/src/workflows/payment_method_modular_forward_compat.rs
new file mode 100644
index 0000000000..c1954fbc17
--- /dev/null
+++ b/crates/router/src/workflows/payment_method_modular_forward_compat.rs
@@ -0,0 +1,337 @@
+use std::str::FromStr;
+
+use common_utils::ext_traits::{Encode, OptionExt, StringExt, ValueExt};
+use error_stack::ResultExt;
+use hyperswitch_masking::Secret;
+use scheduler::{
+ consumer::types::process_data, utils as pt_utils, workflows::ProcessTrackerWorkflow,
+};
+
+#[cfg(feature = "v1")]
+use crate::types::payment_methods as pm_types;
+use crate::{
+ core::payment_methods::{cards, vault},
+ errors,
+ logger::{self, error},
+ routes::SessionState,
+ types::storage::{self, PaymentMethodModularCompatTrackingData},
+};
+
+pub struct PaymentMethodModularForwardCompatWorkflow;
+
+#[async_trait::async_trait]
+impl ProcessTrackerWorkflow<SessionState> for PaymentMethodModularForwardCompatWorkflow {
+ #[cfg(feature = "v1")]
+ async fn execute_workflow<'a>(
+ &'a self,
+ state: &'a SessionState,
+ process: storage::ProcessTracker,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ // Step 1: Parse PT tracking payload and load merchant context (key store + account).
+ logger::info!(process_id=%process.id, "Starting payment method modular compatibility PT");
+ let db = &*state.store;
+ let tracking_data: PaymentMethodModularCompatTrackingData =
+ process
+ .tracking_data
+ .clone()
+ .parse_value("PaymentMethodModularCompatTrackingData")?;
+ logger::info!(process_id=%process.id, ?tracking_data, "Parsed modular compatibility PT tracking data");
+
+ let merchant_id = tracking_data.merchant_id;
+ let key_store = state
+ .store
+ .get_merchant_key_store_by_merchant_id(
+ &merchant_id,
+ &state.store.get_master_key().to_vec().into(),
+ )
+ .await?;
+
+ let merchant_account = db
+ .find_merchant_account_by_merchant_id(&merchant_id, &key_store)
+ .await?;
+
+ let payment_method = db
+ .find_payment_method(
+ &key_store,
+ &tracking_data.payment_method_id,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to fetch payment method for modular compatibility PT")?;
+
+ // Step 2: Populate v1 compat fields used by PM modular service.
+ let pm_id_update = storage::PaymentMethodUpdate::PopulateModularCompatFields {
+ id: tracking_data.payment_method_id.clone(),
+ payment_method_type_v2: payment_method.payment_method,
+ payment_method_subtype: payment_method.payment_method_type,
+ last_modified_by: tracking_data.last_modified_by.clone(),
+ };
+
+ let payment_method = db
+ .update_payment_method(
+ &key_store,
+ payment_method,
+ pm_id_update,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to populate id for payment method in modular compatibility PT",
+ )?;
+
+ let business_status = if payment_method.payment_method
+ != Some(common_enums::PaymentMethod::Card)
+ {
+ // Step 3: Non-card payment methods do not require locker migration.
+ crate::logger::info!(
+ process_id=%process.id,
+ payment_method_id=%payment_method.payment_method_id,
+ "Payment method is non-card; skipping locker migration in modular compatibility PT"
+ );
+ "COMPLETED_BY_PT"
+ } else {
+ let customer_id = payment_method
+ .customer_id
+ .clone()
+ .get_required_value("customer_id")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "customer_id not found for card payment method in compatibility PT",
+ )?;
+
+ let card_network = payment_method
+ .scheme
+ .as_ref()
+ .and_then(|scheme| common_enums::CardNetwork::from_str(scheme).ok());
+
+ // Step 4: Fetch card payload from legacy locker only when locker_id is present.
+ if let Some(card_reference) = payment_method.locker_id.clone() {
+ let locker_card =
+ cards::get_card_from_vault(state, &customer_id, &merchant_id, &card_reference)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to retrieve card from legacy locker in compatibility PT",
+ )?;
+
+ let card_detail = api_models::payment_methods::CardDetail::from((
+ locker_card.get_card(),
+ card_network.clone(),
+ ));
+ let pmd =
+ hyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(card_detail);
+
+ // Step 5: Upsert the card into generic locker via direct AddVault call.
+ let entity_id = hyperswitch_domain_models::vault::V1VaultEntityId::new(
+ key_store.merchant_id.clone(),
+ customer_id.clone(),
+ );
+
+ let payload = pm_types::AddVaultRequest {
+ entity_id,
+ vault_id: crate::types::domain::VaultId::generate(card_reference),
+ data: &pmd,
+ ttl: state.conf.locker.ttl_for_storage_in_secs,
+ }
+ .encode_to_vec()
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode AddVaultRequest")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to add payment method in generic locker in compatibility PT",
+ )?;
+
+ 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 _stored_pm_resp: pm_types::InternalAddVaultResponse = resp
+ .parse_struct("InternalAddVaultResponse")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
+ .attach_printable("Failed to parse data into InternalAddVaultResponse")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to add payment method in generic locker in compatibility PT",
+ )?;
+ logger::info!(
+ process_id=%process.id,
+ payment_method_id=%payment_method.payment_method_id,
+ "Upserted card into generic locker in modular compatibility PT"
+ );
+ } else {
+ logger::info!(
+ process_id=%process.id,
+ payment_method_id=%payment_method.payment_method_id,
+ "Skipping card migration in modular compatibility PT as locker_id is absent"
+ );
+ }
+
+ // Step 6: Migrate network token to generic locker when an NT locker id is present.
+ if let Some(network_token_locker_id) = payment_method.network_token_locker_id.clone() {
+ let locker_network_token = cards::get_card_from_vault(
+ state,
+ &customer_id,
+ &merchant_id,
+ &network_token_locker_id,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to retrieve network token from legacy locker in compatibility PT",
+ )?;
+
+ let locker_network_token_card = locker_network_token.get_card();
+ let network_token_details =
+ hyperswitch_domain_models::payment_method_data::NetworkTokenDetails {
+ network_token: locker_network_token_card.card_number.into(),
+ network_token_exp_month: locker_network_token_card.card_exp_month,
+ network_token_exp_year: locker_network_token_card.card_exp_year,
+ cryptogram: None,
+ card_issuer: payment_method.issuer_name.clone(),
+ card_network,
+ card_type: None,
+ card_issuing_country: None,
+ card_holder_name: locker_network_token_card.name_on_card,
+ nick_name: locker_network_token_card.nick_name.map(Secret::new),
+ par: None,
+ };
+
+ let network_token_pmd =
+ hyperswitch_domain_models::vault::PaymentMethodVaultingData::NetworkToken(
+ network_token_details.clone(),
+ );
+
+ let network_token_entity_id =
+ hyperswitch_domain_models::vault::V1VaultEntityId::new(
+ key_store.merchant_id.clone(),
+ customer_id,
+ );
+
+ let network_token_payload = pm_types::AddVaultRequest {
+ entity_id: network_token_entity_id,
+ vault_id: crate::types::domain::VaultId::generate(
+ network_token_locker_id.clone(),
+ ),
+ data: &network_token_pmd,
+ ttl: state.conf.locker.ttl_for_storage_in_secs,
+ }
+ .encode_to_vec()
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode AddVaultRequest for network token")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to add network token in generic locker in compatibility PT",
+ )?;
+
+ let network_token_query_params =
+ Some(pm_types::VaultQueryParam::from(pm_types::WriteMode::Upsert));
+
+ let network_token_resp = vault::call_to_vault::<pm_types::AddVault>(
+ state,
+ network_token_payload,
+ network_token_query_params,
+ )
+ .await
+ .change_context(errors::VaultError::VaultAPIError)
+ .attach_printable("Call to vault failed for network token")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to add network token in generic locker in compatibility PT",
+ )?;
+
+ let _stored_network_token_resp: pm_types::InternalAddVaultResponse =
+ network_token_resp
+ .parse_struct("InternalAddVaultResponse")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
+ .attach_printable(
+ "Failed to parse network token response into InternalAddVaultResponse",
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to add network token in generic locker in compatibility PT",
+ )?;
+
+ crate::logger::info!(
+ process_id=%process.id,
+ payment_method_id=%payment_method.payment_method_id,
+ "Upserted network token into generic locker in modular compatibility PT"
+ );
+ } else {
+ crate::logger::info!(
+ process_id=%process.id,
+ payment_method_id=%payment_method.payment_method_id,
+ "Skipping network token migration in modular compatibility PT as network_token_locker_id is absent"
+ );
+ }
+
+ "COMPLETED_BY_PT"
+ };
+
+ // Step 7: Mark process as completed once the required branch is done.
+ db.as_scheduler()
+ .finish_process_with_business_status(process, business_status)
+ .await?;
+ crate::logger::info!(
+ business_status,
+ "Finished payment method modular compatibility PT"
+ );
+
+ Ok(())
+ }
+
+ #[cfg(feature = "v2")]
+ async fn execute_workflow<'a>(
+ &'a self,
+ _state: &'a SessionState,
+ _process: storage::ProcessTracker,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ todo!()
+ }
+
+ async fn error_handler<'a>(
+ &'a self,
+ state: &'a SessionState,
+ process: storage::ProcessTracker,
+ _error: errors::ProcessTrackerError,
+ ) -> errors::CustomResult<(), errors::ProcessTrackerError> {
+ let db = &*state.store;
+ let retry_count = process.retry_count;
+ let mapping = process_data::PaymentMethodsPTMapping::default();
+
+ let time_delta = if retry_count == 0 {
+ Some(mapping.default_mapping.start_after)
+ } else {
+ pt_utils::get_delay(retry_count + 1, &mapping.default_mapping.frequencies)
+ };
+
+ let schedule_time = pt_utils::get_time_from_delta(time_delta);
+
+ match schedule_time {
+ Some(s_time) => {
+ db.as_scheduler()
+ .retry_process(process, s_time)
+ .await
+ .map_err(Into::<errors::ProcessTrackerError>::into)?;
+ }
+ None => {
+ db.as_scheduler()
+ .finish_process_with_business_status(process, "RETRIES_EXCEEDED")
+ .await
+ .map_err(Into::<errors::ProcessTrackerError>::into)?;
+ }
+ }
+
+ error!("Failed while executing payment method modular compatibility workflow");
+ Ok(())
+ }
+}
diff --git a/migrations/2026-04-22-045614_add_id_column_to_v1_payment_methods/down.sql b/migrations/2026-04-22-045614_add_id_column_to_v1_payment_methods/down.sql
new file mode 100644
index 0000000000..c82cdc74af
--- /dev/null
+++ b/migrations/2026-04-22-045614_add_id_column_to_v1_payment_methods/down.sql
@@ -0,0 +1,4 @@
+ALTER TABLE payment_methods
+DROP COLUMN IF EXISTS payment_method_subtype,
+DROP COLUMN IF EXISTS payment_method_type_v2,
+DROP COLUMN IF EXISTS id;
diff --git a/migrations/2026-04-22-045614_add_id_column_to_v1_payment_methods/up.sql b/migrations/2026-04-22-045614_add_id_column_to_v1_payment_methods/up.sql
new file mode 100644
index 0000000000..64438c0618
--- /dev/null
+++ b/migrations/2026-04-22-045614_add_id_column_to_v1_payment_methods/up.sql
@@ -0,0 +1,4 @@
+ALTER TABLE payment_methods
+ADD COLUMN IF NOT EXISTS id VARCHAR(64),
+ADD COLUMN IF NOT EXISTS payment_method_type_v2 VARCHAR(64),
+ADD COLUMN IF NOT EXISTS payment_method_subtype VARCHAR(64);