Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

feat(payment-methods): Guest customer support in payments for modular pm (#11534)

Gaurav Rawatdc96818f468d
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index 982b485d94..2ea45b0801 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -74,7 +74,9 @@ pub struct PaymentMethod {
#[derive(Clone, Debug, Identifiable, Queryable, Selectable, Serialize, Deserialize)]
#[diesel(table_name = payment_methods, primary_key(id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentMethod {
- pub customer_id: common_utils::id_type::GlobalCustomerId,
+ //customer_id is made optional in v2 to accommodate guest checkout flow where customer id is not present.
+ //customer_id should only be none in case of guest checkout flow as volatile pm are stored in redis, for all other cases it should be present to maintain the db persistency
+ pub customer_id: Option<common_utils::id_type::GlobalCustomerId>,
pub merchant_id: common_utils::id_type::MerchantId,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
@@ -170,7 +172,7 @@ pub struct PaymentMethodNew {
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)]
#[diesel(table_name = payment_methods)]
pub struct PaymentMethodNew {
- pub customer_id: common_utils::id_type::GlobalCustomerId,
+ pub customer_id: Option<common_utils::id_type::GlobalCustomerId>,
pub merchant_id: common_utils::id_type::MerchantId,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 827d6d3ba2..35ebbc8209 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -1282,7 +1282,7 @@ diesel::table! {
payment_methods (id) {
#[max_length = 64]
- customer_id -> Varchar,
+ customer_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
created_at -> Timestamp,
diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs
index f463544865..26b4bec021 100644
--- a/crates/hyperswitch_domain_models/src/payment_methods.rs
+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs
@@ -8,12 +8,10 @@ use common_enums::enums::MerchantStorageScheme;
#[cfg(feature = "v1")]
use common_utils::crypto::OptionalEncryptableValue;
#[cfg(feature = "v2")]
-use common_utils::{
- crypto::Encryptable, encryption::Encryption, ext_traits::OptionExt,
- types::keymanager::ToEncryptable,
-};
+use common_utils::{crypto::Encryptable, encryption::Encryption, types::keymanager::ToEncryptable};
use common_utils::{
errors::{CustomResult, ParsingError, ValidationError},
+ ext_traits::OptionExt,
id_type, pii, type_name,
types::{keymanager, CreatedBy},
};
@@ -57,7 +55,8 @@ impl VaultId {
#[cfg(feature = "v1")]
#[derive(Clone, Debug)]
pub struct PaymentMethod {
- pub customer_id: id_type::CustomerId,
+ /// Customer_id is made optional to support guest checkout flow when modular pm is enabled
+ pub customer_id: Option<id_type::CustomerId>,
pub merchant_id: id_type::MerchantId,
pub payment_method_id: String,
pub accepted_currency: Option<Vec<storage_enums::Currency>>,
@@ -97,6 +96,7 @@ pub struct PaymentMethod {
pub customer_details: OptionalEncryptableValue,
pub locker_fingerprint_id: Option<String>,
pub network_tokenization_data: OptionalEncryptableValue,
+ pub storage_type: Option<common_enums::StorageType>,
}
#[cfg(feature = "v2")]
@@ -183,6 +183,11 @@ impl PaymentMethod {
self.payment_method
}
+ #[cfg(feature = "v1")]
+ pub fn is_pm_volatile(&self) -> bool {
+ matches!(self.storage_type, Some(common_enums::StorageType::Volatile))
+ }
+
#[cfg(feature = "v2")]
pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethod> {
self.payment_method_type
@@ -417,8 +422,9 @@ impl super::behaviour::Conversion for PaymentMethod {
type NewDstType = diesel_models::payment_method::PaymentMethodNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let (vault_type, external_vault_source) = self.vault_source_details.into();
+ // Note: caller must ensure customer_id is not null before calling convert as storage model requires it.
Ok(Self::DstType {
- customer_id: self.customer_id,
+ customer_id: self.customer_id.get_required_value("customer_id")?,
merchant_id: self.merchant_id,
payment_method_id: self.payment_method_id,
accepted_currency: self.accepted_currency,
@@ -579,8 +585,9 @@ impl super::behaviour::Conversion for PaymentMethod {
))?;
// Construct the domain type
+ // Storage always has customer_id, wrap in Some for domain
Ok(Self {
- customer_id: item.customer_id,
+ customer_id: Some(item.customer_id),
merchant_id: item.merchant_id,
payment_method_id: item.payment_method_id,
accepted_currency: item.accepted_currency,
@@ -624,13 +631,15 @@ impl super::behaviour::Conversion for PaymentMethod {
customer_details,
locker_fingerprint_id: item.locker_fingerprint_id,
network_tokenization_data,
+ storage_type: None,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let (vault_type, external_vault_source) = self.vault_source_details.into();
+ // Note: caller must ensure customer_id is not null before calling convert as storage model requires it.
Ok(Self::NewDstType {
- customer_id: self.customer_id,
+ customer_id: self.customer_id.get_required_value("customer_id")?,
merchant_id: self.merchant_id,
payment_method_id: self.payment_method_id,
accepted_currency: self.accepted_currency,
@@ -688,7 +697,7 @@ impl super::behaviour::Conversion for PaymentMethod {
type NewDstType = diesel_models::payment_method::PaymentMethodNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(Self::DstType {
- customer_id: self.customer_id.get_required_value("GlobalCustomerId")?,
+ customer_id: self.customer_id,
merchant_id: self.merchant_id,
id: self.id,
created_at: self.created_at,
@@ -827,7 +836,7 @@ impl super::behaviour::Conversion for PaymentMethod {
.attach_printable("Error while deserializing Network Tokenization Data")?;
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
- customer_id: Some(storage_model.customer_id),
+ customer_id: storage_model.customer_id,
merchant_id: storage_model.merchant_id,
id: storage_model.id,
created_at: storage_model.created_at,
@@ -873,7 +882,7 @@ impl super::behaviour::Conversion for PaymentMethod {
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(Self::NewDstType {
- customer_id: self.customer_id.get_required_value("GlobalCustomerId")?,
+ customer_id: self.customer_id,
merchant_id: self.merchant_id,
id: self.id,
created_at: self.created_at,
@@ -1602,7 +1611,7 @@ mod tests {
mandate_data: Option<serde_json::Value>,
) -> PaymentMethod {
let payment_method = PaymentMethod {
- customer_id: id_type::CustomerId::default(),
+ customer_id: Some(id_type::CustomerId::default()),
merchant_id: id_type::MerchantId::default(),
payment_method_id: String::from("abc"),
accepted_currency: None,
@@ -1642,6 +1651,7 @@ mod tests {
customer_details: None,
locker_fingerprint_id: None,
network_tokenization_data: None,
+ storage_type: None,
};
payment_method.clone()
}
diff --git a/crates/payment_methods/src/client/create.rs b/crates/payment_methods/src/client/create.rs
index 48f6222812..29a2b19ded 100644
--- a/crates/payment_methods/src/client/create.rs
+++ b/crates/payment_methods/src/client/create.rs
@@ -106,6 +106,7 @@ pub struct CreatePaymentMethodResponse {
pub connector_tokens: Option<Vec<ConnectorTokenDetails>>,
pub network_token: Option<api_models::payment_methods::NetworkTokenResponse>,
pub billing: Option<hyperswitch_domain_models::address::Address>,
+ pub storage_type: Option<common_enums::StorageType>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -191,6 +192,7 @@ impl TryFrom<ModularPaymentMethodResponse> for CreatePaymentMethodResponse {
connector_tokens: response.connector_tokens,
network_token: response.network_token,
billing: response.billing,
+ storage_type: response.storage_type,
})
}
}
diff --git a/crates/payment_methods/src/client/retrieve.rs b/crates/payment_methods/src/client/retrieve.rs
index f3b1182dc0..aafcad9150 100644
--- a/crates/payment_methods/src/client/retrieve.rs
+++ b/crates/payment_methods/src/client/retrieve.rs
@@ -37,6 +37,7 @@ pub struct RetrievePaymentMethodResponse {
pub raw_payment_method_data: Option<RawPaymentMethodData>,
pub network_transaction_id: Option<String>,
pub billing: Option<hyperswitch_domain_models::address::Address>,
+ pub storage_type: Option<common_enums::StorageType>,
}
impl TryFrom<&RetrievePaymentMethodV1Request> for ModularPMRetrieveRequest {
@@ -72,6 +73,7 @@ impl TryFrom<ModularPMRetrieveResponse> for RetrievePaymentMethodResponse {
raw_payment_method_data: v2_resp.raw_payment_method_data,
billing: v2_resp.billing,
network_transaction_id: v2_resp.network_transaction_id,
+ storage_type: v2_resp.storage_type,
})
}
}
diff --git a/crates/payment_methods/src/core/migration/payment_methods.rs b/crates/payment_methods/src/core/migration/payment_methods.rs
index cb07dba9b8..6aa458671f 100644
--- a/crates/payment_methods/src/core/migration/payment_methods.rs
+++ b/crates/payment_methods/src/core/migration/payment_methods.rs
@@ -688,7 +688,7 @@ pub async fn skip_locker_call_and_migrate_payment_method(
.insert_payment_method(
provider.get_key_store(),
domain_pm::PaymentMethod {
- customer_id: customer_id.to_owned(),
+ customer_id: Some(customer_id.to_owned()),
merchant_id: merchant_id.to_owned(),
payment_method_id: payment_method_id.to_string(),
locker_id: None,
@@ -728,6 +728,7 @@ pub async fn skip_locker_call_and_migrate_payment_method(
customer_details: None,
locker_fingerprint_id: None,
network_tokenization_data: None,
+ storage_type: None,
},
provider.get_account().storage_scheme,
)
diff --git a/crates/payment_methods/src/helpers.rs b/crates/payment_methods/src/helpers.rs
index f89fc31027..6a62fe0c17 100644
--- a/crates/payment_methods/src/helpers.rs
+++ b/crates/payment_methods/src/helpers.rs
@@ -278,7 +278,7 @@ impl ForeignFrom<(Option<api::CardDetailFromLocker>, domain::PaymentMethod)>
) -> Self {
Self {
merchant_id: item.merchant_id.to_owned(),
- customer_id: Some(item.customer_id.to_owned()),
+ customer_id: item.customer_id.to_owned(),
payment_method_id: item.get_id().clone(),
payment_method: item.get_payment_method_type(),
payment_method_type: item.get_payment_method_subtype(),
diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs
index 0a8a2ad2d1..7b670105e3 100644
--- a/crates/router/src/core/locker_migration.rs
+++ b/crates/router/src/core/locker_migration.rs
@@ -154,7 +154,7 @@ pub async fn call_to_locker(
#[cfg(feature = "payouts")]
bank_transfer: None,
metadata: pm.metadata,
- customer_id: Some(pm.customer_id),
+ customer_id: pm.customer_id,
card_network: card.card_brand,
client_secret: None,
payment_method_data: None,
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index a487c30bc6..cc2f5e906c 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -2851,13 +2851,7 @@ pub async fn construct_payment_method_object(
.attach_printable("Unable to parse Payment method data")?;
Ok(domain::PaymentMethod {
- customer_id: Some(
- customer_id
- .clone()
- .unwrap_or(id_type::GlobalCustomerId::generate(
- &state.conf.cell_information.id,
- )),
- ), //for guest checkout flow where customer id is not present, generated a temporary customer id to handle to conversion to diesel model.
+ customer_id: customer_id.clone(),
merchant_id: merchant_id.to_owned(),
id: payment_method_id,
locker_id,
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index b21328c2a6..160b36dd84 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -166,7 +166,7 @@ impl PaymentMethodsController for PmCards<'_> {
.insert_payment_method(
self.provider.get_key_store(),
domain::PaymentMethod {
- customer_id: customer_id.to_owned(),
+ customer_id: Some(customer_id.to_owned()),
merchant_id: merchant_id.to_owned(),
payment_method_id: payment_method_id.to_string(),
locker_id,
@@ -207,6 +207,7 @@ impl PaymentMethodsController for PmCards<'_> {
customer_details: payment_method_customer_details_encrypted,
locker_fingerprint_id,
network_tokenization_data: None, // setting this to None as write path will be introduced in a later PR
+ storage_type: None,
},
self.provider.get_account().storage_scheme,
)
@@ -951,9 +952,13 @@ impl PaymentMethodsController for PmCards<'_> {
.get_payment_method_type()
.get_required_value("payment_method")?;
+ let pm_customer_id = payment_method
+ .customer_id
+ .clone()
+ .get_required_value("customer_id")?;
+
utils::when(
- &payment_method.customer_id != customer_id
- || payment_method.merchant_id != *merchant_id,
+ &pm_customer_id != customer_id || payment_method.merchant_id != *merchant_id,
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "The payment_method_id is not valid".to_string(),
@@ -1071,7 +1076,7 @@ impl PaymentMethodsController for PmCards<'_> {
let (card_detail, locker_metadata) = if self.state.conf.locker.locker_enabled {
let locker_card_response = get_card_from_locker(
self.state,
- &pm.customer_id,
+ &pm.customer_id.clone().get_required_value("customer_id")?,
&pm.merchant_id,
pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
@@ -1098,7 +1103,7 @@ impl PaymentMethodsController for PmCards<'_> {
Ok(services::ApplicationResponse::Json(
api::PaymentMethodResponse {
merchant_id: pm.merchant_id.clone(),
- customer_id: Some(pm.customer_id.clone()),
+ customer_id: pm.customer_id.clone(),
payment_method_id: pm.payment_method_id.clone(),
payment_method: pm.get_payment_method_type(),
payment_method_type: pm.get_payment_method_subtype(),
@@ -1134,9 +1139,11 @@ impl PaymentMethodsController for PmCards<'_> {
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+ let customer_id = key.customer_id.clone().get_required_value("customer_id")?;
+
let customer = db
.find_customer_by_customer_id_merchant_id(
- &key.customer_id,
+ &customer_id,
self.provider.get_account().get_id(),
self.provider.get_key_store(),
self.provider.get_account().storage_scheme,
@@ -1148,7 +1155,7 @@ impl PaymentMethodsController for PmCards<'_> {
if key.get_payment_method_type() == Some(enums::PaymentMethod::Card) {
let response = self
.delete_card_from_locker(
- &key.customer_id,
+ &customer_id,
&key.merchant_id,
key.locker_id.as_ref().unwrap_or(&key.payment_method_id),
)
@@ -1158,7 +1165,7 @@ impl PaymentMethodsController for PmCards<'_> {
let resp =
network_tokenization::delete_network_token_from_locker_and_token_service(
self.state,
- &key.customer_id,
+ &customer_id,
&key.merchant_id,
key.payment_method_id.clone(),
key.network_token_locker_id,
@@ -1198,7 +1205,7 @@ impl PaymentMethodsController for PmCards<'_> {
.map(|last_modified_by| last_modified_by.to_string()),
};
db.update_customer_by_customer_id_merchant_id(
- key.customer_id,
+ customer_id,
key.merchant_id,
customer,
customer_update,
@@ -1644,7 +1651,10 @@ pub async fn add_payment_method_data(
return Err((errors::ApiErrorResponse::ClientSecretExpired).into());
}
- let customer_id = payment_method.customer_id.clone();
+ let customer_id = payment_method
+ .customer_id
+ .clone()
+ .get_required_value("customer_id")?;
let customer = db
.find_customer_by_customer_id_merchant_id(
@@ -1854,6 +1864,8 @@ pub async fn update_customer_payment_method(
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?
};
+ let customer_id = pm.customer_id.clone().get_required_value("customer_id")?;
+
if let Some(cs) = &req.client_secret {
let is_client_secret_expired = authenticate_pm_client_secret_and_check_expiry(cs, &pm)?;
@@ -1907,7 +1919,7 @@ pub async fn update_customer_payment_method(
// Fetch the existing card data from locker for getting card number
let locker_card_response = get_card_from_locker(
&state,
- &pm.customer_id,
+ &customer_id,
&pm.merchant_id,
pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
@@ -1943,7 +1955,7 @@ pub async fn update_customer_payment_method(
#[cfg(feature = "payouts")]
wallet: None,
metadata: None,
- customer_id: Some(pm.customer_id.clone()),
+ customer_id: pm.customer_id.clone(),
client_secret: pm.client_secret.clone(),
payment_method_data: None,
card_network: None,
@@ -1959,7 +1971,7 @@ pub async fn update_customer_payment_method(
// Delete old payment method from locker
cards
.delete_card_from_locker(
- &pm.customer_id,
+ &customer_id,
&pm.merchant_id,
pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
@@ -1969,7 +1981,7 @@ pub async fn update_customer_payment_method(
let (mut add_card_resp, _) = Box::pin(cards.add_card_to_locker(
new_pm.clone(),
&updated_card_details,
- &pm.customer_id,
+ &customer_id,
Some(pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id)),
))
.await
@@ -2062,7 +2074,7 @@ pub async fn update_customer_payment_method(
// Return existing payment method data as response without any changes
api::CustomerPaymentMethodUpdateResponse {
merchant_id: pm.merchant_id.to_owned(),
- customer_id: Some(pm.customer_id.clone()),
+ customer_id: pm.customer_id.clone(),
payment_method_id: pm.payment_method_id.clone(),
payment_method: pm.get_payment_method_type(),
payment_method_type: pm.get_payment_method_subtype(),
@@ -2119,7 +2131,7 @@ pub async fn update_customer_payment_method(
Ok(services::ApplicationResponse::Json(
api::CustomerPaymentMethodUpdateResponse {
merchant_id: pm.merchant_id.to_owned(),
- customer_id: Some(pm.customer_id.clone()),
+ customer_id: pm.customer_id.clone(),
payment_method_id: pm.payment_method_id.clone(),
payment_method: pm.get_payment_method_type(),
payment_method_type: pm.get_payment_method_subtype(),
@@ -4666,7 +4678,7 @@ pub async fn list_customer_payment_method(
let pma = api::CustomerPaymentMethod {
payment_token: parent_payment_method_token.to_owned(),
payment_method_id: pm.payment_method_id.clone(),
- customer_id: pm.customer_id.clone(),
+ customer_id: pm.customer_id.clone().get_required_value("customer_id")?,
payment_method,
payment_method_type: pm.get_payment_method_subtype(),
payment_method_issuer: pm.payment_method_issuer,
@@ -4819,7 +4831,7 @@ pub async fn get_pm_list_context(
state,
key_store,
parent_payment_method_token.as_ref(),
- &pm.customer_id,
+ &pm.customer_id.clone().get_required_value("customer_id")?,
&pm.merchant_id,
pm.locker_id.as_ref().unwrap_or(pm.get_id()),
)
@@ -4997,7 +5009,7 @@ pub async fn get_card_details_from_locker(
) -> errors::RouterResult<api::CardDetailFromLocker> {
let card = get_card_from_locker(
state,
- &pm.customer_id,
+ &pm.customer_id.clone().get_required_value("customer_id")?,
&pm.merchant_id,
pm.locker_id.as_ref().unwrap_or(pm.get_id()),
)
@@ -5358,7 +5370,7 @@ impl TempLockerCardSupport {
None,
None,
None,
- Some(pm.customer_id.clone()),
+ pm.customer_id.clone(),
Some(pm.get_id().to_string()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/payment_methods/network_tokenization.rs b/crates/router/src/core/payment_methods/network_tokenization.rs
index 1ad0927dd5..91000fd259 100644
--- a/crates/router/src/core/payment_methods/network_tokenization.rs
+++ b/crates/router/src/core/payment_methods/network_tokenization.rs
@@ -26,8 +26,6 @@ use hyperswitch_masking::{ErasedMaskSerialize, ExposeInterface, Mask, PeekInterf
use josekit::jwe;
use super::transformers::DeleteCardResp;
-#[cfg(feature = "v2")]
-use crate::utils::ext_traits::OptionExt;
use crate::{
core::{errors, payment_methods, payments::helpers},
headers, logger,
@@ -35,6 +33,7 @@ use crate::{
services::{self, encryption},
settings,
types::{api, domain, payment_methods as pm_types},
+ utils::ext_traits::OptionExt,
};
pub const NETWORK_TOKEN_SERVICE: &str = "NETWORK_TOKEN";
@@ -611,7 +610,7 @@ pub async fn get_token_from_tokenization_service(
async {
get_network_token(
state,
- pm_data.customer_id.clone(),
+ pm_data.customer_id.clone().get_required_value("customer_id")?,
network_token_requestor_ref_id,
network_tokenization_service.get_inner(),
)
@@ -780,7 +779,7 @@ pub async fn do_status_check_for_network_token(
async {
check_token_status_with_tokenization_service(
state,
- &payment_method_info.customer_id.clone(),
+ &payment_method_info.customer_id.clone().get_required_value("customer_id")?,
ref_id,
network_tokenization_service.get_inner(),
)
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 62dc74ca22..3a1add8f59 100644
--- a/crates/router/src/core/payment_methods/tokenize/card_executor.rs
+++ b/crates/router/src/core/payment_methods/tokenize/card_executor.rs
@@ -272,7 +272,7 @@ impl<'a> NetworkTokenizationBuilder<'a, CardTokenStored> {
});
let payment_method_response = api::PaymentMethodResponse {
merchant_id: payment_method.merchant_id.clone(),
- customer_id: Some(payment_method.customer_id.clone()),
+ customer_id: payment_method.customer_id.clone(),
payment_method_id: payment_method.payment_method_id.clone(),
payment_method: payment_method.payment_method,
payment_method_type: payment_method.payment_method_type,
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 e0f998d0dd..4ac985cee2 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
@@ -67,7 +67,7 @@ impl<'a> NetworkTokenizationBuilder<'a, TokenizeWithPmId> {
) -> NetworkTokenizationBuilder<'a, PmFetched> {
let payment_method_response = api::PaymentMethodResponse {
merchant_id: payment_method.merchant_id.clone(),
- customer_id: Some(payment_method.customer_id.clone()),
+ customer_id: payment_method.customer_id.clone(),
payment_method_id: payment_method.payment_method_id.clone(),
payment_method: payment_method.payment_method,
payment_method_type: payment_method.payment_method_type,
@@ -224,7 +224,7 @@ impl<'a> NetworkTokenizationBuilder<'a, PmTokenStored> {
) -> NetworkTokenizationBuilder<'a, PmTokenUpdated> {
let payment_method_response = api::PaymentMethodResponse {
merchant_id: payment_method.merchant_id.clone(),
- customer_id: Some(payment_method.customer_id.clone()),
+ customer_id: payment_method.customer_id.clone(),
payment_method_id: payment_method.payment_method_id.clone(),
payment_method: payment_method.payment_method,
payment_method_type: payment_method.payment_method_type,
@@ -317,7 +317,17 @@ impl CardNetworkTokenizeExecutor<'_, domain::TokenizePaymentMethodRequest> {
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "customer",
})?;
- when(payment_method.customer_id != customer_id_in_req, || {
+
+ let customer_id = payment_method
+ .customer_id
+ .clone()
+ .get_required_value("customer_id")
+ .change_context(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "customer",
+ })
+ .attach_printable("Missing customer_id in domain payment method")?;
+
+ when(customer_id != customer_id_in_req, || {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Payment method does not belong to the customer".to_string()
}))
@@ -357,7 +367,7 @@ impl CardNetworkTokenizeExecutor<'_, domain::TokenizePaymentMethodRequest> {
let db = &*self.state.store;
let customer = db
.find_customer_by_customer_id_merchant_id(
- &payment_method.customer_id,
+ &customer_id,
self.merchant_account.get_id(),
self.key_store,
self.merchant_account.storage_scheme,
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 694cad84e9..0ea3ee32cb 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -1288,11 +1288,7 @@ impl DomainPaymentMethodWrapper {
.attach_printable("Failed to serialize connector mandate details")?;
Ok(Self(domain::PaymentMethod {
- //for guest checkout, where customer id, this will fail.
- customer_id: response
- .customer_id
- .clone()
- .get_required_value("CustomerId")?,
+ customer_id: response.customer_id.clone(),
merchant_id: response.merchant_id.clone(),
payment_method_id: response.payment_method_id.clone(),
accepted_currency: None,
@@ -1342,6 +1338,7 @@ impl DomainPaymentMethodWrapper {
customer_details: None,
locker_fingerprint_id: None,
network_tokenization_data: None,
+ storage_type: response.storage_type,
}))
}
@@ -1413,11 +1410,7 @@ impl DomainPaymentMethodWrapper {
.attach_printable("Failed to serialize connector mandate details")?;
Ok(Self(domain::PaymentMethod {
- //for guest checkout, where customer id, this will fail.
- customer_id: response
- .customer_id
- .clone()
- .get_required_value("CustomerId")?,
+ customer_id: response.customer_id.clone(),
merchant_id: response.merchant_id.clone(),
payment_method_id: response.payment_method_id.clone(),
accepted_currency: None,
@@ -1467,6 +1460,7 @@ impl DomainPaymentMethodWrapper {
customer_details: None,
locker_fingerprint_id: None,
network_tokenization_data: None,
+ storage_type: response.storage_type,
}))
}
}
@@ -1524,8 +1518,7 @@ impl TryFrom<CreatePaymentMethodResponse> for DomainPaymentMethodWrapper {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(response: CreatePaymentMethodResponse) -> Result<Self, Self::Error> {
Ok(Self(domain::PaymentMethod {
- //for guest checkout, where customer id, this will fail.
- customer_id: response.customer_id.get_required_value("CustomerId")?,
+ customer_id: response.customer_id,
merchant_id: response.merchant_id,
payment_method_id: response.payment_method_id,
accepted_currency: None,
@@ -1571,6 +1564,7 @@ impl TryFrom<CreatePaymentMethodResponse> for DomainPaymentMethodWrapper {
customer_details: None,
locker_fingerprint_id: None,
network_tokenization_data: None,
+ storage_type: response.storage_type,
}))
}
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 17d5f258a3..bbdece03e3 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -577,7 +577,10 @@ pub async fn get_token_pm_type_mandate_details(
verify_mandate_details_for_recurring_payments(
&payment_method_info.merchant_id,
platform.get_provider().get_account().get_id(),
- &payment_method_info.customer_id,
+ &payment_method_info
+ .customer_id
+ .clone()
+ .get_required_value("customer_id")?,
customer_id,
)?;
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 10dc239013..0edcc4d6d3 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -1093,7 +1093,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
if req.customer_acceptance.is_some() {
logger::info!("Organization is eligible for PM Modular Service, proceeding to create payment method using PM Modular Service.");
//check for req.payment_method_data, if card, create payment method with pm service
- let payment_method_info = match req
+ match req
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.as_ref())
@@ -1139,27 +1139,24 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
logger::info!(
"Payment method created in PM Modular service successfully"
);
- Some(pm_info)
+ //set payment_data.payment_method_info
+ payment_data.set_payment_method_id_in_attempt(Some(
+ pm_info.get_id().clone(),
+ ));
+ payment_data.set_payment_method_info(Some(pm_info));
}
Err(err) => {
logger::error!(
"Error creating payment method in PM Modular service: {:?}",
err
);
- None
}
}
}
_ => {
logger::info!("No supported payment method data found for creating payment method in PM Modular service.");
- None
}
};
- //set payment_data.payment_method_info
- payment_data.payment_attempt.payment_method_id = payment_method_info
- .as_ref()
- .map(|pm_info| pm_info.get_id().clone());
- payment_data.set_payment_method_info(payment_method_info);
Ok(())
} else {
@@ -1231,11 +1228,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
logger::info!("Payment method fetched from PM Modular Service.");
utils::when(
- pm_info.payment_method.0.customer_id
- != req
- .get_customer_id()
- .get_required_value("customer_id")?
- .clone(),
+ pm_info.payment_method.0.customer_id.as_ref() != req.get_customer_id(),
|| {
logger::info!("Payment method id does not belong to the customer id provided in the request.");
Err(errors::ApiErrorResponse::PaymentMethodNotFound)
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 0a0092dd21..864e322c0e 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -879,11 +879,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
logger::info!("Payment method fetched from PM Modular Service.");
utils::when(
- pm_info.payment_method.0.customer_id
- != req
- .get_customer_id()
- .get_required_value("customer_id")?
- .clone(),
+ pm_info.payment_method.0.customer_id.as_ref() != req.get_customer_id(),
|| {
logger::info!("Payment method id does not belong to the customer id provided in the request.");
Err(errors::ApiErrorResponse::PaymentMethodNotFound)
@@ -1457,8 +1453,7 @@ impl PaymentCreate {
platform.get_processor().get_account().get_id(),
payment_method_info
.as_ref()
- .map(|pmd_info| pmd_info.customer_id.clone())
- .as_ref(),
+ .and_then(|pmd_info| pmd_info.customer_id.as_ref()),
platform.get_processor().get_key_store(),
payment_id,
platform.get_processor().get_account().storage_scheme,
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 05ad888d17..b418c4221c 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -84,13 +84,17 @@ where
payment_data.payment_attempt.payment_method,
Some(enums::PaymentMethod::Card)
) {
- //#1 - Check if Payment method id is present in the payment data
- match payment_data
+ let is_volatile = payment_data
+ .get_payment_method_info()
+ .map(|pm| pm.is_pm_volatile());
+
+ let payment_method_id = payment_data
.payment_method_info
.as_ref()
- .map(|pm_info| pm_info.get_id().clone())
- {
- Some(payment_method_id) => {
+ .map(|pm_info| pm_info.get_id().clone());
+
+ match (is_volatile, payment_method_id) {
+ (Some(false), Some(pm_id)) => {
let should_update = resp.status.should_update_payment_method();
logger::info!(
"Payment method is card; is eligible for modular update: {}",
@@ -211,7 +215,7 @@ where
state,
&payment_data.payment_attempt.processor_merchant_id,
&payment_data.payment_attempt.profile_id,
- &payment_method_id,
+ &pm_id,
payload,
)
.await
@@ -223,18 +227,16 @@ where
logger::error!("Failed to call modular payment method update: {}", err);
}
};
- payment_data.payment_attempt.payment_method_id =
- Some(payment_method_id.clone());
+ payment_data.payment_attempt.payment_method_id = Some(pm_id.clone());
} else {
logger::info!("No updates found for modular payment method update call");
}
}
- _ => {
+ (_, _) => {
logger::info!("Payment method is not eligible for modular update");
}
}
}
-
Ok(())
}
diff --git a/crates/router/src/core/payouts/validator.rs b/crates/router/src/core/payouts/validator.rs
index 59501d6cc5..3cb818d28a 100644
--- a/crates/router/src/core/payouts/validator.rs
+++ b/crates/router/src/core/payouts/validator.rs
@@ -184,7 +184,12 @@ pub async fn validate_create_request(
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Unable to find payment method")?;
- utils::when(payment_method.customer_id != customer.customer_id, || {
+ let pm_customer_id = payment_method
+ .customer_id
+ .clone()
+ .get_required_value("customer_id")?;
+
+ utils::when(pm_customer_id != customer.customer_id, || {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Payment method does not belong to this customer_id".to_string(),
})
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index 54f32ec52b..3e69204728 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -496,7 +496,7 @@ async fn store_bank_details_in_payment_methods(
let now = common_utils::date_time::now();
let pm_new = domain::PaymentMethod {
- customer_id: customer_id.clone(),
+ customer_id: Some(customer_id.clone()),
merchant_id: platform.get_processor().get_account().get_id().clone(),
payment_method_id: pm_id,
payment_method: Some(enums::PaymentMethod::BankDebit),
@@ -540,6 +540,7 @@ async fn store_bank_details_in_payment_methods(
customer_details: None,
locker_fingerprint_id: None,
network_tokenization_data: None,
+ storage_type: None,
};
new_entries.push(pm_new);
diff --git a/crates/router/src/core/webhooks/network_tokenization_incoming.rs b/crates/router/src/core/webhooks/network_tokenization_incoming.rs
index b574b34491..405f51a751 100644
--- a/crates/router/src/core/webhooks/network_tokenization_incoming.rs
+++ b/crates/router/src/core/webhooks/network_tokenization_incoming.rs
@@ -247,7 +247,10 @@ pub async fn handle_metadata_update(
is_pan_update: bool,
) -> RouterResult<WebhookResponseTracker> {
let merchant_id = platform.get_processor().get_account().get_id();
- let customer_id = &payment_method.customer_id;
+ let customer_id = &payment_method
+ .customer_id
+ .clone()
+ .get_required_value("customer_id")?;
let payment_method_id = payment_method.get_id().clone();
let status = payment_method.status;
@@ -396,7 +399,7 @@ impl From<(&api::payment_methods::CardDetail, &domain::PaymentMethod)>
(data, payment_method): (&api::payment_methods::CardDetail, &domain::PaymentMethod),
) -> Self {
Self(api::payment_methods::PaymentMethodCreate {
- customer_id: Some(payment_method.customer_id.clone()),
+ customer_id: payment_method.customer_id.clone(),
payment_method: payment_method.payment_method,
payment_method_type: payment_method.payment_method_type,
payment_method_issuer: payment_method.payment_method_issuer.clone(),
diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs
index 0425c75c8f..bd20704426 100644
--- a/crates/router/src/types/api/mandates.rs
+++ b/crates/router/src/types/api/mandates.rs
@@ -58,12 +58,19 @@ impl MandateResponseExt for MandateResponse {
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("payment_method not found")?;
+ let customer_id = payment_method
+ .customer_id
+ .clone()
+ .get_required_value("customer_id")
+ .change_context(errors::ApiErrorResponse::CustomerNotFound)
+ .attach_printable("Missing customer_id in domain payment method")?;
+
let card = if pm == storage_enums::PaymentMethod::Card {
// if locker is disabled , decrypt the payment method data
let card_details = if state.conf.locker.locker_enabled {
let card = payment_methods::cards::get_card_from_locker(
state,
- &payment_method.customer_id,
+ &customer_id,
&payment_method.merchant_id,
payment_method
.locker_id
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 415e8b1335..0b332866ac 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -102,7 +102,7 @@ impl
) -> Self {
Self {
merchant_id: item.merchant_id.to_owned(),
- customer_id: Some(item.customer_id.to_owned()),
+ customer_id: item.customer_id.to_owned(),
payment_method_id: item.get_id().clone(),
payment_method: item.get_payment_method_type(),
payment_method_type: item.get_payment_method_subtype(),
diff --git a/crates/storage_impl/src/payment_method.rs b/crates/storage_impl/src/payment_method.rs
index 28ea879a3f..c16c795dab 100644
--- a/crates/storage_impl/src/payment_method.rs
+++ b/crates/storage_impl/src/payment_method.rs
@@ -8,6 +8,8 @@ impl KvStorePartition for PaymentMethod {}
use std::collections::HashSet;
use common_enums::enums::MerchantStorageScheme;
+#[cfg(feature = "v2")]
+use common_utils::ext_traits::OptionExt;
use common_utils::{errors::CustomResult, id_type};
#[cfg(feature = "v1")]
use diesel_models::kv;
@@ -944,7 +946,12 @@ impl PaymentMethodInterface for MockDb {
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
let find_pm_by = |pm: &&PaymentMethod| {
- pm.customer_id == *customer_id && pm.merchant_id == *merchant_id && pm.status == status
+ let customer_id_matches = pm
+ .customer_id
+ .as_ref()
+ .map(|id| id == customer_id)
+ .unwrap_or(false);
+ customer_id_matches && pm.merchant_id == *merchant_id && pm.status == status
};
let error_message = "cannot find payment method".to_string();
self.get_resources(key_store, payment_methods, find_pm_by, error_message)
@@ -963,9 +970,12 @@ impl PaymentMethodInterface for MockDb {
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
let find_pm_by = |pm: &&PaymentMethod| {
- pm.customer_id == *customer_id
- && pm.merchant_id == *merchant_id
- && statuses.contains(&pm.status)
+ let customer_id_matches = pm
+ .customer_id
+ .as_ref()
+ .map(|id| id == customer_id)
+ .unwrap_or(false);
+ customer_id_matches && pm.merchant_id == *merchant_id && statuses.contains(&pm.status)
};
let error_message = "cannot find payment method".to_string();
self.get_resources(key_store, payment_methods, find_pm_by, error_message)
diff --git a/v2_migrations/2026-03-19-143445-0000_make_customer_id_nullable_in_v2_payment_method_table/down.sql b/v2_migrations/2026-03-19-143445-0000_make_customer_id_nullable_in_v2_payment_method_table/down.sql
new file mode 100644
index 0000000000..cb3abe59ed
--- /dev/null
+++ b/v2_migrations/2026-03-19-143445-0000_make_customer_id_nullable_in_v2_payment_method_table/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_methods
+ALTER COLUMN customer_id SET NOT NULL;
\ No newline at end of file
diff --git a/v2_migrations/2026-03-19-143445-0000_make_customer_id_nullable_in_v2_payment_method_table/up.sql b/v2_migrations/2026-03-19-143445-0000_make_customer_id_nullable_in_v2_payment_method_table/up.sql
new file mode 100644
index 0000000000..c8e1d3b28d
--- /dev/null
+++ b/v2_migrations/2026-03-19-143445-0000_make_customer_id_nullable_in_v2_payment_method_table/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+ALTER TABLE payment_methods
+ALTER COLUMN customer_id DROP NOT NULL;
\ No newline at end of file