Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(customers): Implementing Merchant_cust_ref_id lookup for customer_id (#14603)
Ritam Kabiraj52e9e9e69df8
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex 8173d27170..30e723293c 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -24989,6 +24989,12 @@"maxLength": 64,"minLength": 32},+ "merchant_customer_reference_id": {+ "type": "string",+ "description": "The customer reference supplied in the request path when merchant reference ID lookup is enabled.",+ "example": "merchant_customer_123",+ "nullable": true+ },"payment_method_type": {"$ref": "#/components/schemas/PaymentMethod"},diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex 50ab039d66..c42f75beac 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -3731,6 +3731,11 @@ pub struct PaymentMethodResponseItem {)]pub customer_id: id_type::GlobalCustomerId,+ /// The customer reference supplied in the request path when merchant reference ID lookup is enabled.+ #[serde(skip_serializing_if = "Option::is_none")]+ #[schema(value_type = Option<String>, example = "merchant_customer_123")]+ pub merchant_customer_reference_id: Option<id_type::CustomerId>,+/// The type of payment method use for the payment.#[schema(value_type = PaymentMethod,example = "card")]pub payment_method_type: api_enums::PaymentMethod,diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rsindex 3820d7ef2d..35fd5aa7b4 100644--- a/crates/router/src/core/customers.rs+++ b/crates/router/src/core/customers.rs@@ -26,7 +26,7 @@ use router_env::{instrument, tracing};#[cfg(feature = "v2")]use crate::core::payment_methods::delete_payment_method_by_record;-#[cfg(feature = "v1")]+#[cfg(any(feature = "v1", feature = "v2"))]use crate::core::payments::helpers as payments_helpers;#[cfg(feature = "v2")]use crate::core::utils::create_encrypted_data;@@ -664,6 +664,28 @@ pub async fn retrieve_customer_by_merchant_reference_id())}+/// Whether a customer identifier supplied in the request should be interpreted as the+/// merchant's customer reference instead of a Hyperswitch global customer ID.+#[cfg(feature = "v2")]+pub async fn should_use_merchant_reference_id_as_customer_id(+ state: &SessionState,+ provider: &domain::Provider,+ api_key_type: common_enums::ApiKeyType,+ customer_id: &id_type::CustomerId,+) -> bool {+ match api_key_type {+ common_enums::ApiKeyType::Internal => false,+ common_enums::ApiKeyType::External => {+ payments_helpers::should_use_merchant_reference_id_as_customer_id_for_provider(+ state,+ provider,+ Some(customer_id),+ )+ .await+ }+ }+}+#[instrument(skip(state))]pub async fn list_customers(state: SessionState,diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex b6f725558e..dc4f5e7293 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -84,7 +84,7 @@ use crate::routes::metrics;use crate::{configs::settings,core::{- account_updater,+ account_updater, customers,payment_methods::{transformers as pm_transforms, utils as payment_method_utils},tokenization as tokenization_core,},@@ -4634,9 +4634,47 @@ pub async fn list_saved_payment_methods_for_customer(provider: domain::Provider,customer_id: id_type::GlobalCustomerId,include_new: bool,+ api_key_type: enums::ApiKeyType,) -> RouterResponse<payment_methods::CustomerPaymentMethodsListResponse> {- let customer_payment_methods =- list_payment_methods_core(&state, &provider, &customer_id, include_new).await?;+ let request_customer_id = id_type::CustomerId::try_from(customer_id.clone()).change_context(+ errors::ApiErrorResponse::InvalidRequestData {+ message: "Invalid customer ID supplied in the request path".to_string(),+ },+ )?;+ let merchant_customer_reference_id =+ customers::should_use_merchant_reference_id_as_customer_id(+ &state,+ &provider,+ api_key_type,+ &request_customer_id,+ )+ .await+ .then_some(request_customer_id);++ let customer_id = if let Some(merchant_reference_id) = merchant_customer_reference_id.as_ref() {+ let customer = state+ .store+ .find_customer_by_merchant_reference_id_merchant_id(+ merchant_reference_id,+ provider.get_account().get_id(),+ provider.get_key_store(),+ provider.get_account().storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;+ customer.id+ } else {+ customer_id+ };++ let customer_payment_methods = list_payment_methods_core(+ &state,+ &provider,+ &customer_id,+ merchant_customer_reference_id,+ include_new,+ )+ .await?;Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(customer_payment_methods,@@ -6073,6 +6111,7 @@ pub async fn list_payment_methods_core(state: &SessionState,provider: &domain::Provider,customer_id: &id_type::GlobalCustomerId,+ merchant_customer_reference_id: Option<id_type::CustomerId>,include_new: bool,) -> RouterResult<payment_methods::CustomerPaymentMethodsListResponse> {let db = &*state.store;@@ -6114,6 +6153,7 @@ pub async fn list_payment_methods_core(payment_methods::PaymentMethodResponseItem::foreign_try_from((pm,default_payment_method_id.clone(),+ merchant_customer_reference_id.clone(),))}).collect::<Result<Vec<payment_methods::PaymentMethodResponseItem>, _>>()diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rsindex bc7fecb52c..01cdafee59 100644--- a/crates/router/src/core/payment_methods/transformers.rs+++ b/crates/router/src/core/payment_methods/transformers.rs@@ -1097,14 +1097,16 @@ impltransformers::ForeignTryFrom<(domain::PaymentMethod,Option<id_type::GlobalPaymentMethodId>,+ Option<id_type::CustomerId>,)> for PaymentMethodResponseItem{type Error = error_stack::Report<errors::ValidationError>;fn foreign_try_from(- (item, default_payment_method_id): (+ (item, default_payment_method_id, merchant_customer_reference_id): (domain::PaymentMethod,Option<id_type::GlobalPaymentMethodId>,+ Option<id_type::CustomerId>,),) -> Result<Self, Self::Error> {// For payment methods that are active we should always have the payment method subtype@@ -1223,6 +1225,7 @@ impl.change_context(errors::ValidationError::MissingRequiredField {field_name: "customer_id".into(),})?,+ merchant_customer_reference_id,payment_method_type,payment_method_subtype,created: item.created_at,diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex dd1971a695..5655465750 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -2029,15 +2029,14 @@ 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.+/// Resolves the Superposition flag that decides whether a customer identifier supplied in a+/// request should be interpreted as the customer's `merchant_reference_id`.////// 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")]+/// can continue sending their own `merchant_reference_id` in request fields that historically+/// accepted `customer_id`. This function only resolves the provider-merchant and organization+/// scoped configuration; each caller remains responsible for applying it to its lookup flow.+#[cfg(any(feature = "v1", feature = "v2"))]pub async fn should_use_merchant_reference_id_as_customer_id(state: &SessionState,dimensions: &dimension_state::DimensionsWithProviderMerchantIdAndOrgId,@@ -2054,7 +2053,7 @@ pub async fn should_use_merchant_reference_id_as_customer_id(/// 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")]+#[cfg(any(feature = "v1", feature = "v2"))]pub async fn should_use_merchant_reference_id_as_customer_id_for_provider(state: &SessionState,provider: &domain::Provider,diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rsindex 6c9858809f..d2cdce160d 100644--- a/crates/router/src/routes/payment_methods.rs+++ b/crates/router/src/routes/payment_methods.rs@@ -996,6 +996,7 @@ pub async fn list_customer_payment_method_api(auth.platform.get_provider().clone(),customer_id.clone(),payload.include_new.unwrap_or(false),+ api_key_type,),)},