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(customers): resolve merchant_reference_id as customer_id in v1 payments and payouts (#14589)

Sai Harsha Vardhanb232a7342781
diff --git a/Cargo.lock b/Cargo.lock
index e03f883822..c64c3fb20b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4960,6 +4960,7 @@ dependencies = [
"time 0.3.41",
"url 2.5.4",
"utoipa",
+ "uuid",
]
[[package]]
diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rs
index 1fc6b2acb4..086e87e213 100644
--- a/crates/diesel_models/src/customers.rs
+++ b/crates/diesel_models/src/customers.rs
@@ -70,6 +70,7 @@ impl From<CustomerNew> for Customer {
last_modified_by: customer_new.last_modified_by,
id: customer_new.id,
preferred_connectors: customer_new.preferred_connectors,
+ merchant_reference_id: None,
}
}
}
@@ -172,6 +173,8 @@ pub struct Customer {
pub document_details: Option<Encryption>,
pub id: Option<common_utils::id_type::GlobalCustomerId>,
pub preferred_connectors: Option<pii::SecretSerdeValue>,
+ #[serde(default)]
+ pub merchant_reference_id: Option<common_utils::id_type::CustomerId>,
}
#[cfg(feature = "v2")]
diff --git a/crates/diesel_models/src/query/customers.rs b/crates/diesel_models/src/query/customers.rs
index 76e50fd84e..b38ab22f7b 100644
--- a/crates/diesel_models/src/query/customers.rs
+++ b/crates/diesel_models/src/query/customers.rs
@@ -312,7 +312,6 @@ impl Customer {
}
}
- #[cfg(feature = "v2")]
pub async fn find_optional_by_merchant_id_merchant_reference_id(
conn: &DatabaseConnectionWithContext<'_>,
customer_id: &id_type::CustomerId,
@@ -383,7 +382,6 @@ impl Customer {
.await
}
- #[cfg(feature = "v2")]
pub async fn find_by_merchant_reference_id_merchant_id(
conn: &DatabaseConnectionWithContext<'_>,
merchant_reference_id: &id_type::CustomerId,
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index e7e198fe8e..46ae7d168d 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -516,6 +516,8 @@ diesel::table! {
#[max_length = 64]
id -> Nullable<Varchar>,
preferred_connectors -> Nullable<Jsonb>,
+ #[max_length = 64]
+ merchant_reference_id -> Nullable<Varchar>,
}
}
diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml
index 103b720800..61583446b7 100644
--- a/crates/hyperswitch_domain_models/Cargo.toml
+++ b/crates/hyperswitch_domain_models/Cargo.toml
@@ -50,6 +50,7 @@ strum = { version = "0.26", features = ["derive"] }
time = { version = "0.3.41", features = ["serde", "serde-well-known", "std"] }
url = { version = "2.5.4", features = ["serde"] }
utoipa = { version = "4.2.3", features = ["preserve_order", "preserve_path_order", "time"] }
+uuid = { version = "1.17.0" }
[lints]
workspace = true
diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rs
index 6836852d1c..e4c827788f 100644
--- a/crates/hyperswitch_domain_models/src/customer.rs
+++ b/crates/hyperswitch_domain_models/src/customer.rs
@@ -332,10 +332,14 @@ pub trait CustomerInterface {
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
+ use_merchant_reference_id_lookup: bool,
) -> CustomResult<Option<Customer>, Self::Error>;
/// This function is to retrieve customer details. If the customer is deleted, it returns
- /// customer details that contains the fields as Redacted
+ /// customer details that contains the fields as Redacted.
+ ///
+ /// `use_merchant_reference_id_lookup` behaves as documented on
+ /// [`Self::find_customer_optional_by_customer_id_merchant_id`].
#[cfg(feature = "v1")]
async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
&self,
@@ -343,9 +347,12 @@ pub trait CustomerInterface {
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
+ use_merchant_reference_id_lookup: bool,
) -> CustomResult<Option<Customer>, Self::Error>;
- #[cfg(feature = "v2")]
+ /// Looks up a customer by the `merchant_reference_id` that the merchant supplied while creating
+ /// the customer through the v2 customers API. For v1 this is used when the merchant sends that
+ /// reference id as the `customer_id` in payments requests.
async fn find_optional_by_merchant_id_merchant_reference_id(
&self,
customer_id: &id_type::CustomerId,
@@ -381,6 +388,8 @@ pub trait CustomerInterface {
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Customer, Self::Error>;
+ /// `use_merchant_reference_id_lookup` behaves as documented on
+ /// [`Self::find_customer_optional_by_customer_id_merchant_id`].
#[cfg(feature = "v1")]
async fn find_customer_by_customer_id_merchant_id(
&self,
@@ -388,9 +397,12 @@ pub trait CustomerInterface {
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
+ use_merchant_reference_id_lookup: bool,
) -> CustomResult<Customer, Self::Error>;
- #[cfg(feature = "v2")]
+ /// Looks up a customer by the `merchant_reference_id` that the merchant supplied while
+ /// creating the customer, erroring if none is found. For v1 this backs a `customer_id`-keyed
+ /// find whose id turned out to be a `merchant_reference_id`.
async fn find_customer_by_merchant_reference_id_merchant_id(
&self,
merchant_reference_id: &id_type::CustomerId,
@@ -459,6 +471,29 @@ pub trait CustomerInterface {
) -> CustomResult<CustomerWithoutEncrypted, Self::Error>;
}
+/// Checks whether `input` looks like a global id generated by the v2 customers API
+/// (`<cell_id>_cus_<32-char-uuid>`), as opposed to a merchant-supplied `customer_id` or
+/// `merchant_reference_id`.
+pub fn is_global_customer_id_format(input: &str) -> bool {
+ let mut parts = input.split('_');
+ match (parts.next(), parts.next(), parts.next(), parts.next()) {
+ (Some(cell_id), Some(entity), Some(uuid), None) => {
+ !cell_id.is_empty()
+ && cell_id
+ .chars()
+ .all(|character| character.is_ascii_lowercase() || character.is_ascii_digit())
+ && entity == "cus"
+ && uuid.len() == 32
+ && uuid::Uuid::parse_str(uuid).is_ok()
+ }
+ _ => false,
+ }
+}
+
+pub fn is_customer_id_in_global_format(customer_id: &id_type::CustomerId) -> bool {
+ is_global_customer_id_format(customer_id.get_string_repr())
+}
+
#[cfg(feature = "v1")]
#[instrument]
pub async fn update_connector_customer_in_customers(
diff --git a/crates/payment_methods/src/core/migration/payment_methods.rs b/crates/payment_methods/src/core/migration/payment_methods.rs
index cbff632d80..649162eedf 100644
--- a/crates/payment_methods/src/core/migration/payment_methods.rs
+++ b/crates/payment_methods/src/core/migration/payment_methods.rs
@@ -679,6 +679,7 @@ pub async fn skip_locker_call_and_migrate_payment_method(
&merchant_id,
provider.get_key_store(),
provider.get_account().storage_scheme,
+ false,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index b3390ecada..e3dab3f241 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -450,6 +450,10 @@ pub mod superposition {
pub const PAYMENT_BLOCKLIST_GUARD: &str = "payments.payment_blocklist_guard";
/// Organization-scoped block implicit customer creation configuration key
pub const BLOCK_IMPLICIT_CUSTOMER_CREATION: &str = "payments.block_implicit_customer_creation";
+ /// Resolve the `customer_id` of a payments request through the `merchant_reference_id` of the
+ /// customer (created via the v2 customers API) instead of the `customer_id` column
+ pub const USE_MERCHANT_REFERENCE_ID_AS_CUSTOMER_ID: &str =
+ "payments.use_merchant_reference_id_as_customer_id";
/// Fingerprint secret configuration key retained for migration fallback
pub const FINGERPRINT_SECRET: &str = "vaulting.fingerprint_secret";
/// Poll config for external 3DS authentication key
diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rs
index 4cf24766c0..9d011f32d8 100644
--- a/crates/router/src/core/configs/dimension_config.rs
+++ b/crates/router/src/core/configs/dimension_config.rs
@@ -217,6 +217,24 @@ impl DatabaseBackedConfig for BlockImplicitCustomerCreation {
}
}
+config! {
+ superposition_key = USE_MERCHANT_REFERENCE_ID_AS_CUSTOMER_ID,
+ output = bool,
+ default = false,
+ requires = dimension_state::DimensionsWithProviderMerchantIdAndOrgId,
+ targeting_key = id_type::CustomerId
+}
+
+impl DatabaseBackedConfig for UseMerchantReferenceIdAsCustomerId {
+ const KEY: &'static str = "use_merchant_reference_id_as_customer_id";
+
+ fn db_key(dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {
+ dimensions
+ .get_organization_id()
+ .map(|id| format!("{}_{}", Self::KEY, id.get_string_repr()))
+ }
+}
+
// Retained temporarily so merchants without a database value can fall back to
// their existing Superposition fingerprint secret during migration.
config! {
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index f716256467..3820d7ef2d 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -14,6 +14,9 @@ use common_utils::{
validation::validate_phone_country_code,
};
use error_stack::{report, ResultExt};
+pub use hyperswitch_domain_models::customer::{
+ is_customer_id_in_global_format, is_global_customer_id_format,
+};
use hyperswitch_domain_models::{
payment_methods as payment_methods_domain, type_encryption::AsyncLift,
};
@@ -23,6 +26,8 @@ use router_env::{instrument, tracing};
#[cfg(feature = "v2")]
use crate::core::payment_methods::delete_payment_method_by_record;
+#[cfg(feature = "v1")]
+use crate::core::payments::helpers as payments_helpers;
#[cfg(feature = "v2")]
use crate::core::utils::create_encrypted_data;
#[cfg(feature = "v1")]
@@ -48,26 +53,6 @@ use crate::{
pub const REDACTED: &str = "Redacted";
-pub fn is_global_customer_id_format(input: &str) -> bool {
- let mut parts = input.split('_');
- match (parts.next(), parts.next(), parts.next(), parts.next()) {
- (Some(cell_id), Some(entity), Some(uuid), None) => {
- !cell_id.is_empty()
- && cell_id
- .chars()
- .all(|character| character.is_ascii_lowercase() || character.is_ascii_digit())
- && entity == "cus"
- && uuid.len() == 32
- && uuid::Uuid::parse_str(uuid).is_ok()
- }
- _ => false,
- }
-}
-
-pub fn is_customer_id_in_global_format(customer_id: &id_type::CustomerId) -> bool {
- is_global_customer_id_format(customer_id.get_string_repr())
-}
-
#[instrument(skip(state))]
pub async fn create_customer(
state: SessionState,
@@ -517,6 +502,9 @@ impl<'a> MerchantReferenceIdForCustomer<'a> {
self.merchant_id,
self.key_store,
self.merchant_account.storage_scheme,
+ // This checks whether `cus` itself already exists as a `customer_id`, so it must
+ // not be resolved through the `merchant_reference_id` fallback.
+ false,
)
.await
{
@@ -590,12 +578,21 @@ pub async fn retrieve_customer(
) -> errors::CustomerResponse<customers::CustomerResponse> {
let db = state.store.as_ref();
+ let use_merchant_reference_id =
+ payments_helpers::should_use_merchant_reference_id_as_customer_id_for_provider(
+ &state,
+ &provider,
+ Some(&customer_id),
+ )
+ .await;
+
let response = db
.find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
&customer_id,
provider.get_account().get_id(),
provider.get_key_store(),
provider.get_account().storage_scheme,
+ use_merchant_reference_id,
)
.await
.switch()?
@@ -965,12 +962,20 @@ impl CustomerDeleteBridge for id_type::CustomerId {
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
) -> errors::CustomerResponse<customers::CustomerDeleteResponse> {
+ let use_merchant_reference_id =
+ payments_helpers::should_use_merchant_reference_id_as_customer_id_for_provider(
+ state,
+ provider,
+ Some(self),
+ )
+ .await;
let customer_orig = db
.find_customer_by_customer_id_merchant_id(
self,
provider.get_account().get_id(),
provider.get_key_store(),
provider.get_account().storage_scheme,
+ use_merchant_reference_id,
)
.await
.switch()?;
@@ -1188,11 +1193,21 @@ pub async fn update_customer(
let key_manager_state = &(&state).into();
//Add this in update call if customer can be updated anywhere else
+ #[cfg(feature = "v1")]
+ let use_merchant_reference_id =
+ payments_helpers::should_use_merchant_reference_id_as_customer_id_for_provider(
+ &state,
+ &provider,
+ Some(&update_customer.customer_id),
+ )
+ .await;
+
#[cfg(feature = "v1")]
let verify_id_for_update_customer = VerifyIdForUpdateCustomer {
merchant_reference_id: &update_customer.customer_id,
merchant_account: provider.get_account(),
key_store: provider.get_key_store(),
+ use_merchant_reference_id_lookup: use_merchant_reference_id,
};
#[cfg(feature = "v2")]
@@ -1331,6 +1346,7 @@ struct VerifyIdForUpdateCustomer<'a> {
merchant_reference_id: &'a id_type::CustomerId,
merchant_account: &'a domain::MerchantAccount,
key_store: &'a domain::MerchantKeyStore,
+ use_merchant_reference_id_lookup: bool,
}
#[cfg(feature = "v2")]
@@ -1354,6 +1370,7 @@ impl VerifyIdForUpdateCustomer<'_> {
self.merchant_account.get_id(),
self.key_store,
self.merchant_account.storage_scheme,
+ self.use_merchant_reference_id_lookup,
)
.await
.switch()?;
@@ -1725,6 +1742,7 @@ async fn sync_connector_customer_for_migrated_customer(
merchant_id,
provider.get_key_store(),
storage_scheme,
+ false,
)
.await
.switch()?;
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 6ba432b832..d641382ac1 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -379,12 +379,20 @@ pub async fn render_pm_collect_link(
})?;
// Fetch customer
+ let use_merchant_reference_id =
+ payment_helpers::should_use_merchant_reference_id_as_customer_id_for_provider(
+ &state,
+ &provider,
+ Some(&customer_id),
+ )
+ .await;
let customer = db
.find_customer_by_customer_id_merchant_id(
&customer_id,
&req.merchant_id,
provider.get_key_store(),
provider.get_account().storage_scheme,
+ use_merchant_reference_id,
)
.await
.change_context(errors::ApiErrorResponse::InvalidRequestData {
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 11e1e8260d..f53933e2bb 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -76,6 +76,8 @@ use crate::core::payment_methods::{
utils::{get_merchant_pm_filter_graph, make_pm_graph, refresh_pm_filters_cache},
};
#[cfg(feature = "v1")]
+use crate::core::payments::helpers as payments_helpers;
+#[cfg(feature = "v1")]
use crate::core::payments::tokenization;
#[cfg(feature = "v1")]
use crate::routes::app::SessionStateInfo;
@@ -153,12 +155,20 @@ impl PaymentMethodsController for PmCards<'_> {
initiator: Option<&domain::Initiator>,
) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {
let db = &*self.state.store;
+ let use_merchant_reference_id =
+ payments_helpers::should_use_merchant_reference_id_as_customer_id_for_provider(
+ self.state,
+ self.provider,
+ Some(customer_id),
+ )
+ .await;
let customer = db
.find_customer_by_customer_id_merchant_id(
customer_id,
merchant_id,
self.provider.get_key_store(),
self.provider.get_account().storage_scheme,
+ use_merchant_reference_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
@@ -182,7 +192,7 @@ impl PaymentMethodsController for PmCards<'_> {
.insert_payment_method(
self.provider.get_key_store(),
domain::PaymentMethod {
- customer_id: Some(customer_id.to_owned()),
+ customer_id: Some(customer.get_id().to_owned()),
merchant_id: merchant_id.to_owned(),
payment_method_id: payment_method_id.to_string(),
locker_id,
@@ -1265,12 +1275,20 @@ impl PaymentMethodsController for PmCards<'_> {
let db = &*self.state.store;
// check for the customer
// TODO: customer need not be checked again here, this function can take an optional customer and check for existence of customer based on the optional value
+ let use_merchant_reference_id =
+ payments_helpers::should_use_merchant_reference_id_as_customer_id_for_provider(
+ self.state,
+ self.provider,
+ Some(customer_id),
+ )
+ .await;
let customer = db
.find_customer_by_customer_id_merchant_id(
customer_id,
merchant_id,
self.provider.get_key_store(),
self.provider.get_account().storage_scheme,
+ use_merchant_reference_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
@@ -1703,12 +1721,20 @@ impl PaymentMethodsController for PmCards<'_> {
let customer_id = key.customer_id.clone().get_required_value("customer_id")?;
+ let use_merchant_reference_id =
+ payments_helpers::should_use_merchant_reference_id_as_customer_id_for_provider(
+ self.state,
+ self.provider,
+ Some(&customer_id),
+ )
+ .await;
let customer = db
.find_customer_by_customer_id_merchant_id(
&customer_id,
self.provider.get_account().get_id(),
self.provider.get_key_store(),
self.provider.get_account().storage_scheme,
+ use_merchant_reference_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
@@ -1824,12 +1850,20 @@ impl PaymentMethodsController for PmCards<'_> {
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
+ let use_merchant_reference_id =
+ payments_helpers::should_use_merchant_reference_id_as_customer_id_for_provider(
+ self.state,
+ self.provider,
+ Some(&customer_id),
+ )
+ .await;
let customer_obj = db
.find_customer_by_customer_id_merchant_id(
&customer_id,
merchant_id,
self.provider.get_key_store(),
self.provider.get_account().storage_scheme,
+ use_merchant_reference_id,
)
.await
.change_context(errors::ApiErrorResponse::CustomerNotFound)
@@ -1859,7 +1893,11 @@ impl PaymentMethodsController for PmCards<'_> {
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add PaymentMethod Failed"),
- _ => Ok(self.store_default_payment_method(req, &customer_id, merchant_id)),
+ _ => Ok(self.store_default_payment_method(
+ req,
+ customer_obj.get_id(),
+ merchant_id,
+ )),
}
}
api_enums::PaymentMethod::Card => match req.card.clone() {
@@ -1884,7 +1922,7 @@ impl PaymentMethodsController for PmCards<'_> {
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Card Failed")
}
- _ => Ok(self.store_default_payment_method(req, &customer_id, merchant_id)),
+ _ => Ok(self.store_default_payment_method(req, customer_obj.get_id(), merchant_id)),
},
api_enums::PaymentMethod::BankDebit => match req.payment_method_data.clone() {
Some(api_models::payment_methods::PaymentMethodCreateData::BankDebit(
@@ -1907,7 +1945,7 @@ impl PaymentMethodsController for PmCards<'_> {
message: "PaymentMethodData does not match PaymentMethod".to_string(),
})?,
},
- _ => Ok(self.store_default_payment_method(req, &customer_id, merchant_id)),
+ _ => Ok(self.store_default_payment_method(req, customer_obj.get_id(), merchant_id)),
};
let (mut resp, duplication_check) = response?;
@@ -2524,12 +2562,20 @@ pub async fn add_payment_method_data(
.clone()
.get_required_value("customer_id")?;
+ let use_merchant_reference_id =
+ payments_helpers::should_use_merchant_reference_id_as_customer_id_for_provider(
+ &state,
+ &provider,
+ Some(&customer_id),
+ )
+ .await;
let customer = db
.find_customer_by_customer_id_merchant_id(
&customer_id,
provider.get_account().get_id(),
provider.get_key_store(),
provider.get_account().storage_scheme,
+ use_merchant_reference_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
@@ -3198,14 +3244,14 @@ pub async fn prepare_payment_method_update_from_connector_details(
) -> errors::RouterResult<storage::PaymentMethodUpdate> {
match connector_disclosed_details {
domain::PaymentMethodData::BankRedirect(bank_redirect_update) => {
- prepare_bank_redirect_payment_method_update(
+ Box::pin(prepare_bank_redirect_payment_method_update(
state,
platform,
pm,
merchant_connector_id,
bank_redirect_update.clone(),
business_profile,
- )
+ ))
.await
}
domain::PaymentMethodData::Wallet(domain::WalletData::PaypalRedirect(details)) => {
@@ -3316,13 +3362,13 @@ pub async fn prepare_bank_redirect_payment_method_update(
.await?;
// Vault the bank redirect data using save_in_locker (supports external vault routing)
- let (vault_resp, _dup_check) = tokenization::save_in_locker(
+ let (vault_resp, _dup_check) = Box::pin(tokenization::save_in_locker(
state,
platform,
pm_create_req,
None, // card_detail not needed for bank redirect
business_profile,
- )
+ ))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to vault bank redirect data")?;
@@ -5354,11 +5400,19 @@ pub async fn list_payment_methods(
pi.customer_id
.as_ref()
.async_and_then(|cust| async {
+ let use_merchant_reference_id =
+ payments_helpers::should_use_merchant_reference_id_as_customer_id_for_provider(
+ &state,
+ platform.get_provider(),
+ Some(cust),
+ )
+ .await;
db.find_customer_by_customer_id_merchant_id(
cust,
&pi.merchant_id,
platform.get_provider().get_key_store(),
platform.get_provider().get_account().storage_scheme,
+ use_merchant_reference_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
@@ -6432,12 +6486,20 @@ pub async fn list_customer_payment_method(
})
.unwrap_or(false);
+ let use_merchant_reference_id =
+ payments_helpers::should_use_merchant_reference_id_as_customer_id_for_provider(
+ state,
+ platform.get_provider(),
+ Some(customer_id),
+ )
+ .await;
let customer = db
.find_customer_by_customer_id_merchant_id(
customer_id,
platform.get_provider().get_account().get_id(),
platform.get_provider().get_key_store(),
platform.get_provider().get_account().storage_scheme,
+ use_merchant_reference_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
diff --git a/crates/router/src/core/payment_methods/client.rs b/crates/router/src/core/payment_methods/client.rs
index d87049bf0e..264483db12 100644
--- a/crates/router/src/core/payment_methods/client.rs
+++ b/crates/router/src/core/payment_methods/client.rs
@@ -452,11 +452,19 @@ async fn load_payment_intent_context(
.customer_id
.as_ref()
.async_and_then(|customer_id| async {
+ let use_merchant_reference_id =
+ helpers::should_use_merchant_reference_id_as_customer_id_for_provider(
+ state,
+ platform.get_provider(),
+ Some(customer_id),
+ )
+ .await;
db.find_customer_by_customer_id_merchant_id(
customer_id,
&payment_intent.merchant_id,
platform.get_provider().get_key_store(),
platform.get_provider().get_account().storage_scheme,
+ use_merchant_reference_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
diff --git a/crates/router/src/core/payment_methods/tokenize/card_executor.rs b/crates/router/src/core/payment_methods/tokenize/card_executor.rs
index ac77562697..39ac1b2c6e 100644
--- a/crates/router/src/core/payment_methods/tokenize/card_executor.rs
+++ b/crates/router/src/core/payment_methods/tokenize/card_executor.rs
@@ -363,6 +363,7 @@ impl CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest> {
self.merchant_account.get_id(),
self.key_store,
self.merchant_account.storage_scheme,
+ false,
)
.await
.inspect_err(|err| logger::info!("Error fetching customer: {:?}", err))
diff --git a/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs b/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
index bde01f3b79..19b94ee846 100644
--- a/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
+++ b/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
@@ -383,6 +383,7 @@ impl CardNetworkTokenizeExecutor<'_, domain::TokenizePaymentMethodRequest> {
self.merchant_account.get_id(),
self.key_store,
self.merchant_account.storage_scheme,
+ false,
)
.await
.inspect_err(|err| logger::info!("Error fetching customer: {:?}", err))
diff --git a/crates/router/src/core/payment_methods/validator.rs b/crates/router/src/core/payment_methods/validator.rs
index 53d241d58c..05d4bb5d18 100644
--- a/crates/router/src/core/payment_methods/validator.rs
+++ b/crates/router/src/core/payment_methods/validator.rs
@@ -4,6 +4,8 @@ use diesel_models::generic_link::PaymentMethodCollectLinkData;
use error_stack::ResultExt;
use hyperswitch_masking::Secret;
+#[cfg(feature = "v1")]
+use crate::core::payments::helpers as payment_helpers;
use crate::{
consts,
core::{
@@ -35,12 +37,21 @@ pub async fn validate_request_and_initiate_payment_method_collect_link(
let customer_id = req.customer_id.clone();
let merchant_id = platform.get_provider().get_account().get_id().clone();
#[cfg(feature = "v1")]
+ let use_merchant_reference_id =
+ payment_helpers::should_use_merchant_reference_id_as_customer_id_for_provider(
+ state,
+ platform.get_provider(),
+ Some(&customer_id),
+ )
+ .await;
+ #[cfg(feature = "v1")]
match db
.find_customer_by_customer_id_merchant_id(
&customer_id,
&merchant_id,
platform.get_provider().get_key_store(),
platform.get_provider().get_account().storage_scheme,
+ use_merchant_reference_id,
)
.await
{
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 1df43ec884..cdc8ef04ed 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -13818,21 +13818,31 @@ pub async fn payment_external_authentication<F: Clone + Sync>(
)?;
let optional_customer = match &payment_intent.customer_id {
- Some(customer_id) => Some(
- state
- .store
- .find_customer_by_customer_id_merchant_id(
- customer_id,
- platform.get_provider().get_account().get_id(),
- platform.get_provider().get_key_store(),
- platform.get_provider().get_account().storage_scheme,
+ Some(customer_id) => {
+ let use_merchant_reference_id =
+ helpers::should_use_merchant_reference_id_as_customer_id_for_provider(
+ &state,
+ platform.get_provider(),
+ Some(customer_id),
)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable_lazy(|| {
- format!("error while finding customer with customer_id {customer_id:?}")
- })?,
- ),
+ .await;
+ Some(
+ state
+ .store
+ .find_customer_by_customer_id_merchant_id(
+ customer_id,
+ platform.get_provider().get_account().get_id(),
+ platform.get_provider().get_key_store(),
+ platform.get_provider().get_account().storage_scheme,
+ use_merchant_reference_id,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable_lazy(|| {
+ format!("error while finding customer with customer_id {customer_id:?}")
+ })?,
+ )
+ }
None => None,
};
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 3829738d2e..dd1971a695 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -2029,6 +2029,88 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
todo!()
}
+/// Resolves the superposition flag that decides whether a v1 customer lookup keyed by
+/// `customer_id` should fall back to the `merchant_reference_id` of the customer when the id is
+/// not already in the global id format.
+///
+/// Merchants creating customers via the v2 customers API get a global id as the `customer_id`, but
+/// keep sending their own `merchant_reference_id` as the `customer_id` in payments requests. This
+/// function only resolves the org-level config; the format check and the actual lookup branching
+/// both happen inside the storage layer (`CustomerInterface`), not here.
+#[cfg(feature = "v1")]
+pub async fn should_use_merchant_reference_id_as_customer_id(
+ state: &SessionState,
+ dimensions: &dimension_state::DimensionsWithProviderMerchantIdAndOrgId,
+ customer_id: Option<&id_type::CustomerId>,
+) -> bool {
+ dimensions
+ .get_use_merchant_reference_id_as_customer_id(
+ state.store.as_ref(),
+ state.superposition_service.as_ref(),
+ customer_id,
+ )
+ .await
+}
+
+/// Convenience wrapper over [`should_use_merchant_reference_id_as_customer_id`] for the common
+/// case where only a `Provider` (and no additional dimensions) is available.
+#[cfg(feature = "v1")]
+pub async fn should_use_merchant_reference_id_as_customer_id_for_provider(
+ state: &SessionState,
+ provider: &domain::Provider,
+ customer_id: Option<&id_type::CustomerId>,
+) -> bool {
+ let dimensions = dimension_state::Dimensions::new()
+ .with_provider_merchant_id(provider.get_provider_merchant_id())
+ .with_organization_id(provider.get_account().organization_id.clone());
+
+ should_use_merchant_reference_id_as_customer_id(state, &dimensions, customer_id).await
+}
+
+/// Resolves the customer id received in a payments request to the id of the customer record, so
+/// that it can be compared with ids that are stored against the customer (like the customer id of
+/// a payment method). When the customer cannot be resolved, the id is returned as it is.
+#[cfg(feature = "v1")]
+pub async fn resolve_request_customer_id(
+ state: &SessionState,
+ provider: &domain::Provider,
+ customer_id: &id_type::CustomerId,
+) -> id_type::CustomerId {
+ let use_merchant_reference_id = should_use_merchant_reference_id_as_customer_id_for_provider(
+ state,
+ provider,
+ Some(customer_id),
+ )
+ .await;
+
+ // Skip the customer-table lookup entirely for the (overwhelming) majority of merchants who
+ // don't have this config enabled: the request's `customer_id` is already correct for them, and
+ // this function sits on the hot path of every payment create/confirm.
+ if use_merchant_reference_id {
+ state
+ .store
+ .find_customer_optional_by_customer_id_merchant_id(
+ customer_id,
+ provider.get_account().get_id(),
+ provider.get_key_store(),
+ provider.get_account().storage_scheme,
+ use_merchant_reference_id,
+ )
+ .await
+ .inspect_err(|error| {
+ logger::error!(
+ ?error,
+ "Failed to resolve the customer using the merchant reference id"
+ )
+ })
+ .ok()
+ .flatten()
+ .map_or_else(|| customer_id.clone(), |customer| customer.get_id().clone())
+ } else {
+ customer_id.clone()
+ }
+}
+
#[cfg(feature = "v1")]
#[instrument(skip_all)]
#[allow(clippy::type_complexity)]
@@ -2056,12 +2138,22 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
let key_manager_state = &state.into();
let optional_customer = match customer_id {
Some(customer_id) => {
+ let use_merchant_reference_id = should_use_merchant_reference_id_as_customer_id(
+ state,
+ &dimensions
+ .without_profile_id()
+ .without_processor_merchant_id()
+ .with_organization_id(provider.get_account().organization_id.clone()),
+ Some(&customer_id),
+ )
+ .await;
let customer_data = db
.find_customer_optional_by_customer_id_merchant_id(
&customer_id,
merchant_id,
key_store,
storage_scheme,
+ use_merchant_reference_id,
)
.await?;
let key = key_store.key.get_inner().peek();
@@ -2177,8 +2269,10 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
.map(|last_modified_by| last_modified_by.to_string()),
};
+ // The id of the fetched record is used for the update, because the id
+ // received in the request can be the `merchant_reference_id`.
db.update_customer_by_customer_id_merchant_id(
- customer_id,
+ c.get_id().clone(),
merchant_id.to_owned(),
c,
customer_update,
@@ -2205,7 +2299,11 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
)
.await;
- if should_block_implicit_customer_creation {
+ // A customer looked up through the `merchant_reference_id` has to exist already,
+ // because it can only be created via the v2 customers API. Creating a v1 customer
+ // with the reference id as the `customer_id` would leave it unreachable by the
+ // same lookup.
+ if should_block_implicit_customer_creation || use_merchant_reference_id {
Err(report!(errors::StorageError::ValueNotFound(
"customer".to_owned()
)))?
@@ -2338,12 +2436,21 @@ pub async fn get_customer_if_exists(
match customer_id {
Some(customer_id) => {
+ let use_merchant_reference_id =
+ should_use_merchant_reference_id_as_customer_id_for_provider(
+ state,
+ provider,
+ Some(customer_id),
+ )
+ .await;
+
let customer = db
.find_customer_by_customer_id_merchant_id(
customer_id,
provider.get_account().get_id(),
provider.get_key_store(),
provider.get_account().storage_scheme,
+ use_merchant_reference_id,
)
.await?;
Ok(Some(customer))
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index 3f8e8af906..e7081c7691 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -726,7 +726,7 @@ where
_request: Option<CustomerDetails>,
provider: &domain::Provider,
_initiator: Option<&domain::Initiator>,
- _dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,
+ dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,
_mandate_type: Option<api::MandateTransactionType>,
) -> CustomResult<
(
@@ -743,11 +743,22 @@ where
.customer_id
.as_ref()
.async_map(|customer_id| async {
+ let use_merchant_reference_id =
+ helpers::should_use_merchant_reference_id_as_customer_id(
+ state,
+ &dimensions
+ .without_profile_id()
+ .without_processor_merchant_id()
+ .with_organization_id(provider.get_account().organization_id.clone()),
+ Some(customer_id),
+ )
+ .await;
db.find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
customer_id,
&merchant_key_store.merchant_id,
merchant_key_store,
storage_scheme,
+ use_merchant_reference_id,
)
.await
})
diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
index 51e715d21c..8be4177e20 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -437,7 +437,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
_request: Option<CustomerDetails>,
provider: &domain::Provider,
_initiator: Option<&domain::Initiator>,
- _dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,
+ dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,
_mandate_type: Option<mandates::MandateTransactionType>,
) -> CustomResult<
(CompleteAuthorizeOperation<'a, F>, Option<domain::Customer>),
@@ -454,12 +454,23 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
.customer_id
.as_ref()
.async_map(|customer_id| async {
+ let use_merchant_reference_id =
+ helpers::should_use_merchant_reference_id_as_customer_id(
+ state,
+ &dimensions
+ .without_profile_id()
+ .without_processor_merchant_id()
+ .with_organization_id(provider.get_account().organization_id.clone()),
+ Some(customer_id),
+ )
+ .await;
// We allow CompleteAuthorize even if customer has been redacted
db.find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
customer_id,
&merchant_key_store.merchant_id,
merchant_key_store,
storage_scheme,
+ use_merchant_reference_id,
)
.await
})
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 8ba7d38a2c..301f63b35e 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -2644,8 +2644,18 @@ impl PaymentConfirm {
.await?;
logger::info!("Payment method fetched from PM Modular Service.");
+ // The customer id in the request can be the `merchant_reference_id` of the customer, while
+ // the payment method holds the id of the customer record.
+ let request_customer_id = match req.get_customer_id() {
+ Some(customer_id) => Some(
+ helpers::resolve_request_customer_id(state, platform.get_provider(), customer_id)
+ .await,
+ ),
+ None => None,
+ };
+
utils::when(
- req.get_customer_id().is_some_and(|customer_id| {
+ request_customer_id.as_ref().is_some_and(|customer_id| {
pm_info.payment_method.customer_id.as_ref() != Some(customer_id)
}),
|| {
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 3e27d298c0..ebe773d160 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -1359,8 +1359,18 @@ impl PaymentCreate {
.await?;
logger::info!("Payment method fetched from PM Modular Service.");
+ // The customer id in the request can be the `merchant_reference_id` of the customer, while
+ // the payment method holds the id of the customer record.
+ let request_customer_id = match req.get_customer_id() {
+ Some(customer_id) => Some(
+ helpers::resolve_request_customer_id(state, platform.get_provider(), customer_id)
+ .await,
+ ),
+ None => None,
+ };
+
utils::when(
- req.get_customer_id().is_some_and(|customer_id| {
+ request_customer_id.as_ref().is_some_and(|customer_id| {
pm_info.payment_method.customer_id.as_ref() != Some(customer_id)
}),
|| {
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 129e8c5d3d..7c0009c5d2 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -3734,13 +3734,13 @@ async fn vault_deferred_payment_method<F: Clone>(
)
.await?;
- tokenization::save_in_locker(
+ Box::pin(tokenization::save_in_locker(
state,
platform,
payment_method_create_request,
None,
business_profile,
- )
+ ))
.await
.map(Some)
}
@@ -3899,14 +3899,14 @@ async fn create_deferred_payment_method<F: Clone>(
let provider = platform.get_provider();
let key_store = provider.get_key_store();
- let vault_response = vault_deferred_payment_method(
+ let vault_response = Box::pin(vault_deferred_payment_method(
state,
payment_data,
platform,
business_profile,
&customer_id,
additional_payment_method_data,
- )
+ ))
.await?;
let payment_method =
@@ -3986,14 +3986,14 @@ async fn create_or_update_payment_method_from_payment_response<F: Clone>(
business_profile: &domain::Profile,
) -> RouterResult<()> {
if payment_data.payment_attempt.payment_method_id.is_none() {
- if let Err(error) = create_deferred_payment_method(
+ if let Err(error) = Box::pin(create_deferred_payment_method(
state,
payment_data,
attempt_status,
platform,
business_profile,
connector_returned_payment_method_details,
- )
+ ))
.await
{
logger::error!(?error, "Failed to create deferred payment method");
@@ -4091,13 +4091,15 @@ async fn create_or_update_payment_method_from_payment_response<F: Clone>(
let additional_data_update = if let Some(connector_returned_payment_method_details) =
connector_returned_payment_method_details
{
- payment_methods::cards::prepare_payment_method_update_from_connector_details(
- state,
- platform,
- &payment_method,
- merchant_connector_id,
- connector_returned_payment_method_details,
- business_profile,
+ Box::pin(
+ payment_methods::cards::prepare_payment_method_update_from_connector_details(
+ state,
+ platform,
+ &payment_method,
+ merchant_connector_id,
+ connector_returned_payment_method_details,
+ business_profile,
+ ),
)
.await
.inspect_err(|error| {
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 2bcf3dab04..4195bb461a 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -1434,12 +1434,20 @@ pub async fn save_in_locker_internal(
.clone()
.get_required_value("customer_id")?;
+ let use_merchant_reference_id =
+ helpers::should_use_merchant_reference_id_as_customer_id_for_provider(
+ state,
+ provider,
+ Some(&customer_id),
+ )
+ .await;
let customer_obj = db
.find_customer_by_customer_id_merchant_id(
&customer_id,
provider.get_account().get_id(),
provider.get_key_store(),
provider.get_account().storage_scheme,
+ use_merchant_reference_id,
)
.await
.change_context(errors::ApiErrorResponse::CustomerNotFound)
diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rs
index 08184b86a5..58932ede72 100644
--- a/crates/router/src/core/payout_link.rs
+++ b/crates/router/src/core/payout_link.rs
@@ -143,6 +143,7 @@ pub async fn initiate_payout_link(
&req.merchant_id,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
+ false,
)
.await
.change_context(errors::ApiErrorResponse::InvalidRequestData {
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index b9271875bf..1a70fb7fc1 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -1219,6 +1219,7 @@ pub async fn payouts_list_core(
merchant_id,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
+ false,
)
.await
.map_err(|err| {
@@ -3937,6 +3938,7 @@ pub async fn make_payout_data(
merchant_id,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
+ false,
)
.await
.map_err(|err| err.change_context(errors::ApiErrorResponse::InternalServerError))
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 2a355a706d..6c2f7f09f9 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -19,6 +19,8 @@ use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret, SwitchStrategy
use router_env::logger;
use super::{validator::PayoutExecutionKindValidation, PayoutData};
+#[cfg(feature = "v1")]
+use crate::core::payments::helpers as payments_helpers;
#[cfg(feature = "payouts")]
use crate::core::payments::route_connector_v1_for_payouts;
use crate::{
@@ -936,12 +938,20 @@ pub(super) async fn get_or_create_customer_details(
.get_inner()
.peek();
+ let use_merchant_reference_id =
+ payments_helpers::should_use_merchant_reference_id_as_customer_id_for_provider(
+ state,
+ platform.get_provider(),
+ Some(&customer_id),
+ )
+ .await;
match db
.find_customer_optional_by_customer_id_merchant_id(
&customer_id,
merchant_id,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
+ use_merchant_reference_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?
diff --git a/crates/router/src/core/payouts/proxy.rs b/crates/router/src/core/payouts/proxy.rs
index 2e882f44b6..aff49e5ffd 100644
--- a/crates/router/src/core/payouts/proxy.rs
+++ b/crates/router/src/core/payouts/proxy.rs
@@ -558,6 +558,13 @@ impl ExternalVaultPayout<'_> {
let payout_id = self.validate_proxy_create_identity(&req).await?;
let customer_id = req.get_customer_id().get_required_value("customer_id")?;
let processor = platform.get_processor();
+ let use_merchant_reference_id =
+ helpers::should_use_merchant_reference_id_as_customer_id_for_provider(
+ state,
+ platform.get_provider(),
+ Some(customer_id),
+ )
+ .await;
let customer = state
.store
.find_customer_optional_by_customer_id_merchant_id(
@@ -565,6 +572,7 @@ impl ExternalVaultPayout<'_> {
processor.get_account().get_id(),
processor.get_key_store(),
processor.get_account().storage_scheme,
+ use_merchant_reference_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?
diff --git a/crates/router/src/core/superposition_sdk_config.rs b/crates/router/src/core/superposition_sdk_config.rs
index cf69468fa4..8a11e0c07f 100644
--- a/crates/router/src/core/superposition_sdk_config.rs
+++ b/crates/router/src/core/superposition_sdk_config.rs
@@ -95,11 +95,19 @@ async fn get_payment_context(
pi.customer_id
.as_ref()
.async_and_then(|cust| async {
+ let use_merchant_reference_id =
+ helpers::should_use_merchant_reference_id_as_customer_id_for_provider(
+ state,
+ platform.get_provider(),
+ Some(cust),
+ )
+ .await;
db.find_customer_by_customer_id_merchant_id(
cust,
&pi.merchant_id,
platform.get_provider().get_key_store(),
platform.get_provider().get_account().storage_scheme,
+ use_merchant_reference_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index ba8ce2a210..05bcf2a335 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -3003,14 +3003,14 @@ async fn update_payment_method_associated_data(
let payment_method_id = payment_method.get_id().clone();
let payment_method_update =
- cards::prepare_payment_method_update_from_connector_details(
+ Box::pin(cards::prepare_payment_method_update_from_connector_details(
state,
platform,
&payment_method,
merchant_connector_id,
&connector_disclosed_details,
business_profile,
- )
+ ))
.await?;
let compat_action =
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 8d91856b10..d937760fd4 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -366,6 +366,7 @@ impl CustomerInterface for KafkaStore {
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
+ use_merchant_reference_id_lookup: bool,
) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
self.diesel_store
.find_customer_optional_by_customer_id_merchant_id(
@@ -373,6 +374,7 @@ impl CustomerInterface for KafkaStore {
merchant_id,
key_store,
storage_scheme,
+ use_merchant_reference_id_lookup,
)
.await
}
@@ -384,6 +386,7 @@ impl CustomerInterface for KafkaStore {
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
+ use_merchant_reference_id_lookup: bool,
) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
self.diesel_store
.find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
@@ -391,11 +394,11 @@ impl CustomerInterface for KafkaStore {
merchant_id,
key_store,
storage_scheme,
+ use_merchant_reference_id_lookup,
)
.await
}
- #[cfg(feature = "v2")]
async fn find_optional_by_merchant_id_merchant_reference_id(
&self,
customer_id: &id_type::CustomerId,
@@ -501,6 +504,7 @@ impl CustomerInterface for KafkaStore {
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
+ use_merchant_reference_id_lookup: bool,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
.find_customer_by_customer_id_merchant_id(
@@ -508,11 +512,11 @@ impl CustomerInterface for KafkaStore {
merchant_id,
key_store,
storage_scheme,
+ use_merchant_reference_id_lookup,
)
.await
}
- #[cfg(feature = "v2")]
async fn find_customer_by_merchant_reference_id_merchant_id(
&self,
merchant_reference_id: &id_type::CustomerId,
diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs
index 06ab354dbe..c2a3cf2aff 100644
--- a/crates/router/src/routes/customers.rs
+++ b/crates/router/src/routes/customers.rs
@@ -396,12 +396,12 @@ pub async fn customers_update(
|state, auth: auth::AuthenticationData, request_internal, _| {
Box::pin(async move {
core_utils::validate_legacy_endpoint_access(&state, &auth.platform).await?;
- update_customer(
+ Box::pin(update_customer(
state,
auth.platform.get_provider().clone(),
auth.platform.get_initiator().cloned(),
request_internal,
- )
+ ))
.await
})
},
diff --git a/crates/router/src/routes/payment_methods/migrate.rs b/crates/router/src/routes/payment_methods/migrate.rs
index 27b0077e4e..84afecd5a5 100644
--- a/crates/router/src/routes/payment_methods/migrate.rs
+++ b/crates/router/src/routes/payment_methods/migrate.rs
@@ -457,6 +457,7 @@ impl MigrationBatch<EligibilityVerified> {
&row.merchant_id,
platform.get_provider().get_key_store(),
platform.get_provider().get_account().storage_scheme,
+ false,
)
.await
{
diff --git a/crates/storage_impl/src/customers.rs b/crates/storage_impl/src/customers.rs
index 8778f94618..d8636da481 100644
--- a/crates/storage_impl/src/customers.rs
+++ b/crates/storage_impl/src/customers.rs
@@ -66,7 +66,20 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
+ use_merchant_reference_id_lookup: bool,
) -> CustomResult<Option<domain::Customer>, StorageError> {
+ if use_merchant_reference_id_lookup && !domain::is_customer_id_in_global_format(customer_id)
+ {
+ return self
+ .find_optional_by_merchant_id_merchant_reference_id(
+ customer_id,
+ merchant_id,
+ key_store,
+ storage_scheme,
+ )
+ .await;
+ }
+
let conn = pg_connection_read(self).await?;
let maybe_result = Box::pin(self.find_optional_resource_by_id(
key_store,
@@ -101,7 +114,24 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
+ use_merchant_reference_id_lookup: bool,
) -> CustomResult<Option<domain::Customer>, StorageError> {
+ if use_merchant_reference_id_lookup && !domain::is_customer_id_in_global_format(customer_id)
+ {
+ // Same reasoning as `find_optional_by_merchant_id_merchant_reference_id` above: a
+ // reference-id lookup is always served from the database for v1.
+ return self
+ .router_store
+ .find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
+ customer_id,
+ merchant_id,
+ key_store,
+ storage_scheme,
+ use_merchant_reference_id_lookup,
+ )
+ .await;
+ }
+
let conn = pg_connection_read(self).await?;
Box::pin(self.find_optional_resource_by_id(
key_store,
@@ -122,6 +152,28 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt
.await
}
+ // Customers looked up by `merchant_reference_id` are created by the v2 customers API, which
+ // keeps them under the global id KV partition. The v1 KV layout is keyed by `customer_id`, so
+ // this lookup is always served from the database.
+ #[cfg(feature = "v1")]
+ #[instrument(skip_all)]
+ async fn find_optional_by_merchant_id_merchant_reference_id(
+ &self,
+ merchant_reference_id: &id_type::CustomerId,
+ merchant_id: &id_type::MerchantId,
+ key_store: &MerchantKeyStore,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<Option<domain::Customer>, StorageError> {
+ self.router_store
+ .find_optional_by_merchant_id_merchant_reference_id(
+ merchant_reference_id,
+ merchant_id,
+ key_store,
+ storage_scheme,
+ )
+ .await
+ }
+
#[cfg(feature = "v2")]
async fn find_optional_by_merchant_id_merchant_reference_id(
&self,
@@ -248,6 +300,27 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt
.await
}
+ // Same reasoning as `find_optional_by_merchant_id_merchant_reference_id` above: a
+ // reference-id lookup is always served from the database for v1.
+ #[cfg(feature = "v1")]
+ #[instrument(skip_all)]
+ async fn find_customer_by_merchant_reference_id_merchant_id(
+ &self,
+ merchant_reference_id: &id_type::CustomerId,
+ merchant_id: &id_type::MerchantId,
+ key_store: &MerchantKeyStore,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::Customer, StorageError> {
+ self.router_store
+ .find_customer_by_merchant_reference_id_merchant_id(
+ merchant_reference_id,
+ merchant_id,
+ key_store,
+ storage_scheme,
+ )
+ .await
+ }
+
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_customer_by_merchant_reference_id_merchant_id(
@@ -290,7 +363,20 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
+ use_merchant_reference_id_lookup: bool,
) -> CustomResult<domain::Customer, StorageError> {
+ if use_merchant_reference_id_lookup && !domain::is_customer_id_in_global_format(customer_id)
+ {
+ return self
+ .find_customer_by_merchant_reference_id_merchant_id(
+ customer_id,
+ merchant_id,
+ key_store,
+ storage_scheme,
+ )
+ .await;
+ }
+
let conn = pg_connection_read(self).await?;
let result: domain::Customer = Box::pin(self.find_resource_by_id(
key_store,
@@ -671,8 +757,21 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
- _storage_scheme: MerchantStorageScheme,
+ storage_scheme: MerchantStorageScheme,
+ use_merchant_reference_id_lookup: bool,
) -> CustomResult<Option<domain::Customer>, StorageError> {
+ if use_merchant_reference_id_lookup && !domain::is_customer_id_in_global_format(customer_id)
+ {
+ return self
+ .find_optional_by_merchant_id_merchant_reference_id(
+ customer_id,
+ merchant_id,
+ key_store,
+ storage_scheme,
+ )
+ .await;
+ }
+
let conn = pg_connection_read(self).await?;
let maybe_customer: Option<domain::Customer> = self
.find_optional_resource_new(
@@ -704,7 +803,23 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
+ use_merchant_reference_id_lookup: bool,
) -> CustomResult<Option<domain::Customer>, StorageError> {
+ if use_merchant_reference_id_lookup && !domain::is_customer_id_in_global_format(customer_id)
+ {
+ let conn = pg_connection_read(self).await?;
+ return self
+ .find_optional_resource_new(
+ key_store,
+ diesel_models::Customer::find_optional_by_merchant_id_merchant_reference_id(
+ &conn,
+ customer_id,
+ merchant_id,
+ ),
+ )
+ .await;
+ }
+
let conn = pg_connection_read(self).await?;
self.find_optional_resource_new(
key_store,
@@ -718,7 +833,6 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {
}
#[instrument(skip_all)]
- #[cfg(feature = "v2")]
async fn find_optional_by_merchant_id_merchant_reference_id(
&self,
customer_id: &id_type::CustomerId,
@@ -817,8 +931,21 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
- _storage_scheme: MerchantStorageScheme,
+ storage_scheme: MerchantStorageScheme,
+ use_merchant_reference_id_lookup: bool,
) -> CustomResult<domain::Customer, StorageError> {
+ if use_merchant_reference_id_lookup && !domain::is_customer_id_in_global_format(customer_id)
+ {
+ return self
+ .find_customer_by_merchant_reference_id_merchant_id(
+ customer_id,
+ merchant_id,
+ key_store,
+ storage_scheme,
+ )
+ .await;
+ }
+
let conn = pg_connection_read(self).await?;
let customer: domain::Customer = self
.call_database_new(
@@ -836,7 +963,6 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {
}
}
- #[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_customer_by_merchant_reference_id_merchant_id(
&self,
@@ -1054,6 +1180,7 @@ impl domain::CustomerInterface for MockDb {
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
+ _use_merchant_reference_id_lookup: bool,
) -> CustomResult<Option<domain::Customer>, StorageError> {
let customers = self.customers.lock().await;
self.find_resource_new(key_store, customers, |customer| {
@@ -1069,6 +1196,7 @@ impl domain::CustomerInterface for MockDb {
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
+ _use_merchant_reference_id_lookup: bool,
) -> CustomResult<Option<domain::Customer>, StorageError> {
let customers = self.customers.lock().await;
self.find_resource_new(key_store, customers, |customer| {
@@ -1077,6 +1205,18 @@ impl domain::CustomerInterface for MockDb {
.await
}
+ #[cfg(feature = "v1")]
+ async fn find_optional_by_merchant_id_merchant_reference_id(
+ &self,
+ _customer_id: &id_type::CustomerId,
+ _merchant_id: &id_type::MerchantId,
+ _key_store: &MerchantKeyStore,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<Option<domain::Customer>, StorageError> {
+ // [#172]: Implement function for `MockDb`
+ Err(StorageError::MockDbError)?
+ }
+
#[cfg(feature = "v2")]
async fn find_optional_by_merchant_id_merchant_reference_id(
&self,
@@ -1235,12 +1375,12 @@ impl domain::CustomerInterface for MockDb {
_merchant_id: &id_type::MerchantId,
_key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
+ _use_merchant_reference_id_lookup: bool,
) -> CustomResult<domain::Customer, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
- #[cfg(feature = "v2")]
async fn find_customer_by_merchant_reference_id_merchant_id(
&self,
_merchant_reference_id: &id_type::CustomerId,
@@ -1384,6 +1524,7 @@ impl Conversion for domain::Customer {
.map(|last_modified_by| last_modified_by.to_string()),
id: global_customer_id,
preferred_connectors: self.preferred_connectors,
+ merchant_reference_id: None,
})
}
diff --git a/crates/subscriptions/src/core/subscription_handler.rs b/crates/subscriptions/src/core/subscription_handler.rs
index f1526fb5e6..b9bbda1e94 100644
--- a/crates/subscriptions/src/core/subscription_handler.rs
+++ b/crates/subscriptions/src/core/subscription_handler.rs
@@ -100,6 +100,7 @@ impl<'a> SubscriptionHandler<'a> {
merchant_id,
merchant_key_store,
platform.get_processor().get_account().storage_scheme,
+ false,
)
.await
.change_context(errors::ApiErrorResponse::CustomerNotFound)
diff --git a/crates/subscriptions/src/workflows/invoice_sync.rs b/crates/subscriptions/src/workflows/invoice_sync.rs
index 3d7f2b489b..c97e51e970 100644
--- a/crates/subscriptions/src/workflows/invoice_sync.rs
+++ b/crates/subscriptions/src/workflows/invoice_sync.rs
@@ -72,6 +72,7 @@ impl<'a> InvoiceSyncHandler<'a> {
merchant_account.get_id(),
&key_store,
merchant_account.storage_scheme,
+ false,
)
.await
.attach_printable("Subscriptions: Failed to fetch Customer from DB")?;
diff --git a/migrations/2026-09-28-100000_add_merchant_reference_id_to_customers/down.sql b/migrations/2026-09-28-100000_add_merchant_reference_id_to_customers/down.sql
new file mode 100644
index 0000000000..126e7ff799
--- /dev/null
+++ b/migrations/2026-09-28-100000_add_merchant_reference_id_to_customers/down.sql
@@ -0,0 +1,4 @@
+-- Intentionally a no-op. `customers.merchant_reference_id` is shared with the v2 customers API
+-- (see `v2_compatible_migrations/2024-08-28-081721_add_v2_columns`), which stores the merchant
+-- supplied customer id in it. Dropping the column here would destroy that data.
+SELECT 1;
diff --git a/migrations/2026-09-28-100000_add_merchant_reference_id_to_customers/up.sql b/migrations/2026-09-28-100000_add_merchant_reference_id_to_customers/up.sql
new file mode 100644
index 0000000000..5bb2cb45e2
--- /dev/null
+++ b/migrations/2026-09-28-100000_add_merchant_reference_id_to_customers/up.sql
@@ -0,0 +1,5 @@
+-- The column is also added by `v2_compatible_migrations` (`add_v2_columns`) for deployments that
+-- serve the v2 customers API. `IF NOT EXISTS` keeps both migrations independent of the order they
+-- are run in, and makes this one a no-op wherever the column is already present.
+ALTER TABLE customers
+ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64);