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(account_updater): apply card updates to stored payment methods (#13750)

Kanika Bansaldadaa047f9d0
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs
index b5c4070a88..f9808262f3 100644
--- a/crates/common_utils/src/types.rs
+++ b/crates/common_utils/src/types.rs
@@ -1603,6 +1603,11 @@ impl_enum_str!(
/// merchant id of creator.
merchant_id: String,
},
+ /// AccountUpdater variant, for writes made while applying a reported card change
+ AccountUpdater {
+ /// account updater service that reported the change.
+ service: String,
+ },
}
);
@@ -1614,7 +1619,10 @@ impl CreatedBy {
Self::Api { merchant_id } => id_type::MerchantId::wrap(merchant_id.clone())
.map(|parsed_merchant_id| parsed_merchant_id == *provider_merchant_id)
.unwrap_or_default(),
- Self::Jwt { .. } | Self::Invalid | Self::EmbeddedToken { .. } => false,
+ Self::Jwt { .. }
+ | Self::Invalid
+ | Self::EmbeddedToken { .. }
+ | Self::AccountUpdater { .. } => false,
}
}
}
diff --git a/crates/diesel_models/payment_methods_v2.patch b/crates/diesel_models/payment_methods_v2.patch
new file mode 100644
index 0000000000..a2e0993a79
--- /dev/null
+++ b/crates/diesel_models/payment_methods_v2.patch
@@ -0,0 +1,97 @@
+diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
+--- a/crates/diesel_models/src/schema_v2.rs
++++ b/crates/diesel_models/src/schema_v2.rs
+@@ -1349,14 +1349,79 @@
+ #[max_length = 64]
+ profile_id -> Nullable<Varchar>,
+ #[max_length = 255]
+ secure_link -> Nullable<Varchar>,
+ #[max_length = 64]
+ processor_merchant_id -> Nullable<Varchar>,
++ #[max_length = 255]
++ created_by -> Nullable<Varchar>,
++ }
++}
++
++diesel::table! {
++ use diesel::sql_types::*;
++ use crate::enums::diesel_exports::*;
++
++ payment_methods (id) {
++ #[max_length = 64]
++ customer_id -> Nullable<Varchar>,
++ #[max_length = 64]
++ merchant_id -> Varchar,
++ #[max_length = 64]
++ payment_method_id -> Nullable<Varchar>,
++ created_at -> Timestamp,
++ last_modified -> Timestamp,
++ payment_method -> Nullable<Varchar>,
++ #[max_length = 64]
++ payment_method_type -> Nullable<Varchar>,
++ payment_method_data -> Nullable<Bytea>,
++ #[max_length = 64]
++ locker_id -> Nullable<Varchar>,
++ last_used_at -> Timestamp,
++ connector_mandate_details -> Nullable<Jsonb>,
++ customer_acceptance -> Nullable<Jsonb>,
++ #[max_length = 64]
++ status -> Varchar,
++ #[max_length = 255]
++ network_transaction_id -> Nullable<Varchar>,
++ #[max_length = 128]
++ client_secret -> Nullable<Varchar>,
++ payment_method_billing_address -> Nullable<Bytea>,
++ #[max_length = 64]
++ updated_by -> Nullable<Varchar>,
++ version -> ApiVersion,
++ #[max_length = 128]
++ network_token_requestor_reference_id -> Nullable<Varchar>,
++ #[max_length = 64]
++ network_token_locker_id -> Nullable<Varchar>,
++ network_token_payment_method_data -> Nullable<Bytea>,
++ #[max_length = 64]
++ external_vault_source -> Nullable<Varchar>,
++ #[max_length = 64]
++ vault_type -> Nullable<Varchar>,
+ #[max_length = 255]
+ created_by -> Nullable<Varchar>,
++ #[max_length = 255]
++ last_modified_by -> Nullable<Varchar>,
++ customer_details -> Nullable<Bytea>,
++ #[max_length = 64]
++ 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 = 255]
++ network_transaction_link_id -> Nullable<Varchar>,
++ compatibility_updated_at -> Nullable<Timestamp>,
++ #[max_length = 64]
++ auxiliary_fingerprint_id -> Nullable<Varchar>,
++ connector_payment_method_details -> Nullable<Jsonb>,
++ external_vault_token_data -> Nullable<Bytea>,
+ }
+ }
+
+ diesel::table! {
+ use diesel::sql_types::*;
+ use crate::enums::diesel_exports::*;
+@@ -1917,12 +1982,13 @@
+ merchant_connector_account,
+ merchant_key_store,
+ organization,
+ payment_attempt,
+ payment_intent,
+ payment_link,
++ payment_methods,
+ payout_attempt,
+ payouts,
+ process_tracker,
+ refund,
+ relay,
+ revenue_recovery_retry_stats,
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index b3f91d68bd..3253f047c1 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -410,7 +410,7 @@ pub enum PaymentMethodUpdate {
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: Option<Encryption>,
- locker_fingerprint_id: Option<String>,
+ locker_fingerprint_id: Option<Option<String>>,
connector_mandate_details: Box<Option<CommonMandateReference>>,
external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>,
network_transaction_id: Option<Secret<String>>,
@@ -423,7 +423,7 @@ pub enum PaymentMethodUpdate {
},
StatusAndFingerprintUpdate {
status: Option<storage_enums::PaymentMethodStatus>,
- locker_fingerprint_id: Option<String>,
+ locker_fingerprint_id: Option<Option<String>>,
last_modified_by: Option<String>,
},
// Compatibility-only update used by modular backward-compat inline/PT.
@@ -468,7 +468,7 @@ pub struct PaymentMethodUpdateInternal {
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: Option<Encryption>,
- locker_fingerprint_id: Option<String>,
+ locker_fingerprint_id: Option<Option<String>>,
external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>,
last_modified_by: Option<String>,
customer_details: Option<Encryption>,
diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs
index 7b5fea1f10..a4912c86c4 100644
--- a/crates/diesel_models/src/query/payment_method.rs
+++ b/crates/diesel_models/src/query/payment_method.rs
@@ -1,4 +1,6 @@
use async_bb8_diesel::AsyncRunQueryDsl;
+#[cfg(feature = "v2")]
+use diesel::PgExpressionMethods;
#[cfg(feature = "v1")]
use diesel::Table;
use diesel::{
@@ -279,8 +281,18 @@ impl PaymentMethod {
conn: &DatabaseConnectionWithContext<'_>,
id: &common_utils::id_type::GlobalPaymentMethodId,
) -> StorageResult<Self> {
- generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, pm_id.eq(id.to_owned()))
- .await
+ generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(
+ conn,
+ pm_id.eq(id.to_owned()),
+ Some(1),
+ None,
+ Some(dsl::created_at.desc()),
+ )
+ .await?
+ .into_iter()
+ .next()
+ .ok_or_else(|| error_stack::report!(errors::DatabaseError::NotFound))
+ .attach_printable("Error finding payment method by id")
}
pub async fn find_by_global_customer_id_merchant_id_statuses(
@@ -338,17 +350,25 @@ impl PaymentMethod {
.await
}
- pub async fn update_with_id(
+ pub async fn update_with_id_and_locker_fingerprint_id(
self,
conn: &DatabaseConnectionWithContext<'_>,
payment_method: payment_method::PaymentMethodUpdateInternal,
) -> StorageResult<Self> {
+ let locker_fingerprint_id = self.locker_fingerprint_id.clone();
+
match generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
- >(conn, pm_id.eq(self.id.to_owned()), payment_method)
+ >(
+ conn,
+ pm_id
+ .eq(self.id.to_owned())
+ .and(dsl::locker_fingerprint_id.is_not_distinct_from(locker_fingerprint_id)),
+ payment_method,
+ )
.await
{
Err(error) => match error.current_context() {
diff --git a/crates/router/src/core/account_updater.rs b/crates/router/src/core/account_updater.rs
index d225a5b638..f2ba7d6110 100644
--- a/crates/router/src/core/account_updater.rs
+++ b/crates/router/src/core/account_updater.rs
@@ -1,18 +1,20 @@
mod config;
mod eligibility;
mod refresh;
+mod store;
pub mod types;
use api_models::payment_methods::RawPaymentMethodData;
use common_utils::errors::CustomResult;
+use error_stack::report;
use router_env::{instrument, logger, tracing};
-use unified_connector_service_client::payments as payments_grpc;
+pub use self::store::apply_card_refresh_result;
use self::{
config::resolve_account_updater_config,
- eligibility::check_eligibility_and_build_payment_method,
+ eligibility::{check_eligibility_and_build_payment_method, check_vault_eligibility},
refresh::request_account_updater_refresh,
- types::{AccountUpdaterError, ResolvedAccountUpdaterConfig},
+ types::{AccountUpdaterError, RefreshResult, ResolvedAccountUpdaterConfig},
};
use crate::{
core::configs::dimension_state, events::account_updater as account_updater_events,
@@ -27,24 +29,25 @@ pub async fn run_account_updater<D>(
payment_method: &domain::PaymentMethod,
raw_payment_method_data: Option<&RawPaymentMethodData>,
dimensions: &D,
-) where
+) -> CustomResult<RefreshResult, AccountUpdaterError>
+where
D: dimension_state::DimensionsBase,
{
let config = match resolve_account_updater_config(state, dimensions).await {
Ok(Some(config)) => config,
Ok(None) => {
logger::debug!("Account Updater is not enabled for these dimensions");
- return;
+ Err(report!(AccountUpdaterError::NotEnabled))?
}
Err(error) => {
logger::warn!(?error, "Account Updater config could not be resolved");
- return;
+ Err(error)?
}
};
let started_at = std::time::Instant::now();
- let outcome = refresh_stored_payment_method(
+ let refresh_result = refresh_stored_payment_method(
state,
platform,
profile,
@@ -54,12 +57,8 @@ pub async fn run_account_updater<D>(
)
.await;
- match &outcome {
- Ok(refresh_outcome) => logger::info!(
- account_updater_outcome = refresh_outcome.as_str_name(),
- "Account Updater refresh completed"
- ),
- Err(error) => logger::warn!(?error, "Account Updater refresh did not complete"),
+ if let Err(error) = &refresh_result {
+ logger::warn!(?error, "Account Updater refresh did not complete");
}
let event = account_updater_events::KafkaAccountUpdaterEvent::new(
@@ -67,11 +66,13 @@ pub async fn run_account_updater<D>(
platform.get_processor().get_account().get_id(),
profile.get_id(),
payment_method,
- &outcome,
+ &refresh_result,
started_at.elapsed().as_millis(),
);
state.event_handler.log_event(&event);
+
+ refresh_result
}
async fn refresh_stored_payment_method(
@@ -81,7 +82,9 @@ async fn refresh_stored_payment_method(
payment_method: &domain::PaymentMethod,
raw_payment_method_data: Option<&RawPaymentMethodData>,
config: &ResolvedAccountUpdaterConfig,
-) -> CustomResult<payments_grpc::CardRefreshOutcome, AccountUpdaterError> {
+) -> CustomResult<RefreshResult, AccountUpdaterError> {
+ check_vault_eligibility(state, platform, profile).await?;
+
let refreshable_payment_method = check_eligibility_and_build_payment_method(
payment_method,
raw_payment_method_data,
diff --git a/crates/router/src/core/account_updater/eligibility.rs b/crates/router/src/core/account_updater/eligibility.rs
index 4ef9d76dd8..c9c5608a2e 100644
--- a/crates/router/src/core/account_updater/eligibility.rs
+++ b/crates/router/src/core/account_updater/eligibility.rs
@@ -10,7 +10,11 @@ use unified_connector_service_cards::CardNumber;
use unified_connector_service_client::payments as payments_grpc;
use super::types::{AccountUpdaterError, ResolvedAccountUpdaterConfig};
-use crate::types::{domain, transformers::ForeignFrom};
+use crate::{
+ core::payments::helpers as payment_helpers,
+ routes::SessionState,
+ types::{domain, transformers::ForeignFrom},
+};
#[instrument(skip_all)]
pub fn check_eligibility_and_build_payment_method(
@@ -32,6 +36,25 @@ pub fn check_eligibility_and_build_payment_method(
}
}
+#[instrument(skip_all)]
+pub async fn check_vault_eligibility(
+ state: &SessionState,
+ platform: &domain::Platform,
+ profile: &domain::Profile,
+) -> CustomResult<(), AccountUpdaterError> {
+ when(state.conf.micro_services.use_legacy_locker, || {
+ Err(report!(AccountUpdaterError::LegacyLockerUnsupported))
+ })?;
+
+ let provider_profile = payment_helpers::resolve_provider_profile(state, platform, profile)
+ .await
+ .change_context(AccountUpdaterError::ProviderProfileUnresolved)?;
+
+ when(provider_profile.is_external_vault_enabled(), || {
+ Err(report!(AccountUpdaterError::ExternalVaultUnsupported))
+ })
+}
+
fn check_stored_card_eligibility_and_build_payment_method(
payment_method: &domain::PaymentMethod,
raw_payment_method_data: Option<&RawPaymentMethodData>,
diff --git a/crates/router/src/core/account_updater/refresh.rs b/crates/router/src/core/account_updater/refresh.rs
index bb1916e9c5..63970009b9 100644
--- a/crates/router/src/core/account_updater/refresh.rs
+++ b/crates/router/src/core/account_updater/refresh.rs
@@ -1,11 +1,16 @@
-use common_enums::ExecutionMode;
+use common_enums::{connector_enums::Connector, ExecutionMode};
use common_utils::errors::CustomResult;
use error_stack::{report, ResultExt};
use external_services::grpc_client::LineageIds;
use router_env::{instrument, tracing};
-use unified_connector_service_client::payments as payments_grpc;
+use unified_connector_service_client::payments::{
+ self as payments_grpc, refresh_result, CardRefreshOutcome as Outcome,
+};
-use super::types::{AccountUpdaterError, ResolvedAccountUpdaterConfig};
+use super::types::{
+ AccountUpdaterError, CardOutcome, CardRefreshedData, RefreshResult,
+ ResolvedAccountUpdaterConfig,
+};
use crate::{
core::unified_connector_service::build_unified_connector_service_auth_metadata_without_mca,
routes::SessionState, types::domain,
@@ -18,7 +23,7 @@ pub async fn request_account_updater_refresh(
profile: &domain::Profile,
config: &ResolvedAccountUpdaterConfig,
refreshable_payment_method: payments_grpc::PaymentMethod,
-) -> CustomResult<payments_grpc::CardRefreshOutcome, AccountUpdaterError> {
+) -> CustomResult<RefreshResult, AccountUpdaterError> {
let client = state
.grpc_client
.unified_connector_service_client
@@ -75,15 +80,39 @@ pub async fn request_account_updater_refresh(
);
}
- response
+ let result = response
.result
.and_then(|result| result.result)
- .map(|result| match result {
- payments_grpc::refresh_result::Result::Card(card) => {
- payments_grpc::CardRefreshOutcome::try_from(card.outcome)
- .unwrap_or(payments_grpc::CardRefreshOutcome::Unspecified)
- }
- })
.ok_or_else(|| report!(AccountUpdaterError::RefreshReturnedError))
- .attach_printable("UCS returned neither a result nor an error")
+ .attach_printable("UCS returned neither a result nor an error")?;
+
+ match result {
+ refresh_result::Result::Card(card) => Ok(RefreshResult::Card(build_card_refreshed_data(
+ card,
+ config.service(),
+ )?)),
+ }
+}
+
+fn build_card_refreshed_data(
+ card_result: payments_grpc::CardRefreshResult,
+ service: Connector,
+) -> CustomResult<CardRefreshedData, AccountUpdaterError> {
+ let reported_outcome = card_result.outcome();
+
+ let outcome = match (reported_outcome, card_result.card) {
+ (Outcome::CardRefreshAccountUpdated, Some(card)) => CardOutcome::AccountUpdated(card),
+ (Outcome::CardRefreshExpiryUpdated, Some(card)) => CardOutcome::ExpiryUpdated(card),
+ (Outcome::CardRefreshAccountUpdated | Outcome::CardRefreshExpiryUpdated, None) => {
+ return Err(report!(AccountUpdaterError::RefreshReturnedError)
+ .attach_printable("Account Updater reported a card change but returned no card"))
+ }
+ (Outcome::CardRefreshClosed, _) => CardOutcome::Closed,
+ (Outcome::CardRefreshNoChange, _) => CardOutcome::NoChange,
+ (Outcome::CardRefreshNotFound, _) => CardOutcome::NotFound,
+ (Outcome::CardRefreshContactIssuer, _) => CardOutcome::ContactIssuer,
+ (Outcome::Unspecified, _) => CardOutcome::Unspecified,
+ };
+
+ Ok(CardRefreshedData { outcome, service })
}
diff --git a/crates/router/src/core/account_updater/store.rs b/crates/router/src/core/account_updater/store.rs
new file mode 100644
index 0000000000..45149e1e2d
--- /dev/null
+++ b/crates/router/src/core/account_updater/store.rs
@@ -0,0 +1,373 @@
+use std::str::FromStr;
+
+use common_enums::connector_enums::Connector;
+use common_utils::{
+ errors::CustomResult,
+ ext_traits::{OptionExt, ValueExt},
+ id_type, type_name,
+ types::CreatedBy,
+};
+use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::payment_method_data::CardDetailsPaymentMethod;
+use router_env::{instrument, logger, tracing};
+use unified_connector_service_client::payments as payments_grpc;
+
+use super::types::{AccountUpdaterError, CardRefreshedData, RefreshedCard};
+use crate::{
+ core::{
+ payment_methods::{self as pm_core, vault, PaymentMethodExt},
+ utils as core_utils,
+ },
+ routes::SessionState,
+ types::{api, domain, payment_methods as pm_types, storage},
+};
+
+#[instrument(skip_all)]
+pub async fn apply_card_refresh_result(
+ state: &SessionState,
+ platform: &domain::Platform,
+ profile: &domain::Profile,
+ payment_method: &domain::PaymentMethod,
+ card_result: CardRefreshedData,
+) -> CustomResult<Option<domain::PaymentMethod>, AccountUpdaterError> {
+ let CardRefreshedData { outcome, service } = card_result;
+
+ match outcome.get_new_card_details() {
+ Some(RefreshedCard::CardOpen(refreshed_card)) => {
+ Box::pin(write_refreshed_card(
+ state,
+ platform,
+ profile,
+ payment_method,
+ service,
+ *refreshed_card,
+ ))
+ .await
+ }
+ Some(RefreshedCard::CardClosed) => update_payment_method_status(
+ state,
+ platform,
+ service,
+ payment_method.clone(),
+ common_enums::PaymentMethodStatus::Inactive,
+ )
+ .await
+ .attach_printable("Failed to deactivate the closed payment method")
+ .map(Some),
+ None => Ok(None),
+ }
+}
+
+async fn write_refreshed_card(
+ state: &SessionState,
+ platform: &domain::Platform,
+ profile: &domain::Profile,
+ payment_method: &domain::PaymentMethod,
+ service: Connector,
+ refreshed_card: payments_grpc::CardDetailsWithNoCvc,
+) -> CustomResult<Option<domain::PaymentMethod>, AccountUpdaterError> {
+ let stored_card = payment_method
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.get_inner().get_card_details())
+ .ok_or_else(|| report!(AccountUpdaterError::StoreFailed))
+ .attach_printable("Stored payment method data holds no card to apply a change to")?;
+
+ let customer_id = payment_method
+ .customer_id
+ .clone()
+ .get_required_value("customer_id")
+ .change_context(AccountUpdaterError::StoreFailed)
+ .attach_printable("Payment method has no customer to vault the refreshed card against")?;
+
+ let new_card = build_new_card(refreshed_card, &stored_card)?;
+
+ let vaulting_data = domain::PaymentMethodVaultingData::Card(new_card);
+
+ let (fingerprint_id_result, auxiliary_fingerprint_id_result) = tokio::join!(
+ vault::get_fingerprint_id_for_payment_method(
+ state,
+ &vaulting_data,
+ customer_id.get_string_repr().to_owned(),
+ ),
+ vault::get_auxiliary_fingerprint_id_for_payment_method(
+ state,
+ &vaulting_data,
+ customer_id.get_string_repr().to_owned(),
+ ),
+ );
+
+ let locker_fingerprint_id = fingerprint_id_result
+ .change_context(AccountUpdaterError::StoreFailed)
+ .attach_printable("Failed to fingerprint the refreshed card")?;
+
+ let auxiliary_fingerprint_id = auxiliary_fingerprint_id_result
+ .change_context(AccountUpdaterError::StoreFailed)
+ .attach_printable("Failed to compute the auxiliary fingerprint for the refreshed card")?;
+
+ if payment_method.locker_fingerprint_id.as_deref() == Some(locker_fingerprint_id.as_str()) {
+ logger::info!(
+ "Account Updater reported a change whose fingerprint matches the stored card; nothing written"
+ );
+ Ok(None)
+ } else {
+ Box::pin(store_refreshed_card(
+ state,
+ platform,
+ profile,
+ payment_method,
+ service,
+ vaulting_data,
+ customer_id,
+ locker_fingerprint_id,
+ auxiliary_fingerprint_id,
+ ))
+ .await
+ .map(Some)
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+async fn store_refreshed_card(
+ state: &SessionState,
+ platform: &domain::Platform,
+ profile: &domain::Profile,
+ payment_method: &domain::PaymentMethod,
+ service: Connector,
+ vaulting_data: domain::PaymentMethodVaultingData,
+ customer_id: id_type::GlobalCustomerId,
+ locker_fingerprint_id: String,
+ auxiliary_fingerprint_id: String,
+) -> CustomResult<domain::PaymentMethod, AccountUpdaterError> {
+ let bin_enriched = vaulting_data
+ .populate_bin_details_for_payment_method(state)
+ .await;
+ let vaulting_data = bin_enriched.data;
+
+ let (vault_response, external_vault_source) = pm_core::vault_payment_method(
+ state,
+ &vaulting_data,
+ platform,
+ profile,
+ None,
+ Some(locker_fingerprint_id.clone()),
+ &customer_id,
+ Some(pm_types::WriteMode::Insert),
+ )
+ .await
+ .change_context(AccountUpdaterError::StoreFailed)
+ .attach_printable("Failed to vault the refreshed card")?;
+
+ let refreshed_payment_method = build_refreshed_payment_method(
+ state,
+ platform,
+ payment_method,
+ service,
+ &vaulting_data,
+ Some(vault_response.vault_id.clone()),
+ locker_fingerprint_id,
+ auxiliary_fingerprint_id,
+ external_vault_source,
+ bin_enriched.payment_method_subtype,
+ )
+ .await?;
+
+ let inserted_payment_method =
+ insert_refreshed_payment_method(state, platform, refreshed_payment_method).await?;
+
+ Box::pin(pm_core::delete_payment_method_by_record(
+ state.store.as_ref(),
+ state,
+ platform,
+ profile,
+ payment_method.clone(),
+ ))
+ .await
+ .change_context(AccountUpdaterError::StoreFailed)
+ .attach_printable("Failed to delete the superseded payment method")?;
+
+ update_payment_method_status(
+ state,
+ platform,
+ service,
+ inserted_payment_method,
+ common_enums::PaymentMethodStatus::Active,
+ )
+ .await
+ .inspect_err(|error| {
+ logger::warn!(
+ ?error,
+ "Account Updater stored the refreshed card but could not activate the row"
+ )
+ })
+}
+
+fn build_new_card(
+ refreshed: payments_grpc::CardDetailsWithNoCvc,
+ stored: &CardDetailsPaymentMethod,
+) -> CustomResult<api::payment_methods::CardDetail, AccountUpdaterError> {
+ let card_number = refreshed
+ .card_number
+ .ok_or_else(|| report!(AccountUpdaterError::RefreshReturnedError))
+ .attach_printable("Refreshed card carries no card number")?
+ .get_card_no()
+ .parse::<cards::CardNumber>()
+ .change_context(AccountUpdaterError::RefreshReturnedError)
+ .attach_printable("Refreshed card number failed validation")?;
+
+ let card_exp_month = refreshed
+ .card_exp_month
+ .ok_or_else(|| report!(AccountUpdaterError::RefreshReturnedError))
+ .attach_printable("Refreshed card carries no expiry month")?;
+
+ let card_exp_year = refreshed
+ .card_exp_year
+ .ok_or_else(|| report!(AccountUpdaterError::RefreshReturnedError))
+ .attach_printable("Refreshed card carries no expiry year")?;
+
+ Ok(api::payment_methods::CardDetail {
+ card_number,
+ card_exp_month,
+ card_exp_year,
+ card_holder_name: stored.card_holder_name.clone(),
+ nick_name: stored.nick_name.clone(),
+ card_network: stored.card_network.clone(),
+ card_issuing_country: stored
+ .issuer_country
+ .as_ref()
+ .map(|country| common_enums::CountryAlpha2::from_str(country))
+ .transpose()
+ .ok()
+ .flatten(),
+ card_issuer: stored.card_issuer.clone(),
+ card_type: stored
+ .card_type
+ .as_ref()
+ .map(|card_type| api::payment_methods::CardType::from_str(card_type))
+ .transpose()
+ .ok()
+ .flatten(),
+ card_cvc: None,
+ })
+}
+
+async fn update_payment_method_status(
+ state: &SessionState,
+ platform: &domain::Platform,
+ service: Connector,
+ payment_method: domain::PaymentMethod,
+ status: common_enums::PaymentMethodStatus,
+) -> CustomResult<domain::PaymentMethod, AccountUpdaterError> {
+ let update = storage::PaymentMethodUpdate::StatusUpdate {
+ status: Some(status),
+ last_modified_by: Some(
+ CreatedBy::AccountUpdater {
+ service: service.to_string(),
+ }
+ .to_string(),
+ ),
+ };
+
+ state
+ .store
+ .update_payment_method(
+ platform.get_provider().get_key_store(),
+ payment_method,
+ update,
+ platform.get_provider().get_account().storage_scheme,
+ None,
+ )
+ .await
+ .change_context(AccountUpdaterError::StoreFailed)
+}
+
+#[allow(clippy::too_many_arguments)]
+async fn build_refreshed_payment_method(
+ state: &SessionState,
+ platform: &domain::Platform,
+ payment_method: &domain::PaymentMethod,
+ service: Connector,
+ vaulting_data: &domain::PaymentMethodVaultingData,
+ locker_id: Option<domain::VaultId>,
+ locker_fingerprint_id: String,
+ auxiliary_fingerprint_id: String,
+ external_vault_source: Option<id_type::MerchantConnectorAccountId>,
+ payment_method_subtype: Option<common_enums::PaymentMethodType>,
+) -> CustomResult<domain::PaymentMethod, AccountUpdaterError> {
+ let now = common_utils::date_time::now();
+ let created_by = CreatedBy::AccountUpdater {
+ service: service.to_string(),
+ };
+ let created_by_string = created_by.to_string();
+
+ let encrypted_payment_method_data = core_utils::create_encrypted_data(
+ &state.into(),
+ platform.get_provider().get_key_store(),
+ vaulting_data.get_payment_methods_data(),
+ type_name!(diesel_models::payment_method::PaymentMethod),
+ )
+ .await
+ .change_context(AccountUpdaterError::StoreFailed)
+ .attach_printable("Failed to encrypt the refreshed card for storage")?
+ .deserialize_inner_value(|value| value.parse_value("PaymentMethodsData"))
+ .change_context(AccountUpdaterError::StoreFailed)
+ .attach_printable("Failed to parse the encrypted refreshed card")?;
+
+ Ok(domain::PaymentMethod {
+ id: payment_method.id.clone(),
+ customer_id: payment_method.customer_id.clone(),
+ merchant_id: payment_method.merchant_id.clone(),
+ external_vault_source,
+ created_at: now,
+ last_modified: now,
+ payment_method_type: payment_method.payment_method_type,
+ payment_method_subtype: payment_method_subtype.or(payment_method.payment_method_subtype),
+ payment_method_data: Some(encrypted_payment_method_data),
+ locker_id,
+ last_used_at: now,
+ connector_mandate_details: None,
+ customer_acceptance: payment_method.customer_acceptance.clone(),
+ status: common_enums::PaymentMethodStatus::New,
+ network_transaction_id: payment_method.network_transaction_id.clone(),
+ network_transaction_link_id: payment_method.network_transaction_link_id.clone(),
+ client_secret: None,
+ payment_method_billing_address: payment_method.payment_method_billing_address.clone(),
+ updated_by: Some(created_by_string),
+ locker_fingerprint_id: Some(locker_fingerprint_id),
+ auxiliary_fingerprint_id: Some(auxiliary_fingerprint_id),
+ version: payment_method.version,
+ network_token_requestor_reference_id: payment_method
+ .network_token_requestor_reference_id
+ .clone(),
+ network_token_locker_id: payment_method.network_token_locker_id.clone(),
+ network_token_payment_method_data: payment_method.network_token_payment_method_data.clone(),
+ external_vault_token_data: payment_method.external_vault_token_data.clone(),
+ vault_type: payment_method.vault_type,
+ created_by: Some(created_by.clone()),
+ last_modified_by: Some(created_by),
+ customer_details: payment_method.customer_details.clone(),
+ network_tokenization_data: payment_method.network_tokenization_data.clone(),
+ compatibility_updated_at: None,
+ })
+}
+
+async fn insert_refreshed_payment_method(
+ state: &SessionState,
+ platform: &domain::Platform,
+ payment_method: domain::PaymentMethod,
+) -> CustomResult<domain::PaymentMethod, AccountUpdaterError> {
+ state
+ .store
+ .insert_payment_method(
+ platform.get_provider().get_key_store(),
+ payment_method,
+ platform.get_provider().get_account().storage_scheme,
+ Some(pm_core::payment_method_modular_backward_compat_action(
+ state,
+ &platform.get_provider().get_account().organization_id,
+ )),
+ )
+ .await
+ .change_context(AccountUpdaterError::StoreFailed)
+ .attach_printable("Failed to insert the refreshed payment method row")
+}
diff --git a/crates/router/src/core/account_updater/types.rs b/crates/router/src/core/account_updater/types.rs
index a24f337a0d..89138e007c 100644
--- a/crates/router/src/core/account_updater/types.rs
+++ b/crates/router/src/core/account_updater/types.rs
@@ -4,6 +4,7 @@ use common_enums::{connector_enums::Connector, CardNetwork};
use error_stack::ResultExt;
use hyperswitch_domain_models::router_data::ConnectorAuthType;
use hyperswitch_masking::Secret;
+use unified_connector_service_client::payments as payments_grpc;
use crate::{
configs::settings,
@@ -49,6 +50,13 @@ impl ResolvedAccountUpdaterConfig {
}
}
+ /// The account updater service backing this config, recorded against every row it writes.
+ pub fn service(&self) -> Connector {
+ match self {
+ Self::Juspay(_) => Connector::Juspay,
+ }
+ }
+
/// Builds the connector, auth type and metadata the connector config is resolved from.
pub fn build_connector_credentials(
&self,
@@ -112,9 +120,65 @@ impl From<&settings::AccountUpdaterConfig> for ResolvedAccountUpdaterConfig {
}
}
+pub enum RefreshResult {
+ Card(CardRefreshedData),
+}
+
+pub struct CardRefreshedData {
+ pub outcome: CardOutcome,
+ pub service: Connector,
+}
+
+pub enum CardOutcome {
+ AccountUpdated(payments_grpc::CardDetailsWithNoCvc),
+ ExpiryUpdated(payments_grpc::CardDetailsWithNoCvc),
+ Closed,
+ NoChange,
+ NotFound,
+ ContactIssuer,
+ Unspecified,
+}
+
+pub enum RefreshedCard {
+ CardOpen(Box<payments_grpc::CardDetailsWithNoCvc>),
+ CardClosed,
+}
+
+impl CardOutcome {
+ pub fn as_str_name(&self) -> &'static str {
+ match self {
+ Self::AccountUpdated(_) => {
+ payments_grpc::CardRefreshOutcome::CardRefreshAccountUpdated.as_str_name()
+ }
+ Self::ExpiryUpdated(_) => {
+ payments_grpc::CardRefreshOutcome::CardRefreshExpiryUpdated.as_str_name()
+ }
+ Self::Closed => payments_grpc::CardRefreshOutcome::CardRefreshClosed.as_str_name(),
+ Self::NoChange => payments_grpc::CardRefreshOutcome::CardRefreshNoChange.as_str_name(),
+ Self::NotFound => payments_grpc::CardRefreshOutcome::CardRefreshNotFound.as_str_name(),
+ Self::ContactIssuer => {
+ payments_grpc::CardRefreshOutcome::CardRefreshContactIssuer.as_str_name()
+ }
+ Self::Unspecified => payments_grpc::CardRefreshOutcome::Unspecified.as_str_name(),
+ }
+ }
+
+ pub fn get_new_card_details(self) -> Option<RefreshedCard> {
+ match self {
+ Self::AccountUpdated(card) | Self::ExpiryUpdated(card) => {
+ Some(RefreshedCard::CardOpen(Box::new(card)))
+ }
+ Self::Closed => Some(RefreshedCard::CardClosed),
+ Self::NoChange | Self::NotFound | Self::ContactIssuer | Self::Unspecified => None,
+ }
+ }
+}
+
#[derive(Debug, thiserror::Error, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AccountUpdaterError {
+ #[error("Account Updater is not enabled for these dimensions")]
+ NotEnabled,
#[error("Account Updater application config is missing or invalid")]
MissingApplicationConfig,
#[error("Payment method is not a card")]
@@ -123,10 +187,18 @@ pub enum AccountUpdaterError {
PaymentMethodNotActive,
#[error("Card network is not supported by Account Updater")]
UnsupportedNetwork,
+ #[error("Account Updater is not supported on the legacy locker")]
+ LegacyLockerUnsupported,
+ #[error("Account Updater is not supported on an external vault profile")]
+ ExternalVaultUnsupported,
+ #[error("Could not resolve the provider profile to check the deployment")]
+ ProviderProfileUnresolved,
#[error("Stored card cannot be used for Account Updater")]
CardUnusable,
#[error("Account Updater refresh call failed")]
RefreshCallFailed,
#[error("Account Updater refresh returned an error")]
RefreshReturnedError,
+ #[error("Account Updater could not store the reported card change")]
+ StoreFailed,
}
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 3f37dfd026..ef179fa84b 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -127,8 +127,6 @@ const PAYMENT_METHOD_MODULAR_BACKWARD_COMPAT_TASK: &str = "PM_MOD_BACK_COMPAT";
const PAYMENT_METHOD_MODULAR_BACKWARD_COMPAT_TAG: &str = "PM_MOD_BACK_COMPAT";
const PAYMENT_METHOD_MODULAR_COMPAT_PROCESS_TRACKER_ID_MAX_LENGTH: usize = 126;
const PAYMENT_METHOD_MODULAR_COMPAT_PROCESS_TRACKER_ID_SUFFIX_LENGTH: usize = 8;
-#[cfg(feature = "v2")]
-const PAYMENT_METHOD_REDACTED_FINGERPRINT_ID: &str = "FINGERPRINT_ID_REDACTED";
/// `process_tracker.id` is a `varchar(127)`; ids are built to stay within it.
const NETWORK_TOKENIZATION_PROCESS_TRACKER_ID_MAX_LENGTH: usize = 126;
const NETWORK_TOKENIZATION_PROCESS_TRACKER_ID_SUFFIX_LENGTH: usize = 8;
@@ -5029,7 +5027,7 @@ pub async fn create_pm_additional_data_update(
network_token_locker_id: nt_data.clone().map(|data| data.network_token_locker_id),
network_token_payment_method_data: nt_data.map(|data| data.network_token_pmd.into()),
connector_mandate_details: Box::new(connector_mandate_details_update),
- locker_fingerprint_id: vault_fingerprint_id,
+ locker_fingerprint_id: vault_fingerprint_id.map(Some),
external_vault_source,
network_transaction_id,
network_transaction_link_id: None,
@@ -5978,24 +5976,70 @@ pub async fn retrieve_payment_method(
(raw_payment_method_data, _) => raw_payment_method_data,
};
- if matches!(
- raw_payment_method_access.account_updater,
- RawPaymentMethodFetchAccess::Allowed
- ) {
- let account_updater_dimensions = dimensions
- .with_organization_id(platform.get_provider().get_account().get_org_id().clone())
- .with_profile_id(profile.get_id().clone());
+ let refresh_result = match raw_payment_method_access.account_updater {
+ RawPaymentMethodFetchAccess::Allowed => {
+ let account_updater_dimensions = dimensions
+ .with_organization_id(platform.get_provider().get_account().get_org_id().clone())
+ .with_profile_id(profile.get_id().clone());
- Box::pin(account_updater::run_account_updater(
- &state,
- &platform,
- &profile,
- &payment_method,
- raw_payment_method_data.as_ref(),
- &account_updater_dimensions,
- ))
- .await;
- }
+ Box::pin(account_updater::run_account_updater(
+ &state,
+ &platform,
+ &profile,
+ &payment_method,
+ raw_payment_method_data.as_ref(),
+ &account_updater_dimensions,
+ ))
+ .await
+ .ok()
+ }
+ RawPaymentMethodFetchAccess::Denied => None,
+ };
+
+ let updated_payment_method = match refresh_result {
+ Some(account_updater::types::RefreshResult::Card(card_result)) => {
+ Box::pin(account_updater::apply_card_refresh_result(
+ &state,
+ &platform,
+ &profile,
+ &payment_method,
+ card_result,
+ ))
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Account Updater failed while applying a card change")?
+ }
+ None => None,
+ };
+
+ let payment_method = match updated_payment_method {
+ Some(updated_payment_method) => {
+ let updated_raw_data = Box::pin(
+ raw_payment_method_access
+ .retrieve_raw_card
+ .get_raw_payment_method_data(
+ &state,
+ &platform,
+ &profile,
+ &updated_payment_method,
+ storage_type,
+ ),
+ )
+ .await
+ .attach_printable("Failed to get raw payment method data")?;
+
+ match (updated_raw_data, &mut raw_payment_method_data) {
+ (
+ Some(payment_methods::RawPaymentMethodData::Card(updated_card)),
+ Some(payment_methods::RawPaymentMethodData::CardWithNT(existing)),
+ ) => existing.card_details = updated_card,
+ (updated_raw_data, existing) => *existing = updated_raw_data,
+ }
+
+ updated_payment_method
+ }
+ None => payment_method,
+ };
match raw_payment_method_access.response {
RawPaymentMethodFetchAccess::Allowed => {
@@ -6766,14 +6810,17 @@ pub async fn delete_payment_method_by_record(
profile: &domain::Profile,
payment_method: domain::PaymentMethod,
) -> RouterResult<()> {
+ let last_modified_by = platform
+ .get_initiator()
+ .and_then(|initiator| initiator.to_created_by())
+ .map(|last_modified_by| last_modified_by.to_string());
+
// Soft delete - mark as Redacted (terminal state, no transitions allowed)
let pm_update = storage::PaymentMethodUpdate::StatusAndFingerprintUpdate {
status: Some(enums::PaymentMethodStatus::Redacted),
- last_modified_by: platform
- .get_initiator()
- .and_then(|initiator| initiator.to_created_by())
- .map(|last_modified_by| last_modified_by.to_string()),
- locker_fingerprint_id: Some(PAYMENT_METHOD_REDACTED_FINGERPRINT_ID.to_string()),
+ last_modified_by,
+ // Some(None) sets the locker_fingerprint_id to null
+ locker_fingerprint_id: Some(None),
};
db.update_payment_method(
diff --git a/crates/router/src/events/account_updater.rs b/crates/router/src/events/account_updater.rs
index a02a553425..7e80fccd1f 100644
--- a/crates/router/src/events/account_updater.rs
+++ b/crates/router/src/events/account_updater.rs
@@ -3,11 +3,12 @@ use common_utils::{errors::CustomResult, id_type};
use hyperswitch_domain_models::payment_method_data::PaymentMethodsData;
use serde::Serialize;
use time::OffsetDateTime;
-use unified_connector_service_client::payments as payments_grpc;
use super::EventType;
use crate::{
- core::account_updater::types::AccountUpdaterError, services::kafka::KafkaMessage, types::domain,
+ core::account_updater::types::{AccountUpdaterError, RefreshResult},
+ services::kafka::KafkaMessage,
+ types::domain,
};
#[derive(Debug, Serialize)]
@@ -29,11 +30,11 @@ impl<'a> KafkaAccountUpdaterEvent<'a> {
merchant_id: &'a id_type::MerchantId,
profile_id: &'a id_type::ProfileId,
payment_method: &'a domain::PaymentMethod,
- evaluation: &'a CustomResult<payments_grpc::CardRefreshOutcome, AccountUpdaterError>,
+ evaluation: &'a CustomResult<RefreshResult, AccountUpdaterError>,
latency_ms: u128,
) -> Self {
let (updater_outcome, error_category) = match evaluation {
- Ok(outcome) => (Some(outcome.as_str_name()), None),
+ Ok(RefreshResult::Card(card_result)) => (Some(card_result.outcome.as_str_name()), None),
Err(error) => (None, Some(error.current_context())),
};
diff --git a/crates/storage_impl/src/payment_method.rs b/crates/storage_impl/src/payment_method.rs
index 44df73ec2d..10b61f090c 100644
--- a/crates/storage_impl/src/payment_method.rs
+++ b/crates/storage_impl/src/payment_method.rs
@@ -655,10 +655,13 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
.await
.change_context(errors::StorageError::DecryptionError)?;
let conn = pg_connection_write(self).await?;
- let payment_method: DomainPaymentMethod = Box::pin(self.call_database_new(
- key_store,
- payment_method.update_with_id(&conn, payment_method_update.into()),
- ))
+ let payment_method: DomainPaymentMethod = Box::pin(
+ self.call_database_new(
+ key_store,
+ payment_method
+ .update_with_id_and_locker_fingerprint_id(&conn, payment_method_update.into()),
+ ),
+ )
.await?;
if let Some(compat_action) = compat_action {
@@ -840,10 +843,13 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
.and_then(|initiator| initiator.to_created_by())
.map(|last_modified_by| last_modified_by.to_string()),
};
- Box::pin(self.call_database_new(
- key_store,
- payment_method.update_with_id(&conn, payment_method_update.into()),
- ))
+ Box::pin(
+ self.call_database_new(
+ key_store,
+ payment_method
+ .update_with_id_and_locker_fingerprint_id(&conn, payment_method_update.into()),
+ ),
+ )
.await
}
diff --git a/diesel_v2.toml b/diesel_v2.toml
index 52a0217954..b9faf6b79f 100644
--- a/diesel_v2.toml
+++ b/diesel_v2.toml
@@ -6,6 +6,8 @@
file = "crates/diesel_models/src/schema_v2.rs"
import_types = ["diesel::sql_types::*", "crate::enums::diesel_exports::*"]
generate_missing_sql_type_definitions = false
+patch_file = "crates/diesel_models/payment_methods_v2.patch"
# blocklist has no primary key, which print-schema refuses. Nothing in v2 uses this table, so it is
# simply left out. Anchored because the value is a regex and would otherwise match the sibling tables.
-filter = { except_tables = ["^blocklist$"] }
+# payment_methods has no primary key either, but v2 does use it, so its block comes from patch_file.
+filter = { except_tables = ["^blocklist$", "^payment_methods$"] }
diff --git a/v2_compatible_migrations/2026-08-18-000001_prepare_payment_methods_for_id_index_swap/down.sql b/v2_compatible_migrations/2026-08-18-000001_prepare_payment_methods_for_id_index_swap/down.sql
new file mode 100644
index 0000000000..4ecf0b8032
--- /dev/null
+++ b/v2_compatible_migrations/2026-08-18-000001_prepare_payment_methods_for_id_index_swap/down.sql
@@ -0,0 +1,3 @@
+UPDATE payment_methods
+SET locker_fingerprint_id = 'FINGERPRINT_ID_REDACTED'
+WHERE status = 'redacted';
diff --git a/v2_compatible_migrations/2026-08-18-000001_prepare_payment_methods_for_id_index_swap/up.sql b/v2_compatible_migrations/2026-08-18-000001_prepare_payment_methods_for_id_index_swap/up.sql
new file mode 100644
index 0000000000..a67a83b28b
--- /dev/null
+++ b/v2_compatible_migrations/2026-08-18-000001_prepare_payment_methods_for_id_index_swap/up.sql
@@ -0,0 +1,3 @@
+UPDATE payment_methods
+SET locker_fingerprint_id = NULL
+WHERE status = 'redacted';
diff --git a/v2_compatible_migrations/2026-08-18-000002_add_payment_methods_id_locker_fingerprint_id_index/down.sql b/v2_compatible_migrations/2026-08-18-000002_add_payment_methods_id_locker_fingerprint_id_index/down.sql
new file mode 100644
index 0000000000..0d5e424bf9
--- /dev/null
+++ b/v2_compatible_migrations/2026-08-18-000002_add_payment_methods_id_locker_fingerprint_id_index/down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS payment_methods_id_locker_fingerprint_id_index;
diff --git a/v2_compatible_migrations/2026-08-18-000002_add_payment_methods_id_locker_fingerprint_id_index/metadata.toml b/v2_compatible_migrations/2026-08-18-000002_add_payment_methods_id_locker_fingerprint_id_index/metadata.toml
new file mode 100644
index 0000000000..79e9221c1f
--- /dev/null
+++ b/v2_compatible_migrations/2026-08-18-000002_add_payment_methods_id_locker_fingerprint_id_index/metadata.toml
@@ -0,0 +1 @@
+run_in_transaction = false
diff --git a/v2_compatible_migrations/2026-08-18-000002_add_payment_methods_id_locker_fingerprint_id_index/up.sql b/v2_compatible_migrations/2026-08-18-000002_add_payment_methods_id_locker_fingerprint_id_index/up.sql
new file mode 100644
index 0000000000..c9b78b8877
--- /dev/null
+++ b/v2_compatible_migrations/2026-08-18-000002_add_payment_methods_id_locker_fingerprint_id_index/up.sql
@@ -0,0 +1,2 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS payment_methods_id_locker_fingerprint_id_index
+ON payment_methods (id, locker_fingerprint_id);
diff --git a/v2_compatible_migrations/2026-08-18-000003_add_payment_methods_id_active_index/down.sql b/v2_compatible_migrations/2026-08-18-000003_add_payment_methods_id_active_index/down.sql
new file mode 100644
index 0000000000..99955c06c0
--- /dev/null
+++ b/v2_compatible_migrations/2026-08-18-000003_add_payment_methods_id_active_index/down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS payment_methods_id_active_index;
diff --git a/v2_compatible_migrations/2026-08-18-000003_add_payment_methods_id_active_index/metadata.toml b/v2_compatible_migrations/2026-08-18-000003_add_payment_methods_id_active_index/metadata.toml
new file mode 100644
index 0000000000..79e9221c1f
--- /dev/null
+++ b/v2_compatible_migrations/2026-08-18-000003_add_payment_methods_id_active_index/metadata.toml
@@ -0,0 +1 @@
+run_in_transaction = false
diff --git a/v2_compatible_migrations/2026-08-18-000003_add_payment_methods_id_active_index/up.sql b/v2_compatible_migrations/2026-08-18-000003_add_payment_methods_id_active_index/up.sql
new file mode 100644
index 0000000000..b32359a9d7
--- /dev/null
+++ b/v2_compatible_migrations/2026-08-18-000003_add_payment_methods_id_active_index/up.sql
@@ -0,0 +1,3 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS payment_methods_id_active_index
+ON payment_methods (id)
+WHERE status = 'active';
diff --git a/v2_compatible_migrations/2026-08-18-000004_drop_payment_methods_id_index/down.sql b/v2_compatible_migrations/2026-08-18-000004_drop_payment_methods_id_index/down.sql
new file mode 100644
index 0000000000..08cb41cf95
--- /dev/null
+++ b/v2_compatible_migrations/2026-08-18-000004_drop_payment_methods_id_index/down.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS payment_methods_id_index ON payment_methods (id);
diff --git a/v2_compatible_migrations/2026-08-18-000004_drop_payment_methods_id_index/metadata.toml b/v2_compatible_migrations/2026-08-18-000004_drop_payment_methods_id_index/metadata.toml
new file mode 100644
index 0000000000..79e9221c1f
--- /dev/null
+++ b/v2_compatible_migrations/2026-08-18-000004_drop_payment_methods_id_index/metadata.toml
@@ -0,0 +1 @@
+run_in_transaction = false
diff --git a/v2_compatible_migrations/2026-08-18-000004_drop_payment_methods_id_index/up.sql b/v2_compatible_migrations/2026-08-18-000004_drop_payment_methods_id_index/up.sql
new file mode 100644
index 0000000000..0212bc9988
--- /dev/null
+++ b/v2_compatible_migrations/2026-08-18-000004_drop_payment_methods_id_index/up.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS payment_methods_id_index;
diff --git a/v2_migrations/2026-08-18-000002_drop_payment_methods_pkey/down.sql b/v2_migrations/2026-08-18-000002_drop_payment_methods_pkey/down.sql
new file mode 100644
index 0000000000..b8aea3f371
--- /dev/null
+++ b/v2_migrations/2026-08-18-000002_drop_payment_methods_pkey/down.sql
@@ -0,0 +1 @@
+ALTER TABLE payment_methods ADD PRIMARY KEY (id);
diff --git a/v2_migrations/2026-08-18-000002_drop_payment_methods_pkey/up.sql b/v2_migrations/2026-08-18-000002_drop_payment_methods_pkey/up.sql
new file mode 100644
index 0000000000..c68c94ce77
--- /dev/null
+++ b/v2_migrations/2026-08-18-000002_drop_payment_methods_pkey/up.sql
@@ -0,0 +1 @@
+ALTER TABLE payment_methods DROP CONSTRAINT IF EXISTS payment_methods_pkey;