Skip to content

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

feat(payment-methods): add new status, customer pml changes in pm service (#11276)

Prasunna Soppa786be5412b49
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index 87fd002062..bdb9aee388 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -27123,7 +27123,8 @@
"active",
"inactive",
"processing",
- "awaiting_data"
+ "awaiting_data",
+ "new"
]
},
"PaymentMethodTokenizationDetails": {
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index a79b562c66..478807cb4e 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -5364,6 +5364,13 @@
}
}
},
+ "AcknowledgementStatus": {
+ "type": "string",
+ "enum": [
+ "authenticated",
+ "failed"
+ ]
+ },
"AdditionalMerchantData": {
"oneOf": [
{
@@ -15827,6 +15834,10 @@
"description": "Indicates the limit of last used payment methods",
"example": 1,
"nullable": true
+ },
+ "include_new": {
+ "type": "boolean",
+ "nullable": true
}
},
"additionalProperties": false
@@ -21296,6 +21307,14 @@
}
],
"nullable": true
+ },
+ "acknowledgement_status": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/AcknowledgementStatus"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -21525,6 +21544,11 @@
},
"storage_type": {
"$ref": "#/components/schemas/StorageType"
+ },
+ "keep_alive": {
+ "type": "boolean",
+ "description": "Whether the card with new status should be listed in the session",
+ "nullable": true
}
}
},
@@ -21533,7 +21557,8 @@
"required": [
"id",
"expires_at",
- "client_secret"
+ "client_secret",
+ "keep_alive"
],
"properties": {
"id": {
@@ -21650,6 +21675,10 @@
"description": "SDK authorization token for client SDK usage\nContains encoded authentication details for subsequent API calls",
"example": "cHJvZmlsZV9pZD0uLi4=",
"nullable": true
+ },
+ "keep_alive": {
+ "type": "boolean",
+ "description": "Whether the card with new status should be listed in the session"
}
}
},
@@ -21687,7 +21716,8 @@
"active",
"inactive",
"processing",
- "awaiting_data"
+ "awaiting_data",
+ "new"
]
},
"PaymentMethodSubtypeSpecificData": {
@@ -21865,6 +21895,14 @@
"type": "string",
"description": "The network transaction ID provided by the card network during a Customer Initiated Transaction (CIT)\nwhen `setup_future_usage` is set to `off_session`.",
"nullable": true
+ },
+ "acknowledgement_status": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/AcknowledgementStatus"
+ }
+ ],
+ "nullable": true
}
},
"additionalProperties": false
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 7f6407c59a..05f3c8917f 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -550,31 +550,10 @@ pub struct PaymentMethodUpdate {
/// when `setup_future_usage` is set to `off_session`.
#[schema(value_type = Option<String>)]
pub network_transaction_id: Option<masking::Secret<String>>,
-}
-#[cfg(feature = "v2")]
-impl PaymentMethodUpdate {
- pub fn fetch_card_cvc_update(&self) -> Option<masking::Secret<String>> {
- match &self.payment_method_data {
- Some(PaymentMethodUpdateData::Card(card_update)) => card_update.card_cvc.clone(),
- _ => None,
- }
- }
-
- pub fn is_payment_method_metadata_update(&self) -> bool {
- match &self.payment_method_data {
- Some(PaymentMethodUpdateData::Card(card_update)) => {
- card_update.card_holder_name.is_some() || card_update.nick_name.is_some()
- }
- _ => false,
- }
- }
-
- pub fn is_payment_method_update_required(&self) -> bool {
- self.is_payment_method_metadata_update()
- || self.connector_token_details.is_some()
- || self.network_transaction_id.is_some()
- }
+ /// The acknowledgement status of the payment method update, this is used to determine the status of the payment method update
+ #[schema(value_type = Option<AcknowledgementStatus>)]
+ pub acknowledgement_status: Option<common_enums::AcknowledgementStatus>,
}
#[cfg(feature = "v2")]
@@ -1273,6 +1252,10 @@ pub struct PaymentMethodResponse {
/// Billing details of the payment method
#[schema(value_type = Option<Address>)]
pub billing: Option<payments::Address>,
+
+ /// The acknowledgement status of the payment method update
+ #[schema(value_type = Option<AcknowledgementStatus>)]
+ pub acknowledgement_status: Option<common_enums::AcknowledgementStatus>,
}
#[cfg(feature = "v2")]
@@ -2299,6 +2282,8 @@ pub struct ListMethodsForPaymentMethodsRequest {
/// Indicates the limit of last used payment methods
#[schema(example = 1)]
pub limit: Option<i64>,
+
+ pub include_new: Option<bool>,
}
#[cfg(feature = "v2")]
@@ -2364,6 +2349,13 @@ impl<'de> serde::Deserialize<'de> for ListMethodsForPaymentMethodsRequest {
"limit" => {
set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?;
}
+ "include_new" => {
+ set_or_reject_duplicate(
+ &mut output.include_new,
+ "include_new",
+ map.next_value()?,
+ )?;
+ }
_ => {}
}
}
@@ -3620,6 +3612,9 @@ pub struct PaymentMethodSessionRequest {
/// The storage type for the payment method
#[schema(value_type = StorageType)]
pub storage_type: common_enums::StorageType,
+
+ /// Whether the card with new status should be listed in the session
+ pub keep_alive: Option<bool>,
}
#[cfg(feature = "v2")]
@@ -3779,6 +3774,9 @@ pub struct PaymentMethodSessionResponse {
#[schema(value_type = Option<String>, example = "cHJvZmlsZV9pZD0uLi4=")]
#[serde(skip_serializing_if = "Option::is_none")]
pub sdk_authorization: Option<String>,
+
+ /// Whether the card with new status should be listed in the session
+ pub keep_alive: bool,
}
#[cfg(feature = "v2")]
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 9afc5a06f2..97ba640db9 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2164,6 +2164,8 @@ pub enum PaymentMethodStatus {
Processing,
/// Indicates that the payment method is awaiting some data before changing state to active
AwaitingData,
+ /// Indicates that the payment method is in new state
+ New,
}
impl From<AttemptStatus> for PaymentMethodStatus {
@@ -10559,6 +10561,27 @@ pub enum StorageType {
Persistent,
}
+#[derive(
+ Clone,
+ Debug,
+ Copy,
+ Eq,
+ Hash,
+ PartialEq,
+ serde::Deserialize,
+ serde::Serialize,
+ strum::Display,
+ strum::EnumString,
+ ToSchema,
+)]
+#[router_derive::diesel_enum(storage_type = "text")]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum AcknowledgementStatus {
+ Authenticated,
+ Failed,
+}
+
/// Represents the type of retry for a payment attempt
#[derive(
Clone,
diff --git a/crates/diesel_models/src/payment_methods_session.rs b/crates/diesel_models/src/payment_methods_session.rs
index 06155a150d..ef622933f8 100644
--- a/crates/diesel_models/src/payment_methods_session.rs
+++ b/crates/diesel_models/src/payment_methods_session.rs
@@ -17,6 +17,7 @@ pub struct PaymentMethodSession {
pub associated_payment: Option<common_utils::id_type::GlobalPaymentId>,
pub associated_token_id: Option<common_utils::id_type::GlobalTokenId>,
pub storage_type: common_enums::StorageType,
+ pub keep_alive: bool,
}
#[cfg(feature = "v2")]
@@ -35,6 +36,7 @@ impl PaymentMethodSession {
associated_payment,
associated_token_id,
storage_type,
+ keep_alive,
} = self;
Self {
@@ -50,6 +52,7 @@ impl PaymentMethodSession {
associated_payment,
associated_token_id,
storage_type,
+ keep_alive,
}
}
}
diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs
index 40dd1ab3c6..c26ad5df41 100644
--- a/crates/diesel_models/src/query/payment_method.rs
+++ b/crates/diesel_models/src/query/payment_method.rs
@@ -243,6 +243,26 @@ impl PaymentMethod {
.await
}
+ pub async fn find_by_global_customer_id_merchant_id_statuses(
+ conn: &PgPooledConn,
+ customer_id: &common_utils::id_type::GlobalCustomerId,
+ merchant_id: &common_utils::id_type::MerchantId,
+ statuses: Vec<storage_enums::PaymentMethodStatus>,
+ limit: Option<i64>,
+ ) -> StorageResult<Vec<Self>> {
+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
+ conn,
+ dsl::customer_id
+ .eq(customer_id.to_owned())
+ .and(dsl::merchant_id.eq(merchant_id.to_owned()))
+ .and(dsl::status.eq_any(statuses)),
+ limit,
+ None,
+ Some(dsl::last_used_at.desc()),
+ )
+ .await
+ }
+
pub async fn find_by_global_customer_id_merchant_id_status(
conn: &PgPooledConn,
customer_id: &common_utils::id_type::GlobalCustomerId,
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index c8023bbd0e..5683055237 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -3109,14 +3109,20 @@ pub struct CardDetailsPaymentMethod {
#[cfg(feature = "v2")]
pub struct CardNumberWithStoredDetails {
pub card_number: cards::CardNumber,
+ pub card_cvc: Option<Secret<String>>,
pub card_details: CardDetailsPaymentMethod,
}
#[cfg(feature = "v2")]
impl CardNumberWithStoredDetails {
- pub fn new(card_number: cards::CardNumber, card_details: CardDetailsPaymentMethod) -> Self {
+ pub fn new(
+ card_number: cards::CardNumber,
+ card_cvc: Option<Secret<String>>,
+ card_details: CardDetailsPaymentMethod,
+ ) -> Self {
Self {
card_number,
+ card_cvc,
card_details,
}
}
@@ -3128,6 +3134,7 @@ impl TryFrom<CardNumberWithStoredDetails> for payment_methods::CardDetail {
fn try_from(testing: CardNumberWithStoredDetails) -> Result<Self, Self::Error> {
let card_number = testing.card_number;
+ let card_cvc = testing.card_cvc;
let item = testing.card_details;
Ok(Self {
card_number,
@@ -3150,7 +3157,7 @@ impl TryFrom<CardNumberWithStoredDetails> for payment_methods::CardDetail {
card_type: item
.card_type
.and_then(|card_type| payment_methods::CardType::from_str(&card_type).ok()),
- card_cvc: None,
+ card_cvc,
})
}
}
diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs
index b5c33231f9..b5cb3ef531 100644
--- a/crates/hyperswitch_domain_models/src/payment_methods.rs
+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs
@@ -18,7 +18,9 @@ use common_utils::{
id_type, pii, type_name,
types::{keymanager, CreatedBy},
};
-pub use diesel_models::{enums as storage_enums, PaymentMethodUpdate};
+pub use diesel_models::{
+ enums as storage_enums, PaymentMethodUpdate as StoragePaymentMethodUpdate,
+};
use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface, Secret};
#[cfg(feature = "v1")]
@@ -135,8 +137,7 @@ pub struct PaymentMethod {
pub network_token_payment_method_data:
Option<Encryptable<domain_payment_method_data::PaymentMethodsData>>,
#[encrypt(ty = Value)]
- pub external_vault_token_data:
- Option<Encryptable<api_models::payment_methods::ExternalVaultTokenData>>,
+ pub external_vault_token_data: Option<Encryptable<payment_methods::ExternalVaultTokenData>>,
pub vault_type: Option<storage_enums::VaultType>,
pub created_by: Option<CreatedBy>,
pub last_modified_by: Option<CreatedBy>,
@@ -317,6 +318,95 @@ impl PaymentMethod {
}
}
+#[cfg(feature = "v2")]
+#[derive(Clone, Debug)]
+pub struct PaymentMethodUpdate {
+ pub payment_method_data: Option<payment_methods::PaymentMethodUpdateData>,
+ pub connector_token_details: Option<payment_methods::ConnectorTokenDetails>,
+ pub network_transaction_id: Option<Secret<String>>,
+ pub acknowledgement_status: Option<common_enums::AcknowledgementStatus>,
+ pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,
+ pub source_payment_method_data: Option<crate::vault::PaymentMethodVaultingData>,
+}
+
+#[cfg(feature = "v2")]
+impl From<payment_methods::PaymentMethodUpdate> for PaymentMethodUpdate {
+ fn from(value: payment_methods::PaymentMethodUpdate) -> Self {
+ Self {
+ payment_method_data: value.payment_method_data,
+ connector_token_details: value.connector_token_details,
+ network_transaction_id: value.network_transaction_id,
+ acknowledgement_status: value.acknowledgement_status,
+ network_tokenization: None,
+ source_payment_method_data: None,
+ }
+ }
+}
+
+#[cfg(feature = "v2")]
+impl PaymentMethodUpdate {
+ pub fn fetch_card_cvc_update(&self) -> Option<Secret<String>> {
+ match &self.payment_method_data {
+ Some(payment_methods::PaymentMethodUpdateData::Card(card_update)) => {
+ card_update.card_cvc.clone()
+ }
+ _ => None,
+ }
+ }
+
+ pub fn is_payment_method_metadata_update(&self) -> bool {
+ match &self.payment_method_data {
+ Some(payment_methods::PaymentMethodUpdateData::Card(card_update)) => {
+ card_update.card_holder_name.is_some() || card_update.nick_name.is_some()
+ }
+ _ => false,
+ }
+ }
+
+ pub fn is_payment_method_update_required(&self) -> bool {
+ self.is_payment_method_metadata_update()
+ || self.connector_token_details.is_some()
+ || self.network_transaction_id.is_some()
+ || self.acknowledgement_status.is_some()
+ }
+}
+
+#[cfg(feature = "v2")]
+impl
+ From<(
+ &payment_methods::PaymentMethodCreate,
+ crate::vault::PaymentMethodVaultingData,
+ )> for PaymentMethodUpdate
+{
+ fn from(
+ value: (
+ &payment_methods::PaymentMethodCreate,
+ crate::vault::PaymentMethodVaultingData,
+ ),
+ ) -> Self {
+ let (req, source_payment_method_data) = value;
+ let payment_method_data = match &req.payment_method_data {
+ payment_methods::PaymentMethodCreateData::Card(card_data) => Some(
+ payment_methods::PaymentMethodUpdateData::Card(payment_methods::CardDetailUpdate {
+ card_holder_name: card_data.card_holder_name.clone(),
+ nick_name: card_data.nick_name.clone(),
+ card_cvc: card_data.card_cvc.clone(),
+ }),
+ ),
+ payment_methods::PaymentMethodCreateData::ProxyCard(_) => None,
+ };
+
+ Self {
+ payment_method_data,
+ connector_token_details: None,
+ network_transaction_id: None,
+ acknowledgement_status: None,
+ network_tokenization: req.network_tokenization.clone(),
+ source_payment_method_data: Some(source_payment_method_data),
+ }
+ }
+}
+
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl super::behaviour::Conversion for PaymentMethod {
@@ -800,6 +890,7 @@ pub struct PaymentMethodSession {
pub associated_payment: Option<id_type::GlobalPaymentId>,
pub associated_token_id: Option<id_type::GlobalTokenId>,
pub storage_type: common_enums::StorageType,
+ pub keep_alive: bool,
}
#[cfg(feature = "v2")]
@@ -821,6 +912,7 @@ impl super::behaviour::Conversion for PaymentMethodSession {
return_url: self.return_url,
associated_token_id: self.associated_token_id,
storage_type: self.storage_type,
+ keep_alive: self.keep_alive,
})
}
@@ -876,6 +968,7 @@ impl super::behaviour::Conversion for PaymentMethodSession {
return_url: storage_model.return_url,
associated_token_id: storage_model.associated_token_id,
storage_type: storage_model.storage_type,
+ keep_alive: storage_model.keep_alive,
})
}
.await
@@ -898,6 +991,7 @@ impl super::behaviour::Conversion for PaymentMethodSession {
return_url: self.return_url,
associated_token_id: self.associated_token_id,
storage_type: self.storage_type,
+ keep_alive: self.keep_alive,
})
}
}
@@ -980,6 +1074,18 @@ pub trait PaymentMethodInterface {
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<PaymentMethod>, Self::Error>;
+ #[cfg(feature = "v2")]
+ #[allow(clippy::too_many_arguments)]
+ async fn find_payment_method_by_global_customer_id_merchant_id_statuses(
+ &self,
+ key_store: &MerchantKeyStore,
+ customer_id: &id_type::GlobalCustomerId,
+ merchant_id: &id_type::MerchantId,
+ statuses: Vec<common_enums::PaymentMethodStatus>,
+ limit: Option<i64>,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<Vec<PaymentMethod>, Self::Error>;
+
#[cfg(feature = "v1")]
async fn get_payment_method_count_by_customer_id_merchant_id_status(
&self,
@@ -1005,7 +1111,7 @@ pub trait PaymentMethodInterface {
&self,
key_store: &MerchantKeyStore,
payment_method: PaymentMethod,
- payment_method_update: PaymentMethodUpdate,
+ payment_method_update: StoragePaymentMethodUpdate,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentMethod, Self::Error>;
@@ -1090,6 +1196,7 @@ impl PaymentMethodSession {
associated_payment,
associated_token_id,
storage_type,
+ keep_alive,
} = self;
Self {
id,
@@ -1106,6 +1213,7 @@ impl PaymentMethodSession {
associated_payment,
associated_token_id,
storage_type,
+ keep_alive,
}
}
}
diff --git a/crates/hyperswitch_domain_models/src/vault.rs b/crates/hyperswitch_domain_models/src/vault.rs
index a2d8666953..bca75f1087 100644
--- a/crates/hyperswitch_domain_models/src/vault.rs
+++ b/crates/hyperswitch_domain_models/src/vault.rs
@@ -77,7 +77,29 @@ impl PaymentMethodVaultingData {
payment_methods_data_optional: Option<&Encryptable<payment_methods::PaymentMethodsData>>,
) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> {
match self {
- Self::Card(card_details) => Ok(self.clone()),
+ Self::Card(card_details) => {
+ let payment_methods_data = payment_methods_data_optional
+ .get_required_value("payment methods data")
+ .change_context(
+ errors::api_error_response::ApiErrorResponse::InternalServerError,
+ )
+ .attach_printable("failed to get payment methods data for payment method vaulting data type card number")?;
+
+ let payment_methods_data = payment_methods_data_optional
+ .get_required_value("payment methods data")
+ .change_context(
+ errors::api_error_response::ApiErrorResponse::InternalServerError,
+ )
+ .attach_printable("failed to get payment methods data for payment method vaulting data type card number")?;
+
+ let card_detail = Self::populated_payment_methods_data_for_payment_method_vaulting_data_card_number(
+ &card_details.card_number,
+ card_details.card_cvc.clone(),
+ payment_methods_data,
+ )?;
+
+ Ok(Self::Card(card_detail))
+ }
Self::NetworkToken(_) => Ok(self.clone()),
Self::CardNumber(card_number) => {
let payment_methods_data = payment_methods_data_optional
@@ -89,6 +111,7 @@ impl PaymentMethodVaultingData {
let card_detail = Self::populated_payment_methods_data_for_payment_method_vaulting_data_card_number(
card_number,
+ None,
payment_methods_data,
)?;
@@ -100,6 +123,7 @@ impl PaymentMethodVaultingData {
#[cfg(feature = "v2")]
pub fn populated_payment_methods_data_for_payment_method_vaulting_data_card_number(
card_number: &cards::CardNumber,
+ card_cvc: Option<masking::Secret<String>>,
payment_methods_data: &Encryptable<payment_methods::PaymentMethodsData>,
) -> CustomResult<payment_methods::CardDetail, errors::api_error_response::ApiErrorResponse>
{
@@ -113,6 +137,7 @@ impl PaymentMethodVaultingData {
let card_with_details = payment_method_data::CardNumberWithStoredDetails::new(
card_number.clone(),
+ card_cvc.clone(),
stored_card_metadata.into(),
);
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 1f3bdb5113..4b1f652729 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -384,6 +384,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::enums::GooglePayCardFundingSource,
api_models::enums::VaultTokenType,
api_models::enums::StorageType,
+ api_models::enums::AcknowledgementStatus,
api_models::admin::MerchantConnectorCreate,
api_models::admin::AdditionalMerchantData,
api_models::admin::CardTestingGuardConfig,
diff --git a/crates/payment_methods/src/client/update.rs b/crates/payment_methods/src/client/update.rs
index 1d6cb9ab79..2887bc7ea2 100644
--- a/crates/payment_methods/src/client/update.rs
+++ b/crates/payment_methods/src/client/update.rs
@@ -39,6 +39,8 @@ pub struct UpdatePaymentMethodV1Payload {
pub connector_token_details: Option<ConnectorTokenDetails>,
/// Network transaction ID for off-session updates.
pub network_transaction_id: Option<Secret<String>>,
+
+ pub acknowledgement_status: Option<common_enums::AcknowledgementStatus>,
}
/// Modular service update request payload.
@@ -50,6 +52,8 @@ pub struct ModularPMUpdateRequest {
pub connector_token_details: Option<ConnectorTokenDetails>,
/// Network transaction ID for off-session updates.
pub network_transaction_id: Option<Secret<String>>,
+
+ pub acknowledgement_status: Option<common_enums::AcknowledgementStatus>,
}
/// Payment method update data.
@@ -112,6 +116,7 @@ impl TryFrom<&UpdatePaymentMethodV1Request> for ModularPMUpdateRequest {
payment_method_data: value.payload.payment_method_data.clone(),
connector_token_details: value.payload.connector_token_details.clone(),
network_transaction_id: value.payload.network_transaction_id.clone(),
+ acknowledgement_status: value.payload.acknowledgement_status,
})
}
}
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 95fcdc07cc..638a719330 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -45,6 +45,8 @@ use futures::TryStreamExt;
use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::behaviour::Conversion;
+#[cfg(feature = "v2")]
+use hyperswitch_domain_models::payment_methods::PaymentMethodUpdate as DomainPaymentMethodUpdate;
use hyperswitch_domain_models::{
payment_method_data::BankDebitData,
payments::{payment_attempt::PaymentAttempt, PaymentIntent, VaultData},
@@ -1254,12 +1256,35 @@ async fn payment_method_resolver(
)
.await
{
- Ok(existing_pm) => {
- logger::info!("Payment method is duplicated, returning existing payment method");
- Ok(PaymentMethodResolver(PaymentMethodResolution::Get(
- Box::new(existing_pm),
- )))
- }
+ Ok(existing_pm) => match existing_pm.status {
+ enums::PaymentMethodStatus::New | enums::PaymentMethodStatus::Inactive => {
+ logger::info!(
+ "Payment method is duplicated with update-eligible status, updating existing payment method"
+ );
+ let payment_method_id = existing_pm.id.clone();
+ Ok(PaymentMethodResolver(PaymentMethodResolution::Update {
+ fingerprint_id,
+ payment_method_id,
+ payment_method: Box::new(existing_pm),
+ source_payment_method_data: payment_method_data,
+ }))
+ }
+ enums::PaymentMethodStatus::Active => {
+ logger::info!("Payment method is duplicated, returning existing payment method");
+ Ok(PaymentMethodResolver(PaymentMethodResolution::Get(
+ Box::new(existing_pm),
+ )))
+ }
+ enums::PaymentMethodStatus::AwaitingData | enums::PaymentMethodStatus::Processing => {
+ // no payment method entry will be found with finger print id and awaiting data or processing state
+ logger::info!("Payment method is in awaiting data or processing state, no existing payment method entry found with fingerprint id");
+ Err(
+ report!(errors::ApiErrorResponse::InternalServerError).attach_printable(
+ "Payment method is in invalid state, expected New or Inactive",
+ ),
+ )
+ }
+ },
Err(err) => {
when(!err.current_context().is_db_not_found(), || {
Err(err)
@@ -1279,6 +1304,12 @@ async fn payment_method_resolver(
#[cfg(feature = "v2")]
pub enum PaymentMethodResolution {
Get(Box<domain::PaymentMethod>),
+ Update {
+ fingerprint_id: String,
+ payment_method_id: id_type::GlobalPaymentMethodId,
+ payment_method: Box<domain::PaymentMethod>,
+ source_payment_method_data: domain::PaymentMethodVaultingData,
+ },
Create {
fingerprint_id: String,
payment_method_data: domain::PaymentMethodVaultingData,
@@ -1331,19 +1362,18 @@ async fn create_or_fetch_payment_method_core(
)
.await?;
- resolver
- .execute(
- state,
- &req,
- platform,
- profile,
- merchant_id,
- customer_id,
- payment_method_id,
- payment_method_subtype,
- billing_address,
- )
- .await
+ Box::pin(resolver.execute(
+ state,
+ &req,
+ platform,
+ profile,
+ merchant_id,
+ customer_id,
+ payment_method_id,
+ payment_method_subtype,
+ billing_address,
+ ))
+ .await
}
#[cfg(feature = "v2")]
@@ -1418,11 +1448,68 @@ impl PaymentMethodResolver {
req.customer_id.clone(),
None,
billing,
+ None,
)?;
Ok((resp, *existing_pm))
}
+ PaymentMethodResolution::Update {
+ fingerprint_id,
+ payment_method_id,
+ payment_method,
+ source_payment_method_data,
+ } => {
+ logger::debug!(
+ "Updating duplicated payment method {:?} for fingerprint {}",
+ payment_method_id,
+ fingerprint_id
+ );
+
+ let payment_method = *payment_method;
+ let payment_method_has_network_token_data = payment_method
+ .network_token_requestor_reference_id
+ .is_some()
+ || payment_method.network_token_locker_id.is_some()
+ || payment_method.network_token_payment_method_data.is_some();
+ let network_tokenization_resp = if req.network_tokenization.is_some()
+ && !payment_method_has_network_token_data
+ {
+ let customer_id = payment_method
+ .customer_id
+ .clone()
+ .get_required_value("GlobalCustomerId")?;
+
+ network_tokenize_and_vault_the_pmd(
+ state,
+ &source_payment_method_data,
+ platform,
+ req.network_tokenization.clone(),
+ profile.is_network_tokenization_enabled,
+ &customer_id,
+ )
+ .await
+ } else {
+ None
+ };
+
+ let update_payment_method_data: DomainPaymentMethodUpdate =
+ (req, source_payment_method_data).into();
+
+ let (response, updated_payment_method) = Box::pin(update_payment_method_core(
+ state,
+ platform,
+ profile,
+ update_payment_method_data,
+ &payment_method_id,
+ Some(payment_method),
+ network_tokenization_resp,
+ ))
+ .await?;
+
+ Ok((response, updated_payment_method))
+ }
+
PaymentMethodResolution::Create {
fingerprint_id,
payment_method_data,
@@ -1529,7 +1616,7 @@ async fn execute_payment_method_create(
Some(req.payment_method_type),
payment_method_subtype,
external_vault_source,
- Some(enums::PaymentMethodStatus::Active),
+ Some(enums::PaymentMethodStatus::New),
)
.await
.attach_printable("unable to create payment method data")?;
@@ -1573,6 +1660,7 @@ async fn execute_payment_method_create(
req.customer_id.clone(),
None,
payment_method_billing_address.map(|add| add.get_inner().clone().into()),
+ None,
)?;
Ok((resp, payment_method))
@@ -1730,6 +1818,7 @@ pub async fn create_volatile_payment_method_card_core(
req.customer_id,
None,
None,
+ None,
)?;
Ok((resp, domain_payment_method))
@@ -1848,6 +1937,7 @@ pub async fn create_payment_method_proxy_card_core(
req.customer_id,
None,
None,
+ None,
)?;
Ok((payment_method_response, payment_method))
@@ -2265,6 +2355,7 @@ pub async fn payment_method_intent_create(
Some(customer_id),
None,
None,
+ None,
)?;
Ok(services::ApplicationResponse::Json(resp))
@@ -2315,7 +2406,13 @@ pub async fn list_payment_methods_for_session(
let customer_payment_methods = match payment_method_session.customer_id {
Some(ref customer_id) => {
- list_customer_payment_methods_core(&state, platform.get_provider(), customer_id).await?
+ list_customer_payment_methods_core(
+ &state,
+ platform.get_provider(),
+ customer_id,
+ payment_method_session.keep_alive,
+ )
+ .await?
}
None => Vec::new(),
};
@@ -2365,9 +2462,10 @@ pub async fn list_saved_payment_methods_for_customer(
state: SessionState,
provider: domain::Provider,
customer_id: id_type::GlobalCustomerId,
+ include_new: bool,
) -> RouterResponse<payment_methods::CustomerPaymentMethodsListResponse> {
let customer_payment_methods =
- list_payment_methods_core(&state, &provider, &customer_id).await?;
+ list_payment_methods_core(&state, &provider, &customer_id, include_new).await?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
customer_payment_methods,
@@ -2738,7 +2836,7 @@ pub async fn construct_payment_method_object(
connector_mandate_details: None,
customer_acceptance: None,
client_secret: None,
- status: enums::PaymentMethodStatus::Inactive,
+ status: enums::PaymentMethodStatus::New,
network_transaction_id: None,
created_at: current_time,
last_modified: current_time,
@@ -3568,15 +3666,24 @@ pub async fn list_payment_methods_core(
state: &SessionState,
provider: &domain::Provider,
customer_id: &id_type::GlobalCustomerId,
+ include_new: bool,
) -> RouterResult<payment_methods::CustomerPaymentMethodsListResponse> {
let db = &*state.store;
+ let statuses = if include_new {
+ vec![
+ common_enums::PaymentMethodStatus::Active,
+ common_enums::PaymentMethodStatus::New,
+ ]
+ } else {
+ vec![common_enums::PaymentMethodStatus::Active]
+ };
let saved_payment_methods = db
- .find_payment_method_by_global_customer_id_merchant_id_status(
+ .find_payment_method_by_global_customer_id_merchant_id_statuses(
provider.get_key_store(),
customer_id,
provider.get_account().get_id(),
- common_enums::PaymentMethodStatus::Active,
+ statuses,
None,
provider.get_account().storage_scheme,
)
@@ -3601,15 +3708,23 @@ pub async fn list_customer_payment_methods_core(
state: &SessionState,
provider: &domain::Provider,
customer_id: &id_type::GlobalCustomerId,
+ include_new: bool,
) -> RouterResult<Vec<payment_methods::CustomerPaymentMethodResponseItem>> {
let db = &*state.store;
-
+ let statuses = if include_new {
+ vec![
+ common_enums::PaymentMethodStatus::Active,
+ common_enums::PaymentMethodStatus::New,
+ ]
+ } else {
+ vec![common_enums::PaymentMethodStatus::Active]
+ };
let saved_payment_methods = db
- .find_payment_method_by_global_customer_id_merchant_id_status(
+ .find_payment_method_by_global_customer_id_merchant_id_statuses(
provider.get_key_store(),
customer_id,
provider.get_account().get_id(),
- common_enums::PaymentMethodStatus::Active,
+ statuses,
None,
provider.get_account().storage_scheme,
)
@@ -3709,6 +3824,13 @@ pub async fn retrieve_payment_method(
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Failed to fetch payment method by storage")?;
+ when(
+ payment_method.status == common_enums::PaymentMethodStatus::Inactive,
+ || {
+ Err(report!(errors::ApiErrorResponse::PaymentMethodNotFound)
+ .attach_printable("Payment method is inactive"))
+ },
+ )?;
let raw_payment_method_fetch_access = get_raw_payment_method_data_fetch_access(
db,
@@ -3756,6 +3878,7 @@ pub async fn retrieve_payment_method(
payment_method.customer_id.clone(),
raw_payment_method_data,
billing,
+ None,
)
.map(services::ApplicationResponse::Json)
}
@@ -4056,12 +4179,16 @@ pub async fn update_payment_method(
req: api::PaymentMethodUpdate,
payment_method_id: &id_type::GlobalPaymentMethodId,
) -> RouterResponse<api::PaymentMethodResponse> {
- let response = Box::pin(update_payment_method_core(
+ let update_request = DomainPaymentMethodUpdate::from(req);
+
+ let (response, _updated_payment_method) = Box::pin(update_payment_method_core(
&state,
&platform,
&profile,
- req,
+ update_request,
payment_method_id,
+ None,
+ None,
))
.await?;
@@ -4074,19 +4201,47 @@ pub async fn update_payment_method_core(
state: &SessionState,
platform: &domain::Platform,
profile: &domain::Profile,
- request: api::PaymentMethodUpdate,
+ request: DomainPaymentMethodUpdate,
payment_method_id: &id_type::GlobalPaymentMethodId,
-) -> RouterResult<api::PaymentMethodResponse> {
- let mut handler = pm_types::PaymentMethodUpdateHandler::generate(
- state,
- platform,
- profile,
- request,
- payment_method_id,
- )
+ existing_payment_method: Option<domain::PaymentMethod>,
+ network_tokenization_resp: Option<NetworkTokenPaymentMethodDetails>,
+) -> RouterResult<(api::PaymentMethodResponse, domain::PaymentMethod)> {
+ let mut handler = match existing_payment_method {
+ Some(payment_method) => {
+ let handler = pm_types::PaymentMethodUpdateHandler {
+ platform,
+ profile,
+ request,
+ payment_method,
+ state,
+ };
+ handler.validate()?;
+ handler
+ }
+ None => pm_types::PaymentMethodUpdateHandler::generate(
+ state,
+ platform,
+ profile,
+ request,
+ payment_method_id,
+ )
+ .await
+ .attach_printable("Failed to generate PaymentMethodUpdateHandler")?,
+ };
+
+ Box::pin(execute_payment_method_update_handler(
+ &mut handler,
+ network_tokenization_resp,
+ ))
.await
- .attach_printable("Failed to generate PaymentMethodUpdateHandler")?;
+}
+#[cfg(feature = "v2")]
+#[instrument(skip_all)]
+async fn execute_payment_method_update_handler(
+ handler: &mut pm_types::PaymentMethodUpdateHandler<'_>,
+ network_tokenization_resp: Option<NetworkTokenPaymentMethodDetails>,
+) -> RouterResult<(api::PaymentMethodResponse, domain::PaymentMethod)> {
let card_cvc_details = handler
.update_cvc_if_required()
.await
@@ -4098,7 +4253,7 @@ pub async fn update_payment_method_core(
.attach_printable("Failed to perform vaulting operations for payment method update")?;
handler
- .update_payment_method_if_required(vaulting_data, vaulting_resp)
+ .update_payment_method_if_required(vaulting_data, vaulting_resp, network_tokenization_resp)
.await
.attach_printable("Failed to update payment method in db")?;
@@ -4106,7 +4261,7 @@ pub async fn update_payment_method_core(
.generate_response(card_cvc_details)
.attach_printable("Failed to generate response for payment method update")?;
- Ok(response)
+ Ok((response, handler.payment_method.clone()))
}
#[cfg(feature = "v2")]
@@ -4397,6 +4552,7 @@ pub async fn payment_methods_session_create(
associated_payment: None,
associated_token_id: None,
storage_type: request.storage_type,
+ keep_alive: request.keep_alive.unwrap_or_default(),
};
db.insert_payment_methods_session(
@@ -4631,12 +4787,17 @@ pub async fn payment_methods_session_update_payment_method(
"Failed to update payment method session with associated payment methods",
)?;
- let update_response = Box::pin(update_payment_method_core(
+ let update_request =
+ DomainPaymentMethodUpdate::from(request.payment_method_update_request.clone());
+
+ let (update_response, _updated_payment_method) = Box::pin(update_payment_method_core(
&state,
&platform,
&profile,
- request.payment_method_update_request.clone(),
+ update_request,
&payment_method_id,
+ None,
+ None,
))
.await
.attach_printable("Failed to update saved payment method")?;
@@ -5403,12 +5564,11 @@ impl<'a> pm_types::PaymentMethodUpdateHandler<'a> {
state: &'a SessionState,
platform: &'a domain::Platform,
profile: &'a domain::Profile,
- request: api::PaymentMethodUpdate,
+ request: DomainPaymentMethodUpdate,
payment_method_id: &'a id_type::GlobalPaymentMethodId,
) -> RouterResult<Self> {
- let db = state.store.as_ref();
-
- let payment_method = db
+ let payment_method = state
+ .store
.find_payment_method(
platform.get_provider().get_key_store(),
payment_method_id,
@@ -5424,19 +5584,17 @@ impl<'a> pm_types::PaymentMethodUpdateHandler<'a> {
payment_method,
state,
};
-
handler.validate()?;
-
Ok(handler)
}
fn validate(&self) -> RouterResult<()> {
let payment_method = &self.payment_method;
when(
- payment_method.status != enums::PaymentMethodStatus::Active,
+ payment_method.status == enums::PaymentMethodStatus::Inactive,
|| {
Err(errors::ApiErrorResponse::InvalidRequestData {
- message: "Only Active Payment Methods can be updated".to_string(),
+ message: "Inactive Payment Method cannot be updated".to_string(),
})
},
)?;
@@ -5444,6 +5602,29 @@ impl<'a> pm_types::PaymentMethodUpdateHandler<'a> {
Ok(())
}
+ fn is_card_metadata_changed_for_same_fingerprint(
+ &self,
+ vault_request_data: &domain::PaymentMethodVaultingData,
+ ) -> bool {
+ let updated_card_metadata = vault_request_data
+ .get_payment_methods_data()
+ .get_card_details()
+ .map(|card_details| (card_details.card_holder_name, card_details.nick_name));
+
+ let existing_card_metadata = self
+ .payment_method
+ .payment_method_data
+ .clone()
+ .and_then(|payment_method_data| payment_method_data.into_inner().get_card_details())
+ .map(|card_details| (card_details.card_holder_name, card_details.nick_name));
+
+ match (existing_card_metadata, updated_card_metadata) {
+ (Some(existing), Some(updated)) => existing != updated,
+ (None, Some(_)) => true,
+ _ => false,
+ }
+ }
+
pub async fn update_cvc_if_required(
&self,
) -> RouterResult<Option<payment_methods::CardCVCTokenStorageDetails>> {
@@ -5525,10 +5706,17 @@ impl<'a> pm_types::PaymentMethodUpdateHandler<'a> {
match is_stored_payment_method_same_as_in_request {
Some(true) => {
- logger::info!(
- "Payment method vault data is same as in request, skipping vault update"
- );
- Ok((None, None))
+ if self.is_card_metadata_changed_for_same_fingerprint(&vault_request_data) {
+ logger::info!(
+ "Payment method fingerprint is same, updating only payment method metadata in db"
+ );
+ Ok((Some(vault_request_data), None))
+ } else {
+ logger::info!(
+ "Payment method vault data is same as in request, skipping vault update"
+ );
+ Ok((None, None))
+ }
}
Some(false) | None => {
logger::info!("Payment method vault data is different from request, proceeding with vault update");
@@ -5557,11 +5745,23 @@ impl<'a> pm_types::PaymentMethodUpdateHandler<'a> {
&mut self,
vault_request_data: Option<domain::PaymentMethodVaultingData>,
vault_resp: Option<pm_types::AddVaultResponse>,
+ network_tokenization_resp: Option<NetworkTokenPaymentMethodDetails>,
) -> RouterResult<()> {
- if !self.request.is_payment_method_update_required() {
+ if !self.request.is_payment_method_update_required() && network_tokenization_resp.is_none()
+ {
return Ok(());
}
+ let pm_status = match self.request.acknowledgement_status {
+ Some(common_enums::AcknowledgementStatus::Authenticated) => {
+ Some(common_enums::PaymentMethodStatus::Active)
+ }
+ Some(common_enums::AcknowledgementStatus::Failed) => {
+ Some(common_enums::PaymentMethodStatus::Inactive)
+ }
+ None => None,
+ };
+
let db = self.state.store.as_ref();
let pm_update = create_pm_additional_data_update(
@@ -5577,11 +5777,11 @@ impl<'a> pm_types::PaymentMethodUpdateHandler<'a> {
&self.payment_method,
self.request.connector_token_details.clone(),
self.request.network_transaction_id.clone(),
+ network_tokenization_resp,
None,
None,
None,
- None,
- None,
+ pm_status,
)
.await
.attach_printable("Unable to create Payment method data")?;
@@ -5616,6 +5816,7 @@ impl<'a> pm_types::PaymentMethodUpdateHandler<'a> {
.payment_method_billing_address
.clone()
.map(|billing| billing.get_inner().clone().into()),
+ self.request.acknowledgement_status,
)?;
Ok(response)
diff --git a/crates/router/src/core/payment_methods/migration.rs b/crates/router/src/core/payment_methods/migration.rs
index 5a4b6f9047..36905503c3 100644
--- a/crates/router/src/core/payment_methods/migration.rs
+++ b/crates/router/src/core/payment_methods/migration.rs
@@ -5,7 +5,7 @@ use csv::Reader;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
api::ApplicationResponse, errors::api_error_response as errors,
- payment_methods::PaymentMethodUpdate, platform,
+ payment_methods::StoragePaymentMethodUpdate as PaymentMethodUpdate, platform,
};
use masking::{ExposeInterface, PeekInterface};
use payment_methods::core::migration::MerchantConnectorValidator;
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index ed62ae6069..6fbbd9b66f 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -577,6 +577,7 @@ pub fn generate_pm_vaulting_req_from_update_request(
}
#[cfg(feature = "v2")]
+#[allow(clippy::too_many_arguments)]
pub fn generate_payment_method_response(
payment_method: &domain::PaymentMethod,
single_use_token: &Option<payment_method_data::SingleUsePaymentMethodToken>,
@@ -585,6 +586,7 @@ pub fn generate_payment_method_response(
customer_id: Option<id_type::GlobalCustomerId>,
raw_payment_method_data: Option<api_models::payment_methods::RawPaymentMethodData>,
billing: Option<api::Address>,
+ acknowledgement_status: Option<common_enums::AcknowledgementStatus>,
) -> errors::RouterResult<api::PaymentMethodResponse> {
let pmd = payment_method
.payment_method_data
@@ -654,6 +656,7 @@ pub fn generate_payment_method_response(
.map(Secret::new),
raw_payment_method_data,
billing,
+ acknowledgement_status,
};
Ok(resp)
@@ -1053,6 +1056,7 @@ pub fn generate_payment_method_session_response(
card_cvc_token_storage,
payment_method_data,
sdk_authorization,
+ keep_alive: payment_method_session.keep_alive,
}
}
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index bbfd6a27fd..3cba1ce92a 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -1219,6 +1219,15 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
.await?;
logger::info!("Payment method fetched from PM Modular Service.");
+ utils::when(
+ pm_info.payment_method.0.customer_id
+ != req.customer_id.clone().get_required_value("customer_id")?,
+ || {
+ logger::info!("Payment method id does not belong to the customer id provided in the request.");
+ Err(errors::ApiErrorResponse::PaymentMethodNotFound)
+ },
+ )?;
+
Some(pm_info)
} else {
None
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 8b9c6bfd64..88037512b3 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -877,6 +877,15 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
.await?;
logger::info!("Payment method fetched from PM Modular Service.");
+ utils::when(
+ pm_info.payment_method.0.customer_id
+ != req.customer_id.clone().get_required_value("customer_id")?,
+ || {
+ logger::info!("Payment method id does not belong to the customer id provided in the request.");
+ Err(errors::ApiErrorResponse::PaymentMethodNotFound)
+ },
+ )?;
+
Some(pm_info)
} else {
None
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index b0f0cfff19..ea2bbb99a5 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -178,19 +178,24 @@ where
}
_ => None,
});
-
- // #4 - Build connector token details only when a mandate reference is available.
+ let acknowledgement_status = if resp.status.should_update_payment_method() {
+ Some(common_enums::AcknowledgementStatus::Authenticated)
+ } else {
+ None
+ };
let payload = UpdatePaymentMethodV1Payload {
payment_method_data,
connector_token_details,
network_transaction_id: network_transaction_id.map(masking::Secret::new),
+ acknowledgement_status,
};
// #5 - Execute the modular payment-method update call if there is something to be updated
if payload.payment_method_data.is_some()
|| payload.connector_token_details.is_some()
|| payload.network_transaction_id.is_some()
+ || payload.acknowledgement_status.is_some()
{
match call_modular_payment_method_update(
state,
@@ -3580,14 +3585,22 @@ impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::SetupMandateRe
connector_token_details_for_payment_method_update,
),
network_transaction_id: None,
+ acknowledgement_status: None, //based on the response from the connector we can decide the acknowledgement status to be sent to payment method service
};
+ let payment_method_update_request =
+ hyperswitch_domain_models::payment_methods::PaymentMethodUpdate::from(
+ payment_method_update_request,
+ );
+
Box::pin(payment_methods::update_payment_method_core(
state,
platform,
business_profile,
payment_method_update_request,
&payment_method_id,
+ None,
+ None,
))
.await
.attach_printable("Failed to update payment method")?;
diff --git a/crates/router/src/core/payments/payment_methods.rs b/crates/router/src/core/payments/payment_methods.rs
index 99a64b3b5d..aa1c1a4672 100644
--- a/crates/router/src/core/payments/payment_methods.rs
+++ b/crates/router/src/core/payments/payment_methods.rs
@@ -60,6 +60,7 @@ pub async fn list_payment_methods(
&state,
platform.get_provider(),
customer_id,
+ false, // include_new field is false because we want to fetch saved payment methods for the customer, and not fetch new payment methods based on the current request
)
.await?,
),
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 7b024652c2..2160b73338 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -2183,6 +2183,28 @@ impl PaymentMethodInterface for KafkaStore {
.await
}
+ #[cfg(feature = "v2")]
+ async fn find_payment_method_by_global_customer_id_merchant_id_statuses(
+ &self,
+ key_store: &domain::MerchantKeyStore,
+ customer_id: &id_type::GlobalCustomerId,
+ merchant_id: &id_type::MerchantId,
+ statuses: Vec<common_enums::PaymentMethodStatus>,
+ limit: Option<i64>,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> {
+ self.diesel_store
+ .find_payment_method_by_global_customer_id_merchant_id_statuses(
+ key_store,
+ customer_id,
+ merchant_id,
+ statuses,
+ limit,
+ storage_scheme,
+ )
+ .await
+ }
+
#[cfg(feature = "v1")]
async fn get_payment_method_count_by_customer_id_merchant_id_status(
&self,
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index eb5c45d517..0fb285168e 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -866,11 +866,12 @@ pub async fn list_customer_payment_method_api(
state,
&req,
payload,
- |state, auth: auth::AuthenticationData, _, _| {
+ |state, auth: auth::AuthenticationData, payload, _| {
payment_methods_routes::list_saved_payment_methods_for_customer(
state,
auth.platform.get_provider().clone(),
customer_id.clone(),
+ payload.include_new.unwrap_or(false),
)
},
&*auth_type,
diff --git a/crates/router/src/types/payment_methods.rs b/crates/router/src/types/payment_methods.rs
index e01e2e26d8..17e98fefb7 100644
--- a/crates/router/src/types/payment_methods.rs
+++ b/crates/router/src/types/payment_methods.rs
@@ -454,7 +454,7 @@ pub struct PanMetadataUpdateBody {
pub struct PaymentMethodUpdateHandler<'a> {
pub platform: &'a hyperswitch_domain_models::platform::Platform,
pub profile: &'a hyperswitch_domain_models::business_profile::Profile,
- pub request: api_models::payment_methods::PaymentMethodUpdate,
+ pub request: hyperswitch_domain_models::payment_methods::PaymentMethodUpdate,
pub payment_method: hyperswitch_domain_models::payment_methods::PaymentMethod,
pub state: &'a crate::routes::app::SessionState,
}
diff --git a/crates/storage_impl/src/payment_method.rs b/crates/storage_impl/src/payment_method.rs
index 33c0d68c0a..10e63761e9 100644
--- a/crates/storage_impl/src/payment_method.rs
+++ b/crates/storage_impl/src/payment_method.rs
@@ -354,6 +354,29 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {
.await
}
+ #[cfg(feature = "v2")]
+ #[instrument(skip_all)]
+ async fn find_payment_method_by_global_customer_id_merchant_id_statuses(
+ &self,
+ key_store: &MerchantKeyStore,
+ customer_id: &id_type::GlobalCustomerId,
+ merchant_id: &id_type::MerchantId,
+ statuses: Vec<common_enums::PaymentMethodStatus>,
+ limit: Option<i64>,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
+ self.router_store
+ .find_payment_method_by_global_customer_id_merchant_id_statuses(
+ key_store,
+ customer_id,
+ merchant_id,
+ statuses,
+ limit,
+ storage_scheme,
+ )
+ .await
+ }
+
#[cfg(feature = "v1")]
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
@@ -645,6 +668,31 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
.await
}
+ #[cfg(feature = "v2")]
+ #[instrument(skip_all)]
+ async fn find_payment_method_by_global_customer_id_merchant_id_statuses(
+ &self,
+ key_store: &MerchantKeyStore,
+ customer_id: &id_type::GlobalCustomerId,
+ merchant_id: &id_type::MerchantId,
+ statuses: Vec<common_enums::PaymentMethodStatus>,
+ limit: Option<i64>,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
+ let conn = pg_connection_read(self).await?;
+ self.find_resources(
+ key_store,
+ PaymentMethod::find_by_global_customer_id_merchant_id_statuses(
+ &conn,
+ customer_id,
+ merchant_id,
+ statuses,
+ limit,
+ ),
+ )
+ .await
+ }
+
#[cfg(feature = "v1")]
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
@@ -895,6 +943,27 @@ impl PaymentMethodInterface for MockDb {
.await
}
+ #[cfg(feature = "v2")]
+ async fn find_payment_method_by_global_customer_id_merchant_id_statuses(
+ &self,
+ key_store: &MerchantKeyStore,
+ customer_id: &id_type::GlobalCustomerId,
+ merchant_id: &id_type::MerchantId,
+ statuses: Vec<common_enums::PaymentMethodStatus>,
+ _limit: Option<i64>,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> 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 error_message = "cannot find payment method".to_string();
+ self.get_resources(key_store, payment_methods, find_pm_by, error_message)
+ .await
+ }
+
#[cfg(feature = "v1")]
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,