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(router): add `encrypted_payment_method_data` to payment_attempt to conditionally persist sensitive additional payment_method_data (#10484)

Sai Harsha Vardhan6c9202fc1458
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 3cedcdc10f..f9073d9773 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2416,6 +2416,26 @@ impl PaymentMethod {
| Self::MobilePayment => false,
}
}
+
+ pub fn is_additional_payment_method_data_sensitive(&self) -> bool {
+ match self {
+ Self::BankRedirect => true,
+ Self::Card
+ | Self::CardRedirect
+ | Self::PayLater
+ | Self::Wallet
+ | Self::GiftCard
+ | Self::BankTransfer
+ | Self::Crypto
+ | Self::BankDebit
+ | Self::Reward
+ | Self::RealTimePayment
+ | Self::Upi
+ | Self::Voucher
+ | Self::OpenBanking
+ | Self::MobilePayment => false,
+ }
+ }
}
/// Indicates the gateway system through which the payment is processed.
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index 20f49c2d34..30e8df2f79 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -117,6 +117,7 @@ pub struct PaymentAttempt {
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub extended_authorization_last_applied_at: Option<PrimitiveDateTime>,
pub tokenization: Option<common_enums::Tokenization>,
+ pub encrypted_payment_method_data: Option<common_utils::encryption::Encryption>,
#[diesel(deserialize_as = RequiredFromNullable<storage_enums::PaymentMethod>)]
pub payment_method_type_v2: storage_enums::PaymentMethod,
pub connector_payment_id: Option<ConnectorTransactionId>,
@@ -242,6 +243,7 @@ pub struct PaymentAttempt {
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub extended_authorization_last_applied_at: Option<PrimitiveDateTime>,
pub tokenization: Option<common_enums::Tokenization>,
+ pub encrypted_payment_method_data: Option<common_utils::encryption::Encryption>,
}
#[cfg(feature = "v1")]
@@ -389,6 +391,7 @@ pub struct PaymentAttemptNew {
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub extended_authorization_last_applied_at: Option<PrimitiveDateTime>,
pub tokenization: Option<common_enums::Tokenization>,
+ pub encrypted_payment_method_data: Option<common_utils::encryption::Encryption>,
}
#[cfg(feature = "v1")]
@@ -478,6 +481,7 @@ pub struct PaymentAttemptNew {
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub extended_authorization_last_applied_at: Option<PrimitiveDateTime>,
pub tokenization: Option<common_enums::Tokenization>,
+ pub encrypted_payment_method_data: Option<common_utils::encryption::Encryption>,
}
#[cfg(feature = "v1")]
@@ -611,6 +615,7 @@ pub enum PaymentAttemptUpdate {
extended_authorization_last_applied_at: Option<PrimitiveDateTime>,
tokenization: Option<common_enums::Tokenization>,
payment_method_data: Option<serde_json::Value>,
+ encrypted_payment_method_data: Option<common_utils::encryption::Encryption>,
connector_mandate_detail: Option<ConnectorMandateReferenceId>,
charges: Option<common_types::payments::ConnectorChargeResponseData>,
setup_future_usage_applied: Option<storage_enums::FutureUsage>,
@@ -644,6 +649,7 @@ pub enum PaymentAttemptUpdate {
unified_message: Option<Option<String>>,
connector_transaction_id: Option<String>,
payment_method_data: Option<serde_json::Value>,
+ encrypted_payment_method_data: Option<common_utils::encryption::Encryption>,
authentication_type: Option<storage_enums::AuthenticationType>,
issuer_error_code: Option<String>,
issuer_error_message: Option<String>,
@@ -1056,6 +1062,7 @@ impl PaymentAttemptUpdateInternal {
attempts_group_id: source.attempts_group_id,
is_stored_credential: source.is_stored_credential,
authorized_amount: source.authorized_amount,
+ encrypted_payment_method_data: source.encrypted_payment_method_data,
}
}
}
@@ -1082,6 +1089,7 @@ pub struct PaymentAttemptUpdateInternal {
pub error_code: Option<Option<String>>,
pub connector_metadata: Option<serde_json::Value>,
pub payment_method_data: Option<serde_json::Value>,
+ pub encrypted_payment_method_data: Option<common_utils::encryption::Encryption>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub payment_experience: Option<storage_enums::PaymentExperience>,
pub business_sub_label: Option<String>,
@@ -1316,6 +1324,7 @@ impl PaymentAttemptUpdate {
extended_authorization_applied,
extended_authorization_last_applied_at,
tokenization,
+ encrypted_payment_method_data,
card_discovery,
charges,
issuer_error_code,
@@ -1350,6 +1359,8 @@ impl PaymentAttemptUpdate {
error_code: error_code.unwrap_or(source.error_code),
connector_metadata: connector_metadata.or(source.connector_metadata),
payment_method_data: payment_method_data.or(source.payment_method_data),
+ encrypted_payment_method_data: encrypted_payment_method_data
+ .or(source.encrypted_payment_method_data),
payment_method_type: payment_method_type.or(source.payment_method_type),
payment_experience: payment_experience.or(source.payment_experience),
business_sub_label: business_sub_label.or(source.business_sub_label),
@@ -2754,6 +2765,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential: None,
request_extended_authorization: None,
authorized_amount: None,
+ encrypted_payment_method_data: None,
},
PaymentAttemptUpdate::AuthenticationTypeUpdate {
authentication_type,
@@ -2826,6 +2838,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential: None,
request_extended_authorization: None,
authorized_amount: None,
+ encrypted_payment_method_data: None,
},
PaymentAttemptUpdate::ConfirmUpdate {
amount,
@@ -2935,6 +2948,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential,
request_extended_authorization,
authorized_amount: None,
+ encrypted_payment_method_data: None,
},
PaymentAttemptUpdate::VoidUpdate {
status,
@@ -3008,6 +3022,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential: None,
request_extended_authorization: None,
authorized_amount: None,
+ encrypted_payment_method_data: None,
},
PaymentAttemptUpdate::RejectUpdate {
status,
@@ -3082,6 +3097,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential: None,
request_extended_authorization: None,
authorized_amount: None,
+ encrypted_payment_method_data: None,
},
PaymentAttemptUpdate::BlocklistUpdate {
status,
@@ -3156,6 +3172,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential: None,
request_extended_authorization: None,
authorized_amount: None,
+ encrypted_payment_method_data: None,
},
PaymentAttemptUpdate::ConnectorMandateDetailUpdate {
connector_mandate_detail,
@@ -3229,6 +3246,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential: None,
request_extended_authorization: None,
authorized_amount: None,
+ encrypted_payment_method_data: None,
},
PaymentAttemptUpdate::PaymentMethodDetailsUpdate {
payment_method_id,
@@ -3301,6 +3319,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential: None,
request_extended_authorization: None,
authorized_amount: None,
+ encrypted_payment_method_data: None,
},
PaymentAttemptUpdate::ResponseUpdate {
status,
@@ -3326,6 +3345,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
extended_authorization_last_applied_at,
tokenization,
payment_method_data,
+ encrypted_payment_method_data,
connector_mandate_detail,
charges,
setup_future_usage_applied,
@@ -3406,6 +3426,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential: None,
request_extended_authorization: None,
authorized_amount,
+ encrypted_payment_method_data,
}
}
PaymentAttemptUpdate::ErrorUpdate {
@@ -3420,6 +3441,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
unified_message,
connector_transaction_id,
payment_method_data,
+ encrypted_payment_method_data,
authentication_type,
issuer_error_code,
issuer_error_message,
@@ -3498,6 +3520,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential: None,
request_extended_authorization: None,
authorized_amount: None,
+ encrypted_payment_method_data,
}
}
PaymentAttemptUpdate::StatusUpdate { status, updated_by } => Self {
@@ -3568,6 +3591,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential: None,
request_extended_authorization: None,
authorized_amount: None,
+ encrypted_payment_method_data: None,
},
PaymentAttemptUpdate::UpdateTrackers {
payment_token,
@@ -3648,6 +3672,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential,
request_extended_authorization: None,
authorized_amount: None,
+ encrypted_payment_method_data: None,
},
PaymentAttemptUpdate::UnresolvedResponseUpdate {
status,
@@ -3733,6 +3758,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential: None,
request_extended_authorization: None,
authorized_amount: None,
+ encrypted_payment_method_data: None,
}
}
PaymentAttemptUpdate::PreprocessingUpdate {
@@ -3817,6 +3843,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential: None,
request_extended_authorization: None,
authorized_amount: None,
+ encrypted_payment_method_data: None,
}
}
PaymentAttemptUpdate::CaptureUpdate {
@@ -3891,6 +3918,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential: None,
request_extended_authorization: None,
authorized_amount: None,
+ encrypted_payment_method_data: None,
},
PaymentAttemptUpdate::AmountToCaptureUpdate {
status,
@@ -3964,6 +3992,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential: None,
request_extended_authorization: None,
authorized_amount: None,
+ encrypted_payment_method_data: None,
},
PaymentAttemptUpdate::ConnectorResponse {
authentication_data,
@@ -4046,6 +4075,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential: None,
request_extended_authorization: None,
authorized_amount: None,
+ encrypted_payment_method_data: None,
}
}
PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate {
@@ -4119,6 +4149,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential: None,
request_extended_authorization: None,
authorized_amount: None,
+ encrypted_payment_method_data: None,
},
PaymentAttemptUpdate::AuthenticationUpdate {
status,
@@ -4194,6 +4225,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential: None,
request_extended_authorization: None,
authorized_amount: None,
+ encrypted_payment_method_data: None,
},
PaymentAttemptUpdate::ManualUpdate {
status,
@@ -4279,6 +4311,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential: None,
request_extended_authorization: None,
authorized_amount: None,
+ encrypted_payment_method_data: None,
}
}
PaymentAttemptUpdate::PostSessionTokensUpdate {
@@ -4352,6 +4385,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
is_stored_credential: None,
request_extended_authorization: None,
authorized_amount: None,
+ encrypted_payment_method_data: None,
},
}
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 72029168ea..705746a668 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1096,6 +1096,7 @@ diesel::table! {
extended_authorization_last_applied_at -> Nullable<Timestamp>,
#[max_length = 64]
tokenization -> Nullable<Varchar>,
+ encrypted_payment_method_data -> Nullable<Bytea>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 535efc0f40..68638555b8 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -1038,6 +1038,7 @@ diesel::table! {
extended_authorization_last_applied_at -> Nullable<Timestamp>,
#[max_length = 64]
tokenization -> Nullable<Varchar>,
+ encrypted_payment_method_data -> Nullable<Bytea>,
payment_method_type_v2 -> Nullable<Varchar>,
#[max_length = 128]
connector_payment_id -> Nullable<Varchar>,
diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs
index 3b28454798..8c0101f3d3 100644
--- a/crates/diesel_models/src/user/sample_data.rs
+++ b/crates/diesel_models/src/user/sample_data.rs
@@ -177,6 +177,7 @@ pub struct PaymentAttemptBatchNew {
pub payment_experience: Option<PaymentExperience>,
pub payment_method_type: Option<PaymentMethodType>,
pub payment_method_data: Option<serde_json::Value>,
+ pub encrypted_payment_method_data: Option<common_utils::encryption::Encryption>,
pub business_sub_label: Option<String>,
pub straight_through_algorithm: Option<serde_json::Value>,
pub preprocessing_step_id: Option<String>,
@@ -272,6 +273,7 @@ impl PaymentAttemptBatchNew {
.and_then(|network| network.as_str())
.map(|network| network.to_string()),
payment_method_data: self.payment_method_data,
+ encrypted_payment_method_data: self.encrypted_payment_method_data,
business_sub_label: self.business_sub_label,
straight_through_algorithm: self.straight_through_algorithm,
preprocessing_step_id: self.preprocessing_step_id,
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 359f7c0d14..3d27367ca5 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -8,16 +8,15 @@ use common_types::primitive_wrappers::{
ExtendedAuthorizationAppliedBool, OvercaptureEnabledBool, RequestExtendedAuthorizationBool,
};
#[cfg(feature = "v2")]
+use common_utils::ext_traits::Encode;
use common_utils::{
- crypto::Encryptable, encryption::Encryption, ext_traits::Encode,
- types::keymanager::ToEncryptable,
-};
-use common_utils::{
+ crypto::Encryptable,
+ encryption::Encryption,
errors::{CustomResult, ValidationError},
ext_traits::{OptionExt, ValueExt},
id_type, pii,
types::{
- keymanager::{self, KeyManagerState},
+ keymanager::{self, KeyManagerState, ToEncryptable},
ConnectorTransactionId, ConnectorTransactionIdTrait, CreatedBy, MinorUnit,
},
};
@@ -34,17 +33,13 @@ use diesel_models::{
PaymentAttemptRecoveryData as DieselPassiveChurnRecoveryData,
};
use error_stack::ResultExt;
-#[cfg(feature = "v2")]
-use masking::PeekInterface;
-use masking::Secret;
+use masking::{PeekInterface, Secret};
#[cfg(feature = "v1")]
use router_env::logger;
-#[cfg(feature = "v2")]
use rustc_hash::FxHashMap;
#[cfg(feature = "v1")]
use serde::Deserialize;
use serde::Serialize;
-#[cfg(feature = "v2")]
use serde_json::Value;
use time::PrimitiveDateTime;
use url::Url;
@@ -52,14 +47,13 @@ use url::Url;
#[cfg(all(feature = "v1", feature = "olap"))]
use super::PaymentIntent;
#[cfg(feature = "v2")]
+use crate::{address::Address, consts, router_response_types};
use crate::{
- address::Address,
- consts,
+ behaviour, errors,
merchant_key_store::MerchantKeyStore,
- router_response_types,
type_encryption::{crypto_operation, CryptoOperation},
+ ForeignIDRef,
};
-use crate::{behaviour, errors, ForeignIDRef};
#[cfg(feature = "v1")]
use crate::{
mandates::{MandateDataType, MandateDetails},
@@ -72,8 +66,9 @@ pub trait PaymentAttemptInterface {
#[cfg(feature = "v1")]
async fn insert_payment_attempt(
&self,
- payment_attempt: PaymentAttemptNew,
+ payment_attempt: PaymentAttempt,
storage_scheme: storage_enums::MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v2")]
@@ -90,6 +85,7 @@ pub trait PaymentAttemptInterface {
this: PaymentAttempt,
payment_attempt: PaymentAttemptUpdate,
storage_scheme: storage_enums::MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v2")]
@@ -108,6 +104,7 @@ pub trait PaymentAttemptInterface {
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v1")]
@@ -116,6 +113,7 @@ pub trait PaymentAttemptInterface {
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v1")]
@@ -124,6 +122,7 @@ pub trait PaymentAttemptInterface {
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v2")]
@@ -140,6 +139,7 @@ pub trait PaymentAttemptInterface {
merchant_id: &id_type::MerchantId,
connector_txn_id: &str,
storage_scheme: storage_enums::MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v2")]
@@ -158,6 +158,7 @@ pub trait PaymentAttemptInterface {
merchant_id: &id_type::MerchantId,
attempt_id: &str,
storage_scheme: storage_enums::MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v1")]
@@ -166,6 +167,7 @@ pub trait PaymentAttemptInterface {
attempt_id: &str,
merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v2")]
@@ -190,6 +192,7 @@ pub trait PaymentAttemptInterface {
preprocessing_id: &str,
merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v1")]
@@ -198,6 +201,7 @@ pub trait PaymentAttemptInterface {
merchant_id: &id_type::MerchantId,
payment_id: &id_type::PaymentId,
storage_scheme: storage_enums::MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> error_stack::Result<Vec<PaymentAttempt>, Self::Error>;
#[cfg(all(feature = "v1", feature = "olap"))]
@@ -956,7 +960,7 @@ impl PaymentAttempt {
}
#[cfg(feature = "v1")]
-#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
+#[derive(Clone, Debug, PartialEq, Serialize, router_derive::ToEncryption)]
pub struct PaymentAttempt {
pub payment_id: id_type::PaymentId,
pub merchant_id: id_type::MerchantId,
@@ -985,15 +989,15 @@ pub struct PaymentAttempt {
pub cancellation_reason: Option<String>,
pub amount_to_capture: Option<MinorUnit>,
pub mandate_id: Option<String>,
- pub browser_info: Option<serde_json::Value>,
+ pub browser_info: Option<Value>,
pub error_code: Option<String>,
pub payment_token: Option<String>,
- pub connector_metadata: Option<serde_json::Value>,
+ pub connector_metadata: Option<Value>,
pub payment_experience: Option<storage_enums::PaymentExperience>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
- pub payment_method_data: Option<serde_json::Value>,
+ pub payment_method_data: Option<Value>,
pub business_sub_label: Option<String>,
- pub straight_through_algorithm: Option<serde_json::Value>,
+ pub straight_through_algorithm: Option<Value>,
pub preprocessing_step_id: Option<String>,
// providing a location to store mandate details intermediately for transaction
pub mandate_details: Option<MandateDataType>,
@@ -1003,7 +1007,7 @@ pub struct PaymentAttempt {
pub connector_response_reference_id: Option<String>,
pub amount_capturable: MinorUnit,
pub updated_by: String,
- pub authentication_data: Option<serde_json::Value>,
+ pub authentication_data: Option<Value>,
pub encoded_data: Option<String>,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub unified_code: Option<String>,
@@ -1044,6 +1048,8 @@ pub struct PaymentAttempt {
pub is_stored_credential: Option<bool>,
/// stores the authorized amount in case of partial authorization
pub authorized_amount: Option<MinorUnit>,
+ #[encrypt(ty = Value)]
+ pub encrypted_payment_method_data: Option<Encryptable<pii::SecretSerdeValue>>,
}
#[cfg(feature = "v1")]
@@ -1310,10 +1316,10 @@ impl PaymentAttempt {
}
pub fn get_payment_method_data(&self) -> Option<api_models::payments::AdditionalPaymentData> {
- self.payment_method_data
+ self.check_and_get_payment_method_data_based_on_encryption_strategy()
.clone()
.and_then(|data| match data {
- serde_json::Value::Null => None,
+ Value::Null => None,
_ => Some(data.parse_value("AdditionalPaymentData")),
})
.transpose()
@@ -1334,7 +1340,7 @@ impl PaymentAttempt {
}
}
- fn get_connector_metadata_value(&self) -> Option<&serde_json::Value> {
+ fn get_connector_metadata_value(&self) -> Option<&Value> {
self.connector_metadata.as_ref()
}
pub fn get_upi_next_action(
@@ -1398,6 +1404,23 @@ impl PaymentAttempt {
_ => None,
})
}
+
+ pub fn check_and_get_payment_method_data_based_on_encryption_strategy(&self) -> Option<Value> {
+ if self
+ .payment_method
+ .map(|payment_method| payment_method.is_additional_payment_method_data_sensitive())
+ .unwrap_or(false)
+ {
+ self.encrypted_payment_method_data
+ .clone()
+ .map(|encrypted_payment_method_data| {
+ encrypted_payment_method_data.get_inner().peek().clone()
+ })
+ .or(self.payment_method_data.clone())
+ } else {
+ self.payment_method_data.clone()
+ }
+ }
}
#[derive(Clone, Debug, Eq, PartialEq)]
@@ -1411,91 +1434,7 @@ pub struct PaymentListFilters {
}
#[cfg(feature = "v1")]
-#[derive(Clone, Debug, Serialize, Deserialize)]
-pub struct PaymentAttemptNew {
- pub payment_id: id_type::PaymentId,
- pub merchant_id: id_type::MerchantId,
- pub attempt_id: String,
- pub status: storage_enums::AttemptStatus,
- /// amount + surcharge_amount + tax_amount
- /// This field will always be derived before updating in the Database
- pub net_amount: NetAmount,
- pub currency: Option<storage_enums::Currency>,
- // pub auto_capture: Option<bool>,
- pub save_to_locker: Option<bool>,
- pub connector: Option<String>,
- pub error_message: Option<String>,
- pub offer_amount: Option<MinorUnit>,
- pub payment_method_id: Option<String>,
- pub payment_method: Option<storage_enums::PaymentMethod>,
- pub capture_method: Option<storage_enums::CaptureMethod>,
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
- pub capture_on: Option<PrimitiveDateTime>,
- pub confirm: bool,
- pub authentication_type: Option<storage_enums::AuthenticationType>,
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
- pub created_at: Option<PrimitiveDateTime>,
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
- pub modified_at: Option<PrimitiveDateTime>,
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
- pub last_synced: Option<PrimitiveDateTime>,
- pub cancellation_reason: Option<String>,
- pub amount_to_capture: Option<MinorUnit>,
- pub mandate_id: Option<String>,
- pub browser_info: Option<serde_json::Value>,
- pub payment_token: Option<String>,
- pub error_code: Option<String>,
- pub connector_metadata: Option<serde_json::Value>,
- pub payment_experience: Option<storage_enums::PaymentExperience>,
- pub payment_method_type: Option<storage_enums::PaymentMethodType>,
- pub payment_method_data: Option<serde_json::Value>,
- pub business_sub_label: Option<String>,
- pub straight_through_algorithm: Option<serde_json::Value>,
- pub preprocessing_step_id: Option<String>,
- pub mandate_details: Option<MandateDataType>,
- pub error_reason: Option<String>,
- pub connector_response_reference_id: Option<String>,
- pub multiple_capture_count: Option<i16>,
- pub amount_capturable: MinorUnit,
- pub updated_by: String,
- pub authentication_data: Option<serde_json::Value>,
- pub encoded_data: Option<String>,
- pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
- pub unified_code: Option<String>,
- pub unified_message: Option<String>,
- pub external_three_ds_authentication_attempted: Option<bool>,
- pub authentication_connector: Option<String>,
- pub authentication_id: Option<id_type::AuthenticationId>,
- pub mandate_data: Option<MandateDetails>,
- pub payment_method_billing_address_id: Option<String>,
- pub fingerprint_id: Option<String>,
- pub client_source: Option<String>,
- pub client_version: Option<String>,
- pub customer_acceptance: Option<pii::SecretSerdeValue>,
- pub profile_id: id_type::ProfileId,
- pub organization_id: id_type::OrganizationId,
- pub connector_mandate_detail: Option<ConnectorMandateReferenceId>,
- pub tokenization: Option<common_enums::Tokenization>,
- pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
- pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>,
- pub capture_before: Option<PrimitiveDateTime>,
- pub extended_authorization_last_applied_at: Option<PrimitiveDateTime>,
- pub card_discovery: Option<common_enums::CardDiscovery>,
- /// merchant who owns the credentials of the processor, i.e. processor owner
- pub processor_merchant_id: id_type::MerchantId,
- /// merchant or user who invoked the resource-based API (identifier) and the source (Api, Jwt(Dashboard))
- pub created_by: Option<CreatedBy>,
- pub setup_future_usage_applied: Option<storage_enums::FutureUsage>,
- pub routing_approach: Option<storage_enums::RoutingApproach>,
- pub connector_request_reference_id: Option<String>,
- pub network_transaction_id: Option<String>,
- pub network_details: Option<NetworkDetails>,
- pub is_stored_credential: Option<bool>,
- pub authorized_amount: Option<MinorUnit>,
-}
-
-#[cfg(feature = "v1")]
-#[derive(Debug, Clone, Serialize, Deserialize)]
+#[derive(Debug, Clone, Serialize)]
pub enum PaymentAttemptUpdate {
Update {
net_amount: NetAmount,
@@ -1504,7 +1443,7 @@ pub enum PaymentAttemptUpdate {
authentication_type: Option<storage_enums::AuthenticationType>,
payment_method: Option<storage_enums::PaymentMethod>,
payment_token: Option<String>,
- payment_method_data: Option<serde_json::Value>,
+ payment_method_data: Option<Value>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
payment_experience: Option<storage_enums::PaymentExperience>,
business_sub_label: Option<String>,
@@ -1518,7 +1457,7 @@ pub enum PaymentAttemptUpdate {
UpdateTrackers {
payment_token: Option<String>,
connector: Option<String>,
- straight_through_algorithm: Option<serde_json::Value>,
+ straight_through_algorithm: Option<Value>,
amount_capturable: Option<MinorUnit>,
surcharge_amount: Option<MinorUnit>,
tax_amount: Option<MinorUnit>,
@@ -1538,14 +1477,14 @@ pub enum PaymentAttemptUpdate {
authentication_type: Option<storage_enums::AuthenticationType>,
capture_method: Option<storage_enums::CaptureMethod>,
payment_method: Option<storage_enums::PaymentMethod>,
- browser_info: Option<serde_json::Value>,
+ browser_info: Option<Value>,
connector: Option<String>,
payment_token: Option<String>,
- payment_method_data: Option<serde_json::Value>,
+ payment_method_data: Option<Value>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
payment_experience: Option<storage_enums::PaymentExperience>,
business_sub_label: Option<String>,
- straight_through_algorithm: Option<serde_json::Value>,
+ straight_through_algorithm: Option<Value>,
error_code: Option<Option<String>>,
error_message: Option<Option<String>>,
updated_by: String,
@@ -1602,7 +1541,7 @@ pub enum PaymentAttemptUpdate {
authentication_type: Option<storage_enums::AuthenticationType>,
payment_method_id: Option<String>,
mandate_id: Option<String>,
- connector_metadata: Option<serde_json::Value>,
+ connector_metadata: Option<Value>,
payment_token: Option<String>,
error_code: Option<Option<String>>,
error_message: Option<Option<String>>,
@@ -1610,14 +1549,15 @@ pub enum PaymentAttemptUpdate {
connector_response_reference_id: Option<String>,
amount_capturable: Option<MinorUnit>,
updated_by: String,
- authentication_data: Option<serde_json::Value>,
+ authentication_data: Option<Value>,
encoded_data: Option<String>,
unified_code: Option<Option<String>>,
unified_message: Option<Option<String>>,
capture_before: Option<PrimitiveDateTime>,
extended_authorization_last_applied_at: Option<PrimitiveDateTime>,
extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>,
- payment_method_data: Option<serde_json::Value>,
+ payment_method_data: Option<Value>,
+ encrypted_payment_method_data: Option<Encryptable<pii::SecretSerdeValue>>,
connector_mandate_detail: Option<ConnectorMandateReferenceId>,
tokenization: Option<common_enums::Tokenization>,
charges: Option<common_types::payments::ConnectorChargeResponseData>,
@@ -1652,7 +1592,8 @@ pub enum PaymentAttemptUpdate {
unified_code: Option<Option<String>>,
unified_message: Option<Option<String>>,
connector_transaction_id: Option<String>,
- payment_method_data: Option<serde_json::Value>,
+ payment_method_data: Option<Value>,
+ encrypted_payment_method_data: Option<Encryptable<pii::SecretSerdeValue>>,
authentication_type: Option<storage_enums::AuthenticationType>,
issuer_error_code: Option<String>,
issuer_error_message: Option<String>,
@@ -1671,14 +1612,14 @@ pub enum PaymentAttemptUpdate {
PreprocessingUpdate {
status: storage_enums::AttemptStatus,
payment_method_id: Option<String>,
- connector_metadata: Option<serde_json::Value>,
+ connector_metadata: Option<Value>,
preprocessing_step_id: Option<String>,
connector_transaction_id: Option<String>,
connector_response_reference_id: Option<String>,
updated_by: String,
},
ConnectorResponse {
- authentication_data: Option<serde_json::Value>,
+ authentication_data: Option<Value>,
encoded_data: Option<String>,
connector_transaction_id: Option<String>,
connector: Option<String>,
@@ -1709,7 +1650,7 @@ pub enum PaymentAttemptUpdate {
},
PostSessionTokensUpdate {
updated_by: String,
- connector_metadata: Option<serde_json::Value>,
+ connector_metadata: Option<Value>,
},
}
@@ -1934,6 +1875,7 @@ impl PaymentAttemptUpdate {
extended_authorization_applied,
extended_authorization_last_applied_at,
payment_method_data,
+ encrypted_payment_method_data,
connector_mandate_detail,
tokenization,
charges,
@@ -1972,6 +1914,7 @@ impl PaymentAttemptUpdate {
network_transaction_id,
is_overcapture_enabled,
authorized_amount,
+ encrypted_payment_method_data: encrypted_payment_method_data.map(Encryption::from),
},
Self::UnresolvedResponseUpdate {
status,
@@ -2013,6 +1956,7 @@ impl PaymentAttemptUpdate {
issuer_error_code,
issuer_error_message,
network_details,
+ encrypted_payment_method_data,
} => DieselPaymentAttemptUpdate::ErrorUpdate {
connector,
status,
@@ -2029,6 +1973,7 @@ impl PaymentAttemptUpdate {
issuer_error_code,
issuer_error_message,
network_details,
+ encrypted_payment_method_data: encrypted_payment_method_data.map(Encryption::from),
},
Self::CaptureUpdate {
multiple_capture_count,
@@ -2363,14 +2308,15 @@ impl behaviour::Conversion for PaymentAttempt {
network_details: self.network_details,
is_stored_credential: self.is_stored_credential,
authorized_amount: self.authorized_amount,
+ encrypted_payment_method_data: self.encrypted_payment_method_data.map(Encryption::from),
})
}
async fn convert_back(
- _state: &KeyManagerState,
+ state: &KeyManagerState,
storage_model: Self::DstType,
- _key: &Secret<Vec<u8>>,
- _key_manager_identifier: keymanager::Identifier,
+ key: &Secret<Vec<u8>>,
+ key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
@@ -2379,6 +2325,25 @@ impl behaviour::Conversion for PaymentAttempt {
let connector_transaction_id = storage_model
.get_optional_connector_transaction_id()
.cloned();
+ let decrypted_data = crypto_operation(
+ state,
+ common_utils::type_name!(Self::DstType),
+ CryptoOperation::BatchDecrypt(EncryptedPaymentAttempt::to_encryptable(
+ EncryptedPaymentAttempt {
+ encrypted_payment_method_data: storage_model.encrypted_payment_method_data,
+ },
+ )),
+ key_manager_identifier,
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_batchoperation())?;
+
+ let decrypted_data = EncryptedPaymentAttempt::from_encryptable(decrypted_data)
+ .change_context(common_utils::errors::CryptoError::DecodingFailed)
+ .attach_printable("Invalid batch operation data")?;
+
+ let encrypted_payment_method_data = decrypted_data.encrypted_payment_method_data;
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
payment_id: storage_model.payment_id,
merchant_id: storage_model.merchant_id.clone(),
@@ -2469,6 +2434,7 @@ impl behaviour::Conversion for PaymentAttempt {
network_details: storage_model.network_details,
is_stored_credential: storage_model.is_stored_credential,
authorized_amount: storage_model.authorized_amount,
+ encrypted_payment_method_data,
})
}
.await
@@ -2565,6 +2531,7 @@ impl behaviour::Conversion for PaymentAttempt {
network_details: self.network_details,
is_stored_credential: self.is_stored_credential,
authorized_amount: self.authorized_amount,
+ encrypted_payment_method_data: self.encrypted_payment_method_data.map(Encryption::from),
})
}
}
@@ -2743,6 +2710,7 @@ impl behaviour::Conversion for PaymentAttempt {
is_stored_credential: None,
authorized_amount,
tokenization: None,
+ encrypted_payment_method_data: None,
})
}
@@ -3030,6 +2998,7 @@ impl behaviour::Conversion for PaymentAttempt {
attempts_group_id,
is_stored_credential: None,
authorized_amount,
+ encrypted_payment_method_data: None,
})
}
}
diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rs
index 7c7d301467..8721352555 100644
--- a/crates/router/src/core/blocklist/utils.rs
+++ b/crates/router/src/core/blocklist/utils.rs
@@ -430,6 +430,7 @@ where
payment_data.payment_attempt.clone(),
attempt_update,
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rs
index 013dd16e8a..e4a7c56992 100644
--- a/crates/router/src/core/disputes.rs
+++ b/crates/router/src/core/disputes.rs
@@ -85,6 +85,7 @@ pub async fn retrieve_dispute(
&dispute.attempt_id,
platform.get_processor().get_account().get_id(),
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -304,6 +305,7 @@ pub async fn accept_dispute(
&dispute.attempt_id,
platform.get_processor().get_account().get_id(),
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -427,6 +429,7 @@ pub async fn submit_evidence(
&dispute.attempt_id,
platform.get_processor().get_account().get_id(),
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/core/files/helpers.rs b/crates/router/src/core/files/helpers.rs
index c5cb6b5617..fd767fc066 100644
--- a/crates/router/src/core/files/helpers.rs
+++ b/crates/router/src/core/files/helpers.rs
@@ -334,6 +334,7 @@ pub async fn upload_and_get_provider_provider_file_id_profile_id(
&dispute.attempt_id,
platform.get_processor().get_account().get_id(),
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs
index 5c62f12178..27f4e147b0 100644
--- a/crates/router/src/core/fraud_check.rs
+++ b/crates/router/src/core/fraud_check.rs
@@ -841,6 +841,7 @@ pub async fn make_fulfillment_api_call(
&payment_intent.active_attempt.get_id(),
platform.get_processor().get_account().get_id(),
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
index bc2451a050..980340567d 100644
--- a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
+++ b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
@@ -586,6 +586,7 @@ where
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
frm_data.merchant_account.storage_scheme,
+ key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs
index f26a8f04ed..0b93618b20 100644
--- a/crates/router/src/core/payment_link.rs
+++ b/crates/router/src/core/payment_link.rs
@@ -216,6 +216,7 @@ pub async fn form_payment_link_data(
&merchant_id,
&attempt_id.clone(),
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -249,6 +250,7 @@ pub async fn form_payment_link_data(
&merchant_id,
&attempt_id.clone(),
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -848,6 +850,7 @@ pub async fn get_payment_link_status(
&merchant_id,
&attempt_id.clone(),
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 25001f364d..7e64920415 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -2736,6 +2736,7 @@ pub async fn list_payment_methods(
&pi.merchant_id,
&pi.active_attempt.get_id(),
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
@@ -3125,6 +3126,7 @@ pub async fn list_payment_methods(
payment_attempt.clone(),
attempt_update,
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -4545,6 +4547,7 @@ async fn perform_surcharge_ops(
platform.get_processor().get_account().get_id(),
&payment_intent.active_attempt.get_id(),
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 3074a6d6c5..b5f6d63ecb 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3732,6 +3732,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {
&payment_intent.active_attempt.get_id(),
&merchant_id,
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -8275,6 +8276,7 @@ pub async fn list_payments(
&pi.active_attempt.get_id(),
// since OLAP doesn't have KV. Force to get the data from PSQL.
storage_enums::MerchantStorageScheme::PostgresOnly,
+ platform.get_processor().get_key_store(),
)
.await
{
@@ -10709,6 +10711,7 @@ pub async fn payment_external_authentication<F: Clone + Sync>(
merchant_id,
&attempt_id.clone(),
storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -11079,6 +11082,7 @@ pub async fn payments_manual_update(
&merchant_id,
&attempt_id.clone(),
merchant_account.storage_scheme,
+ &key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
@@ -11144,6 +11148,7 @@ pub async fn payments_manual_update(
payment_attempt.clone(),
attempt_update,
merchant_account.storage_scheme,
+ &key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index d098630d34..13f5e38d45 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -24,7 +24,7 @@ use common_utils::{
new_type::{MaskedIban, MaskedSortCode},
pii, type_name,
types::{
- keymanager::{Identifier, ToEncryptable},
+ keymanager::{Identifier, KeyManagerState, ToEncryptable},
MinorUnit,
},
};
@@ -772,6 +772,7 @@ pub async fn get_token_for_recurring_mandate(
&mandate.merchant_id,
payment_intent.active_attempt.get_id().as_str(),
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
@@ -4728,10 +4729,10 @@ impl AttemptType {
old_payment_attempt: PaymentAttempt,
new_attempt_count: i16,
storage_scheme: enums::MerchantStorageScheme,
- ) -> storage::PaymentAttemptNew {
- let created_at @ modified_at @ last_synced = Some(common_utils::date_time::now());
+ ) -> PaymentAttempt {
+ let created_at @ modified_at @ last_synced = common_utils::date_time::now();
- storage::PaymentAttemptNew {
+ PaymentAttempt {
attempt_id: old_payment_attempt
.payment_id
.get_attempt_id(new_attempt_count),
@@ -4756,7 +4757,7 @@ impl AttemptType {
authentication_type: old_payment_attempt.authentication_type,
created_at,
modified_at,
- last_synced,
+ last_synced: Some(last_synced),
cancellation_reason: None,
amount_to_capture: old_payment_attempt.amount_to_capture,
@@ -4820,6 +4821,14 @@ impl AttemptType {
is_stored_credential: old_payment_attempt.is_stored_credential,
authorized_amount: old_payment_attempt.authorized_amount,
tokenization: None,
+ encrypted_payment_method_data: None,
+ connector_transaction_id: None,
+ charge_id: None,
+ charges: None,
+ issuer_error_code: None,
+ issuer_error_message: None,
+ debit_routing_savings: None,
+ is_overcapture_enabled: None,
}
}
@@ -4867,7 +4876,11 @@ impl AttemptType {
#[cfg(feature = "v1")]
let new_payment_attempt = db
- .insert_payment_attempt(new_payment_attempt_to_insert, storage_scheme)
+ .insert_payment_attempt(
+ new_payment_attempt_to_insert,
+ storage_scheme,
+ key_store,
+ )
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment {
payment_id: fetched_payment_intent.get_id().to_owned(),
@@ -7031,6 +7044,44 @@ pub fn add_connector_response_to_additional_payment_data(
}
}
+#[cfg(feature = "v1")]
+pub async fn get_payment_method_data_and_encrypted_payment_method_data(
+ payment_attempt: &PaymentAttempt,
+ key_manager_state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ additional_payment_method_data_intermediate: Option<serde_json::Value>,
+) -> CustomResult<
+ (
+ Option<serde_json::Value>,
+ Option<Encryptable<masking::Secret<serde_json::Value>>>,
+ ),
+ errors::ApiErrorResponse,
+> {
+ if payment_attempt
+ .payment_method
+ .as_ref()
+ .map(|payment_method| payment_method.is_additional_payment_method_data_sensitive())
+ .unwrap_or(false)
+ {
+ let encrypted_payment_method_data = additional_payment_method_data_intermediate
+ .clone()
+ .async_map(|additional_payment_method_data_intermediate| {
+ create_encrypted_data(
+ key_manager_state,
+ key_store,
+ additional_payment_method_data_intermediate,
+ )
+ })
+ .await
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encrypt additional_payment_method_data")?;
+ Ok((None, encrypted_payment_method_data))
+ } else {
+ Ok((additional_payment_method_data_intermediate, None))
+ }
+}
+
pub fn update_additional_payment_data_with_connector_response_pm_data(
additional_payment_data: Option<serde_json::Value>,
connector_response_pm_data: Option<AdditionalPaymentMethodConnectorResponse>,
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index 6cc342aba5..3cb2683851 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -495,7 +495,7 @@ pub trait UpdateTracker<F, D, Req>: Send {
customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
updated_customer: Option<storage::CustomerUpdate>,
- mechant_key_store: &domain::MerchantKeyStore,
+ merchant_key_store: &domain::MerchantKeyStore,
frm_suggestion: Option<FrmSuggestion>,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(BoxedOperation<'b, F, Req, D>, D)>
diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs
index f153c20fae..ae476e22aa 100644
--- a/crates/router/src/core/payments/operations/payment_approve.rs
+++ b/crates/router/src/core/payments/operations/payment_approve.rs
@@ -97,6 +97,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCaptureR
merchant_id,
&attempt_id.clone(),
storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -266,6 +267,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsCaptureReque
updated_by: storage_scheme.to_string(),
},
storage_scheme,
+ key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs
index f6838241da..4483eb1061 100644
--- a/crates/router/src/core/payments/operations/payment_cancel.rs
+++ b/crates/router/src/core/payments/operations/payment_cancel.rs
@@ -83,6 +83,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelRe
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -289,6 +290,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelReques
updated_by: storage_scheme.to_string(),
},
storage_scheme,
+ key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs b/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs
index 83f924d0ef..9148b599ee 100644
--- a/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs
@@ -84,6 +84,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelPo
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs
index f3513a65a5..16e6484173 100644
--- a/crates/router/src/core/payments/operations/payment_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_capture.rs
@@ -78,6 +78,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, api::Paymen
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -297,7 +298,7 @@ impl<F: Clone + Sync> UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCa
_customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
- _mechant_key_store: &domain::MerchantKeyStore,
+ merchant_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentCaptureOperation<'b, F>, payments::PaymentData<F>)>
@@ -322,6 +323,7 @@ impl<F: Clone + Sync> UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCa
updated_by: storage_scheme.to_string(),
},
storage_scheme,
+ merchant_key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?
diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
index eee498b1ed..8a25482ca9 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -101,6 +101,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
merchant_id,
&payment_intent.active_attempt.get_id(),
storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index ca0f2b8528..a972d180d9 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -182,6 +182,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
let m_payment_id = payment_intent.payment_id.clone();
let m_merchant_id = merchant_id.clone();
+ let merchant_key_store = platform.get_processor().get_key_store().clone();
let payment_attempt_fut = tokio::spawn(
async move {
@@ -191,6 +192,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
&m_merchant_id,
attempt_id.as_str(),
storage_scheme,
+ &merchant_key_store,
)
.map(|x| x.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))
.await
@@ -1942,6 +1944,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for
payment_data.mandate_id.is_some(),
payment_data.payment_attempt.is_stored_credential,
);
+ let cloned_key_store = key_store.clone();
let payment_attempt_fut = tokio::spawn(
async move {
m_db.update_payment_attempt_with_attempt_id(
@@ -2006,6 +2009,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for
tokenization: payment_data.payment_attempt.get_tokenization_strategy(),
},
storage_scheme,
+ &cloned_key_store,
)
.map(|x| x.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))
.await
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 47e4bea103..c6c42a0432 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -354,7 +354,11 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
#[cfg(feature = "v1")]
let mut payment_attempt = db
- .insert_payment_attempt(payment_attempt_new, storage_scheme)
+ .insert_payment_attempt(
+ payment_attempt_new,
+ storage_scheme,
+ platform.get_processor().get_key_store(),
+ )
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment {
payment_id: payment_id.clone(),
@@ -899,6 +903,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for
is_stored_credential,
},
storage_scheme,
+ key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -1137,7 +1142,7 @@ impl PaymentCreate {
customer_acceptance: &Option<common_payments_types::CustomerAcceptance>,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
- storage::PaymentAttemptNew,
+ PaymentAttempt,
Option<api_models::payments::AdditionalPaymentData>,
)> {
let payment_method_data =
@@ -1148,7 +1153,7 @@ impl PaymentCreate {
payment_method_data_request.payment_method_data.as_ref()
});
- let created_at @ modified_at @ last_synced = Some(common_utils::date_time::now());
+ let created_at @ modified_at @ last_synced = common_utils::date_time::now();
let status = helpers::payment_attempt_status_fsm(payment_method_data, request.confirm);
let (amount, currency) = (money.0, Some(money.1));
@@ -1326,7 +1331,7 @@ impl PaymentCreate {
request.is_stored_credential,
);
Ok((
- storage::PaymentAttemptNew {
+ PaymentAttempt {
payment_id: payment_id.to_owned(),
merchant_id: merchant_id.to_owned(),
attempt_id,
@@ -1338,7 +1343,7 @@ impl PaymentCreate {
confirm: request.confirm.unwrap_or(false),
created_at,
modified_at,
- last_synced,
+ last_synced: Some(last_synced),
authentication_type: request.authentication_type,
browser_info,
payment_experience: request.payment_experience,
@@ -1410,7 +1415,15 @@ impl PaymentCreate {
network_details:None,
is_stored_credential,
authorized_amount: None,
- tokenization:request.tokenization
+ tokenization:request.tokenization,
+ connector_transaction_id: None,
+ charge_id: None,
+ charges: None,
+ issuer_error_code: None,
+ issuer_error_message: None,
+ debit_routing_savings: None,
+ is_overcapture_enabled: None,
+ encrypted_payment_method_data: None,
},
additional_pm_data,
diff --git a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs
index 4e7933047a..a6160c30f4 100644
--- a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs
+++ b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs
@@ -77,6 +77,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsPostSess
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs
index 1a09e51bc6..fbb335a2a9 100644
--- a/crates/router/src/core/payments/operations/payment_reject.rs
+++ b/crates/router/src/core/payments/operations/payment_reject.rs
@@ -79,6 +79,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest
merchant_id,
attempt_id.clone().as_str(),
storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -272,6 +273,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, PaymentsCancelRequest> fo
payment_data.payment_attempt.clone(),
attempt_status_update,
storage_scheme,
+ key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index c118f2ce51..ee541d8aaf 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -13,16 +13,15 @@ use common_utils::{
};
use error_stack::{report, ResultExt};
use futures::FutureExt;
-use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payments::{
PaymentConfirmData, PaymentIntentData, PaymentStatusData,
};
+use hyperswitch_domain_models::{behaviour::Conversion, payments::payment_attempt::PaymentAttempt};
#[cfg(feature = "v2")]
use masking::PeekInterface;
use router_derive;
use router_env::{instrument, logger, tracing};
-use storage_impl::DataModelExt;
use tracing_futures::Instrument;
use super::{Operation, OperationSessionSetters, PostUpdateTracker};
@@ -362,6 +361,7 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
payment_attempt,
payment_attempt_update,
storage_scheme,
+ cloned_platform.get_processor().get_key_store(),
)
.await;
@@ -370,7 +370,7 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
.store
.update_payment_attempt_with_attempt_id(
&(&state).into(),
- &key_store,
+ &key_store.clone(),
payment_attempt,
payment_attempt_update,
storage_scheme,
@@ -469,6 +469,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsIncrementalAu
payment_data.payment_attempt.clone(),
payment_attempt_update,
storage_scheme,
+ key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -819,7 +820,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsPostSessionTo
types::PaymentsPostSessionTokensData,
types::PaymentsResponseData,
>,
- _key_store: &domain::MerchantKeyStore,
+ key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
_locale: &Option<String>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] _routable_connector: Vec<
@@ -846,6 +847,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsPostSessionTo
payment_data.payment_attempt.clone(),
payment_attempt_update,
storage_scheme,
+ key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -1456,13 +1458,14 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>> {
+ let key_manager_state = &state.into();
// Update additional payment data with the payment method response that we received from connector
// This is for details like whether 3ds was upgraded and which version of 3ds was used
// also some connectors might send card network details in the response, which is captured and stored
let additional_payment_data = payment_data.payment_attempt.get_payment_method_data();
- let additional_payment_method_data = match payment_data.payment_method_data.clone() {
+ let additional_payment_method_data_intermediate = match payment_data.payment_method_data.clone() {
Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::NetworkToken(_))
| Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardDetailsForNetworkTransactionId(_)) => {
payment_data.payment_attempt.payment_method_data.clone()
@@ -1485,6 +1488,16 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
}
};
+ // If the additional PM data is sensitive, encrypt it and populate encrypted_payment_method_data; otherwise populate additional_payment_method_data
+ let (additional_payment_method_data, encrypted_payment_method_data) =
+ payments_helpers::get_payment_method_data_and_encrypted_payment_method_data(
+ &payment_data.payment_attempt,
+ key_manager_state,
+ key_store,
+ additional_payment_method_data_intermediate,
+ )
+ .await?;
+
router_data.payment_method_status.and_then(|status| {
payment_data
.payment_method_info
@@ -1625,6 +1638,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
unified_message: Some(unified_translated_message),
connector_transaction_id: err.connector_transaction_id.clone(),
payment_method_data: additional_payment_method_data,
+ encrypted_payment_method_data,
authentication_type: auth_update,
issuer_error_code: err.network_decline_code.clone(),
issuer_error_message: err.network_error_message.clone(),
@@ -1666,6 +1680,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
unified_message: None,
connector_transaction_id,
payment_method_data: None,
+ encrypted_payment_method_data: None,
authentication_type: auth_update,
issuer_error_code: None,
issuer_error_message: None,
@@ -1981,6 +1996,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
authentication_data,
encoded_data,
payment_method_data: additional_payment_method_data,
+ encrypted_payment_method_data,
capture_before,
extended_authorization_applied,
extended_authorization_last_applied_at,
@@ -2116,16 +2132,35 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
let m_payment_attempt_update = payment_attempt_update.clone();
let m_payment_attempt = payment_attempt.clone();
+ let diesel_payment_attempt = payment_attempt
+ .clone()
+ .convert()
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while construcing diesel attempt model")?;
+
let payment_attempt = payment_attempt_update
.map(|payment_attempt_update| {
- PaymentAttempt::from_storage_model(
- payment_attempt_update
- .to_storage_model()
- .apply_changeset(payment_attempt.clone().to_storage_model()),
+ payment_attempt_update
+ .to_storage_model()
+ .apply_changeset(diesel_payment_attempt)
+ })
+ .async_map(|diesel_payment_attempt| async {
+ PaymentAttempt::convert_back(
+ key_manager_state,
+ diesel_payment_attempt,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while construcing domain attempt model")
})
- .unwrap_or_else(|| payment_attempt);
+ .await
+ .transpose()?
+ .unwrap_or(payment_attempt);
+ let cloned_key_store = key_store.clone();
let payment_attempt_fut = tokio::spawn(
async move {
Box::pin(async move {
@@ -2136,6 +2171,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
m_payment_attempt,
payment_attempt_update,
storage_scheme,
+ &cloned_key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?,
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 43f65d3349..5d7c260d9a 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -83,6 +83,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsSessionR
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index f906206b33..116ac5c228 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -86,6 +86,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsStartReq
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -237,7 +238,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsStartRequest
_customer: Option<domain::Customer>,
_storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
- _mechant_key_store: &domain::MerchantKeyStore,
+ _merchant_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentSessionOperation<'b, F>, PaymentData<F>)>
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index 2324ee4999..a9284007c3 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -310,7 +310,7 @@ async fn get_tracker_for_sync<
let attempts = match request.expand_attempts {
Some(true) => {
Some(db
- .find_attempts_by_merchant_id_payment_id(platform.get_processor().get_account().get_id(), &payment_id, storage_scheme)
+ .find_attempts_by_merchant_id_payment_id(platform.get_processor().get_account().get_id(), &payment_id, storage_scheme, platform.get_processor().get_key_store())
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
@@ -619,6 +619,7 @@ pub async fn get_payment_intent_payment_attempt(
merchant_id,
pi.active_attempt.get_id().as_str(),
storage_scheme,
+ key_store,
)
.await?;
}
@@ -628,6 +629,7 @@ pub async fn get_payment_intent_payment_attempt(
merchant_id,
id,
storage_scheme,
+ key_store,
)
.await?;
pi = db
@@ -641,7 +643,12 @@ pub async fn get_payment_intent_payment_attempt(
}
api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => {
pa = db
- .find_payment_attempt_by_attempt_id_merchant_id(id, merchant_id, storage_scheme)
+ .find_payment_attempt_by_attempt_id_merchant_id(
+ id,
+ merchant_id,
+ storage_scheme,
+ key_store,
+ )
.await?;
pi = db
.find_payment_intent_by_payment_id_merchant_id(
@@ -658,6 +665,7 @@ pub async fn get_payment_intent_payment_attempt(
id,
merchant_id,
storage_scheme,
+ key_store,
)
.await?;
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 7f2daa54ea..aa8fe86bb3 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -122,6 +122,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -844,6 +845,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for
),
},
storage_scheme,
+ key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/core/payments/operations/payment_update_metadata.rs b/crates/router/src/core/payments/operations/payment_update_metadata.rs
index fbc6376e98..ab3fb387f0 100644
--- a/crates/router/src/core/payments/operations/payment_update_metadata.rs
+++ b/crates/router/src/core/payments/operations/payment_update_metadata.rs
@@ -81,6 +81,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsUpdateMe
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/core/payments/operations/payments_extend_authorization.rs b/crates/router/src/core/payments/operations/payments_extend_authorization.rs
index 06bef42a18..fddfcc3eef 100644
--- a/crates/router/src/core/payments/operations/payments_extend_authorization.rs
+++ b/crates/router/src/core/payments/operations/payments_extend_authorization.rs
@@ -83,6 +83,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsExtendAu
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
index 1803fb1858..3286b90d53 100644
--- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
+++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
@@ -93,6 +93,7 @@ impl<F: Send + Clone + Sync>
merchant_id,
attempt_id.clone().as_str(),
storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/core/payments/operations/tax_calculation.rs b/crates/router/src/core/payments/operations/tax_calculation.rs
index 3f3d0c0daa..5054157ed0 100644
--- a/crates/router/src/core/payments/operations/tax_calculation.rs
+++ b/crates/router/src/core/payments/operations/tax_calculation.rs
@@ -94,6 +94,7 @@ impl<F: Send + Clone + Sync>
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
index 8d1be8da01..6f1802c932 100644
--- a/crates/router/src/core/payments/retry.rs
+++ b/crates/router/src/core/payments/retry.rs
@@ -467,7 +467,7 @@ where
);
let db = &*state.store;
- let additional_payment_method_data =
+ let additional_payment_method_data_intermediate =
payments::helpers::update_additional_payment_data_with_connector_response_pm_data(
payment_data
.get_payment_attempt()
@@ -478,6 +478,17 @@ where
.clone()
.and_then(|connector_response| connector_response.additional_payment_method_data),
)?;
+ let key_manager_state = &state.into();
+
+ // If the additional PM data is sensitive, encrypt it and populate encrypted_payment_method_data; otherwise populate additional_payment_method_data
+ let (additional_payment_method_data, encrypted_payment_method_data) =
+ payments::helpers::get_payment_method_data_and_encrypted_payment_method_data(
+ payment_data.get_payment_attempt(),
+ key_manager_state,
+ key_store,
+ additional_payment_method_data_intermediate,
+ )
+ .await?;
let debit_routing_savings = payment_data.get_payment_method_data().and_then(|data| {
payments::helpers::get_debit_routing_savings_amount(
@@ -539,6 +550,7 @@ where
extended_authorization_applied: None,
extended_authorization_last_applied_at: None,
payment_method_data: additional_payment_method_data,
+ encrypted_payment_method_data,
connector_mandate_detail: None,
charges,
setup_future_usage_applied: None,
@@ -557,6 +569,7 @@ where
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
storage_scheme,
+ key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -598,6 +611,7 @@ where
unified_message: option_gsm.map(|gsm| gsm.unified_message),
connector_transaction_id: error_response.connector_transaction_id.clone(),
payment_method_data: additional_payment_method_data,
+ encrypted_payment_method_data,
authentication_type: auth_update,
issuer_error_code: error_response.network_decline_code.clone(),
issuer_error_message: error_response.network_error_message.clone(),
@@ -609,6 +623,7 @@ where
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
storage_scheme,
+ key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -628,7 +643,7 @@ where
#[cfg(feature = "v1")]
let payment_attempt = db
- .insert_payment_attempt(new_payment_attempt, storage_scheme)
+ .insert_payment_attempt(new_payment_attempt, storage_scheme, key_store)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error inserting payment attempt")?;
@@ -670,9 +685,9 @@ pub fn make_new_payment_attempt(
new_attempt_count: i16,
is_step_up: bool,
setup_future_usage_intent: Option<storage_enums::FutureUsage>,
-) -> storage::PaymentAttemptNew {
- let created_at @ modified_at @ last_synced = Some(common_utils::date_time::now());
- storage::PaymentAttemptNew {
+) -> storage::PaymentAttempt {
+ let created_at @ modified_at @ last_synced = common_utils::date_time::now();
+ storage::PaymentAttempt {
connector: Some(connector),
attempt_id: old_payment_attempt
.payment_id
@@ -702,7 +717,7 @@ pub fn make_new_payment_attempt(
client_version: old_payment_attempt.client_version,
created_at,
modified_at,
- last_synced,
+ last_synced: Some(last_synced),
profile_id: old_payment_attempt.profile_id,
organization_id: old_payment_attempt.organization_id,
net_amount: old_payment_attempt.net_amount,
@@ -749,6 +764,14 @@ pub fn make_new_payment_attempt(
is_stored_credential: old_payment_attempt.is_stored_credential,
authorized_amount: old_payment_attempt.authorized_amount,
tokenization: Default::default(),
+ encrypted_payment_method_data: Default::default(),
+ connector_transaction_id: Default::default(),
+ charge_id: Default::default(),
+ charges: Default::default(),
+ issuer_error_code: Default::default(),
+ issuer_error_message: Default::default(),
+ debit_routing_savings: Default::default(),
+ is_overcapture_enabled: Default::default(),
}
}
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 49395c5166..f8303e8e63 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -3310,8 +3310,7 @@ where
let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> =
payment_data
.get_payment_attempt()
- .payment_method_data
- .clone()
+ .check_and_get_payment_method_data_based_on_encryption_strategy()
.map(|data| data.parse_value("payment_method_data"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
@@ -3477,8 +3476,7 @@ where
.unwrap_or("".to_owned());
let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> =
payment_attempt
- .payment_method_data
- .clone()
+ .check_and_get_payment_method_data_based_on_encryption_strategy()
.and_then(|data| match data {
serde_json::Value::Null => None, // This is to handle the case when the payment_method_data is null
_ => Some(data.parse_value("AdditionalPaymentData")),
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 0e80cc3c0d..361ade40aa 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -105,6 +105,7 @@ pub async fn refund_create_core(
&req.payment_id,
merchant_id,
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::SuccessfulPaymentNotFound)?;
@@ -671,6 +672,7 @@ pub async fn refund_retrieve_core(
payment_id,
merchant_id,
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
@@ -1921,6 +1923,7 @@ pub async fn trigger_refund_execute_workflow(
&refund_core.payment_id,
&refund.merchant_id,
merchant_account.storage_scheme,
+ &key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/core/user/sample_data.rs b/crates/router/src/core/user/sample_data.rs
index 952d5fdd17..55abc92afb 100644
--- a/crates/router/src/core/user/sample_data.rs
+++ b/crates/router/src/core/user/sample_data.rs
@@ -57,6 +57,7 @@ pub async fn generate_sample_data_for_user(
(pi, pa, rf, dp)
},
);
+ let key_manager_state = &(&state).into();
state
.store
@@ -65,7 +66,11 @@ pub async fn generate_sample_data_for_user(
.switch()?;
state
.store
- .insert_payment_attempts_batch_for_sample_data(payment_attempts)
+ .insert_payment_attempts_batch_for_sample_data(
+ payment_attempts,
+ key_manager_state,
+ &key_store,
+ )
.await
.switch()?;
state
@@ -108,7 +113,7 @@ pub async fn delete_sample_data_for_user(
.switch()?;
state
.store
- .delete_payment_attempts_for_sample_data(&merchant_id_del)
+ .delete_payment_attempts_for_sample_data(&merchant_id_del, key_manager_state, &key_store)
.await
.switch()?;
state
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index d8854adb10..2c4f5d5724 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -20,6 +20,7 @@ use error_stack::{report, ResultExt};
use hyperswitch_domain_models::payouts::payout_attempt::PayoutAttempt;
use hyperswitch_domain_models::{
mandates::CommonMandateReference,
+ merchant_key_store::MerchantKeyStore,
payments::{payment_attempt::PaymentAttempt, HeaderPayload},
router_request_types::VerifyWebhookSourceRequestData,
router_response_types::{VerifyWebhookSourceResponseData, VerifyWebhookStatus},
@@ -1307,6 +1308,7 @@ async fn payments_incoming_webhook_flow(
id,
platform.get_processor().get_account().get_id(),
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await?;
@@ -1960,6 +1962,7 @@ pub async fn get_payment_attempt_from_object_reference_id(
platform.get_processor().get_account().get_id(),
id,
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound),
@@ -1968,6 +1971,7 @@ pub async fn get_payment_attempt_from_object_reference_id(
id,
platform.get_processor().get_account().get_id(),
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound),
@@ -1976,6 +1980,7 @@ pub async fn get_payment_attempt_from_object_reference_id(
id,
platform.get_processor().get_account().get_id(),
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound),
@@ -2615,6 +2620,7 @@ async fn get_payment_id(
payment_id: &api::PaymentIdType,
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: enums::MerchantStorageScheme,
+ key_store: &MerchantKeyStore,
) -> errors::RouterResult<common_utils::id_type::PaymentId> {
let pay_id = || async {
match payment_id {
@@ -2624,11 +2630,17 @@ async fn get_payment_id(
merchant_id,
id,
storage_scheme,
+ key_store,
)
.await
.map(|p| p.payment_id),
api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => db
- .find_payment_attempt_by_attempt_id_merchant_id(id, merchant_id, storage_scheme)
+ .find_payment_attempt_by_attempt_id_merchant_id(
+ id,
+ merchant_id,
+ storage_scheme,
+ key_store,
+ )
.await
.map(|p| p.payment_id),
api_models::payments::PaymentIdType::PreprocessingId(ref id) => db
@@ -2636,6 +2648,7 @@ async fn get_payment_id(
id,
merchant_id,
storage_scheme,
+ key_store,
)
.await
.map(|p| p.payment_id),
@@ -2955,6 +2968,7 @@ async fn update_connector_mandate_details(
payment_attempt.clone(),
attempt_update,
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 97e4f114be..833911662f 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1408,12 +1408,13 @@ impl PaymentAttemptInterface for KafkaStore {
#[cfg(feature = "v1")]
async fn insert_payment_attempt(
&self,
- payment_attempt: storage::PaymentAttemptNew,
+ payment_attempt: storage::PaymentAttempt,
storage_scheme: MerchantStorageScheme,
+ key_store: &domain::MerchantKeyStore,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
let attempt = self
.diesel_store
- .insert_payment_attempt(payment_attempt, storage_scheme)
+ .insert_payment_attempt(payment_attempt, storage_scheme, key_store)
.await?;
if let Err(er) = self
@@ -1456,6 +1457,7 @@ impl PaymentAttemptInterface for KafkaStore {
this: storage::PaymentAttempt,
payment_attempt: storage::PaymentAttemptUpdate,
storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
let mut attempt = self
.diesel_store
@@ -1463,6 +1465,7 @@ impl PaymentAttemptInterface for KafkaStore {
this.clone(),
payment_attempt.clone(),
storage_scheme,
+ merchant_key_store,
)
.await?;
@@ -1516,6 +1519,7 @@ impl PaymentAttemptInterface for KafkaStore {
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
+ key_store: &domain::MerchantKeyStore,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
self.diesel_store
.find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
@@ -1523,6 +1527,7 @@ impl PaymentAttemptInterface for KafkaStore {
payment_id,
merchant_id,
storage_scheme,
+ key_store,
)
.await
}
@@ -1533,12 +1538,14 @@ impl PaymentAttemptInterface for KafkaStore {
merchant_id: &id_type::MerchantId,
connector_txn_id: &str,
storage_scheme: MerchantStorageScheme,
+ key_store: &domain::MerchantKeyStore,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
self.diesel_store
.find_payment_attempt_by_merchant_id_connector_txn_id(
merchant_id,
connector_txn_id,
storage_scheme,
+ key_store,
)
.await
}
@@ -1568,6 +1575,7 @@ impl PaymentAttemptInterface for KafkaStore {
merchant_id: &id_type::MerchantId,
attempt_id: &str,
storage_scheme: MerchantStorageScheme,
+ key_store: &domain::MerchantKeyStore,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
self.diesel_store
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
@@ -1575,6 +1583,7 @@ impl PaymentAttemptInterface for KafkaStore {
merchant_id,
attempt_id,
storage_scheme,
+ key_store,
)
.await
}
@@ -1585,9 +1594,15 @@ impl PaymentAttemptInterface for KafkaStore {
attempt_id: &str,
merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
+ key_store: &domain::MerchantKeyStore,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
self.diesel_store
- .find_payment_attempt_by_attempt_id_merchant_id(attempt_id, merchant_id, storage_scheme)
+ .find_payment_attempt_by_attempt_id_merchant_id(
+ attempt_id,
+ merchant_id,
+ storage_scheme,
+ key_store,
+ )
.await
}
@@ -1625,12 +1640,14 @@ impl PaymentAttemptInterface for KafkaStore {
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
+ key_store: &domain::MerchantKeyStore,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
self.diesel_store
.find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
payment_id,
merchant_id,
storage_scheme,
+ key_store,
)
.await
}
@@ -1641,12 +1658,14 @@ impl PaymentAttemptInterface for KafkaStore {
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
+ key_store: &domain::MerchantKeyStore,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
self.diesel_store
.find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id(
payment_id,
merchant_id,
storage_scheme,
+ key_store,
)
.await
}
@@ -1673,12 +1692,14 @@ impl PaymentAttemptInterface for KafkaStore {
preprocessing_id: &str,
merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
+ key_store: &domain::MerchantKeyStore,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
self.diesel_store
.find_payment_attempt_by_preprocessing_id_merchant_id(
preprocessing_id,
merchant_id,
storage_scheme,
+ key_store,
)
.await
}
@@ -1762,9 +1783,15 @@ impl PaymentAttemptInterface for KafkaStore {
merchant_id: &id_type::MerchantId,
payment_id: &id_type::PaymentId,
storage_scheme: MerchantStorageScheme,
+ key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<storage::PaymentAttempt>, errors::StorageError> {
self.diesel_store
- .find_attempts_by_merchant_id_payment_id(merchant_id, payment_id, storage_scheme)
+ .find_attempts_by_merchant_id_payment_id(
+ merchant_id,
+ payment_id,
+ storage_scheme,
+ key_store,
+ )
.await
}
}
@@ -3497,13 +3524,15 @@ impl BatchSampleDataInterface for KafkaStore {
async fn insert_payment_attempts_batch_for_sample_data(
&self,
batch: Vec<diesel_models::user::sample_data::PaymentAttemptBatchNew>,
+ state: &KeyManagerState,
+ key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
) -> CustomResult<
Vec<hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>,
storage_impl::errors::StorageError,
> {
let payment_attempts_list = self
.diesel_store
- .insert_payment_attempts_batch_for_sample_data(batch)
+ .insert_payment_attempts_batch_for_sample_data(batch, state, key_store)
.await?;
for payment_attempt in payment_attempts_list.iter() {
@@ -3585,13 +3614,15 @@ impl BatchSampleDataInterface for KafkaStore {
async fn delete_payment_attempts_for_sample_data(
&self,
merchant_id: &id_type::MerchantId,
+ state: &KeyManagerState,
+ key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
) -> CustomResult<
Vec<hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>,
storage_impl::errors::StorageError,
> {
let payment_attempts_list = self
.diesel_store
- .delete_payment_attempts_for_sample_data(merchant_id)
+ .delete_payment_attempts_for_sample_data(merchant_id, state, key_store)
.await?;
for payment_attempt in payment_attempts_list.iter() {
diff --git a/crates/router/src/db/user/sample_data.rs b/crates/router/src/db/user/sample_data.rs
index 5a7b09028b..15973ec277 100644
--- a/crates/router/src/db/user/sample_data.rs
+++ b/crates/router/src/db/user/sample_data.rs
@@ -14,7 +14,7 @@ use hyperswitch_domain_models::{
merchant_key_store::MerchantKeyStore,
payments::{payment_attempt::PaymentAttempt, PaymentIntent},
};
-use storage_impl::{errors::StorageError, DataModelExt};
+use storage_impl::errors::StorageError;
use crate::{connection::pg_connection_write, core::errors::CustomResult, services::Store};
@@ -32,6 +32,8 @@ pub trait BatchSampleDataInterface {
async fn insert_payment_attempts_batch_for_sample_data(
&self,
batch: Vec<PaymentAttemptBatchNew>,
+ state: &KeyManagerState,
+ key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentAttempt>, StorageError>;
#[cfg(feature = "v1")]
@@ -58,6 +60,8 @@ pub trait BatchSampleDataInterface {
async fn delete_payment_attempts_for_sample_data(
&self,
merchant_id: &common_utils::id_type::MerchantId,
+ state: &KeyManagerState,
+ key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentAttempt>, StorageError>;
#[cfg(feature = "v1")]
@@ -113,6 +117,8 @@ impl BatchSampleDataInterface for Store {
async fn insert_payment_attempts_batch_for_sample_data(
&self,
batch: Vec<PaymentAttemptBatchNew>,
+ state: &KeyManagerState,
+ key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentAttempt>, StorageError> {
let conn = pg_connection_write(self)
.await
@@ -120,11 +126,18 @@ impl BatchSampleDataInterface for Store {
sample_data_queries::insert_payment_attempts(&conn, batch)
.await
.map_err(diesel_error_to_data_error)
- .map(|res| {
- res.into_iter()
- .map(PaymentAttempt::from_storage_model)
- .collect()
- })
+ .map(|v| {
+ try_join_all(v.into_iter().map(|payment_intent| {
+ PaymentAttempt::convert_back(
+ state,
+ payment_intent,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ }))
+ .map(|join_result| join_result.change_context(StorageError::DecryptionError))
+ })?
+ .await
}
#[cfg(feature = "v1")]
@@ -184,6 +197,8 @@ impl BatchSampleDataInterface for Store {
async fn delete_payment_attempts_for_sample_data(
&self,
merchant_id: &common_utils::id_type::MerchantId,
+ state: &KeyManagerState,
+ key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentAttempt>, StorageError> {
let conn = pg_connection_write(self)
.await
@@ -192,10 +207,17 @@ impl BatchSampleDataInterface for Store {
.await
.map_err(diesel_error_to_data_error)
.map(|res| {
- res.into_iter()
- .map(PaymentAttempt::from_storage_model)
- .collect()
- })
+ try_join_all(res.into_iter().map(|res| {
+ PaymentAttempt::convert_back(
+ state,
+ res,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ }))
+ .map(|join_result| join_result.change_context(StorageError::DecryptionError))
+ })?
+ .await
}
#[cfg(feature = "v1")]
@@ -241,6 +263,8 @@ impl BatchSampleDataInterface for storage_impl::MockDb {
async fn insert_payment_attempts_batch_for_sample_data(
&self,
_batch: Vec<PaymentAttemptBatchNew>,
+ _state: &KeyManagerState,
+ _key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentAttempt>, StorageError> {
Err(StorageError::MockDbError)?
}
@@ -275,6 +299,8 @@ impl BatchSampleDataInterface for storage_impl::MockDb {
async fn delete_payment_attempts_for_sample_data(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
+ _state: &KeyManagerState,
+ _key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentAttempt>, StorageError> {
Err(StorageError::MockDbError)?
}
diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs
index 9e4e9ca30b..a151be33bc 100644
--- a/crates/router/src/types/storage.rs
+++ b/crates/router/src/types/storage.rs
@@ -51,8 +51,6 @@ pub use diesel_models::{
process_tracker::business_status, ProcessTracker, ProcessTrackerNew, ProcessTrackerRunner,
ProcessTrackerUpdate,
};
-#[cfg(feature = "v1")]
-pub use hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptNew;
#[cfg(feature = "payouts")]
pub use hyperswitch_domain_models::payouts::{
payout_attempt::{PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate},
diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs
index 66e5b60022..dd673769ce 100644
--- a/crates/router/src/types/storage/payment_attempt.rs
+++ b/crates/router/src/types/storage/payment_attempt.rs
@@ -124,7 +124,7 @@ impl AttemptStatusExt for enums::AttemptStatus {
feature = "dummy_connector"
))]
mod tests {
- use hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptNew;
+ use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt;
use tokio::sync::oneshot;
use uuid::Uuid;
@@ -161,12 +161,13 @@ mod tests {
common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data();
let current_time = common_utils::date_time::now();
let connector = types::Connector::DummyConnector1.to_string();
- let payment_attempt = PaymentAttemptNew {
+ let merchant_id = common_utils::id_type::MerchantId::default();
+ let payment_attempt = PaymentAttempt {
payment_id: payment_id.clone(),
connector: Some(connector),
- created_at: current_time.into(),
- modified_at: current_time.into(),
- merchant_id: Default::default(),
+ created_at: current_time,
+ modified_at: current_time,
+ merchant_id: merchant_id.clone(),
attempt_id: Default::default(),
status: Default::default(),
net_amount: Default::default(),
@@ -232,14 +233,33 @@ mod tests {
is_stored_credential: None,
authorized_amount: Default::default(),
tokenization: Default::default(),
+ charge_id: Default::default(),
+ charges: Default::default(),
+ issuer_error_code: Default::default(),
+ issuer_error_message: Default::default(),
+ debit_routing_savings: Default::default(),
+ is_overcapture_enabled: Default::default(),
+ connector_transaction_id: Default::default(),
+ encrypted_payment_method_data: Default::default(),
};
let store = state
.stores
.get(state.conf.multitenancy.get_tenant_ids().first().unwrap())
.unwrap();
+ let key_store = store
+ .get_merchant_key_store_by_merchant_id(
+ &merchant_id,
+ &store.get_master_key().to_vec().into(),
+ )
+ .await
+ .unwrap();
let response = store
- .insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly)
+ .insert_payment_attempt(
+ payment_attempt,
+ enums::MerchantStorageScheme::PostgresOnly,
+ &key_store,
+ )
.await
.unwrap();
eprintln!("{response:?}");
@@ -259,12 +279,12 @@ mod tests {
let merchant_id = common_utils::id_type::MerchantId::new_from_unix_timestamp();
let connector = types::Connector::DummyConnector1.to_string();
- let payment_attempt = PaymentAttemptNew {
+ let payment_attempt = PaymentAttempt {
payment_id: payment_id.clone(),
merchant_id: merchant_id.clone(),
connector: Some(connector),
- created_at: current_time.into(),
- modified_at: current_time.into(),
+ created_at: current_time,
+ modified_at: current_time,
attempt_id: attempt_id.clone(),
status: Default::default(),
net_amount: Default::default(),
@@ -330,13 +350,32 @@ mod tests {
is_stored_credential: Default::default(),
authorized_amount: Default::default(),
tokenization: Default::default(),
+ charge_id: Default::default(),
+ charges: Default::default(),
+ issuer_error_code: Default::default(),
+ issuer_error_message: Default::default(),
+ debit_routing_savings: Default::default(),
+ is_overcapture_enabled: Default::default(),
+ connector_transaction_id: Default::default(),
+ encrypted_payment_method_data: Default::default(),
};
let store = state
.stores
.get(state.conf.multitenancy.get_tenant_ids().first().unwrap())
.unwrap();
+ let key_store = store
+ .get_merchant_key_store_by_merchant_id(
+ &merchant_id,
+ &store.get_master_key().to_vec().into(),
+ )
+ .await
+ .unwrap();
store
- .insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly)
+ .insert_payment_attempt(
+ payment_attempt,
+ enums::MerchantStorageScheme::PostgresOnly,
+ &key_store,
+ )
.await
.unwrap();
@@ -346,6 +385,7 @@ mod tests {
&merchant_id,
&attempt_id,
enums::MerchantStorageScheme::PostgresOnly,
+ &key_store,
)
.await
.unwrap();
@@ -370,12 +410,12 @@ mod tests {
let current_time = common_utils::date_time::now();
let connector = types::Connector::DummyConnector1.to_string();
- let payment_attempt = PaymentAttemptNew {
+ let payment_attempt = PaymentAttempt {
payment_id: payment_id.clone(),
merchant_id: merchant_id.clone(),
connector: Some(connector),
- created_at: current_time.into(),
- modified_at: current_time.into(),
+ created_at: current_time,
+ modified_at: current_time,
mandate_id: Some("man_121212".to_string()),
attempt_id: uuid.clone(),
status: Default::default(),
@@ -441,13 +481,32 @@ mod tests {
is_stored_credential: Default::default(),
authorized_amount: Default::default(),
tokenization: Default::default(),
+ charge_id: Default::default(),
+ charges: Default::default(),
+ issuer_error_code: Default::default(),
+ issuer_error_message: Default::default(),
+ debit_routing_savings: Default::default(),
+ is_overcapture_enabled: Default::default(),
+ connector_transaction_id: Default::default(),
+ encrypted_payment_method_data: Default::default(),
};
let store = state
.stores
.get(state.conf.multitenancy.get_tenant_ids().first().unwrap())
.unwrap();
+ let key_store = store
+ .get_merchant_key_store_by_merchant_id(
+ &merchant_id,
+ &store.get_master_key().to_vec().into(),
+ )
+ .await
+ .unwrap();
store
- .insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly)
+ .insert_payment_attempt(
+ payment_attempt,
+ enums::MerchantStorageScheme::PostgresOnly,
+ &key_store,
+ )
.await
.unwrap();
@@ -457,6 +516,7 @@ mod tests {
&merchant_id,
&uuid,
enums::MerchantStorageScheme::PostgresOnly,
+ &key_store,
)
.await
.unwrap();
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index 8b85f9f646..6d1c30437a 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -187,6 +187,7 @@ pub async fn find_payment_intent_from_payment_id_type(
platform.get_processor().get_account().get_id(),
&connector_transaction_id,
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -205,6 +206,7 @@ pub async fn find_payment_intent_from_payment_id_type(
&attempt_id,
platform.get_processor().get_account().get_id(),
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -255,6 +257,7 @@ pub async fn find_payment_intent_from_refund_id_type(
&refund.attempt_id,
platform.get_processor().get_account().get_id(),
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -373,6 +376,7 @@ pub async fn get_mca_from_payment_intent(
&payment_intent.active_attempt.get_id(),
platform.get_processor().get_account().get_id(),
platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs
index 0acf9e9869..b2d43ff610 100644
--- a/crates/router/src/utils/user/sample_data.rs
+++ b/crates/router/src/utils/user/sample_data.rs
@@ -397,6 +397,7 @@ pub async fn generate_sample_data(
is_stored_credential: None,
authorized_amount: None,
tokenization: None,
+ encrypted_payment_method_data: None,
};
let refund = if refunds_count < number_of_refunds && !is_failed_payment {
diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs
index a604493ad0..d9213bcc99 100644
--- a/crates/router/src/workflows/payment_sync.rs
+++ b/crates/router/src/workflows/payment_sync.rs
@@ -162,7 +162,8 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow {
authentication_type: None,
issuer_error_code: None,
issuer_error_message: None,
- network_details:None
+ network_details:None,
+ encrypted_payment_method_data: None,
};
payment_data.payment_attempt = db
@@ -170,6 +171,7 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow {
payment_data.payment_attempt,
payment_attempt_update,
merchant_account.storage_scheme,
+ &key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index a853d5d93b..eec4e9bebd 100644
--- a/crates/storage_impl/src/mock_db/payment_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs
@@ -2,18 +2,16 @@ use common_utils::errors::CustomResult;
#[cfg(feature = "v2")]
use common_utils::id_type;
use diesel_models::enums as storage_enums;
-#[cfg(feature = "v2")]
-use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;
+use error_stack::ResultExt;
#[cfg(feature = "v1")]
-use hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptNew;
-use hyperswitch_domain_models::payments::payment_attempt::{
- PaymentAttempt, PaymentAttemptInterface, PaymentAttemptUpdate,
+use hyperswitch_domain_models::behaviour::Conversion;
+use hyperswitch_domain_models::{
+ merchant_key_store::MerchantKeyStore,
+ payments::payment_attempt::{PaymentAttempt, PaymentAttemptInterface, PaymentAttemptUpdate},
};
use super::MockDb;
use crate::errors::StorageError;
-#[cfg(feature = "v1")]
-use crate::DataModelExt;
#[async_trait::async_trait]
impl PaymentAttemptInterface for MockDb {
@@ -25,6 +23,7 @@ impl PaymentAttemptInterface for MockDb {
_merchant_id: &common_utils::id_type::MerchantId,
_attempt_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
+ _merchant_key_store: &MerchantKeyStore,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
@@ -82,6 +81,7 @@ impl PaymentAttemptInterface for MockDb {
_attempt_id: &str,
_merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
+ _merchant_key_store: &MerchantKeyStore,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
@@ -115,6 +115,7 @@ impl PaymentAttemptInterface for MockDb {
_preprocessing_id: &str,
_merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
+ _merchant_key_store: &MerchantKeyStore,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
@@ -126,6 +127,7 @@ impl PaymentAttemptInterface for MockDb {
_merchant_id: &common_utils::id_type::MerchantId,
_connector_txn_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
+ _merchant_key_store: &MerchantKeyStore,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
@@ -149,6 +151,7 @@ impl PaymentAttemptInterface for MockDb {
_merchant_id: &common_utils::id_type::MerchantId,
_payment_id: &common_utils::id_type::PaymentId,
_storage_scheme: storage_enums::MerchantStorageScheme,
+ _merchant_key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentAttempt>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
@@ -158,11 +161,11 @@ impl PaymentAttemptInterface for MockDb {
#[allow(clippy::panic)]
async fn insert_payment_attempt(
&self,
- payment_attempt: PaymentAttemptNew,
+ payment_attempt: PaymentAttempt,
storage_scheme: storage_enums::MerchantStorageScheme,
+ _merchant_key_store: &MerchantKeyStore,
) -> CustomResult<PaymentAttempt, StorageError> {
let mut payment_attempts = self.payment_attempts.lock().await;
- let time = common_utils::date_time::now();
let payment_attempt = PaymentAttempt {
payment_id: payment_attempt.payment_id,
merchant_id: payment_attempt.merchant_id,
@@ -181,8 +184,8 @@ impl PaymentAttemptInterface for MockDb {
capture_on: payment_attempt.capture_on,
confirm: payment_attempt.confirm,
authentication_type: payment_attempt.authentication_type,
- created_at: payment_attempt.created_at.unwrap_or(time),
- modified_at: payment_attempt.modified_at.unwrap_or(time),
+ created_at: payment_attempt.created_at,
+ modified_at: payment_attempt.modified_at,
last_synced: payment_attempt.last_synced,
cancellation_reason: payment_attempt.cancellation_reason,
amount_to_capture: payment_attempt.amount_to_capture,
@@ -243,6 +246,7 @@ impl PaymentAttemptInterface for MockDb {
is_stored_credential: payment_attempt.is_stored_credential,
authorized_amount: payment_attempt.authorized_amount,
tokenization: payment_attempt.tokenization,
+ encrypted_payment_method_data: payment_attempt.encrypted_payment_method_data,
};
payment_attempts.push(payment_attempt.clone());
Ok(payment_attempt)
@@ -268,6 +272,7 @@ impl PaymentAttemptInterface for MockDb {
this: PaymentAttempt,
payment_attempt: PaymentAttemptUpdate,
_storage_scheme: storage_enums::MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> CustomResult<PaymentAttempt, StorageError> {
let mut payment_attempts = self.payment_attempts.lock().await;
@@ -275,12 +280,24 @@ impl PaymentAttemptInterface for MockDb {
.iter_mut()
.find(|item| item.attempt_id == this.attempt_id)
.unwrap();
-
- *item = PaymentAttempt::from_storage_model(
- payment_attempt
- .to_storage_model()
- .apply_changeset(this.to_storage_model()),
- );
+ let diesel_payment_attempt = this
+ .convert()
+ .await
+ .change_context(StorageError::EncryptionError)?;
+ let updated_diesel_payment_attempt = payment_attempt
+ .to_storage_model()
+ .apply_changeset(diesel_payment_attempt);
+ let key_manager_state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
+ *item = PaymentAttempt::convert_back(
+ key_manager_state,
+ updated_diesel_payment_attempt,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)?;
Ok(item.clone())
}
@@ -304,6 +321,7 @@ impl PaymentAttemptInterface for MockDb {
_payment_id: &common_utils::id_type::PaymentId,
_merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
+ _merchant_key_store: &MerchantKeyStore,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
@@ -317,6 +335,7 @@ impl PaymentAttemptInterface for MockDb {
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
+ _merchant_key_store: &MerchantKeyStore,
) -> CustomResult<PaymentAttempt, StorageError> {
let payment_attempts = self.payment_attempts.lock().await;
@@ -337,6 +356,7 @@ impl PaymentAttemptInterface for MockDb {
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
+ _merchant_key_store: &MerchantKeyStore,
) -> CustomResult<PaymentAttempt, StorageError> {
let payment_attempts = self.payment_attempts.lock().await;
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index fe515d3e02..6a3d305f68 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -1,11 +1,6 @@
-use common_utils::errors::CustomResult;
+use common_utils::{errors::CustomResult, ext_traits::AsyncExt};
#[cfg(feature = "v1")]
-use common_utils::{
- fallback_reverse_lookup_not_found,
- types::{ConnectorTransactionId, ConnectorTransactionIdTrait, CreatedBy},
-};
-#[cfg(feature = "v1")]
-use diesel_models::payment_attempt::PaymentAttemptNew as DieselPaymentAttemptNew;
+use common_utils::{fallback_reverse_lookup_not_found, types::ConnectorTransactionId};
use diesel_models::{
enums::{
MandateAmountData as DieselMandateAmountData, MandateDataType as DieselMandateType,
@@ -16,15 +11,14 @@ use diesel_models::{
reverse_lookup::{ReverseLookup, ReverseLookupNew},
};
use error_stack::ResultExt;
-#[cfg(feature = "v1")]
-use hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptNew;
+#[cfg(all(feature = "v1", feature = "olap"))]
+use futures::future::{try_join_all, FutureExt};
#[cfg(feature = "v2")]
+use hyperswitch_domain_models::behaviour::ReverseConversion;
use hyperswitch_domain_models::{
- behaviour::{Conversion, ReverseConversion},
- merchant_key_store::MerchantKeyStore,
-};
-use hyperswitch_domain_models::{
+ behaviour::Conversion,
mandates::{MandateAmountData, MandateDataType, MandateDetails},
+ merchant_key_store::MerchantKeyStore,
payments::payment_attempt::{PaymentAttempt, PaymentAttemptInterface, PaymentAttemptUpdate},
};
#[cfg(all(feature = "v1", feature = "olap"))]
@@ -55,19 +49,36 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
#[instrument(skip_all)]
async fn insert_payment_attempt(
&self,
- payment_attempt: PaymentAttemptNew,
+ payment_attempt: PaymentAttempt,
_storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_write(self).await?;
- payment_attempt
- .to_storage_model()
+ let diesel_payment_attempt = payment_attempt
+ .construct_new()
+ .await
+ .change_context(errors::StorageError::EncryptionError)?;
+ let key_manager_state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
+ diesel_payment_attempt
.insert(&conn)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
- .map(PaymentAttempt::from_storage_model)
+ .async_map(|diesel_payment_attempt| async {
+ PaymentAttempt::convert_back(
+ key_manager_state,
+ diesel_payment_attempt,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await?
}
#[cfg(feature = "v2")]
@@ -106,16 +117,32 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
this: PaymentAttempt,
payment_attempt: PaymentAttemptUpdate,
_storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_write(self).await?;
- this.to_storage_model()
+ let key_manager_state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
+ this.convert()
+ .await
+ .change_context(errors::StorageError::EncryptionError)?
.update_with_attempt_id(&conn, payment_attempt.to_storage_model())
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
- .map(PaymentAttempt::from_storage_model)
+ .async_map(|diesel_payment_attempt| async {
+ PaymentAttempt::convert_back(
+ key_manager_state,
+ diesel_payment_attempt,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await?
}
#[cfg(feature = "v2")]
@@ -159,8 +186,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
+ let key_manager_state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
DieselPaymentAttempt::find_by_connector_transaction_id_payment_id_merchant_id(
&conn,
connector_transaction_id,
@@ -172,7 +203,17 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
- .map(PaymentAttempt::from_storage_model)
+ .async_map(|diesel_payment_attempt| async {
+ PaymentAttempt::convert_back(
+ key_manager_state,
+ diesel_payment_attempt,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await?
}
#[cfg(feature = "v1")]
@@ -182,8 +223,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
+ let key_manager_state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
DieselPaymentAttempt::find_last_successful_attempt_by_payment_id_merchant_id(
&conn,
payment_id,
@@ -194,7 +239,17 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
- .map(PaymentAttempt::from_storage_model)
+ .async_map(|diesel_payment_attempt| async {
+ PaymentAttempt::convert_back(
+ key_manager_state,
+ diesel_payment_attempt,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await?
}
#[cfg(feature = "v1")]
@@ -204,8 +259,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
+ let key_manager_state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
DieselPaymentAttempt::find_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id(
&conn,
payment_id,
@@ -216,7 +275,16 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
- .map(PaymentAttempt::from_storage_model)
+ .async_map(|diesel_payment_attempt| async {
+ PaymentAttempt::convert_back(
+ key_manager_state,
+ diesel_payment_attempt,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }).await?
}
#[cfg(feature = "v2")]
@@ -253,8 +321,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
merchant_id: &common_utils::id_type::MerchantId,
connector_txn_id: &str,
_storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
+ let key_manager_state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
DieselPaymentAttempt::find_by_merchant_id_connector_txn_id(
&conn,
merchant_id,
@@ -265,7 +337,17 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
- .map(PaymentAttempt::from_storage_model)
+ .async_map(|diesel_payment_attempt| async {
+ PaymentAttempt::convert_back(
+ key_manager_state,
+ diesel_payment_attempt,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await?
}
#[instrument(skip_all)]
@@ -306,8 +388,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
merchant_id: &common_utils::id_type::MerchantId,
attempt_id: &str,
_storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
+ let key_manager_state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
DieselPaymentAttempt::find_by_payment_id_merchant_id_attempt_id(
&conn,
@@ -320,7 +406,17 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
- .map(PaymentAttempt::from_storage_model)
+ .async_map(|diesel_payment_attempt| async {
+ PaymentAttempt::convert_back(
+ key_manager_state,
+ diesel_payment_attempt,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await?
}
#[cfg(all(feature = "v1", feature = "olap"))]
@@ -334,7 +430,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
use hyperswitch_domain_models::behaviour::Conversion;
let conn = pg_connection_read(self).await?;
- let intents = futures::future::try_join_all(pi.iter().cloned().map(|pi| async {
+ let intents = try_join_all(pi.iter().cloned().map(|pi| async {
Conversion::convert(pi)
.await
.change_context(errors::StorageError::EncryptionError)
@@ -373,8 +469,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
preprocessing_id: &str,
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
+ let key_manager_state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
DieselPaymentAttempt::find_by_merchant_id_preprocessing_id(
&conn,
@@ -386,7 +486,17 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
- .map(PaymentAttempt::from_storage_model)
+ .async_map(|diesel_payment_attempt| async {
+ PaymentAttempt::convert_back(
+ key_manager_state,
+ diesel_payment_attempt,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await?
}
#[cfg(feature = "v1")]
@@ -396,19 +506,32 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
_storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentAttempt>, errors::StorageError> {
let conn = pg_connection_read(self).await?;
+ let key_manager_state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
DieselPaymentAttempt::find_by_merchant_id_payment_id(&conn, merchant_id, payment_id)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
- .map(|a| {
- a.into_iter()
- .map(PaymentAttempt::from_storage_model)
- .collect()
- })
+ .map(|v| {
+ try_join_all(v.into_iter().map(|diesel_payment_attempt| {
+ PaymentAttempt::convert_back(
+ key_manager_state,
+ diesel_payment_attempt,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ }))
+ .map(|join_result| {
+ join_result.change_context(errors::StorageError::DecryptionError)
+ })
+ })?
+ .await
}
#[cfg(feature = "v1")]
@@ -418,8 +541,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
attempt_id: &str,
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
+ let key_manager_state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
DieselPaymentAttempt::find_by_merchant_id_attempt_id(&conn, merchant_id, attempt_id)
.await
@@ -427,7 +554,17 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
- .map(PaymentAttempt::from_storage_model)
+ .async_map(|diesel_payment_attempt| async {
+ PaymentAttempt::convert_back(
+ key_manager_state,
+ diesel_payment_attempt,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await?
}
#[cfg(feature = "v2")]
@@ -587,8 +724,9 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
#[instrument(skip_all)]
async fn insert_payment_attempt(
&self,
- payment_attempt: PaymentAttemptNew,
+ payment_attempt: PaymentAttempt,
storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
self,
@@ -599,7 +737,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
- .insert_payment_attempt(payment_attempt, storage_scheme)
+ .insert_payment_attempt(payment_attempt, storage_scheme, merchant_key_store)
.await
}
MerchantStorageScheme::RedisKv => {
@@ -628,12 +766,8 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
capture_on: payment_attempt.capture_on,
confirm: payment_attempt.confirm,
authentication_type: payment_attempt.authentication_type,
- created_at: payment_attempt
- .created_at
- .unwrap_or_else(common_utils::date_time::now),
- modified_at: payment_attempt
- .created_at
- .unwrap_or_else(common_utils::date_time::now),
+ created_at: payment_attempt.created_at,
+ modified_at: payment_attempt.created_at,
last_synced: payment_attempt.last_synced,
amount_to_capture: payment_attempt.amount_to_capture,
cancellation_reason: payment_attempt.cancellation_reason.clone(),
@@ -698,6 +832,9 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
is_stored_credential: payment_attempt.is_stored_credential,
authorized_amount: payment_attempt.authorized_amount,
tokenization: payment_attempt.tokenization,
+ encrypted_payment_method_data: payment_attempt
+ .encrypted_payment_method_data
+ .clone(),
};
let field = format!("pa_{}", created_attempt.attempt_id);
@@ -705,7 +842,10 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
insertable: Box::new(kv::Insertable::PaymentAttempt(Box::new(
- payment_attempt.to_storage_model(),
+ payment_attempt
+ .construct_new()
+ .await
+ .change_context(errors::StorageError::EncryptionError)?,
))),
},
};
@@ -725,11 +865,15 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
self.insert_reverse_lookup(reverse_lookup, storage_scheme)
.await?;
- match Box::pin(kv_wrapper::<PaymentAttempt, _, _>(
+ match Box::pin(kv_wrapper::<DieselPaymentAttempt, _, _>(
self,
KvOperation::HSetNx(
&field,
- &created_attempt.clone().to_storage_model(),
+ &created_attempt
+ .clone()
+ .convert()
+ .await
+ .change_context(errors::StorageError::EncryptionError)?,
redis_entry,
),
key,
@@ -858,6 +1002,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
this: PaymentAttempt,
payment_attempt: PaymentAttemptUpdate,
storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let key = PartitionKey::MerchantIdPaymentId {
merchant_id: &this.merchant_id,
@@ -873,19 +1018,35 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
- .update_payment_attempt_with_attempt_id(this, payment_attempt, storage_scheme)
+ .update_payment_attempt_with_attempt_id(
+ this,
+ payment_attempt,
+ storage_scheme,
+ merchant_key_store,
+ )
.await
}
MerchantStorageScheme::RedisKv => {
let key_str = key.to_string();
let old_connector_transaction_id = &this.get_connector_payment_id();
let old_preprocessing_id = &this.preprocessing_step_id;
- let updated_attempt = PaymentAttempt::from_storage_model(
- payment_attempt
- .clone()
- .to_storage_model()
- .apply_changeset(this.clone().to_storage_model()),
- );
+ let key_manager_state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
+ let updated_attempt = PaymentAttempt::convert_back(
+ key_manager_state,
+ payment_attempt.clone().to_storage_model().apply_changeset(
+ this.clone()
+ .convert()
+ .await
+ .change_context(errors::StorageError::EncryptionError)?,
+ ),
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::EncryptionError)
+ .attach_printable("Error while constructing domain model")?;
// Check for database presence as well Maybe use a read replica here ?
let redis_value = serde_json::to_string(&updated_attempt)
.change_context(errors::StorageError::KVError)?;
@@ -894,7 +1055,11 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
op: kv::DBOperation::Update {
updatable: Box::new(kv::Updateable::PaymentAttemptUpdate(Box::new(
kv::PaymentAttemptUpdateMems {
- orig: this.clone().to_storage_model(),
+ orig: this
+ .clone()
+ .convert()
+ .await
+ .change_context(errors::StorageError::EncryptionError)?,
update_data: payment_attempt.to_storage_model(),
},
))),
@@ -1032,6 +1197,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
self,
@@ -1047,6 +1213,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_id,
merchant_id,
storage_scheme,
+ merchant_key_store,
)
.await
}
@@ -1066,6 +1233,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_id,
merchant_id,
storage_scheme,
+ merchant_key_store,
)
.await
);
@@ -1073,12 +1241,24 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
let key = PartitionKey::CombinationKey {
combination: &lookup.pk_id,
};
+ let key_manager_state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
Box::pin(try_redis_get_else_try_database_get(
async {
- Box::pin(kv_wrapper(self, KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id), key)).await?.try_into_hget()
+ let diesel_payment_attempt = Box::pin(kv_wrapper(self, KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id), key)).await?.try_into_hget()?;
+ PaymentAttempt::convert_back(
+ key_manager_state,
+ diesel_payment_attempt,
+ merchant_key_store.key.get_inner(),
+ merchant_id.clone().into(),
+ )
+ .await
+ .change_context(redis_interface::errors::RedisError::UnknownResult)
+ .attach_printable("Error while constructing domain model")
},
- || async {self.router_store.find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(connector_transaction_id, payment_id, merchant_id, storage_scheme).await},
+ || async {self.router_store.find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(connector_transaction_id, payment_id, merchant_id, storage_scheme, merchant_key_store).await},
))
.await
}
@@ -1092,6 +1272,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let database_call = || {
self.router_store
@@ -1099,6 +1280,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_id,
merchant_id,
storage_scheme,
+ merchant_key_store,
)
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
@@ -1115,16 +1297,19 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_id,
};
let pattern = "pa_*";
+ let key_manager_state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
let redis_fut = async {
- let kv_result = Box::pin(kv_wrapper::<PaymentAttempt, _, _>(
+ let kv_result = Box::pin(kv_wrapper::<DieselPaymentAttempt, _, _>(
self,
KvOperation::<DieselPaymentAttempt>::Scan(pattern),
key,
))
.await?
.try_into_scan();
- kv_result.and_then(|mut payment_attempts| {
+ let diesel_payment_attempt = kv_result.and_then(|mut payment_attempts| {
payment_attempts.sort_by(|a, b| b.modified_at.cmp(&a.modified_at));
payment_attempts
.iter()
@@ -1133,7 +1318,16 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
.ok_or(error_stack::report!(
redis_interface::errors::RedisError::NotFound
))
- })
+ })?;
+ PaymentAttempt::convert_back(
+ key_manager_state,
+ diesel_payment_attempt,
+ merchant_key_store.key.get_inner(),
+ merchant_id.clone().into(),
+ )
+ .await
+ .change_context(redis_interface::errors::RedisError::UnknownResult)
+ .attach_printable("Error while constructing domain model")
};
Box::pin(try_redis_get_else_try_database_get(
redis_fut,
@@ -1151,6 +1345,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let database_call = || {
self.router_store
@@ -1158,6 +1353,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_id,
merchant_id,
storage_scheme,
+ merchant_key_store,
)
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
@@ -1174,16 +1370,19 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_id,
};
let pattern = "pa_*";
+ let key_manager_state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
let redis_fut = async {
- let kv_result = Box::pin(kv_wrapper::<PaymentAttempt, _, _>(
+ let kv_result = Box::pin(kv_wrapper::<DieselPaymentAttempt, _, _>(
self,
KvOperation::<DieselPaymentAttempt>::Scan(pattern),
key,
))
.await?
.try_into_scan();
- kv_result.and_then(|mut payment_attempts| {
+ let diesel_payment_attempt = kv_result.and_then(|mut payment_attempts| {
payment_attempts.sort_by(|a, b| b.modified_at.cmp(&a.modified_at));
payment_attempts
.iter()
@@ -1195,7 +1394,16 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
.ok_or(error_stack::report!(
redis_interface::errors::RedisError::NotFound
))
- })
+ })?;
+ PaymentAttempt::convert_back(
+ key_manager_state,
+ diesel_payment_attempt,
+ merchant_key_store.key.get_inner(),
+ merchant_id.clone().into(),
+ )
+ .await
+ .change_context(redis_interface::errors::RedisError::UnknownResult)
+ .attach_printable("Error while constructing domain model")
};
Box::pin(try_redis_get_else_try_database_get(
redis_fut,
@@ -1313,6 +1521,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
merchant_id: &common_utils::id_type::MerchantId,
connector_txn_id: &str,
storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
self,
@@ -1327,6 +1536,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
merchant_id,
connector_txn_id,
storage_scheme,
+ merchant_key_store,
)
.await
}
@@ -1343,6 +1553,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
merchant_id,
connector_txn_id,
storage_scheme,
+ merchant_key_store,
)
.await
);
@@ -1350,15 +1561,27 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
let key = PartitionKey::CombinationKey {
combination: &lookup.pk_id,
};
+ let key_manager_state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
Box::pin(try_redis_get_else_try_database_get(
async {
- Box::pin(kv_wrapper(
+ let diesel_payment_attempt = Box::pin(kv_wrapper(
self,
KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id),
key,
))
.await?
- .try_into_hget()
+ .try_into_hget()?;
+ PaymentAttempt::convert_back(
+ key_manager_state,
+ diesel_payment_attempt,
+ merchant_key_store.key.get_inner(),
+ merchant_id.clone().into(),
+ )
+ .await
+ .change_context(redis_interface::errors::RedisError::UnknownResult)
+ .attach_printable("Error while constructing domain model")
},
|| async {
self.router_store
@@ -1366,6 +1589,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
merchant_id,
connector_txn_id,
storage_scheme,
+ merchant_key_store,
)
.await
},
@@ -1383,6 +1607,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
merchant_id: &common_utils::id_type::MerchantId,
attempt_id: &str,
storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
self,
@@ -1398,6 +1623,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
merchant_id,
attempt_id,
storage_scheme,
+ merchant_key_store,
)
.await
}
@@ -1407,15 +1633,27 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_id,
};
let field = format!("pa_{attempt_id}");
+ let key_manager_state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
Box::pin(try_redis_get_else_try_database_get(
async {
- Box::pin(kv_wrapper(
+ let diesel_payment_attempt = Box::pin(kv_wrapper(
self,
KvOperation::<DieselPaymentAttempt>::HGet(&field),
key,
))
.await?
- .try_into_hget()
+ .try_into_hget()?;
+ PaymentAttempt::convert_back(
+ key_manager_state,
+ diesel_payment_attempt,
+ merchant_key_store.key.get_inner(),
+ merchant_id.clone().into(),
+ )
+ .await
+ .change_context(redis_interface::errors::RedisError::UnknownResult)
+ .attach_printable("Error while constructing domain model")
},
|| async {
self.router_store
@@ -1424,6 +1662,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
merchant_id,
attempt_id,
storage_scheme,
+ merchant_key_store,
)
.await
},
@@ -1440,6 +1679,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
attempt_id: &str,
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
self,
@@ -1454,6 +1694,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
attempt_id,
merchant_id,
storage_scheme,
+ merchant_key_store,
)
.await
}
@@ -1467,6 +1708,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
attempt_id,
merchant_id,
storage_scheme,
+ merchant_key_store,
)
.await
);
@@ -1474,15 +1716,27 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
let key = PartitionKey::CombinationKey {
combination: &lookup.pk_id,
};
+ let key_manager_state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
Box::pin(try_redis_get_else_try_database_get(
async {
- Box::pin(kv_wrapper(
+ let diesel_payment_attempt = Box::pin(kv_wrapper(
self,
KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id),
key,
))
.await?
- .try_into_hget()
+ .try_into_hget()?;
+ PaymentAttempt::convert_back(
+ key_manager_state,
+ diesel_payment_attempt,
+ merchant_key_store.key.get_inner(),
+ merchant_id.clone().into(),
+ )
+ .await
+ .change_context(redis_interface::errors::RedisError::UnknownResult)
+ .attach_printable("Error while constructing domain model")
},
|| async {
self.router_store
@@ -1490,6 +1744,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
attempt_id,
merchant_id,
storage_scheme,
+ merchant_key_store,
)
.await
},
@@ -1547,6 +1802,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
preprocessing_id: &str,
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
self,
@@ -1561,6 +1817,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
preprocessing_id,
merchant_id,
storage_scheme,
+ merchant_key_store,
)
.await
}
@@ -1577,22 +1834,35 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
preprocessing_id,
merchant_id,
storage_scheme,
+ merchant_key_store,
)
.await
);
let key = PartitionKey::CombinationKey {
combination: &lookup.pk_id,
};
+ let key_manager_state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
Box::pin(try_redis_get_else_try_database_get(
async {
- Box::pin(kv_wrapper(
+ let diesel_payment_attempt = Box::pin(kv_wrapper(
self,
KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id),
key,
))
.await?
- .try_into_hget()
+ .try_into_hget()?;
+ PaymentAttempt::convert_back(
+ key_manager_state,
+ diesel_payment_attempt,
+ merchant_key_store.key.get_inner(),
+ merchant_id.clone().into(),
+ )
+ .await
+ .change_context(redis_interface::errors::RedisError::UnknownResult)
+ .attach_printable("Error while constructing domain model")
},
|| async {
self.router_store
@@ -1600,6 +1870,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
preprocessing_id,
merchant_id,
storage_scheme,
+ merchant_key_store,
)
.await
},
@@ -1616,6 +1887,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
storage_scheme: MerchantStorageScheme,
+ merchant_key_store: &MerchantKeyStore,
) -> error_stack::Result<Vec<PaymentAttempt>, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
self,
@@ -1630,6 +1902,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
merchant_id,
payment_id,
storage_scheme,
+ merchant_key_store,
)
.await
}
@@ -1638,6 +1911,9 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
merchant_id,
payment_id,
};
+ let key_manager_state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
Box::pin(try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper(
@@ -1647,6 +1923,22 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
))
.await?
.try_into_scan()
+ .map(|v| {
+ try_join_all(v.into_iter().map(|diesel_payment_attempt| {
+ PaymentAttempt::convert_back(
+ key_manager_state,
+ diesel_payment_attempt,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ }))
+ .map(|join_result| {
+ join_result
+ .change_context(errors::RedisError::UnknownResult)
+ .attach_printable("Error while constructing domain model")
+ })
+ })?
+ .await
},
|| async {
self.router_store
@@ -1654,6 +1946,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
merchant_id,
payment_id,
storage_scheme,
+ merchant_key_store,
)
.await
},
@@ -1799,404 +2092,6 @@ impl DataModelExt for MandateDataType {
}
}
-#[cfg(feature = "v1")]
-impl DataModelExt for PaymentAttempt {
- type StorageModel = DieselPaymentAttempt;
-
- fn to_storage_model(self) -> Self::StorageModel {
- let (connector_transaction_id, processor_transaction_data) = self
- .connector_transaction_id
- .map(ConnectorTransactionId::form_id_and_data)
- .map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
- .unwrap_or((None, None));
- DieselPaymentAttempt {
- payment_id: self.payment_id,
- merchant_id: self.merchant_id,
- attempt_id: self.attempt_id,
- status: self.status,
- amount: self.net_amount.get_order_amount(),
- net_amount: Some(self.net_amount.get_total_amount()),
- currency: self.currency,
- save_to_locker: self.save_to_locker,
- connector: self.connector,
- error_message: self.error_message,
- offer_amount: self.offer_amount,
- surcharge_amount: self.net_amount.get_surcharge_amount(),
- tax_amount: self.net_amount.get_tax_on_surcharge(),
- payment_method_id: self.payment_method_id,
- payment_method: self.payment_method,
- connector_transaction_id,
- capture_method: self.capture_method,
- capture_on: self.capture_on,
- confirm: self.confirm,
- authentication_type: self.authentication_type,
- created_at: self.created_at,
- modified_at: self.modified_at,
- last_synced: self.last_synced,
- cancellation_reason: self.cancellation_reason,
- amount_to_capture: self.amount_to_capture,
- mandate_id: self.mandate_id,
- browser_info: self.browser_info,
- error_code: self.error_code,
- payment_token: self.payment_token,
- connector_metadata: self.connector_metadata,
- payment_experience: self.payment_experience,
- payment_method_type: self.payment_method_type,
- card_network: self
- .payment_method_data
- .as_ref()
- .and_then(|data| data.as_object())
- .and_then(|card| card.get("card"))
- .and_then(|data| data.as_object())
- .and_then(|card| card.get("card_network"))
- .and_then(|network| network.as_str())
- .map(|network| network.to_string()),
- payment_method_data: self.payment_method_data,
- business_sub_label: self.business_sub_label,
- straight_through_algorithm: self.straight_through_algorithm,
- preprocessing_step_id: self.preprocessing_step_id,
- mandate_details: self.mandate_details.map(|d| d.to_storage_model()),
- error_reason: self.error_reason,
- multiple_capture_count: self.multiple_capture_count,
- connector_response_reference_id: self.connector_response_reference_id,
- amount_capturable: self.amount_capturable,
- updated_by: self.updated_by,
- authentication_data: self.authentication_data,
- encoded_data: self.encoded_data,
- merchant_connector_id: self.merchant_connector_id,
- unified_code: self.unified_code,
- unified_message: self.unified_message,
- external_three_ds_authentication_attempted: self
- .external_three_ds_authentication_attempted,
- authentication_connector: self.authentication_connector,
- authentication_id: self.authentication_id,
- mandate_data: self.mandate_data.map(|d| d.to_storage_model()),
- payment_method_billing_address_id: self.payment_method_billing_address_id,
- fingerprint_id: self.fingerprint_id,
- charge_id: self.charge_id,
- client_source: self.client_source,
- client_version: self.client_version,
- customer_acceptance: self.customer_acceptance,
- organization_id: self.organization_id,
- profile_id: self.profile_id,
- shipping_cost: self.net_amount.get_shipping_cost(),
- order_tax_amount: self.net_amount.get_order_tax_amount(),
- connector_mandate_detail: self.connector_mandate_detail,
- request_extended_authorization: self.request_extended_authorization,
- extended_authorization_applied: self.extended_authorization_applied,
- extended_authorization_last_applied_at: self.extended_authorization_last_applied_at,
- capture_before: self.capture_before,
- processor_transaction_data,
- card_discovery: self.card_discovery,
- charges: self.charges,
- issuer_error_code: self.issuer_error_code,
- issuer_error_message: self.issuer_error_message,
- setup_future_usage_applied: self.setup_future_usage_applied,
- routing_approach: self.routing_approach,
- // Below fields are deprecated. Please add any new fields above this line.
- connector_transaction_data: None,
- processor_merchant_id: Some(self.processor_merchant_id),
- created_by: self.created_by.map(|created_by| created_by.to_string()),
- connector_request_reference_id: self.connector_request_reference_id,
- network_transaction_id: self.network_transaction_id,
- is_overcapture_enabled: self.is_overcapture_enabled,
- network_details: self.network_details,
- is_stored_credential: self.is_stored_credential,
- authorized_amount: self.authorized_amount,
- tokenization: self.tokenization,
- }
- }
-
- fn from_storage_model(storage_model: Self::StorageModel) -> Self {
- let connector_transaction_id = storage_model
- .get_optional_connector_transaction_id()
- .cloned();
- Self {
- net_amount: hyperswitch_domain_models::payments::payment_attempt::NetAmount::new(
- storage_model.amount,
- storage_model.shipping_cost,
- storage_model.order_tax_amount,
- storage_model.surcharge_amount,
- storage_model.tax_amount,
- ),
- payment_id: storage_model.payment_id,
- merchant_id: storage_model.merchant_id.clone(),
- attempt_id: storage_model.attempt_id,
- status: storage_model.status,
- currency: storage_model.currency,
- save_to_locker: storage_model.save_to_locker,
- connector: storage_model.connector,
- error_message: storage_model.error_message,
- offer_amount: storage_model.offer_amount,
- payment_method_id: storage_model.payment_method_id,
- payment_method: storage_model.payment_method,
- connector_transaction_id,
- capture_method: storage_model.capture_method,
- capture_on: storage_model.capture_on,
- confirm: storage_model.confirm,
- authentication_type: storage_model.authentication_type,
- created_at: storage_model.created_at,
- modified_at: storage_model.modified_at,
- last_synced: storage_model.last_synced,
- cancellation_reason: storage_model.cancellation_reason,
- amount_to_capture: storage_model.amount_to_capture,
- mandate_id: storage_model.mandate_id,
- browser_info: storage_model.browser_info,
- error_code: storage_model.error_code,
- payment_token: storage_model.payment_token,
- connector_metadata: storage_model.connector_metadata,
- payment_experience: storage_model.payment_experience,
- payment_method_type: storage_model.payment_method_type,
- payment_method_data: storage_model.payment_method_data,
- business_sub_label: storage_model.business_sub_label,
- straight_through_algorithm: storage_model.straight_through_algorithm,
- preprocessing_step_id: storage_model.preprocessing_step_id,
- mandate_details: storage_model
- .mandate_details
- .map(MandateDataType::from_storage_model),
- error_reason: storage_model.error_reason,
- multiple_capture_count: storage_model.multiple_capture_count,
- connector_response_reference_id: storage_model.connector_response_reference_id,
- amount_capturable: storage_model.amount_capturable,
- updated_by: storage_model.updated_by,
- authentication_data: storage_model.authentication_data,
- encoded_data: storage_model.encoded_data,
- merchant_connector_id: storage_model.merchant_connector_id,
- unified_code: storage_model.unified_code,
- unified_message: storage_model.unified_message,
- external_three_ds_authentication_attempted: storage_model
- .external_three_ds_authentication_attempted,
- authentication_connector: storage_model.authentication_connector,
- authentication_id: storage_model.authentication_id,
- mandate_data: storage_model
- .mandate_data
- .map(MandateDetails::from_storage_model),
- payment_method_billing_address_id: storage_model.payment_method_billing_address_id,
- fingerprint_id: storage_model.fingerprint_id,
- charge_id: storage_model.charge_id,
- client_source: storage_model.client_source,
- client_version: storage_model.client_version,
- customer_acceptance: storage_model.customer_acceptance,
- organization_id: storage_model.organization_id,
- profile_id: storage_model.profile_id,
- connector_mandate_detail: storage_model.connector_mandate_detail,
- request_extended_authorization: storage_model.request_extended_authorization,
- extended_authorization_applied: storage_model.extended_authorization_applied,
- extended_authorization_last_applied_at: storage_model
- .extended_authorization_last_applied_at,
- capture_before: storage_model.capture_before,
- card_discovery: storage_model.card_discovery,
- charges: storage_model.charges,
- issuer_error_code: storage_model.issuer_error_code,
- issuer_error_message: storage_model.issuer_error_message,
- processor_merchant_id: storage_model
- .processor_merchant_id
- .unwrap_or(storage_model.merchant_id),
- created_by: storage_model
- .created_by
- .and_then(|created_by| created_by.parse::<CreatedBy>().ok()),
- setup_future_usage_applied: storage_model.setup_future_usage_applied,
- routing_approach: storage_model.routing_approach,
- connector_request_reference_id: storage_model.connector_request_reference_id,
- debit_routing_savings: None,
- network_transaction_id: storage_model.network_transaction_id,
- is_overcapture_enabled: storage_model.is_overcapture_enabled,
- network_details: storage_model.network_details,
- is_stored_credential: storage_model.is_stored_credential,
- authorized_amount: storage_model.authorized_amount,
- tokenization: storage_model.tokenization,
- }
- }
-}
-
-#[cfg(feature = "v1")]
-impl DataModelExt for PaymentAttemptNew {
- type StorageModel = DieselPaymentAttemptNew;
-
- fn to_storage_model(self) -> Self::StorageModel {
- DieselPaymentAttemptNew {
- net_amount: Some(self.net_amount.get_total_amount()),
- payment_id: self.payment_id,
- merchant_id: self.merchant_id,
- attempt_id: self.attempt_id,
- status: self.status,
- amount: self.net_amount.get_order_amount(),
- currency: self.currency,
- save_to_locker: self.save_to_locker,
- connector: self.connector,
- error_message: self.error_message,
- offer_amount: self.offer_amount,
- surcharge_amount: self.net_amount.get_surcharge_amount(),
- tax_amount: self.net_amount.get_tax_on_surcharge(),
- payment_method_id: self.payment_method_id,
- payment_method: self.payment_method,
- capture_method: self.capture_method,
- capture_on: self.capture_on,
- confirm: self.confirm,
- authentication_type: self.authentication_type,
- created_at: self.created_at.unwrap_or_else(common_utils::date_time::now),
- modified_at: self
- .modified_at
- .unwrap_or_else(common_utils::date_time::now),
- last_synced: self.last_synced,
- cancellation_reason: self.cancellation_reason,
- amount_to_capture: self.amount_to_capture,
- mandate_id: self.mandate_id,
- browser_info: self.browser_info,
- payment_token: self.payment_token,
- error_code: self.error_code,
- connector_metadata: self.connector_metadata,
- payment_experience: self.payment_experience,
- payment_method_type: self.payment_method_type,
- card_network: self
- .payment_method_data
- .as_ref()
- .and_then(|data| data.as_object())
- .and_then(|card| card.get("card"))
- .and_then(|value| value.as_object())
- .and_then(|map| map.get("card_network"))
- .and_then(|network| network.as_str())
- .map(|network| network.to_string()),
- payment_method_data: self.payment_method_data,
- business_sub_label: self.business_sub_label,
- straight_through_algorithm: self.straight_through_algorithm,
- preprocessing_step_id: self.preprocessing_step_id,
- mandate_details: self.mandate_details.map(|d| d.to_storage_model()),
- error_reason: self.error_reason,
- connector_response_reference_id: self.connector_response_reference_id,
- multiple_capture_count: self.multiple_capture_count,
- amount_capturable: self.amount_capturable,
- updated_by: self.updated_by,
- authentication_data: self.authentication_data,
- encoded_data: self.encoded_data,
- merchant_connector_id: self.merchant_connector_id,
- unified_code: self.unified_code,
- unified_message: self.unified_message,
- external_three_ds_authentication_attempted: self
- .external_three_ds_authentication_attempted,
- authentication_connector: self.authentication_connector,
- authentication_id: self.authentication_id,
- mandate_data: self.mandate_data.map(|d| d.to_storage_model()),
- payment_method_billing_address_id: self.payment_method_billing_address_id,
- fingerprint_id: self.fingerprint_id,
- client_source: self.client_source,
- client_version: self.client_version,
- customer_acceptance: self.customer_acceptance,
- organization_id: self.organization_id,
- profile_id: self.profile_id,
- shipping_cost: self.net_amount.get_shipping_cost(),
- order_tax_amount: self.net_amount.get_order_tax_amount(),
- connector_mandate_detail: self.connector_mandate_detail,
- request_extended_authorization: self.request_extended_authorization,
- extended_authorization_applied: self.extended_authorization_applied,
- extended_authorization_last_applied_at: self.extended_authorization_last_applied_at,
- capture_before: self.capture_before,
- card_discovery: self.card_discovery,
- processor_merchant_id: Some(self.processor_merchant_id),
- created_by: self.created_by.map(|created_by| created_by.to_string()),
- setup_future_usage_applied: self.setup_future_usage_applied,
- routing_approach: self.routing_approach,
- connector_request_reference_id: self.connector_request_reference_id,
- network_transaction_id: self.network_transaction_id,
- network_details: self.network_details,
- is_stored_credential: self.is_stored_credential,
- authorized_amount: self.authorized_amount,
- tokenization: self.tokenization,
- }
- }
-
- fn from_storage_model(storage_model: Self::StorageModel) -> Self {
- Self {
- net_amount: hyperswitch_domain_models::payments::payment_attempt::NetAmount::new(
- storage_model.amount,
- storage_model.shipping_cost,
- storage_model.order_tax_amount,
- storage_model.surcharge_amount,
- storage_model.tax_amount,
- ),
- payment_id: storage_model.payment_id,
- merchant_id: storage_model.merchant_id.clone(),
- attempt_id: storage_model.attempt_id,
- status: storage_model.status,
- currency: storage_model.currency,
- save_to_locker: storage_model.save_to_locker,
- connector: storage_model.connector,
- error_message: storage_model.error_message,
- offer_amount: storage_model.offer_amount,
- payment_method_id: storage_model.payment_method_id,
- payment_method: storage_model.payment_method,
- capture_method: storage_model.capture_method,
- capture_on: storage_model.capture_on,
- confirm: storage_model.confirm,
- authentication_type: storage_model.authentication_type,
- created_at: Some(storage_model.created_at),
- modified_at: Some(storage_model.modified_at),
- last_synced: storage_model.last_synced,
- cancellation_reason: storage_model.cancellation_reason,
- amount_to_capture: storage_model.amount_to_capture,
- mandate_id: storage_model.mandate_id,
- browser_info: storage_model.browser_info,
- payment_token: storage_model.payment_token,
- error_code: storage_model.error_code,
- connector_metadata: storage_model.connector_metadata,
- payment_experience: storage_model.payment_experience,
- payment_method_type: storage_model.payment_method_type,
- payment_method_data: storage_model.payment_method_data,
- business_sub_label: storage_model.business_sub_label,
- straight_through_algorithm: storage_model.straight_through_algorithm,
- preprocessing_step_id: storage_model.preprocessing_step_id,
- mandate_details: storage_model
- .mandate_details
- .map(MandateDataType::from_storage_model),
- error_reason: storage_model.error_reason,
- connector_response_reference_id: storage_model.connector_response_reference_id,
- multiple_capture_count: storage_model.multiple_capture_count,
- amount_capturable: storage_model.amount_capturable,
- updated_by: storage_model.updated_by,
- authentication_data: storage_model.authentication_data,
- encoded_data: storage_model.encoded_data,
- merchant_connector_id: storage_model.merchant_connector_id,
- unified_code: storage_model.unified_code,
- unified_message: storage_model.unified_message,
- external_three_ds_authentication_attempted: storage_model
- .external_three_ds_authentication_attempted,
- authentication_connector: storage_model.authentication_connector,
- authentication_id: storage_model.authentication_id,
- mandate_data: storage_model
- .mandate_data
- .map(MandateDetails::from_storage_model),
- payment_method_billing_address_id: storage_model.payment_method_billing_address_id,
- fingerprint_id: storage_model.fingerprint_id,
- client_source: storage_model.client_source,
- client_version: storage_model.client_version,
- customer_acceptance: storage_model.customer_acceptance,
- organization_id: storage_model.organization_id,
- profile_id: storage_model.profile_id,
- connector_mandate_detail: storage_model.connector_mandate_detail,
- request_extended_authorization: storage_model.request_extended_authorization,
- extended_authorization_applied: storage_model.extended_authorization_applied,
- extended_authorization_last_applied_at: storage_model
- .extended_authorization_last_applied_at,
- capture_before: storage_model.capture_before,
- card_discovery: storage_model.card_discovery,
- processor_merchant_id: storage_model
- .processor_merchant_id
- .unwrap_or(storage_model.merchant_id),
- created_by: storage_model
- .created_by
- .and_then(|created_by| created_by.parse::<CreatedBy>().ok()),
- setup_future_usage_applied: storage_model.setup_future_usage_applied,
- routing_approach: storage_model.routing_approach,
- connector_request_reference_id: storage_model.connector_request_reference_id,
- network_transaction_id: storage_model.network_transaction_id,
- network_details: storage_model.network_details,
- is_stored_credential: storage_model.is_stored_credential,
- authorized_amount: storage_model.authorized_amount,
- tokenization: storage_model.tokenization,
- }
- }
-}
-
#[inline]
#[instrument(skip_all)]
async fn add_connector_txn_id_to_reverse_lookup<T: DatabaseStore>(
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index 177cd2057b..dcd3a791d9 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -29,6 +29,8 @@ use diesel_models::{
enums::MerchantStorageScheme, kv, payment_intent::PaymentIntent as DieselPaymentIntent,
};
use error_stack::ResultExt;
+#[cfg(all(feature = "v1", feature = "olap"))]
+use futures::future::try_join_all;
#[cfg(feature = "olap")]
use hyperswitch_domain_models::payments::{
payment_attempt::PaymentAttempt, payment_intent::PaymentIntentFetchConstraints,
@@ -1101,10 +1103,6 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, StorageError> {
- use futures::{future::try_join_all, FutureExt};
-
- use crate::DataModelExt;
-
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = DieselPaymentIntent::table()
@@ -1273,35 +1271,43 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
let keymanager_state = self
.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?;
+
query
.get_results_async::<(
DieselPaymentIntent,
diesel_models::payment_attempt::PaymentAttempt,
)>(conn)
.await
- .map(|results| {
- try_join_all(results.into_iter().map(|(pi, pa)| {
- PaymentIntent::convert_back(
+ .async_map(|results| {
+ try_join_all(results.into_iter().map(|(pi, pa)| async {
+ let payment_intent = PaymentIntent::convert_back(
keymanager_state,
pi,
merchant_key_store.key.get_inner(),
merchant_id.to_owned().into(),
)
- .map(|payment_intent| {
- payment_intent.map(|payment_intent| {
- (payment_intent, PaymentAttempt::from_storage_model(pa))
- })
- })
+ .await
+ .change_context(StorageError::DecryptionError)?;
+
+ let payment_attempt = PaymentAttempt::convert_back(
+ keymanager_state,
+ pa,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)?;
+
+ Ok((payment_intent, payment_attempt))
}))
- .map(|join_result| join_result.change_context(StorageError::DecryptionError))
})
+ .await
.map_err(|er| {
StorageError::DatabaseError(
error_stack::report!(diesel_models::errors::DatabaseError::from(er))
.attach_printable("Error filtering payment records"),
)
})?
- .await
}
#[cfg(all(feature = "v2", feature = "olap"))]
diff --git a/migrations/2025-11-25-131915_add-enc-payment-method-data-in-attempt/down.sql b/migrations/2025-11-25-131915_add-enc-payment-method-data-in-attempt/down.sql
new file mode 100644
index 0000000000..da79e06dd7
--- /dev/null
+++ b/migrations/2025-11-25-131915_add-enc-payment-method-data-in-attempt/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_attempt DROP COLUMN IF EXISTS encrypted_payment_method_data;
\ No newline at end of file
diff --git a/migrations/2025-11-25-131915_add-enc-payment-method-data-in-attempt/up.sql b/migrations/2025-11-25-131915_add-enc-payment-method-data-in-attempt/up.sql
new file mode 100644
index 0000000000..2c6207decb
--- /dev/null
+++ b/migrations/2025-11-25-131915_add-enc-payment-method-data-in-attempt/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS encrypted_payment_method_data BYTEA;