diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index ed591af7a6..42fb5dad54 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -10603,58 +10603,6 @@ "display_wait_screen" ] }, - "PaymentIdType": { - "oneOf": [ - { - "type": "object", - "required": [ - "PaymentIntentId" - ], - "properties": { - "PaymentIntentId": { - "type": "string", - "description": "The identifier for payment intent" - } - } - }, - { - "type": "object", - "required": [ - "ConnectorTransactionId" - ], - "properties": { - "ConnectorTransactionId": { - "type": "string", - "description": "The identifier for connector transaction" - } - } - }, - { - "type": "object", - "required": [ - "PaymentAttemptId" - ], - "properties": { - "PaymentAttemptId": { - "type": "string", - "description": "The identifier for payment attempt" - } - } - }, - { - "type": "object", - "required": [ - "PreprocessingId" - ], - "properties": { - "PreprocessingId": { - "type": "string", - "description": "The identifier for preprocessing step" - } - } - } - ] - }, "PaymentLinkConfig": { "type": "object", "required": [ @@ -14422,7 +14370,8 @@ ], "properties": { "resource_id": { - "$ref": "#/components/schemas/PaymentIdType" + "type": "string", + "description": "The type of ID (ex: payment intent id, payment attempt id or connector txn id)" }, "merchant_id": { "type": "string", @@ -14526,28 +14475,6 @@ } } }, - "PaymentsStartRequest": { - "type": "object", - "required": [ - "payment_id", - "merchant_id", - "attempt_id" - ], - "properties": { - "payment_id": { - "type": "string", - "description": "Unique identifier for the payment. This ensures idempotency for multiple payments\nthat have been done by a single merchant. This field is auto generated and is returned in the API response." - }, - "merchant_id": { - "type": "string", - "description": "The identifier for the Merchant Account." - }, - "attempt_id": { - "type": "string", - "description": "The identifier for the payment transaction" - } - } - }, "PaymentsUpdateRequest": { "type": "object", "properties": { diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 70bfc8c986..df713aa14a 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -14616,58 +14616,6 @@ "display_wait_screen" ] }, - "PaymentIdType": { - "oneOf": [ - { - "type": "object", - "required": [ - "PaymentIntentId" - ], - "properties": { - "PaymentIntentId": { - "type": "string", - "description": "The identifier for payment intent" - } - } - }, - { - "type": "object", - "required": [ - "ConnectorTransactionId" - ], - "properties": { - "ConnectorTransactionId": { - "type": "string", - "description": "The identifier for connector transaction" - } - } - }, - { - "type": "object", - "required": [ - "PaymentAttemptId" - ], - "properties": { - "PaymentAttemptId": { - "type": "string", - "description": "The identifier for payment attempt" - } - } - }, - { - "type": "object", - "required": [ - "PreprocessingId" - ], - "properties": { - "PreprocessingId": { - "type": "string", - "description": "The identifier for preprocessing step" - } - } - } - ] - }, "PaymentLinkConfig": { "type": "object", "required": [ @@ -18435,7 +18383,8 @@ ], "properties": { "resource_id": { - "$ref": "#/components/schemas/PaymentIdType" + "type": "string", + "description": "The type of ID (ex: payment intent id, payment attempt id or connector txn id)" }, "merchant_id": { "type": "string", @@ -18539,28 +18488,6 @@ } } }, - "PaymentsStartRequest": { - "type": "object", - "required": [ - "payment_id", - "merchant_id", - "attempt_id" - ], - "properties": { - "payment_id": { - "type": "string", - "description": "Unique identifier for the payment. This ensures idempotency for multiple payments\nthat have been done by a single merchant. This field is auto generated and is returned in the API response." - }, - "merchant_id": { - "type": "string", - "description": "The identifier for the Merchant Account." - }, - "attempt_id": { - "type": "string", - "description": "The identifier for the payment transaction" - } - } - }, "PaymentsUpdateRequest": { "type": "object", "properties": { diff --git a/crates/analytics/src/api_event/events.rs b/crates/analytics/src/api_event/events.rs index 039172d1e0..3003288ddd 100644 --- a/crates/analytics/src/api_event/events.rs +++ b/crates/analytics/src/api_event/events.rs @@ -35,7 +35,7 @@ where match query_param.query_param { QueryType::Payment { payment_id } => { query_builder - .add_filter_clause("payment_id", payment_id) + .add_filter_clause("payment_id", &payment_id) .switch()?; query_builder .add_filter_in_range_clause( @@ -62,7 +62,7 @@ where refund_id, } => { query_builder - .add_filter_clause("payment_id", payment_id) + .add_filter_clause("payment_id", &payment_id) .switch()?; query_builder .add_filter_clause("refund_id", refund_id) @@ -76,7 +76,7 @@ where dispute_id, } => { query_builder - .add_filter_clause("payment_id", payment_id) + .add_filter_clause("payment_id", &payment_id) .switch()?; query_builder .add_filter_clause("dispute_id", dispute_id) @@ -103,7 +103,7 @@ where #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct ApiLogsResult { pub merchant_id: common_utils::id_type::MerchantId, - pub payment_id: Option, + pub payment_id: Option, pub refund_id: Option, pub payment_method_id: Option, pub payment_method: Option, diff --git a/crates/analytics/src/connector_events/events.rs b/crates/analytics/src/connector_events/events.rs index 9bdbba3297..3c04bab1a4 100644 --- a/crates/analytics/src/connector_events/events.rs +++ b/crates/analytics/src/connector_events/events.rs @@ -31,7 +31,7 @@ where .switch()?; query_builder - .add_filter_clause("payment_id", query_param.payment_id) + .add_filter_clause("payment_id", &query_param.payment_id) .switch()?; if let Some(refund_id) = query_param.refund_id { diff --git a/crates/analytics/src/outgoing_webhook_event/events.rs b/crates/analytics/src/outgoing_webhook_event/events.rs index 9aaddec256..c7b4c80cfd 100644 --- a/crates/analytics/src/outgoing_webhook_event/events.rs +++ b/crates/analytics/src/outgoing_webhook_event/events.rs @@ -30,7 +30,7 @@ where .add_filter_clause("merchant_id", merchant_id) .switch()?; query_builder - .add_filter_clause("payment_id", query_param.payment_id) + .add_filter_clause("payment_id", &query_param.payment_id) .switch()?; if let Some(event_id) = query_param.event_id { @@ -76,7 +76,7 @@ pub struct OutgoingWebhookLogsResult { pub event_id: String, pub event_type: String, pub outgoing_webhook_event_type: String, - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub refund_id: Option, pub attempt_id: Option, pub dispute_id: Option, diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index d9f85f9e77..7e2fdd1244 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -360,6 +360,12 @@ impl ToSql for &common_utils::id_type::MerchantId { } } +impl ToSql for &common_utils::id_type::PaymentId { + fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result { + Ok(self.get_string_repr().to_owned()) + } +} + /// Implement `ToSql` on arrays of types that impl `ToString`. macro_rules! impl_to_sql_for_to_string { ($($type:ty),+) => { diff --git a/crates/analytics/src/sdk_events/events.rs b/crates/analytics/src/sdk_events/events.rs index 3120c75138..5fdf92f242 100644 --- a/crates/analytics/src/sdk_events/events.rs +++ b/crates/analytics/src/sdk_events/events.rs @@ -37,7 +37,7 @@ where .add_filter_clause("merchant_id", publishable_key) .switch()?; query_builder - .add_filter_clause("payment_id", request.payment_id) + .add_filter_clause("payment_id", &request.payment_id) .switch()?; query_builder .add_custom_filter_clause("event_name", static_event_list, FilterTypes::In) @@ -58,7 +58,7 @@ where #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct SdkEventsResult { pub merchant_id: common_utils::id_type::MerchantId, - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub event_name: Option, pub log_type: Option, pub first_event: bool, diff --git a/crates/api_models/src/analytics/api_event.rs b/crates/api_models/src/analytics/api_event.rs index 5fe8e4ff3a..ac8c014ed9 100644 --- a/crates/api_models/src/analytics/api_event.rs +++ b/crates/api_models/src/analytics/api_event.rs @@ -20,14 +20,14 @@ pub enum FilterType { #[serde(tag = "type")] pub enum QueryType { Payment { - payment_id: String, + payment_id: common_utils::id_type::PaymentId, }, Refund { - payment_id: String, + payment_id: common_utils::id_type::PaymentId, refund_id: String, }, Dispute { - payment_id: String, + payment_id: common_utils::id_type::PaymentId, dispute_id: String, }, } diff --git a/crates/api_models/src/analytics/outgoing_webhook_event.rs b/crates/api_models/src/analytics/outgoing_webhook_event.rs index b6f0aca056..e2373ca5ca 100644 --- a/crates/api_models/src/analytics/outgoing_webhook_event.rs +++ b/crates/api_models/src/analytics/outgoing_webhook_event.rs @@ -1,6 +1,6 @@ #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct OutgoingWebhookLogsRequest { - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub event_id: Option, pub refund_id: Option, pub dispute_id: Option, diff --git a/crates/api_models/src/analytics/sdk_events.rs b/crates/api_models/src/analytics/sdk_events.rs index 9e33181ec6..b2abbbe00e 100644 --- a/crates/api_models/src/analytics/sdk_events.rs +++ b/crates/api_models/src/analytics/sdk_events.rs @@ -8,7 +8,7 @@ use super::{NameDescription, TimeRange}; #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct SdkEventsRequest { - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub time_range: TimeRange, } diff --git a/crates/api_models/src/disputes.rs b/crates/api_models/src/disputes.rs index 42803c519c..5c2a2cc03d 100644 --- a/crates/api_models/src/disputes.rs +++ b/crates/api_models/src/disputes.rs @@ -10,7 +10,8 @@ pub struct DisputeResponse { /// The identifier for dispute pub dispute_id: String, /// The identifier for payment_intent - pub payment_id: String, + #[schema(value_type = String)] + pub payment_id: common_utils::id_type::PaymentId, /// The identifier for payment_attempt pub attempt_id: String, /// The dispute amount diff --git a/crates/api_models/src/errors/types.rs b/crates/api_models/src/errors/types.rs index 48e9ce5670..2b88bdba91 100644 --- a/crates/api_models/src/errors/types.rs +++ b/crates/api_models/src/errors/types.rs @@ -70,7 +70,7 @@ impl<'a> From<&'a ApiErrorResponse> for ErrorResponse<'a> { #[derive(Debug, serde::Serialize, Default, Clone)] pub struct Extra { #[serde(skip_serializing_if = "Option::is_none")] - pub payment_id: Option, + pub payment_id: Option, #[serde(skip_serializing_if = "Option::is_none")] pub data: Option, #[serde(skip_serializing_if = "Option::is_none")] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 0aa917166e..5cb159302a 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -68,12 +68,22 @@ pub struct BankCodeResponse { pub eligible_connectors: Vec, } -#[derive(Debug, PartialEq)] +#[derive(Debug, PartialEq, Clone)] pub struct ClientSecret { - pub payment_id: String, + pub payment_id: id_type::PaymentId, pub secret: String, } +impl ClientSecret { + pub fn get_client_secret(&self) -> String { + format!( + "{}_secret_{}", + self.payment_id.get_string_repr(), + self.secret + ) + } +} + impl<'de> Deserialize<'de> for ClientSecret { fn deserialize(deserializer: D) -> Result where @@ -96,8 +106,12 @@ impl<'de> Deserialize<'de> for ClientSecret { E::invalid_value(Unexpected::Str(value), &"a string with '_secret_'") })?; + let payment_id = + id_type::PaymentId::try_from(std::borrow::Cow::Owned(payment_id.to_owned())) + .map_err(de::Error::custom)?; + Ok(ClientSecret { - payment_id: payment_id.to_owned(), + payment_id, secret: secret.to_owned(), }) } @@ -112,7 +126,11 @@ impl Serialize for ClientSecret { where S: Serializer, { - let combined = format!("{}_secret_{}", self.payment_id, self.secret); + let combined = format!( + "{}_secret_{}", + self.payment_id.get_string_repr(), + self.secret + ); serializer.serialize_str(&combined) } } @@ -120,6 +138,7 @@ impl Serialize for ClientSecret { #[cfg(test)] mod client_secret_tests { #![allow(clippy::expect_used)] + #![allow(clippy::unwrap_used)] use serde_json; @@ -128,11 +147,17 @@ mod client_secret_tests { #[test] fn test_serialize_client_secret() { let client_secret1 = ClientSecret { - payment_id: "pay_3TgelAms4RQec8xSStjF".to_string(), + payment_id: id_type::PaymentId::try_from(std::borrow::Cow::Borrowed( + "pay_3TgelAms4RQec8xSStjF", + )) + .unwrap(), secret: "fc34taHLw1ekPgNh92qr".to_string(), }; let client_secret2 = ClientSecret { - payment_id: "pay_3Tgel__Ams4RQ_secret_ec8xSStjF".to_string(), + payment_id: id_type::PaymentId::try_from(std::borrow::Cow::Borrowed( + "pay_3Tgel__Ams4RQ_secret_ec8xSStjF", + )) + .unwrap(), secret: "fc34taHLw1ekPgNh92qr".to_string(), }; @@ -157,15 +182,24 @@ mod client_secret_tests { r#""pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret__secret_fc34taHLw1ekPgNh92qr""#; let expected1 = ClientSecret { - payment_id: "pay_3TgelAms4RQec8xSStjF".to_string(), + payment_id: id_type::PaymentId::try_from(std::borrow::Cow::Borrowed( + "pay_3TgelAms4RQec8xSStjF", + )) + .unwrap(), secret: "fc34taHLw1ekPgNh92qr".to_string(), }; let expected2 = ClientSecret { - payment_id: "pay_3Tgel__Ams4RQ_secret_ec8xSStjF".to_string(), + payment_id: id_type::PaymentId::try_from(std::borrow::Cow::Borrowed( + "pay_3Tgel__Ams4RQ_secret_ec8xSStjF", + )) + .unwrap(), secret: "fc34taHLw1ekPgNh92qr".to_string(), }; let expected3 = ClientSecret { - payment_id: "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_".to_string(), + payment_id: id_type::PaymentId::try_from(std::borrow::Cow::Borrowed( + "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_", + )) + .unwrap(), secret: "fc34taHLw1ekPgNh92qr".to_string(), }; @@ -942,7 +976,7 @@ impl From for Amount { #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct PaymentsRedirectRequest { - pub payment_id: String, + pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub connector: String, pub param: String, @@ -999,7 +1033,7 @@ pub struct ConnectorMandateReferenceId { pub struct UpdateHistory { pub connector_mandate_id: Option, pub payment_method_id: String, - pub original_payment_id: Option, + pub original_payment_id: Option, } impl MandateIds { @@ -3055,7 +3089,7 @@ pub struct PaymentMethodDataResponseWithBilling { #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum PaymentIdType { /// The identifier for payment intent - PaymentIntentId(String), + PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt @@ -3068,7 +3102,11 @@ impl fmt::Display for PaymentIdType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PaymentIntentId(payment_id) => { - write!(f, "payment_intent_id = \"{payment_id}\"") + write!( + f, + "payment_intent_id = \"{}\"", + payment_id.get_string_repr() + ) } Self::ConnectorTransactionId(connector_transaction_id) => write!( f, @@ -3084,20 +3122,6 @@ impl fmt::Display for PaymentIdType { } } -impl PaymentIdType { - pub fn and_then(self, f: F) -> Result - where - F: FnOnce(String) -> Result, - { - match self { - Self::PaymentIntentId(s) => f(s).map(Self::PaymentIntentId), - Self::ConnectorTransactionId(s) => f(s).map(Self::ConnectorTransactionId), - Self::PaymentAttemptId(s) => f(s).map(Self::PaymentAttemptId), - Self::PreprocessingId(s) => f(s).map(Self::PreprocessingId), - } - } -} - impl Default for PaymentIdType { fn default() -> Self { Self::PaymentIntentId(Default::default()) @@ -3295,7 +3319,7 @@ pub struct PhoneDetails { pub struct PaymentsCaptureRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] - pub payment_id: String, + pub payment_id: id_type::PaymentId, /// The unique identifier for the merchant #[schema(value_type = Option)] pub merchant_id: Option, @@ -3571,9 +3595,10 @@ pub struct PaymentsResponse { #[schema( min_length = 30, max_length = 30, - example = "pay_mbabizu24mvu3mela5njyhpit4" + example = "pay_mbabizu24mvu3mela5njyhpit4", + value_type = String, )] - pub payment_id: String, + pub payment_id: id_type::PaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request @@ -3942,12 +3967,12 @@ pub struct PaymentListConstraints { pub customer_id: Option, /// A cursor for use in pagination, fetch the next list after some object - #[schema(example = "pay_fafa124123")] - pub starting_after: Option, + #[schema(example = "pay_fafa124123", value_type = Option)] + pub starting_after: Option, /// A cursor for use in pagination, fetch the previous list before some object - #[schema(example = "pay_fafa124123")] - pub ending_before: Option, + #[schema(example = "pay_fafa124123", value_type = Option)] + pub ending_before: Option, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] @@ -4032,7 +4057,7 @@ pub struct PaymentListResponseV2 { #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentListFilterConstraints { /// The identifier for payment - pub payment_id: Option, + pub payment_id: Option, /// The identifier for business profile pub profile_id: Option, /// The identifier for customer @@ -4153,7 +4178,7 @@ pub struct TimeRange { #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)] pub struct VerifyResponse { - pub verify_id: Option, + pub verify_id: Option, pub merchant_id: Option, // pub status: enums::VerifyStatus, pub client_secret: Option>, @@ -4308,7 +4333,7 @@ impl From for PaymentMethodDataResponse { #[derive(Debug, Clone, serde::Serialize)] pub struct PgRedirectResponse { - pub payment_id: String, + pub payment_id: id_type::PaymentId, pub status: api_enums::IntentStatus, pub gateway_id: String, pub customer_id: Option, @@ -4335,6 +4360,7 @@ pub struct PaymentsResponseForm { #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRetrieveRequest { /// The type of ID (ex: payment intent id, payment attempt id or connector txn id) + #[schema(value_type = String)] pub resource_id: PaymentIdType, /// The identifier for the Merchant Account. #[schema(value_type = Option)] @@ -4429,7 +4455,8 @@ pub struct RedirectResponse { #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest { /// The identifier for the payment - pub payment_id: String, + #[schema(value_type = String)] + pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: String, /// The list of the supported wallets @@ -4951,7 +4978,8 @@ pub struct ApplepayErrorResponse { #[derive(Default, Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment - pub payment_id: String, + #[schema(value_type = String)] + pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK #[schema(value_type = String)] pub client_secret: Secret, @@ -4977,7 +5005,7 @@ pub struct PaymentRetrieveBody { #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBodyWithCredentials { /// The identifier for payment. - pub payment_id: String, + pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. #[schema(value_type = Option)] pub merchant_id: Option, @@ -4991,7 +5019,7 @@ pub struct PaymentRetrieveBodyWithCredentials { pub struct PaymentsCompleteAuthorizeRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] - pub payment_id: String, + pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Option
, /// Client Secret @@ -5003,7 +5031,7 @@ pub struct PaymentsCompleteAuthorizeRequest { pub struct PaymentsCancelRequest { /// The identifier for the payment #[serde(skip)] - pub payment_id: String, + pub payment_id: id_type::PaymentId, /// The reason for the payment cancel pub cancellation_reason: Option, /// Merchant connector details used to make payments. @@ -5015,7 +5043,7 @@ pub struct PaymentsCancelRequest { pub struct PaymentsIncrementalAuthorizationRequest { /// The identifier for the payment #[serde(skip)] - pub payment_id: String, + pub payment_id: id_type::PaymentId, /// The total amount including previously authorized amount and additional amount #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, @@ -5027,7 +5055,7 @@ pub struct PaymentsIncrementalAuthorizationRequest { pub struct PaymentsExternalAuthenticationRequest { /// The identifier for the payment #[serde(skip)] - pub payment_id: String, + pub payment_id: id_type::PaymentId, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret, @@ -5044,7 +5072,7 @@ pub struct PaymentsExternalAuthenticationRequest { pub struct PaymentsManualUpdateRequest { /// The identifier for the payment #[serde(skip)] - pub payment_id: String, + pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID @@ -5065,7 +5093,7 @@ pub struct PaymentsManualUpdateRequest { #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateResponse { /// The identifier for the payment - pub payment_id: String, + pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID @@ -5148,23 +5176,22 @@ pub struct PaymentsExternalAuthenticationResponse { pub struct PaymentsApproveRequest { /// The identifier for the payment #[serde(skip)] - pub payment_id: String, + pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRejectRequest { /// The identifier for the payment #[serde(skip)] - pub payment_id: String, + pub payment_id: id_type::PaymentId, } -#[derive(Default, Debug, serde::Deserialize, serde::Serialize, ToSchema, Clone)] +#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentsStartRequest { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. This field is auto generated and is returned in the API response. - pub payment_id: String, + pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. - #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The identifier for the payment transaction pub attempt_id: String, @@ -5195,7 +5222,7 @@ pub struct FrmMessage { } mod payment_id_type { - use std::fmt; + use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, @@ -5218,7 +5245,9 @@ mod payment_id_type { where E: de::Error, { - Ok(PaymentIdType::PaymentIntentId(value.to_string())) + common_utils::id_type::PaymentId::try_from(Cow::Owned(value.to_string())) + .map_err(de::Error::custom) + .map(PaymentIdType::PaymentIntentId) } } @@ -5412,7 +5441,8 @@ pub struct RetrievePaymentLinkResponse { pub struct PaymentLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, - pub payment_id: String, + #[schema(value_type = String)] + pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Serialize)] @@ -5428,7 +5458,7 @@ pub struct PaymentLinkDetails { pub currency: api_enums::Currency, pub pub_key: String, pub client_secret: String, - pub payment_id: String, + pub payment_id: id_type::PaymentId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub merchant_logo: String, @@ -5455,7 +5485,7 @@ pub struct SecurePaymentLinkDetails { pub struct PaymentLinkStatusDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, - pub payment_id: String, + pub payment_id: id_type::PaymentId, pub merchant_logo: String, pub merchant_name: String, #[serde(with = "common_utils::custom_serde::iso8601")] diff --git a/crates/api_models/src/pm_auth.rs b/crates/api_models/src/pm_auth.rs index a949f618bd..8ed52907da 100644 --- a/crates/api_models/src/pm_auth.rs +++ b/crates/api_models/src/pm_auth.rs @@ -9,8 +9,8 @@ use common_utils::{ pub struct LinkTokenCreateRequest { pub language: Option, // optional language field to be passed pub client_secret: Option, // client secret to be passed in req body - pub payment_id: String, // payment_id to be passed in req body for redis pm_auth connector name fetch - pub payment_method: PaymentMethod, // payment_method to be used for filtering pm_auth connector + pub payment_id: id_type::PaymentId, // payment_id to be passed in req body for redis pm_auth connector name fetch + pub payment_method: PaymentMethod, // payment_method to be used for filtering pm_auth connector pub payment_method_type: PaymentMethodType, // payment_method_type to be used for filtering pm_auth connector } @@ -26,7 +26,7 @@ pub struct LinkTokenCreateResponse { pub struct ExchangeTokenCreateRequest { pub public_token: String, pub client_secret: Option, - pub payment_id: String, + pub payment_id: id_type::PaymentId, pub payment_method: PaymentMethod, pub payment_method_type: PaymentMethodType, } diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs index 1f3361d004..649c0dbf5c 100644 --- a/crates/api_models/src/refunds.rs +++ b/crates/api_models/src/refunds.rs @@ -19,9 +19,10 @@ pub struct RefundRequest { #[schema( max_length = 30, min_length = 30, - example = "pay_mbabizu24mvu3mela5njyhpit4" + example = "pay_mbabizu24mvu3mela5njyhpit4", + value_type = String, )] - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refunds initiated against the same payment. If this is not passed by the merchant, this field shall be auto generated and provided in the API response. It is recommended to generate uuid(v4) as the refund_id. #[schema( @@ -129,7 +130,8 @@ pub struct RefundResponse { /// Unique Identifier for the refund pub refund_id: String, /// The payment id against which refund is initiated - pub payment_id: String, + #[schema(value_type = String)] + pub payment_id: common_utils::id_type::PaymentId, /// The refund amount, which should be less than or equal to the total payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc #[schema(value_type = i64 , minimum = 100, example = 6540)] pub amount: MinorUnit, @@ -169,7 +171,8 @@ pub struct RefundResponse { #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundListRequest { /// The identifier for the payment - pub payment_id: Option, + #[schema(value_type = Option)] + pub payment_id: Option, /// The identifier for the refund pub refund_id: Option, /// The identifier for business profile diff --git a/crates/api_models/src/user/dashboard_metadata.rs b/crates/api_models/src/user/dashboard_metadata.rs index 91d1471d9e..1d606ef63e 100644 --- a/crates/api_models/src/user/dashboard_metadata.rs +++ b/crates/api_models/src/user/dashboard_metadata.rs @@ -68,7 +68,7 @@ pub struct ConfiguredRouting { #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TestPayment { - pub payment_id: String, + pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs index b245e67e85..ce9b303066 100644 --- a/crates/api_models/src/webhooks.rs +++ b/crates/api_models/src/webhooks.rs @@ -77,7 +77,7 @@ pub enum WebhookFlow { /// This enum tells about the affect a webhook had on an object pub enum WebhookResponseTracker { Payment { - payment_id: String, + payment_id: common_utils::id_type::PaymentId, status: common_enums::IntentStatus, }, #[cfg(feature = "payouts")] @@ -86,13 +86,13 @@ pub enum WebhookResponseTracker { status: common_enums::PayoutStatus, }, Refund { - payment_id: String, + payment_id: common_utils::id_type::PaymentId, refund_id: String, status: common_enums::RefundStatus, }, Dispute { dispute_id: String, - payment_id: String, + payment_id: common_utils::id_type::PaymentId, status: common_enums::DisputeStatus, }, Mandate { @@ -103,11 +103,11 @@ pub enum WebhookResponseTracker { } impl WebhookResponseTracker { - pub fn get_payment_id(&self) -> Option { + pub fn get_payment_id(&self) -> Option { match self { Self::Payment { payment_id, .. } | Self::Refund { payment_id, .. } - | Self::Dispute { payment_id, .. } => Some(payment_id.to_string()), + | Self::Dispute { payment_id, .. } => Some(payment_id.to_owned()), Self::NoEffect | Self::Mandate { .. } => None, #[cfg(feature = "payouts")] Self::Payout { .. } => None, diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index 7a0bbb5cbe..1e752a0f9b 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -16,10 +16,10 @@ pub enum ApiEventsType { payout_id: String, }, Payment { - payment_id: String, + payment_id: id_type::PaymentId, }, Refund { - payment_id: Option, + payment_id: Option, refund_id: String, }, PaymentMethod { @@ -46,13 +46,13 @@ pub enum ApiEventsType { }, Webhooks { connector: String, - payment_id: Option, + payment_id: Option, }, Routing, ResourceListAPI, PaymentRedirectionResponse { connector: Option, - payment_id: Option, + payment_id: Option, }, Gsm, // TODO: This has to be removed once the corresponding apiEventTypes are created @@ -80,6 +80,14 @@ pub enum ApiEventsType { impl ApiEventMetric for serde_json::Value {} impl ApiEventMetric for () {} +impl ApiEventMetric for id_type::PaymentId { + fn get_api_event_type(&self) -> Option { + Some(ApiEventsType::Payment { + payment_id: self.clone(), + }) + } +} + impl ApiEventMetric for Result { fn get_api_event_type(&self) -> Option { match self { diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs index 5182c821d0..1473881183 100644 --- a/crates/common_utils/src/id_type.rs +++ b/crates/common_utils/src/id_type.rs @@ -7,6 +7,7 @@ mod customer; mod merchant; mod merchant_connector_account; mod organization; +mod payment; mod profile; mod routing; @@ -23,6 +24,7 @@ use diesel::{ pub use merchant::MerchantId; pub use merchant_connector_account::MerchantConnectorAccountId; pub use organization::OrganizationId; +pub use payment::PaymentId; pub use profile::ProfileId; pub use routing::RoutingId; use serde::{Deserialize, Serialize}; diff --git a/crates/common_utils/src/id_type/payment.rs b/crates/common_utils/src/id_type/payment.rs new file mode 100644 index 0000000000..87e6eff29f --- /dev/null +++ b/crates/common_utils/src/id_type/payment.rs @@ -0,0 +1,86 @@ +use crate::{ + errors::{CustomResult, ValidationError}, + generate_id_with_default_len, + id_type::{AlphaNumericId, LengthId}, +}; + +crate::id_type!( + PaymentId, + "A type for payment_id that can be used for payment ids" +); +crate::impl_id_type_methods!(PaymentId, "payment_id"); + +// This is to display the `PaymentId` as PaymentId(abcd) +crate::impl_debug_id_type!(PaymentId); +crate::impl_default_id_type!(PaymentId, "pay"); +crate::impl_try_from_cow_str_id_type!(PaymentId, "payment_id"); + +crate::impl_queryable_id_type!(PaymentId); +crate::impl_to_sql_from_sql_id_type!(PaymentId); + +impl PaymentId { + /// Get the hash key to be stored in redis + pub fn get_hash_key_for_kv_store(&self) -> String { + format!("pi_{}", self.0 .0 .0) + } + + // This function should be removed once we have a better way to handle mandatory payment id in other flows + /// Get payment id in the format of irrelevant_payment_id_in_{flow} + pub fn get_irrelevant_id(flow: &str) -> Self { + let alphanumeric_id = + AlphaNumericId::new_unchecked(format!("irrelevant_payment_id_in_{flow}")); + let id = LengthId::new_unchecked(alphanumeric_id); + Self(id) + } + + /// Get the attempt id for the payment id based on the attempt count + pub fn get_attempt_id(&self, attempt_count: i16) -> String { + format!("{}_{attempt_count}", self.get_string_repr()) + } + + /// Generate a client id for the payment id + pub fn generate_client_secret(&self) -> String { + generate_id_with_default_len(&format!("{}_secret", self.get_string_repr())) + } + + /// Generate a key for pm_auth + pub fn get_pm_auth_key(&self) -> String { + format!("pm_auth_{}", self.get_string_repr()) + } + + /// Get external authentication request poll id + pub fn get_external_authentication_request_poll_id(&self) -> String { + format!("external_authentication_{}", self.get_string_repr()) + } + + /// Generate a test payment id with prefix test_ + pub fn generate_test_payment_id_for_sample_data() -> Self { + let id = generate_id_with_default_len("test"); + let alphanumeric_id = AlphaNumericId::new_unchecked(id); + let id = LengthId::new_unchecked(alphanumeric_id); + Self(id) + } + + /// Wrap a string inside PaymentId + pub fn wrap(payment_id_string: String) -> CustomResult { + Self::try_from(std::borrow::Cow::from(payment_id_string)) + } +} + +#[cfg(feature = "metrics")] +/// This is implemented so that we can use payment id directly as attribute in metrics +impl From for router_env::opentelemetry::Value { + fn from(val: PaymentId) -> Self { + let string_value = val.0 .0 .0; + Self::String(router_env::opentelemetry::StringValue::from(string_value)) + } +} + +// #[cfg(feature = "metrics")] +// /// This is implemented so that we can use payment id directly as attribute in metrics +// impl router_env::tracing::Value for PaymentId { +// fn record(&self, key: &router_env::types::Field, visitor: &mut dyn router_env::types::Visit) { +// let string_value = self.get_string_repr(); +// visitor.record_str(key, &string_value); +// } +// } diff --git a/crates/diesel_models/src/address.rs b/crates/diesel_models/src/address.rs index aaaa7fb747..a1cfb66871 100644 --- a/crates/diesel_models/src/address.rs +++ b/crates/diesel_models/src/address.rs @@ -29,7 +29,7 @@ pub struct AddressNew { pub country_code: Option, pub customer_id: Option, pub merchant_id: common_utils::id_type::MerchantId, - pub payment_id: Option, + pub payment_id: Option, pub created_at: PrimitiveDateTime, pub modified_at: PrimitiveDateTime, pub updated_by: String, @@ -55,7 +55,7 @@ pub struct Address { pub modified_at: PrimitiveDateTime, pub customer_id: Option, pub merchant_id: common_utils::id_type::MerchantId, - pub payment_id: Option, + pub payment_id: Option, pub updated_by: String, pub email: Option, } diff --git a/crates/diesel_models/src/authentication.rs b/crates/diesel_models/src/authentication.rs index 488066ff25..0310e60ebb 100644 --- a/crates/diesel_models/src/authentication.rs +++ b/crates/diesel_models/src/authentication.rs @@ -42,7 +42,7 @@ pub struct Authentication { pub acs_trans_id: Option, pub acs_signed_content: Option, pub profile_id: common_utils::id_type::ProfileId, - pub payment_id: Option, + pub payment_id: Option, pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, pub ds_trans_id: Option, pub directory_server_id: Option, @@ -89,7 +89,7 @@ pub struct AuthenticationNew { pub acs_trans_id: Option, pub acs_signed_content: Option, pub profile_id: common_utils::id_type::ProfileId, - pub payment_id: Option, + pub payment_id: Option, pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, pub ds_trans_id: Option, pub directory_server_id: Option, diff --git a/crates/diesel_models/src/authorization.rs b/crates/diesel_models/src/authorization.rs index 2792bfdd55..8f9fc5721e 100644 --- a/crates/diesel_models/src/authorization.rs +++ b/crates/diesel_models/src/authorization.rs @@ -12,7 +12,7 @@ use crate::{enums as storage_enums, schema::incremental_authorization}; pub struct Authorization { pub authorization_id: String, pub merchant_id: common_utils::id_type::MerchantId, - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub amount: MinorUnit, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, @@ -30,7 +30,7 @@ pub struct Authorization { pub struct AuthorizationNew { pub authorization_id: String, pub merchant_id: common_utils::id_type::MerchantId, - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub amount: MinorUnit, pub status: storage_enums::AuthorizationStatus, pub error_code: Option, diff --git a/crates/diesel_models/src/capture.rs b/crates/diesel_models/src/capture.rs index 714a6a3735..0b0b86222e 100644 --- a/crates/diesel_models/src/capture.rs +++ b/crates/diesel_models/src/capture.rs @@ -11,7 +11,7 @@ use crate::{enums as storage_enums, schema::captures}; #[diesel(table_name = captures, primary_key(capture_id), check_for_backend(diesel::pg::Pg))] pub struct Capture { pub capture_id: String, - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::CaptureStatus, pub amount: MinorUnit, @@ -36,7 +36,7 @@ pub struct Capture { #[diesel(table_name = captures)] pub struct CaptureNew { pub capture_id: String, - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::CaptureStatus, pub amount: MinorUnit, diff --git a/crates/diesel_models/src/dispute.rs b/crates/diesel_models/src/dispute.rs index 1c70655406..130e46aa9c 100644 --- a/crates/diesel_models/src/dispute.rs +++ b/crates/diesel_models/src/dispute.rs @@ -15,7 +15,7 @@ pub struct DisputeNew { pub currency: String, pub dispute_stage: storage_enums::DisputeStage, pub dispute_status: storage_enums::DisputeStatus, - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub attempt_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub connector_status: String, @@ -41,7 +41,7 @@ pub struct Dispute { pub currency: String, pub dispute_stage: storage_enums::DisputeStage, pub dispute_status: storage_enums::DisputeStatus, - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub attempt_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub connector_status: String, diff --git a/crates/diesel_models/src/events.rs b/crates/diesel_models/src/events.rs index 2cc2bfff3b..b6c5efe0fd 100644 --- a/crates/diesel_models/src/events.rs +++ b/crates/diesel_models/src/events.rs @@ -99,17 +99,17 @@ impl ToEncryptable, Encryption> for EventWithEn #[diesel(sql_type = diesel::sql_types::Jsonb)] pub enum EventMetadata { Payment { - payment_id: String, + payment_id: common_utils::id_type::PaymentId, }, Payout { payout_id: String, }, Refund { - payment_id: String, + payment_id: common_utils::id_type::PaymentId, refund_id: String, }, Dispute { - payment_id: String, + payment_id: common_utils::id_type::PaymentId, attempt_id: String, dispute_id: String, }, diff --git a/crates/diesel_models/src/fraud_check.rs b/crates/diesel_models/src/fraud_check.rs index 36fe01ea71..6b709cc07c 100644 --- a/crates/diesel_models/src/fraud_check.rs +++ b/crates/diesel_models/src/fraud_check.rs @@ -11,7 +11,7 @@ use crate::{ #[diesel(table_name = fraud_check, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct FraudCheck { pub frm_id: String, - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub attempt_id: String, pub created_at: PrimitiveDateTime, @@ -33,7 +33,7 @@ pub struct FraudCheck { #[diesel(table_name = fraud_check)] pub struct FraudCheckNew { pub frm_id: String, - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub attempt_id: String, pub created_at: PrimitiveDateTime, diff --git a/crates/diesel_models/src/mandate.rs b/crates/diesel_models/src/mandate.rs index dc6916f3c4..09a4ab17d0 100644 --- a/crates/diesel_models/src/mandate.rs +++ b/crates/diesel_models/src/mandate.rs @@ -32,7 +32,7 @@ pub struct Mandate { pub end_date: Option, pub metadata: Option, pub connector_mandate_ids: Option, - pub original_payment_id: Option, + pub original_payment_id: Option, pub merchant_connector_id: Option, pub updated_by: Option, } @@ -70,7 +70,7 @@ pub struct MandateNew { pub end_date: Option, pub metadata: Option, pub connector_mandate_ids: Option, - pub original_payment_id: Option, + pub original_payment_id: Option, pub merchant_connector_id: Option, pub updated_by: Option, } @@ -96,7 +96,7 @@ pub enum MandateUpdate { connector_mandate_id: Option, connector_mandate_ids: Option, payment_method_id: String, - original_payment_id: Option, + original_payment_id: Option, }, } @@ -133,7 +133,7 @@ pub struct MandateUpdateInternal { connector_mandate_ids: Option, connector_mandate_id: Option, payment_method_id: Option, - original_payment_id: Option, + original_payment_id: Option, updated_by: Option, } diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index fd769d4dbd..4e57ec3420 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -15,7 +15,7 @@ use crate::schema_v2::payment_attempt; )] #[diesel(table_name = payment_attempt, primary_key(attempt_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentAttempt { - pub payment_id: String, + pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub attempt_id: String, pub status: storage_enums::AttemptStatus, @@ -89,7 +89,7 @@ pub struct PaymentAttempt { )] #[diesel(table_name = payment_attempt, primary_key(attempt_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentAttempt { - pub payment_id: String, + pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub attempt_id: String, pub status: storage_enums::AttemptStatus, @@ -176,7 +176,7 @@ pub struct PaymentListFilters { #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_attempt)] pub struct PaymentAttemptNew { - pub payment_id: String, + pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub attempt_id: String, pub status: storage_enums::AttemptStatus, diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index c96629ea44..179769f9c3 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -14,7 +14,7 @@ use crate::schema_v2::payment_intent; #[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable)] #[diesel(table_name = payment_intent, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentIntent { - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, @@ -76,7 +76,7 @@ pub struct PaymentIntent { #[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable)] #[diesel(table_name = payment_intent, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentIntent { - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, @@ -139,7 +139,7 @@ pub struct PaymentIntent { )] #[diesel(table_name = payment_intent)] pub struct PaymentIntentNew { - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, diff --git a/crates/diesel_models/src/payment_link.rs b/crates/diesel_models/src/payment_link.rs index 51e3b89d60..c5fa9ade0d 100644 --- a/crates/diesel_models/src/payment_link.rs +++ b/crates/diesel_models/src/payment_link.rs @@ -9,7 +9,7 @@ use crate::{enums as storage_enums, schema::payment_link}; #[diesel(table_name = payment_link, primary_key(payment_link_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentLink { pub payment_link_id: String, - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub link_to_pay: String, pub merchant_id: common_utils::id_type::MerchantId, pub amount: MinorUnit, @@ -40,7 +40,7 @@ pub struct PaymentLink { #[diesel(table_name = payment_link)] pub struct PaymentLinkNew { pub payment_link_id: String, - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub link_to_pay: String, pub merchant_id: common_utils::id_type::MerchantId, pub amount: MinorUnit, diff --git a/crates/diesel_models/src/query/address.rs b/crates/diesel_models/src/query/address.rs index 572a5c7fe0..23c3711a8a 100644 --- a/crates/diesel_models/src/query/address.rs +++ b/crates/diesel_models/src/query/address.rs @@ -107,7 +107,7 @@ impl Address { pub async fn find_by_merchant_id_payment_id_address_id<'a>( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, address_id: &str, ) -> StorageResult { match generics::generic_find_one::<::Table, _, _>( diff --git a/crates/diesel_models/src/query/authorization.rs b/crates/diesel_models/src/query/authorization.rs index 61b0fb06a0..d0f75f523e 100644 --- a/crates/diesel_models/src/query/authorization.rs +++ b/crates/diesel_models/src/query/authorization.rs @@ -59,7 +59,7 @@ impl Authorization { pub async fn find_by_merchant_id_payment_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, ) -> StorageResult> { generics::generic_filter::<::Table, _, _, _>( conn, diff --git a/crates/diesel_models/src/query/capture.rs b/crates/diesel_models/src/query/capture.rs index fb2859be7a..e194dc9f64 100644 --- a/crates/diesel_models/src/query/capture.rs +++ b/crates/diesel_models/src/query/capture.rs @@ -50,7 +50,7 @@ impl Capture { pub async fn find_all_by_merchant_id_payment_id_authorized_attempt_id( merchant_id: &common_utils::id_type::MerchantId, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, authorized_attempt_id: &str, conn: &PgPooledConn, ) -> StorageResult> { diff --git a/crates/diesel_models/src/query/connector_response.rs b/crates/diesel_models/src/query/connector_response.rs index 24d1f297cb..c60a67a2fa 100644 --- a/crates/diesel_models/src/query/connector_response.rs +++ b/crates/diesel_models/src/query/connector_response.rs @@ -136,7 +136,7 @@ impl ConnectorResponse { #[instrument(skip(conn))] pub async fn find_by_payment_id_merchant_id_attempt_id( conn: &PgPooledConn, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, attempt_id: &str, ) -> StorageResult { diff --git a/crates/diesel_models/src/query/dispute.rs b/crates/diesel_models/src/query/dispute.rs index 585bdc8257..0aac120cf5 100644 --- a/crates/diesel_models/src/query/dispute.rs +++ b/crates/diesel_models/src/query/dispute.rs @@ -18,7 +18,7 @@ impl Dispute { pub async fn find_by_merchant_id_payment_id_connector_dispute_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, connector_dispute_id: &str, ) -> StorageResult> { generics::generic_find_one_optional::<::Table, _, _>( @@ -48,7 +48,7 @@ impl Dispute { pub async fn find_by_merchant_id_payment_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, ) -> StorageResult> { generics::generic_filter::< ::Table, diff --git a/crates/diesel_models/src/query/fraud_check.rs b/crates/diesel_models/src/query/fraud_check.rs index 223c2802f5..b60c078d75 100644 --- a/crates/diesel_models/src/query/fraud_check.rs +++ b/crates/diesel_models/src/query/fraud_check.rs @@ -40,7 +40,7 @@ impl FraudCheck { pub async fn get_with_payment_id( conn: &PgPooledConn, - payment_id: String, + payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> StorageResult { generics::generic_find_one::<::Table, _, _>( @@ -54,7 +54,7 @@ impl FraudCheck { pub async fn get_with_payment_id_if_present( conn: &PgPooledConn, - payment_id: String, + payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> StorageResult> { generics::generic_find_one_optional::<::Table, _, _>( diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs index 2af603f695..d8a9d5f40f 100644 --- a/crates/diesel_models/src/query/payment_attempt.rs +++ b/crates/diesel_models/src/query/payment_attempt.rs @@ -58,7 +58,7 @@ impl PaymentAttempt { pub async fn find_optional_by_payment_id_merchant_id( conn: &PgPooledConn, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult> { generics::generic_find_one_optional::<::Table, _, _>( @@ -73,7 +73,7 @@ impl PaymentAttempt { pub async fn find_by_connector_transaction_id_payment_id_merchant_id( conn: &PgPooledConn, connector_transaction_id: &str, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult { generics::generic_find_one::<::Table, _, _>( @@ -88,7 +88,7 @@ impl PaymentAttempt { pub async fn find_last_successful_attempt_by_payment_id_merchant_id( conn: &PgPooledConn, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult { // perform ordering on the application level instead of database level @@ -110,7 +110,7 @@ impl PaymentAttempt { pub async fn find_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( conn: &PgPooledConn, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult { // perform ordering on the application level instead of database level @@ -178,7 +178,7 @@ impl PaymentAttempt { pub async fn find_by_payment_id_merchant_id_attempt_id( conn: &PgPooledConn, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, attempt_id: &str, ) -> StorageResult { @@ -196,7 +196,7 @@ impl PaymentAttempt { pub async fn find_by_merchant_id_payment_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, ) -> StorageResult> { generics::generic_filter::< ::Table, diff --git a/crates/diesel_models/src/query/payment_intent.rs b/crates/diesel_models/src/query/payment_intent.rs index 452e5cbc3f..86069e1c66 100644 --- a/crates/diesel_models/src/query/payment_intent.rs +++ b/crates/diesel_models/src/query/payment_intent.rs @@ -46,7 +46,7 @@ impl PaymentIntent { pub async fn find_by_payment_id_merchant_id( conn: &PgPooledConn, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult { generics::generic_find_one::<::Table, _, _>( @@ -60,7 +60,7 @@ impl PaymentIntent { pub async fn find_optional_by_payment_id_merchant_id( conn: &PgPooledConn, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult> { generics::generic_find_one_optional::<::Table, _, _>( diff --git a/crates/diesel_models/src/query/refund.rs b/crates/diesel_models/src/query/refund.rs index 53d57356d4..902916bf98 100644 --- a/crates/diesel_models/src/query/refund.rs +++ b/crates/diesel_models/src/query/refund.rs @@ -107,7 +107,7 @@ impl Refund { pub async fn find_by_payment_id_merchant_id( conn: &PgPooledConn, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult> { generics::generic_filter::< diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs index a0828b3175..42b0ffa620 100644 --- a/crates/diesel_models/src/refund.rs +++ b/crates/diesel_models/src/refund.rs @@ -23,7 +23,7 @@ use crate::{enums as storage_enums, schema::refund}; pub struct Refund { pub internal_reference_id: String, pub refund_id: String, //merchant_reference id - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub connector_transaction_id: String, pub connector: String, @@ -67,7 +67,7 @@ pub struct Refund { #[diesel(table_name = refund)] pub struct RefundNew { pub refund_id: String, - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub internal_reference_id: String, pub external_reference_id: Option, @@ -294,7 +294,7 @@ pub struct RefundCoreWorkflow { pub refund_internal_reference_id: String, pub connector_transaction_id: String, pub merchant_id: common_utils::id_type::MerchantId, - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, } impl common_utils::events::ApiEventMetric for Refund { diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs index 89f8af3d94..2b1359968f 100644 --- a/crates/diesel_models/src/user/sample_data.rs +++ b/crates/diesel_models/src/user/sample_data.rs @@ -19,7 +19,7 @@ use crate::{ )] #[diesel(table_name = payment_attempt)] pub struct PaymentAttemptBatchNew { - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub attempt_id: String, pub status: AttemptStatus, diff --git a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs index e42fdb93be..a289881e3a 100644 --- a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs +++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs @@ -76,7 +76,9 @@ pub enum ApiErrorResponse { #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment method with the specified details already exists in our records")] DuplicatePaymentMethod, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment with the specified payment_id already exists in our records")] - DuplicatePayment { payment_id: String }, + DuplicatePayment { + payment_id: common_utils::id_type::PaymentId, + }, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payout with the specified payout_id '{payout_id}' already exists in our records")] DuplicatePayout { payout_id: String }, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The config with the specified key already exists in our records")] @@ -374,7 +376,7 @@ impl ErrorSwitch for ApiErrorRespon } Self::DuplicatePaymentMethod => AER::BadRequest(ApiError::new("HE", 1, "The payment method with the specified details already exists in our records", None)), Self::DuplicatePayment { payment_id } => { - AER::BadRequest(ApiError::new("HE", 1, "The payment with the specified payment_id already exists in our records", Some(Extra {reason: Some(format!("{payment_id} already exists")), ..Default::default()}))) + AER::BadRequest(ApiError::new("HE", 1, "The payment with the specified payment_id already exists in our records", Some(Extra {reason: Some(format!("{payment_id:?} already exists")), ..Default::default()}))) } Self::DuplicatePayout { payout_id } => { AER::BadRequest(ApiError::new("HE", 1, format!("The payout with the specified payout_id '{payout_id}' already exists in our records"), None)) diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 3873dfcd29..70ab814d98 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -12,7 +12,7 @@ use crate::RemoteStorageObject; #[derive(Clone, Debug, PartialEq, serde::Serialize)] pub struct PaymentIntent { - pub payment_id: String, + pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 370b37d5a1..1fc327ef4e 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -40,21 +40,21 @@ pub trait PaymentAttemptInterface { async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, connector_transaction_id: &str, - payment_id: &str, + payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result; async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, - payment_id: &str, + payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result; async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, - payment_id: &str, + payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result; @@ -68,7 +68,7 @@ pub trait PaymentAttemptInterface { async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, - payment_id: &str, + payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, attempt_id: &str, storage_scheme: storage_enums::MerchantStorageScheme, @@ -91,7 +91,7 @@ pub trait PaymentAttemptInterface { async fn find_attempts_by_merchant_id_payment_id( &self, merchant_id: &id_type::MerchantId, - payment_id: &str, + payment_id: &id_type::PaymentId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result, errors::StorageError>; @@ -118,7 +118,7 @@ pub trait PaymentAttemptInterface { #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct PaymentAttempt { - pub payment_id: String, + pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub attempt_id: String, pub status: storage_enums::AttemptStatus, @@ -210,7 +210,7 @@ pub struct PaymentListFilters { #[derive(Clone, Debug, Serialize, Deserialize)] pub struct PaymentAttemptNew { - pub payment_id: String, + pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub attempt_id: String, pub status: storage_enums::AttemptStatus, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index f857e241e1..6c9ba443de 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -35,7 +35,7 @@ pub trait PaymentIntentInterface { async fn find_payment_intent_by_payment_id_merchant_id( &self, state: &KeyManagerState, - payment_id: &str, + payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, merchant_key_store: &MerchantKeyStore, storage_scheme: storage_enums::MerchantStorageScheme, @@ -103,7 +103,7 @@ pub struct CustomerData { #[derive(Clone, Debug, PartialEq)] pub struct PaymentIntentNew { - pub payment_id: String, + pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, @@ -731,7 +731,9 @@ impl From for diesel_models::PaymentIntentUpdateInt } pub enum PaymentIntentFetchConstraints { - Single { payment_intent_id: String }, + Single { + payment_intent_id: id_type::PaymentId, + }, List(Box), } @@ -749,8 +751,8 @@ pub struct PaymentIntentListParams { pub merchant_connector_id: Option>, pub profile_id: Option, pub customer_id: Option, - pub starting_after_id: Option, - pub ending_before_id: Option, + pub starting_after_id: Option, + pub ending_before_id: Option, pub limit: Option, pub order: api_models::payments::Order, } diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index cd641243a3..122acbb0ad 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -18,6 +18,8 @@ pub struct RouterData { pub customer_id: Option, pub connector_customer: Option, pub connector: String, + // TODO: This should be a PaymentId type. + // Make this change after all the connector dependency has been removed from connectors pub payment_id: String, pub attempt_id: String, pub status: common_enums::enums::AttemptStatus, diff --git a/crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs b/crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs index 441d3a70b4..30a87c5c13 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs @@ -72,7 +72,7 @@ pub struct FraudCheckFulfillmentData { pub struct FrmFulfillmentRequest { ///unique payment_id for the transaction #[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")] - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, ///unique order_id for the order_details in the transaction #[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")] pub order_id: String, diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 0db9c9a775..4e7b4aa10f 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -365,10 +365,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentsConfirmRequest, api_models::payments::PaymentsResponse, api_models::payments::PaymentsCreateResponseOpenApi, - api_models::payments::PaymentsStartRequest, api_models::payments::PaymentRetrieveBody, api_models::payments::PaymentsRetrieveRequest, - api_models::payments::PaymentIdType, api_models::payments::PaymentsCaptureRequest, api_models::payments::PaymentsSessionRequest, api_models::payments::PaymentsSessionResponse, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 691481858f..2ca40ee66c 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -283,10 +283,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentsConfirmRequest, api_models::payments::PaymentsResponse, api_models::payments::PaymentsCreateResponseOpenApi, - api_models::payments::PaymentsStartRequest, api_models::payments::PaymentRetrieveBody, api_models::payments::PaymentsRetrieveRequest, - api_models::payments::PaymentIdType, api_models::payments::PaymentsCaptureRequest, api_models::payments::PaymentsSessionRequest, api_models::payments::PaymentsSessionResponse, diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index e0a9b6c8f8..547b6e1e54 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -206,7 +206,9 @@ pub enum StripeErrorCode { PaymentIntentMandateInvalid { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "The payment with the specified payment_id already exists in our records.")] - DuplicatePayment { payment_id: String }, + DuplicatePayment { + payment_id: common_utils::id_type::PaymentId, + }, #[error(error_type = StripeErrorType::ConnectorError, code = "", message = "{code}: {message}")] ExternalConnectorError { diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs index 3017b8c89b..43737183e3 100644 --- a/crates/router/src/compatibility/stripe/payment_intents.rs +++ b/crates/router/src/compatibility/stripe/payment_intents.rs @@ -36,7 +36,14 @@ pub async fn payment_intents_create( Err(err) => return api::log_and_return_error_response(err), }; - tracing::Span::current().record("payment_id", payload.id.clone().unwrap_or_default()); + tracing::Span::current().record( + "payment_id", + payload + .id + .as_ref() + .map(|payment_id| payment_id.get_string_repr()) + .unwrap_or_default(), + ); logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?payload); @@ -91,11 +98,11 @@ pub async fn payment_intents_create( pub async fn payment_intents_retrieve( state: web::Data, req: HttpRequest, - path: web::Path, + path: web::Path, query_payload: web::Query, ) -> HttpResponse { let payload = payment_types::PaymentsRetrieveRequest { - resource_id: api_types::PaymentIdType::PaymentIntentId(path.to_string()), + resource_id: api_types::PaymentIdType::PaymentIntentId(path.into_inner()), merchant_id: None, force_sync: true, connector: None, @@ -166,9 +173,7 @@ pub async fn payment_intents_retrieve_with_gateway_creds( }; let payload = payment_types::PaymentsRetrieveRequest { - resource_id: payment_types::PaymentIdType::PaymentIntentId( - json_payload.payment_id.to_string(), - ), + resource_id: payment_types::PaymentIdType::PaymentIntentId(json_payload.payment_id), merchant_id: json_payload.merchant_id.clone(), force_sync: json_payload.force_sync.unwrap_or(false), merchant_connector_details: json_payload.merchant_connector_details.clone(), @@ -229,7 +234,7 @@ pub async fn payment_intents_update( qs_config: web::Data, req: HttpRequest, form_payload: web::Bytes, - path: web::Path, + path: web::Path, ) -> HttpResponse { let payment_id = path.into_inner(); let stripe_payload: types::StripePaymentIntentRequest = match qs_config @@ -298,7 +303,7 @@ pub async fn payment_intents_confirm( qs_config: web::Data, req: HttpRequest, form_payload: web::Bytes, - path: web::Path, + path: web::Path, ) -> HttpResponse { let payment_id = path.into_inner(); let stripe_payload: types::StripePaymentIntentRequest = match qs_config @@ -310,7 +315,10 @@ pub async fn payment_intents_confirm( } }; - tracing::Span::current().record("payment_id", stripe_payload.id.as_ref()); + tracing::Span::current().record( + "payment_id", + stripe_payload.id.as_ref().map(|id| id.get_string_repr()), + ); logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?stripe_payload); @@ -373,7 +381,7 @@ pub async fn payment_intents_capture( qs_config: web::Data, req: HttpRequest, form_payload: web::Bytes, - path: web::Path, + path: web::Path, ) -> HttpResponse { let stripe_payload: payment_types::PaymentsCaptureRequest = match qs_config .deserialize_bytes(&form_payload) @@ -384,7 +392,7 @@ pub async fn payment_intents_capture( } }; - tracing::Span::current().record("payment_id", stripe_payload.payment_id.clone()); + tracing::Span::current().record("payment_id", stripe_payload.payment_id.get_string_repr()); logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?stripe_payload); @@ -437,7 +445,7 @@ pub async fn payment_intents_cancel( qs_config: web::Data, req: HttpRequest, form_payload: web::Bytes, - path: web::Path, + path: web::Path, ) -> HttpResponse { let payment_id = path.into_inner(); let stripe_payload: types::StripePaymentCancelRequest = match qs_config @@ -449,7 +457,7 @@ pub async fn payment_intents_cancel( } }; - tracing::Span::current().record("payment_id", payment_id.clone()); + tracing::Span::current().record("payment_id", payment_id.get_string_repr()); logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?stripe_payload); diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index e76ed607b2..f0e4b1169c 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -244,7 +244,7 @@ pub struct OnlineMandate { #[derive(Deserialize, Clone, Debug)] pub struct StripePaymentIntentRequest { - pub id: Option, + pub id: Option, pub amount: Option, // amount in cents, hence passed as integer pub connector: Option>, pub currency: Option, @@ -462,7 +462,7 @@ impl From for payments::PaymentsCancelRequest { #[derive(Default, Eq, PartialEq, Serialize, Debug)] pub struct StripePaymentIntentResponse { - pub id: String, + pub id: id_type::PaymentId, pub object: &'static str, pub amount: i64, pub amount_received: Option, @@ -615,8 +615,8 @@ impl Charges { #[serde(deny_unknown_fields)] pub struct StripePaymentListConstraints { pub customer: Option, - pub starting_after: Option, - pub ending_before: Option, + pub starting_after: Option, + pub ending_before: Option, #[serde(default = "default_limit")] pub limit: u32, pub created: Option, diff --git a/crates/router/src/compatibility/stripe/refunds.rs b/crates/router/src/compatibility/stripe/refunds.rs index 565cec5855..87a629556b 100644 --- a/crates/router/src/compatibility/stripe/refunds.rs +++ b/crates/router/src/compatibility/stripe/refunds.rs @@ -27,7 +27,7 @@ pub async fn refund_create( Err(err) => return api::log_and_return_error_response(err), }; - tracing::Span::current().record("payment_id", payload.payment_intent.clone()); + tracing::Span::current().record("payment_id", payload.payment_intent.get_string_repr()); logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?payload); diff --git a/crates/router/src/compatibility/stripe/refunds/types.rs b/crates/router/src/compatibility/stripe/refunds/types.rs index d00da0d858..2e8b74ff4f 100644 --- a/crates/router/src/compatibility/stripe/refunds/types.rs +++ b/crates/router/src/compatibility/stripe/refunds/types.rs @@ -9,7 +9,7 @@ use crate::types::api::{admin, refunds}; pub struct StripeCreateRefundRequest { pub refund_id: Option, pub amount: Option, - pub payment_intent: String, + pub payment_intent: common_utils::id_type::PaymentId, pub reason: Option, pub metadata: Option, pub merchant_connector_details: Option, @@ -27,7 +27,7 @@ pub struct StripeRefundResponse { pub id: String, pub amount: i64, pub currency: String, - pub payment_intent: String, + pub payment_intent: common_utils::id_type::PaymentId, pub status: StripeRefundStatus, pub created: Option, pub metadata: pii::SecretSerdeValue, diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rs index d9147b08b9..72e9e4435d 100644 --- a/crates/router/src/compatibility/stripe/setup_intents.rs +++ b/crates/router/src/compatibility/stripe/setup_intents.rs @@ -90,11 +90,11 @@ pub async fn setup_intents_create( pub async fn setup_intents_retrieve( state: web::Data, req: HttpRequest, - path: web::Path, + path: web::Path, query_payload: web::Query, ) -> HttpResponse { let payload = payment_types::PaymentsRetrieveRequest { - resource_id: api_types::PaymentIdType::PaymentIntentId(path.to_string()), + resource_id: api_types::PaymentIdType::PaymentIntentId(path.into_inner()), merchant_id: None, force_sync: true, connector: None, @@ -155,7 +155,7 @@ pub async fn setup_intents_update( qs_config: web::Data, req: HttpRequest, form_payload: web::Bytes, - path: web::Path, + path: web::Path, ) -> HttpResponse { let setup_id = path.into_inner(); let stripe_payload: types::StripeSetupIntentRequest = match qs_config @@ -230,7 +230,7 @@ pub async fn setup_intents_confirm( qs_config: web::Data, req: HttpRequest, form_payload: web::Bytes, - path: web::Path, + path: web::Path, ) -> HttpResponse { let setup_id = path.into_inner(); let stripe_payload: types::StripeSetupIntentRequest = match qs_config diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index 8d59ef4031..58a4d95b28 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -451,7 +451,7 @@ pub(crate) fn into_stripe_next_action( #[derive(Default, Eq, PartialEq, Serialize)] pub struct StripeSetupIntentResponse { - pub id: String, + pub id: id_type::PaymentId, pub object: String, pub status: StripeSetupStatus, pub client_secret: Option>, @@ -536,8 +536,8 @@ impl From for StripeSetupIntentResponse { #[serde(deny_unknown_fields)] pub struct StripePaymentListConstraints { pub customer: Option, - pub starting_after: Option, - pub ending_before: Option, + pub starting_after: Option, + pub ending_before: Option, #[serde(default = "default_limit")] pub limit: u32, pub created: Option, diff --git a/crates/router/src/compatibility/stripe/webhooks.rs b/crates/router/src/compatibility/stripe/webhooks.rs index 998702b5de..8445011f56 100644 --- a/crates/router/src/compatibility/stripe/webhooks.rs +++ b/crates/router/src/compatibility/stripe/webhooks.rs @@ -94,7 +94,7 @@ pub struct StripeDisputeResponse { pub id: String, pub amount: String, pub currency: String, - pub payment_intent: String, + pub payment_intent: common_utils::id_type::PaymentId, pub reason: Option, pub status: StripeDisputeStatus, } diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 14f61d1ded..e04fe3e3fb 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -314,7 +314,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CreateCustomerProfileRequest { create_customer_profile_request: AuthorizedotnetZeroMandateRequest { merchant_authentication, profile: Profile { - //The payment ID is included in the description because the connector requires unique description when creating a mandate. + // The payment ID is included in the description because the connector requires unique description when creating a mandate. description: item.payment_id.clone(), payment_profiles: PaymentProfiles { customer_type: CustomerType::Individual, diff --git a/crates/router/src/connector/worldline.rs b/crates/router/src/connector/worldline.rs index 901f9ab8e4..6c8e1a1e95 100644 --- a/crates/router/src/connector/worldline.rs +++ b/crates/router/src/connector/worldline.rs @@ -228,9 +228,9 @@ impl ConnectorIntegration, - payment_id: Option, + payment_id: Option, ) -> CustomResult { let (authentication_connector, three_ds_connector_account) = utils::get_authentication_connector_data(state, key_store, business_profile).await?; diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rs index 02d64e449a..4a1298bb7b 100644 --- a/crates/router/src/core/authentication/transformers.rs +++ b/crates/router/src/core/authentication/transformers.rs @@ -17,8 +17,6 @@ use crate::{ utils::ext_traits::OptionExt, }; -const IRRELEVANT_PAYMENT_ID_IN_AUTHENTICATION_FLOW: &str = - "irrelevant_payment_id_in_AUTHENTICATION_flow"; const IRRELEVANT_ATTEMPT_ID_IN_AUTHENTICATION_FLOW: &str = "irrelevant_attempt_id_in_AUTHENTICATION_flow"; const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_AUTHENTICATION_FLOW: &str = @@ -143,7 +141,9 @@ pub fn construct_router_data( customer_id: None, connector_customer: None, connector: authentication_connector_name, - payment_id: IRRELEVANT_PAYMENT_ID_IN_AUTHENTICATION_FLOW.to_owned(), + payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("authentication") + .get_string_repr() + .to_owned(), attempt_id: IRRELEVANT_ATTEMPT_ID_IN_AUTHENTICATION_FLOW.to_owned(), status: common_enums::AttemptStatus::default(), payment_method, diff --git a/crates/router/src/core/authentication/utils.rs b/crates/router/src/core/authentication/utils.rs index cd93a1cf62..5dc309a06c 100644 --- a/crates/router/src/core/authentication/utils.rs +++ b/crates/router/src/core/authentication/utils.rs @@ -179,7 +179,7 @@ pub async fn create_new_authentication( authentication_connector: String, token: String, profile_id: common_utils::id_type::ProfileId, - payment_id: Option, + payment_id: Option, merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, ) -> RouterResult { let authentication_id = diff --git a/crates/router/src/core/fraud_check/flows/checkout_flow.rs b/crates/router/src/core/fraud_check/flows/checkout_flow.rs index 10c2974c1b..74606eb591 100644 --- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs +++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs @@ -73,7 +73,7 @@ impl ConstructFlowSpecificData( flow: std::marker::PhantomData, merchant_id: merchant_account.get_id().clone(), connector, - payment_id: payment_attempt.payment_id.clone(), + payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), attempt_id: payment_attempt.attempt_id.clone(), status: payment_attempt.status, payment_method, diff --git a/crates/router/src/core/fraud_check/flows/record_return.rs b/crates/router/src/core/fraud_check/flows/record_return.rs index f74dfccef2..6603f09cad 100644 --- a/crates/router/src/core/fraud_check/flows/record_return.rs +++ b/crates/router/src/core/fraud_check/flows/record_return.rs @@ -69,7 +69,7 @@ impl ConstructFlowSpecificData Domain for FraudCheckPost { Ok(Some(FrmRouterData { merchant_id: router_data.merchant_id, connector: router_data.connector, - payment_id: router_data.payment_id, + payment_id: router_data.payment_id.clone(), attempt_id: router_data.attempt_id, request: FrmRequest::Sale(FraudCheckSaleData { amount: router_data.request.amount, diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs b/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs index ceae8af3fd..c1a54acc9b 100644 --- a/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs +++ b/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs @@ -175,7 +175,7 @@ impl Domain for FraudCheckPre { Ok(Some(FrmRouterData { merchant_id: router_data.merchant_id, connector: router_data.connector, - payment_id: router_data.payment_id, + payment_id: router_data.payment_id.clone(), attempt_id: router_data.attempt_id, request: FrmRequest::Transaction(FraudCheckTransactionData { amount: router_data.request.amount, @@ -213,7 +213,7 @@ impl Domain for FraudCheckPre { Ok(FrmRouterData { merchant_id: router_data.merchant_id, connector: router_data.connector, - payment_id: router_data.payment_id, + payment_id: router_data.payment_id.clone(), attempt_id: router_data.attempt_id, request: FrmRequest::Checkout(FraudCheckCheckoutData { amount: router_data.request.amount, diff --git a/crates/router/src/core/fraud_check/types.rs b/crates/router/src/core/fraud_check/types.rs index 7f9d21216b..dc1528eb9b 100644 --- a/crates/router/src/core/fraud_check/types.rs +++ b/crates/router/src/core/fraud_check/types.rs @@ -23,7 +23,7 @@ use crate::types::{ #[derive(Clone, Default, Debug)] pub struct PaymentIntentCore { - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, } #[derive(Clone, Debug)] diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index 8118d8a322..9cc252ffd0 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -2,7 +2,7 @@ pub mod helpers; pub mod utils; use api_models::payments; use common_utils::{ext_traits::Encode, id_type}; -use diesel_models::{enums as storage_enums, Mandate}; +use diesel_models::enums as storage_enums; use error_stack::{report, ResultExt}; use futures::future; use router_env::{instrument, logger, metrics::add_attributes, tracing}; @@ -277,76 +277,6 @@ where _ => Some(router_data.request.get_payment_method_data()), } } -pub async fn update_mandate_procedure( - state: &SessionState, - resp: types::RouterData, - mandate: Mandate, - merchant_id: &id_type::MerchantId, - pm_id: Option, - storage_scheme: MerchantStorageScheme, -) -> errors::RouterResult> -where - FData: MandateBehaviour, -{ - let mandate_details = match &resp.response { - Ok(types::PaymentsResponseData::TransactionResponse { - mandate_reference, .. - }) => mandate_reference, - Ok(_) => Err(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unexpected response received")?, - Err(_) => return Ok(resp), - }; - - let old_record = payments::UpdateHistory { - connector_mandate_id: mandate.connector_mandate_id.clone(), - payment_method_id: mandate.payment_method_id.clone(), - original_payment_id: mandate.original_payment_id.clone(), - }; - - let mandate_ref = mandate - .connector_mandate_ids - .clone() - .parse_value::("Connector Reference Id") - .change_context(errors::ApiErrorResponse::MandateDeserializationFailed)?; - - let mut update_history = mandate_ref.update_history.unwrap_or_default(); - update_history.push(old_record); - - let updated_mandate_ref = payments::ConnectorMandateReferenceId { - connector_mandate_id: mandate_details - .as_ref() - .and_then(|mandate_ref| mandate_ref.connector_mandate_id.clone()), - payment_method_id: pm_id.clone(), - update_history: Some(update_history), - }; - - let connector_mandate_ids = updated_mandate_ref - .encode_to_value() - .change_context(errors::ApiErrorResponse::InternalServerError) - .map(masking::Secret::new)?; - - let mandate_id = mandate.mandate_id.clone(); - let _update_mandate_details = state - .store - .update_mandate_by_merchant_id_mandate_id( - merchant_id, - &mandate_id, - diesel_models::MandateUpdate::ConnectorMandateIdUpdate { - connector_mandate_id: mandate_details - .as_ref() - .and_then(|man_ref| man_ref.connector_mandate_id.clone()), - connector_mandate_ids: Some(connector_mandate_ids), - payment_method_id: pm_id - .unwrap_or("Error retrieving the payment_method_id".to_string()), - original_payment_id: Some(resp.payment_id.clone()), - }, - mandate, - storage_scheme, - ) - .await - .change_context(errors::ApiErrorResponse::MandateUpdateFailed)?; - Ok(resp) -} pub async fn mandate_procedure( state: &SessionState, @@ -355,6 +285,7 @@ pub async fn mandate_procedure( pm_id: Option, merchant_connector_id: Option, storage_scheme: MerchantStorageScheme, + payment_id: &id_type::PaymentId, ) -> errors::RouterResult> where FData: MandateBehaviour, @@ -439,7 +370,7 @@ where let Some(new_mandate_data) = payment_helper::generate_mandate( resp.merchant_id.clone(), - resp.payment_id.clone(), + payment_id.to_owned(), resp.connector.clone(), resp.request.get_setup_mandate_details().cloned(), customer_id, diff --git a/crates/router/src/core/mandate/utils.rs b/crates/router/src/core/mandate/utils.rs index 81dbfd1d41..de4b0b77fe 100644 --- a/crates/router/src/core/mandate/utils.rs +++ b/crates/router/src/core/mandate/utils.rs @@ -8,8 +8,6 @@ use crate::{ core::{errors, payments::helpers}, types::{self, domain, PaymentAddress}, }; -const IRRELEVANT_PAYMENT_ID_IN_MANDATE_REVOKE_FLOW: &str = - "irrelevant_payment_id_in_mandate_revoke_flow"; const IRRELEVANT_ATTEMPT_ID_IN_MANDATE_REVOKE_FLOW: &str = "irrelevant_attempt_id_in_mandate_revoke_flow"; @@ -34,7 +32,11 @@ pub async fn construct_mandate_revoke_router_data( connector: mandate.connector, payment_id: mandate .original_payment_id - .unwrap_or_else(|| IRRELEVANT_PAYMENT_ID_IN_MANDATE_REVOKE_FLOW.to_string()), + .unwrap_or_else(|| { + common_utils::id_type::PaymentId::get_irrelevant_id("mandate_revoke") + }) + .get_string_repr() + .to_owned(), attempt_id: IRRELEVANT_ATTEMPT_ID_IN_MANDATE_REVOKE_FLOW.to_string(), status: diesel_models::enums::AttemptStatus::default(), payment_method: diesel_models::enums::PaymentMethod::default(), diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs index bb39bede2d..c56f495647 100644 --- a/crates/router/src/core/payment_link.rs +++ b/crates/router/src/core/payment_link.rs @@ -69,7 +69,7 @@ pub async fn form_payment_link_data( merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, merchant_id: common_utils::id_type::MerchantId, - payment_id: String, + payment_id: common_utils::id_type::PaymentId, locale: Option, ) -> RouterResult<(PaymentLink, PaymentLinkData, PaymentLinkConfig)> { let db = &*state.store; @@ -269,7 +269,7 @@ pub async fn initiate_secure_payment_link_flow( merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, merchant_id: common_utils::id_type::MerchantId, - payment_id: String, + payment_id: common_utils::id_type::PaymentId, request_headers: &header::HeaderMap, ) -> RouterResponse { let locale = get_header_value_by_key(ACCEPT_LANGUAGE.into(), request_headers)? @@ -368,7 +368,7 @@ pub async fn initiate_payment_link_flow( merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, merchant_id: common_utils::id_type::MerchantId, - payment_id: String, + payment_id: common_utils::id_type::PaymentId, request_headers: &header::HeaderMap, ) -> RouterResponse { let locale = get_header_value_by_key(ACCEPT_LANGUAGE.into(), request_headers)? @@ -664,7 +664,7 @@ pub async fn get_payment_link_status( merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, merchant_id: common_utils::id_type::MerchantId, - payment_id: String, + payment_id: common_utils::id_type::PaymentId, request_headers: &header::HeaderMap, ) -> RouterResponse { let locale = get_header_value_by_key(ACCEPT_LANGUAGE.into(), request_headers)? diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 82353bebe6..378492596c 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3060,7 +3060,7 @@ pub async fn list_payment_methods( } } - let pm_auth_key = format!("pm_auth_{}", payment_intent.payment_id); + let pm_auth_key = payment_intent.payment_id.get_pm_auth_key(); let redis_expiry = state.conf.payment_method_auth.get_inner().redis_expiry; if let Some(rc) = redis_conn { diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 75fe544ae5..1f9eab87e1 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -920,7 +920,7 @@ pub trait PaymentRedirectFlow: Sync { req: PaymentsRedirectResponseData, connector_action: CallConnectorAction, connector: String, - payment_id: String, + payment_id: id_type::PaymentId, ) -> RouterResult; fn get_payment_action(&self) -> services::PaymentAction; @@ -928,7 +928,7 @@ pub trait PaymentRedirectFlow: Sync { fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, - payment_id: String, + payment_id: id_type::PaymentId, connector: String, ) -> RouterResult>; @@ -1017,7 +1017,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { req: PaymentsRedirectResponseData, connector_action: CallConnectorAction, _connector: String, - _payment_id: String, + _payment_id: id_type::PaymentId, ) -> RouterResult { let key_manager_state = &state.into(); @@ -1083,7 +1083,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, - payment_id: String, + payment_id: id_type::PaymentId, connector: String, ) -> RouterResult> { let payments_response = &payment_flow_response.payments_response; @@ -1153,7 +1153,7 @@ impl PaymentRedirectFlow for PaymentRedirectSync { req: PaymentsRedirectResponseData, connector_action: CallConnectorAction, _connector: String, - _payment_id: String, + _payment_id: id_type::PaymentId, ) -> RouterResult { let key_manager_state = &state.into(); @@ -1212,7 +1212,7 @@ impl PaymentRedirectFlow for PaymentRedirectSync { fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, - payment_id: String, + payment_id: id_type::PaymentId, connector: String, ) -> RouterResult> { Ok(services::ApplicationResponse::JsonForRedirection( @@ -1247,7 +1247,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize { req: PaymentsRedirectResponseData, connector_action: CallConnectorAction, connector: String, - payment_id: String, + payment_id: id_type::PaymentId, ) -> RouterResult { let merchant_id = merchant_account.get_id().clone(); let key_manager_state = &state.into(); @@ -1444,7 +1444,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize { fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, - payment_id: String, + payment_id: id_type::PaymentId, connector: String, ) -> RouterResult> { let payments_response = &payment_flow_response.payments_response; @@ -2951,7 +2951,7 @@ pub async fn list_payments( if matches!(error.current_context(), StorageError::ValueNotFound(_)) { logger::warn!( ?error, - "payment_attempts missing for payment_id : {}", + "payment_attempts missing for payment_id : {:?}", pi.payment_id, ); return None; @@ -4413,7 +4413,7 @@ pub async fn payment_external_authentication( pub async fn get_extended_card_info( state: SessionState, merchant_id: id_type::MerchantId, - payment_id: String, + payment_id: id_type::PaymentId, ) -> RouterResponse { let redis_conn = state .store diff --git a/crates/router/src/core/payments/access_token.rs b/crates/router/src/core/payments/access_token.rs index 8ac89f76ad..e6e79a6c70 100644 --- a/crates/router/src/core/payments/access_token.rs +++ b/crates/router/src/core/payments/access_token.rs @@ -89,7 +89,7 @@ pub async fn add_access_token< let res = match old_access_token { Some(access_token) => { router_env::logger::debug!( - "Access token found in redis for merchant_id: {:?}, payment_id: {}, connector: {} which has expiry of: {} seconds", + "Access token found in redis for merchant_id: {:?}, payment_id: {:?}, connector: {} which has expiry of: {} seconds", merchant_account.get_id(), router_data.payment_id, connector.connector_name, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 34fb2e954b..c2a14871a4 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -119,7 +119,7 @@ pub async fn create_or_update_address_for_payment_by_request( merchant_id: &id_type::MerchantId, customer_id: Option<&id_type::CustomerId>, merchant_key_store: &domain::MerchantKeyStore, - payment_id: &str, + payment_id: &id_type::PaymentId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult, errors::ApiErrorResponse> { let key = merchant_key_store.key.get_inner().peek(); @@ -189,7 +189,7 @@ pub async fn create_or_update_address_for_payment_by_request( key_manager_state, address, address_update, - payment_id.to_string(), + payment_id.to_owned(), merchant_key_store, storage_scheme, ) @@ -223,7 +223,7 @@ pub async fn create_or_update_address_for_payment_by_request( let payment_address = domain::PaymentAddress { address, - payment_id: payment_id.to_string(), + payment_id: payment_id.clone(), customer_id: customer_id.cloned(), }; @@ -256,7 +256,7 @@ pub async fn create_or_find_address_for_payment_by_request( merchant_id: &id_type::MerchantId, customer_id: Option<&id_type::CustomerId>, merchant_key_store: &domain::MerchantKeyStore, - payment_id: &str, + payment_id: &id_type::PaymentId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult, errors::ApiErrorResponse> { let key = merchant_key_store.key.get_inner().peek(); @@ -287,7 +287,7 @@ pub async fn create_or_find_address_for_payment_by_request( let payment_address = domain::PaymentAddress { address, - payment_id: payment_id.to_string(), + payment_id: payment_id.clone(), customer_id: customer_id.cloned(), }; @@ -366,7 +366,7 @@ pub async fn get_address_by_id( state: &SessionState, address_id: Option, merchant_key_store: &domain::MerchantKeyStore, - payment_id: &str, + payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult, errors::ApiErrorResponse> { @@ -1119,7 +1119,7 @@ pub fn create_startpay_url( format!( "{}/payments/redirect/{}/{}/{}", base_url, - payment_intent.payment_id, + payment_intent.payment_id.get_string_repr(), payment_intent.merchant_id.get_string_repr(), payment_attempt.attempt_id ) @@ -1135,7 +1135,7 @@ pub fn create_redirect_url( format!( "{}/payments/{}/{}/redirect/response/{}", router_base_url, - payment_attempt.payment_id, + payment_attempt.payment_id.get_string_repr(), payment_attempt.merchant_id.get_string_repr(), connector_name, ) + creds_identifier_path.as_ref() @@ -1147,7 +1147,7 @@ pub fn create_authentication_url( ) -> String { format!( "{router_base_url}/payments/{}/3ds/authentication", - payment_attempt.payment_id + payment_attempt.payment_id.get_string_repr() ) } @@ -1159,7 +1159,7 @@ pub fn create_authorize_url( format!( "{}/payments/{}/{}/authorize/{}", router_base_url, - payment_attempt.payment_id, + payment_attempt.payment_id.get_string_repr(), payment_attempt.merchant_id.get_string_repr(), connector_name ) @@ -1185,7 +1185,7 @@ pub fn create_complete_authorize_url( format!( "{}/payments/{}/{}/redirect/complete/{}", router_base_url, - payment_attempt.payment_id, + payment_attempt.payment_id.get_string_repr(), payment_attempt.merchant_id.get_string_repr(), connector_name ) @@ -2512,7 +2512,7 @@ pub(super) fn validate_payment_list_request_for_joins( } pub fn get_handle_response_url( - payment_id: String, + payment_id: id_type::PaymentId, business_profile: &domain::BusinessProfile, response: &api::PaymentsResponse, connector: String, @@ -2628,7 +2628,7 @@ pub async fn delete_ephemeral_key( } pub fn make_pg_redirect_response( - payment_id: String, + payment_id: id_type::PaymentId, response: &api::PaymentsResponse, connector: String, ) -> api::PgRedirectResponse { @@ -2719,7 +2719,7 @@ pub fn check_if_operation_confirm(operations: Op) -> bool { #[allow(clippy::too_many_arguments)] pub fn generate_mandate( merchant_id: id_type::MerchantId, - payment_id: String, + payment_id: id_type::PaymentId, connector: String, setup_mandate_details: Option, customer_id: &Option, @@ -2892,6 +2892,12 @@ pub async fn verify_payment_intent_time_and_client_secret( .async_map(|cs| async move { let payment_id = get_payment_id_from_client_secret(&cs)?; + let payment_id = id_type::PaymentId::wrap(payment_id).change_context( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "payment_id", + }, + )?; + let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &state.into(), @@ -2956,13 +2962,14 @@ pub(crate) fn get_payment_id_from_client_secret(cs: &str) -> RouterResult( pub fn get_redis_key_for_extended_card_info( merchant_id: &id_type::MerchantId, - payment_id: &str, + payment_id: &id_type::PaymentId, ) -> String { format!( - "{}_{payment_id}_extended_card_info", - merchant_id.get_string_repr() + "{}_{}_extended_card_info", + merchant_id.get_string_repr(), + payment_id.get_string_repr() ) } diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index 8efa124b49..ebc00e42e5 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -194,7 +194,7 @@ pub trait Domain: Send + Sync { async fn store_extended_card_info_temporarily<'a>( &'a self, _state: &SessionState, - _payment_id: &str, + _payment_id: &common_utils::id_type::PaymentId, _business_profile: &domain::BusinessProfile, _payment_method_data: &Option, ) -> CustomResult<(), errors::ApiErrorResponse> { diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index 7034cfab2f..3ad4cff9ef 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -275,10 +275,7 @@ impl ValidateRequest for Paymen Box::new(self), operations::ValidateResult { merchant_id: merchant_account.get_id().to_owned(), - payment_id: api::PaymentIdType::PaymentIntentId(crate::core::utils::validate_id( - request.payment_id.clone(), - "payment_id", - )?), + payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.clone()), storage_scheme: merchant_account.storage_scheme, requeue: false, }, diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index 4a26e53344..689184a619 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -76,7 +76,7 @@ impl GetTracker, api::PaymentsCancelRequest> let mut payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( - payment_intent.payment_id.as_str(), + &payment_intent.payment_id, merchant_id, payment_intent.active_attempt.get_id().as_str(), storage_scheme, diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index de7ee99619..5c04fc99ef 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -67,7 +67,7 @@ impl GetTracker, api::PaymentsCaptu payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( - payment_intent.payment_id.as_str(), + &payment_intent.payment_id, merchant_id, payment_intent.active_attempt.get_id().as_str(), storage_scheme, 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 c5fa1214ce..f45872c2a8 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -15,7 +15,6 @@ use crate::{ self, helpers, operations, CustomerAcceptance, CustomerDetails, PaymentAddress, PaymentData, }, - utils as core_utils, }, routes::{app::ReqState, SessionState}, services, @@ -208,7 +207,7 @@ impl GetTracker, api::PaymentsRequest> for Co merchant_id, payment_intent.customer_id.as_ref(), key_store, - payment_id.as_ref(), + &payment_id, storage_scheme, ) .await?; @@ -531,7 +530,7 @@ impl ValidateRequest for CompleteAutho Box::new(self), operations::ValidateResult { merchant_id: merchant_account.get_id().to_owned(), - payment_id: payment_id.and_then(|id| core_utils::validate_id(id, "payment_id"))?, + payment_id, storage_scheme: merchant_account.storage_scheme, requeue: matches!( request.retry_action, diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index b0a7e09142..3e7944838a 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -182,7 +182,7 @@ impl GetTracker, api::PaymentsRequest> for Pa async move { store .find_payment_attempt_by_payment_id_merchant_id_attempt_id( - m_payment_id.as_str(), + &m_payment_id, &m_merchant_id, attempt_id.as_str(), storage_scheme, @@ -213,7 +213,7 @@ impl GetTracker, api::PaymentsRequest> for Pa .as_ref() .or(m_customer_details_customer_id.as_ref()), &m_key_store, - m_payment_intent_payment_id.as_ref(), + &m_payment_intent_payment_id, storage_scheme, ) .await @@ -241,7 +241,7 @@ impl GetTracker, api::PaymentsRequest> for Pa .as_ref() .or(m_customer_details_customer_id.as_ref()), &m_key_store, - m_payment_intent_payment_id.as_ref(), + &m_payment_intent_payment_id, storage_scheme, ) .await @@ -509,7 +509,7 @@ impl GetTracker, api::PaymentsRequest> for Pa .as_ref() .or(m_customer_details_customer_id.as_ref()), &m_key_store, - m_payment_intent_payment_id.as_ref(), + &m_payment_intent_payment_id, storage_scheme, ) .await @@ -963,7 +963,7 @@ impl Domain for PaymentConfirm { async fn store_extended_card_info_temporarily<'a>( &'a self, state: &SessionState, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, business_profile: &domain::BusinessProfile, payment_method_data: &Option, ) -> CustomResult<(), errors::ApiErrorResponse> { @@ -1521,7 +1521,7 @@ impl ValidateRequest for PaymentConfir Box::new(self), operations::ValidateResult { merchant_id: merchant_account.get_id().to_owned(), - payment_id: payment_id.and_then(|id| core_utils::validate_id(id, "payment_id"))?, + payment_id, storage_scheme: merchant_account.storage_scheme, requeue: matches!( request.retry_action, diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index a7b181460d..200d549097 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -234,9 +234,9 @@ impl GetTracker, api::PaymentsRequest> for Pa &state.conf, merchant_id, ) { - payment_id.to_string() + payment_id.get_string_repr().to_string() } else { - utils::get_payment_attempt_id(payment_id.clone(), 1) + payment_id.get_attempt_id(1) }; let session_expiry = @@ -873,7 +873,7 @@ impl PaymentCreate { #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn make_payment_attempt( - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, organization_id: &common_utils::id_type::OrganizationId, money: (api::Amount, enums::Currency), @@ -968,9 +968,9 @@ impl PaymentCreate { &state.conf, merchant_id, ) { - payment_id.to_string() + payment_id.get_string_repr().to_owned() } else { - utils::get_payment_attempt_id(payment_id, 1) + payment_id.get_attempt_id(1) }; let surcharge_amount = request .surcharge_details @@ -1000,7 +1000,7 @@ impl PaymentCreate { Ok(( storage::PaymentAttemptNew { - payment_id: payment_id.to_string(), + payment_id: payment_id.to_owned(), merchant_id: merchant_id.to_owned(), attempt_id, status, @@ -1078,7 +1078,7 @@ impl PaymentCreate { #[allow(clippy::too_many_arguments)] async fn make_payment_intent( state: &SessionState, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, money: (api::Amount, enums::Currency), @@ -1101,8 +1101,7 @@ impl PaymentCreate { }), request.confirm, ); - let client_secret = - utils::generate_id(consts::ID_LENGTH, format!("{payment_id}_secret").as_str()); + let client_secret = payment_id.generate_client_secret(); let (amount, currency) = (money.0, Some(money.1)); let order_details = request @@ -1199,7 +1198,7 @@ impl PaymentCreate { .attach_printable("Unable to encrypt customer details")?; Ok(storage::PaymentIntent { - payment_id: payment_id.to_string(), + payment_id: payment_id.to_owned(), merchant_id: merchant_account.get_id().to_owned(), status, amount: MinorUnit::from(amount), @@ -1294,7 +1293,7 @@ async fn create_payment_link( request: &api::PaymentsRequest, payment_link_config: api_models::admin::PaymentLinkConfig, merchant_id: &common_utils::id_type::MerchantId, - payment_id: String, + payment_id: common_utils::id_type::PaymentId, db: &dyn StorageInterface, amount: api::Amount, description: Option, @@ -1310,7 +1309,7 @@ async fn create_payment_link( "{}/payment_link/{}/{}?locale={}", domain_name, merchant_id.get_string_repr(), - payment_id.clone(), + payment_id.get_string_repr(), locale_str.clone(), ); @@ -1319,7 +1318,7 @@ async fn create_payment_link( "{}/payment_link/s/{}/{}?locale={}", domain_name, merchant_id.get_string_repr(), - payment_id.clone(), + payment_id.get_string_repr(), locale_str, ) }); diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index b148d5bbcc..928d69dc1c 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -73,7 +73,7 @@ impl GetTracker, PaymentsCancelRequest> for P let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( - payment_intent.payment_id.as_str(), + &payment_intent.payment_id, merchant_id, attempt_id.clone().as_str(), storage_scheme, diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 290190e59d..5583d41a23 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -180,6 +180,7 @@ impl PostUpdateTracker, types::PaymentsAuthor payment_method_id.clone(), merchant_connector_id.clone(), merchant_account.storage_scheme, + &payment_data.payment_intent.payment_id, ) .await?; payment_data.payment_attempt.payment_method_id = payment_method_id; @@ -707,6 +708,7 @@ impl PostUpdateTracker, types::SetupMandateRequestDa payment_method_id.clone(), merchant_connector_id.clone(), merchant_account.storage_scheme, + &payment_data.payment_intent.payment_id, ) .await?; payment_data.payment_attempt.payment_method_id = payment_method_id; diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 6b101b6bd1..4bf740f146 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -75,7 +75,7 @@ impl GetTracker, api::PaymentsSessionRequest> let mut payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( - payment_intent.payment_id.as_str(), + &payment_intent.payment_id, merchant_id, payment_intent.active_attempt.get_id().as_str(), storage_scheme, diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 9a29b36b55..2304ab1256 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -75,7 +75,7 @@ impl GetTracker, api::PaymentsStartRequest> f )?; payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( - payment_intent.payment_id.as_str(), + &payment_intent.payment_id, merchant_id, payment_intent.active_attempt.get_id().as_str(), storage_scheme, diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index f2453e52c8..f9aa1c2be5 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -231,7 +231,7 @@ async fn get_tracker_for_sync< helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?; - let payment_id_str = payment_attempt.payment_id.clone(); + let payment_id = payment_attempt.payment_id.clone(); currency = payment_attempt.currency.get_required_value("currency")?; amount = payment_attempt.get_total_amount().into(); @@ -271,11 +271,11 @@ async fn get_tracker_for_sync< let attempts = match request.expand_attempts { Some(true) => { Some(db - .find_attempts_by_merchant_id_payment_id(merchant_account.get_id(), &payment_id_str, storage_scheme) + .find_attempts_by_merchant_id_payment_id(merchant_account.get_id(), &payment_id, storage_scheme) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { - format!("Error while retrieving attempt list for, merchant_id: {:?}, payment_id: {payment_id_str}",merchant_account.get_id()) + format!("Error while retrieving attempt list for, merchant_id: {:?}, payment_id: {payment_id:?}",merchant_account.get_id()) })?) }, _ => None, @@ -292,7 +292,7 @@ async fn get_tracker_for_sync< .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { - format!("Error while retrieving capture list for, merchant_id: {:?}, payment_id: {payment_id_str}", merchant_account.get_id()) + format!("Error while retrieving capture list for, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id()) })?; Some(payment_types::MultipleCaptureData::new_for_sync( captures, @@ -304,7 +304,7 @@ async fn get_tracker_for_sync< let refunds = db .find_refund_by_payment_id_merchant_id( - &payment_id_str, + &payment_id, merchant_account.get_id(), storage_scheme, ) @@ -312,41 +312,38 @@ async fn get_tracker_for_sync< .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!( - "Failed while getting refund list for, payment_id: {}, merchant_id: {:?}", - &payment_id_str, + "Failed while getting refund list for, payment_id: {:?}, merchant_id: {:?}", + &payment_id, merchant_account.get_id() ) })?; let authorizations = db - .find_all_authorizations_by_merchant_id_payment_id( - merchant_account.get_id(), - &payment_id_str, - ) + .find_all_authorizations_by_merchant_id_payment_id(merchant_account.get_id(), &payment_id) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!( - "Failed while getting authorizations list for, payment_id: {}, merchant_id: {:?}", - &payment_id_str, + "Failed while getting authorizations list for, payment_id: {:?}, merchant_id: {:?}", + &payment_id, merchant_account.get_id() ) })?; let disputes = db - .find_disputes_by_merchant_id_payment_id(merchant_account.get_id(), &payment_id_str) + .find_disputes_by_merchant_id_payment_id(merchant_account.get_id(), &payment_id) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { - format!("Error while retrieving dispute list for, merchant_id: {:?}, payment_id: {payment_id_str}", merchant_account.get_id()) + format!("Error while retrieving dispute list for, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id()) })?; let frm_response = db - .find_fraud_check_by_payment_id(payment_id_str.to_string(), merchant_account.get_id().clone()) + .find_fraud_check_by_payment_id(payment_id.to_owned(), merchant_account.get_id().clone()) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { - format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {payment_id_str}", merchant_account.get_id()) + format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id()) }); let contains_encoded_data = payment_attempt.encoded_data.is_some(); @@ -531,7 +528,7 @@ pub async fn get_payment_intent_payment_attempt( .await?; pa = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( - pi.payment_id.as_str(), + &pi.payment_id, merchant_id, pi.active_attempt.get_id().as_str(), storage_scheme, @@ -549,7 +546,7 @@ pub async fn get_payment_intent_payment_attempt( pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, - pa.payment_id.as_str(), + &pa.payment_id, merchant_id, key_store, storage_scheme, @@ -563,7 +560,7 @@ pub async fn get_payment_intent_payment_attempt( pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, - pa.payment_id.as_str(), + &pa.payment_id, merchant_id, key_store, storage_scheme, @@ -582,7 +579,7 @@ pub async fn get_payment_intent_payment_attempt( pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, - pa.payment_id.as_str(), + &pa.payment_id, merchant_id, key_store, storage_scheme, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 4efb26e6d2..e42f0ccdfd 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -22,7 +22,6 @@ use crate::{ mandate::helpers as m_helpers, payment_methods::cards::create_encrypted_data, payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, - utils as core_utils, }, routes::{app::ReqState, SessionState}, services, @@ -114,7 +113,7 @@ impl GetTracker, api::PaymentsRequest> for Pa payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( - payment_intent.payment_id.as_str(), + &payment_intent.payment_id, merchant_id, payment_intent.active_attempt.get_id().as_str(), storage_scheme, @@ -883,7 +882,7 @@ impl ValidateRequest for PaymentUpdate Box::new(self), operations::ValidateResult { merchant_id: merchant_account.get_id().to_owned(), - payment_id: payment_id.and_then(|id| core_utils::validate_id(id, "payment_id"))?, + payment_id, storage_scheme: merchant_account.storage_scheme, requeue: matches!( request.retry_action, 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 e3e3bf4260..72ae1d6190 100644 --- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs +++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs @@ -89,7 +89,7 @@ impl let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( - payment_intent.payment_id.as_str(), + &payment_intent.payment_id, merchant_id, attempt_id.clone().as_str(), storage_scheme, diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index d655fc42a1..5fed8bf222 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -25,7 +25,6 @@ use crate::{ }, services, types::{self, api, domain, storage}, - utils, }; #[instrument(skip_all)] @@ -496,10 +495,9 @@ pub fn make_new_payment_attempt( let created_at @ modified_at @ last_synced = Some(common_utils::date_time::now()); storage::PaymentAttemptNew { connector: Some(connector), - attempt_id: utils::get_payment_attempt_id( - &old_payment_attempt.payment_id, - new_attempt_count, - ), + attempt_id: old_payment_attempt + .payment_id + .get_attempt_id(new_attempt_count), payment_id: old_payment_attempt.payment_id, merchant_id: old_payment_attempt.merchant_id, status: old_payment_attempt.status, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index eeb1c84c09..cb4c0ce289 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -182,7 +182,11 @@ where merchant_id: merchant_account.get_id().clone(), customer_id, connector: connector_id.to_owned(), - payment_id: payment_data.payment_attempt.payment_id.clone(), + payment_id: payment_data + .payment_attempt + .payment_id + .get_string_repr() + .to_owned(), attempt_id: payment_data.payment_attempt.attempt_id.clone(), status: payment_data.payment_attempt.status, payment_method, @@ -798,7 +802,7 @@ where .parse_value("PaymentChargeRequest") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!( - "Failed to parse PaymentChargeRequest for payment_intent {}", + "Failed to parse PaymentChargeRequest for payment_intent {:?}", payment_intent.payment_id ))?; diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 515a7be959..e45beb8c04 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -776,7 +776,7 @@ pub async fn payouts_list_core( match db .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_id, - &utils::get_payment_attempt_id(payout.payout_id.clone(), payout.attempt_count), + &utils::get_payout_attempt_id(payout.payout_id.clone(), payout.attempt_count), storage_enums::MerchantStorageScheme::PostgresOnly, ) .await @@ -2269,6 +2269,15 @@ pub async fn payout_create_db_entries( _ => None, }; + // We have to do this because the function that is being used to create / get address is from payments + // which expects a payment_id + let payout_id_as_payment_id_type = + common_utils::id_type::PaymentId::try_from(std::borrow::Cow::Owned(payout_id.to_string())) + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "payout_id contains invalid data".to_string(), + }) + .attach_printable("Error converting payout_id to PaymentId type")?; + // Get or create address let billing_address = payment_helpers::create_or_find_address_for_payment_by_request( state, @@ -2277,7 +2286,7 @@ pub async fn payout_create_db_entries( merchant_id, customer_id.as_ref(), key_store, - payout_id, + &payout_id_as_payment_id_type, merchant_account.storage_scheme, ) .await?; @@ -2345,7 +2354,7 @@ pub async fn payout_create_db_entries( }) .attach_printable("Error inserting payouts in db")?; // Make payout_attempt entry - let payout_attempt_id = utils::get_payment_attempt_id(payout_id, 1); + let payout_attempt_id = utils::get_payout_attempt_id(payout_id, 1); let payout_attempt_req = storage::PayoutAttemptNew { payout_attempt_id: payout_attempt_id.to_string(), @@ -2436,7 +2445,7 @@ pub async fn make_payout_data( .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; core_utils::validate_profile_id_from_auth_layer(auth_profile_id, &payouts)?; - let payout_attempt_id = utils::get_payment_attempt_id(payout_id, payouts.attempt_count); + let payout_attempt_id = utils::get_payout_attempt_id(payout_id, payouts.attempt_count); let payout_attempt = db .find_payout_attempt_by_merchant_id_payout_attempt_id( @@ -2448,7 +2457,17 @@ pub async fn make_payout_data( .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; let customer_id = payouts.customer_id.as_ref(); - let payout_id = &payouts.payout_id; + + // We have to do this because the function that is being used to create / get address is from payments + // which expects a payment_id + let payout_id_as_payment_id_type = common_utils::id_type::PaymentId::try_from( + std::borrow::Cow::Owned(payouts.payout_id.clone()), + ) + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "payout_id contains invalid data".to_string(), + }) + .attach_printable("Error converting payout_id to PaymentId type")?; + let billing_address = payment_helpers::create_or_find_address_for_payment_by_request( state, None, @@ -2456,11 +2475,13 @@ pub async fn make_payout_data( merchant_id, customer_id, key_store, - payout_id, + &payout_id_as_payment_id_type, merchant_account.storage_scheme, ) .await?; + let payout_id = &payouts.payout_id; + let customer_details = customer_id .async_map(|customer_id| async move { db.find_customer_optional_by_customer_id_merchant_id( diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 46e97a1e0e..1249b5d305 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -1094,6 +1094,15 @@ pub async fn update_payouts_and_payout_attempt( payout_data.payouts.customer_id.clone() }; + // We have to do this because the function that is being used to create / get address is from payments + // which expects a payment_id + let payout_id_as_payment_id_type = + id_type::PaymentId::try_from(std::borrow::Cow::Owned(payout_id.clone())) + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "payout_id contains invalid data".to_string(), + }) + .attach_printable("Error converting payout_id to PaymentId type")?; + // Fetch address details from request and create new or else use existing address that was attached let billing_address = payment_helpers::create_or_find_address_for_payment_by_request( state, @@ -1102,7 +1111,7 @@ pub async fn update_payouts_and_payout_attempt( merchant_account.get_id(), customer_id.as_ref(), merchant_key_store, - &payout_id, + &payout_id_as_payment_id_type, merchant_account.storage_scheme, ) .await?; diff --git a/crates/router/src/core/payouts/retry.rs b/crates/router/src/core/payouts/retry.rs index 08fef69988..e190e627bd 100644 --- a/crates/router/src/core/payouts/retry.rs +++ b/crates/router/src/core/payouts/retry.rs @@ -273,7 +273,7 @@ pub async fn modify_trackers( .attach_printable("Error updating payouts")?; let payout_attempt_id = - utils::get_payment_attempt_id(payout_id.to_owned(), payout_data.payouts.attempt_count); + utils::get_payout_attempt_id(payout_id.to_owned(), payout_data.payouts.attempt_count); let payout_attempt_req = storage::PayoutAttemptNew { payout_attempt_id: payout_attempt_id.to_string(), diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index 4a462b4bc6..6710a7c86d 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -63,7 +63,7 @@ pub async fn create_link_token( .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; - let pm_auth_key = format!("pm_auth_{}", payload.payment_id); + let pm_auth_key = payload.payment_id.get_pm_auth_key(); redis_conn .exists::>(&pm_auth_key) @@ -678,7 +678,7 @@ async fn get_selected_config_from_redis( .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; - let pm_auth_key = format!("pm_auth_{}", payload.payment_id); + let pm_auth_key = payload.payment_id.get_pm_auth_key(); redis_conn .exists::>(&pm_auth_key) diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 867a2ccff5..1761c0bad0 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -420,7 +420,7 @@ pub async fn refund_retrieve_core( .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; core_utils::validate_profile_id_from_auth_layer(profile_id, &refund)?; - let payment_id = refund.payment_id.as_str(); + let payment_id = &refund.payment_id; payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index c1086f7d14..3fe3947deb 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -42,7 +42,6 @@ pub const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_DISPUTE_FLOW: &str = #[cfg(feature = "payouts")] pub const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_PAYOUTS_FLOW: &str = "irrelevant_connector_request_reference_id_in_payouts_flow"; -const IRRELEVANT_PAYMENT_ID_IN_DISPUTE_FLOW: &str = "irrelevant_payment_id_in_dispute_flow"; const IRRELEVANT_ATTEMPT_ID_IN_DISPUTE_FLOW: &str = "irrelevant_attempt_id_in_dispute_flow"; #[cfg(all(feature = "payouts", feature = "v2", feature = "customer_v2"))] @@ -148,7 +147,9 @@ pub async fn construct_payout_router_data<'a, F>( customer_id: customer_details.to_owned().map(|c| c.customer_id), connector_customer: connector_customer_id, connector: connector_name.to_string(), - payment_id: "".to_string(), + payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("payout") + .get_string_repr() + .to_owned(), attempt_id: "".to_string(), status: enums::AttemptStatus::Failure, payment_method: enums::PaymentMethod::default(), @@ -298,7 +299,7 @@ pub async fn construct_refund_router_data<'a, F>( merchant_id: merchant_account.get_id().clone(), customer_id: payment_intent.customer_id.to_owned(), connector: connector_id.to_string(), - payment_id: payment_attempt.payment_id.clone(), + payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), attempt_id: payment_attempt.attempt_id.clone(), status, payment_method: payment_method_type, @@ -617,7 +618,7 @@ pub async fn construct_accept_dispute_router_data<'a>( flow: PhantomData, merchant_id: merchant_account.get_id().clone(), connector: dispute.connector.to_string(), - payment_id: payment_attempt.payment_id.clone(), + payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), attempt_id: payment_attempt.attempt_id.clone(), status: payment_attempt.status, payment_method, @@ -712,7 +713,7 @@ pub async fn construct_submit_evidence_router_data<'a>( flow: PhantomData, merchant_id: merchant_account.get_id().clone(), connector: connector_id.to_string(), - payment_id: payment_attempt.payment_id.clone(), + payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), attempt_id: payment_attempt.attempt_id.clone(), status: payment_attempt.status, payment_method, @@ -805,7 +806,7 @@ pub async fn construct_upload_file_router_data<'a>( flow: PhantomData, merchant_id: merchant_account.get_id().clone(), connector: connector_id.to_string(), - payment_id: payment_attempt.payment_id.clone(), + payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), attempt_id: payment_attempt.attempt_id.clone(), status: payment_attempt.status, payment_method, @@ -902,7 +903,7 @@ pub async fn construct_defend_dispute_router_data<'a>( flow: PhantomData, merchant_id: merchant_account.get_id().clone(), connector: connector_id.to_string(), - payment_id: payment_attempt.payment_id.clone(), + payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), attempt_id: payment_attempt.attempt_id.clone(), status: payment_attempt.status, payment_method, @@ -994,7 +995,9 @@ pub async fn construct_retrieve_file_router_data<'a>( connector: connector_id.to_string(), customer_id: None, connector_customer: None, - payment_id: IRRELEVANT_PAYMENT_ID_IN_DISPUTE_FLOW.to_string(), + payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("dispute") + .get_string_repr() + .to_owned(), attempt_id: IRRELEVANT_ATTEMPT_ID_IN_DISPUTE_FLOW.to_string(), status: diesel_models::enums::AttemptStatus::default(), payment_method: diesel_models::enums::PaymentMethod::default(), @@ -1062,7 +1065,7 @@ pub fn get_connector_request_reference_id( is_merchant_enabled_for_payment_id_as_connector_request_id(conf, merchant_id); // Send payment_id if config is enabled for a merchant, else send attempt_id if is_config_enabled_for_merchant { - payment_attempt.payment_id.clone() + payment_attempt.payment_id.get_string_repr().to_owned() } else { payment_attempt.attempt_id.clone() } @@ -1203,14 +1206,16 @@ pub fn get_poll_id(merchant_id: &common_utils::id_type::MerchantId, unique_id: S merchant_id.get_poll_id(&unique_id) } -pub fn get_external_authentication_request_poll_id(payment_id: &String) -> String { - format!("external_authentication_{}", payment_id) +pub fn get_external_authentication_request_poll_id( + payment_id: &common_utils::id_type::PaymentId, +) -> String { + payment_id.get_external_authentication_request_poll_id() } pub fn get_html_redirect_response_for_external_authentication( return_url_with_query_params: String, payment_response: &api_models::payments::PaymentsResponse, - payment_id: String, + payment_id: common_utils::id_type::PaymentId, poll_config: &PollConfig, ) -> RouterResult { // if intent_status is requires_customer_action then set poll_id, fetch poll config and do a poll_status post message, else do open_url post message to redirect to return_url diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index 79d6d5d6b8..bf92854135 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -520,7 +520,7 @@ async fn payments_incoming_webhook_flow( let lock_action = api_locking::LockAction::Hold { input: api_locking::LockingInput { - unique_locking_key: payment_id, + unique_locking_key: payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::Payments, override_lock_retries: None, }, @@ -612,7 +612,7 @@ async fn payments_incoming_webhook_flow( &key_store, outgoing_event_type, enums::EventClass::Payments, - payment_id.clone(), + payment_id.get_string_repr().to_owned(), enums::EventObjectType::PaymentDetails, api::OutgoingWebhookContent::PaymentDetails(payments_response), primary_object_created_at, @@ -1117,7 +1117,7 @@ async fn external_authentication_incoming_webhook_flow( &key_store, outgoing_event_type, enums::EventClass::Payments, - payment_id.clone(), + payment_id.get_string_repr().to_owned(), enums::EventObjectType::PaymentDetails, api::OutgoingWebhookContent::PaymentDetails(payments_response), primary_object_created_at, @@ -1321,7 +1321,7 @@ async fn frm_incoming_webhook_flow( &key_store, outgoing_event_type, enums::EventClass::Payments, - payment_id.clone(), + payment_id.get_string_repr().to_owned(), enums::EventObjectType::PaymentDetails, api::OutgoingWebhookContent::PaymentDetails(payments_response), primary_object_created_at, @@ -1484,7 +1484,7 @@ async fn bank_transfer_webhook_flow( &key_store, outgoing_event_type, enums::EventClass::Payments, - payment_id.clone(), + payment_id.get_string_repr().to_owned(), enums::EventObjectType::PaymentDetails, api::OutgoingWebhookContent::PaymentDetails(payments_response), primary_object_created_at, @@ -1500,16 +1500,15 @@ async fn bank_transfer_webhook_flow( } } -#[inline] async fn get_payment_id( db: &dyn StorageInterface, payment_id: &api::PaymentIdType, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: enums::MerchantStorageScheme, -) -> errors::RouterResult { +) -> errors::RouterResult { let pay_id = || async { match payment_id { - api_models::payments::PaymentIdType::PaymentIntentId(ref id) => Ok(id.to_string()), + api_models::payments::PaymentIdType::PaymentIntentId(ref id) => Ok(id.to_owned()), api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => db .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_id, diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs index f837fbba0d..8987a9384d 100644 --- a/crates/router/src/core/webhooks/utils.rs +++ b/crates/router/src/core/webhooks/utils.rs @@ -13,8 +13,6 @@ use crate::{ types::{self, api, domain, PaymentAddress}, }; -const IRRELEVANT_PAYMENT_ID_IN_SOURCE_VERIFICATION_FLOW: &str = - "irrelevant_payment_id_in_source_verification_flow"; const IRRELEVANT_ATTEMPT_ID_IN_SOURCE_VERIFICATION_FLOW: &str = "irrelevant_attempt_id_in_source_verification_flow"; const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_SOURCE_VERIFICATION_FLOW: &str = @@ -76,7 +74,9 @@ pub async fn construct_webhook_router_data<'a>( merchant_id: merchant_account.get_id().clone(), connector: connector_name.to_string(), customer_id: None, - payment_id: IRRELEVANT_PAYMENT_ID_IN_SOURCE_VERIFICATION_FLOW.to_string(), + payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("source_verification_flow") + .get_string_repr() + .to_owned(), attempt_id: IRRELEVANT_ATTEMPT_ID_IN_SOURCE_VERIFICATION_FLOW.to_string(), status: diesel_models::enums::AttemptStatus::default(), payment_method: diesel_models::enums::PaymentMethod::default(), diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 4e3142bfec..a789af1aa2 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -300,7 +300,7 @@ impl FraudCheckInterface for KafkaStore { } async fn find_fraud_check_by_payment_id( &self, - payment_id: String, + payment_id: id_type::PaymentId, merchant_id: id_type::MerchantId, ) -> CustomResult { let frm = self @@ -318,7 +318,7 @@ impl FraudCheckInterface for KafkaStore { } async fn find_fraud_check_by_payment_id_if_present( &self, - payment_id: String, + payment_id: id_type::PaymentId, merchant_id: id_type::MerchantId, ) -> CustomResult, StorageError> { let frm = self diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs index 10ad8ebe80..af2fffa509 100644 --- a/crates/router/src/db/address.rs +++ b/crates/router/src/db/address.rs @@ -33,7 +33,7 @@ where state: &KeyManagerState, this: domain::PaymentAddress, address: domain::AddressUpdate, - payment_id: String, + payment_id: id_type::PaymentId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult; @@ -48,7 +48,7 @@ where async fn insert_address_for_payments( &self, state: &KeyManagerState, - payment_id: &str, + payment_id: &id_type::PaymentId, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, @@ -65,7 +65,7 @@ where &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, - payment_id: &str, + payment_id: &id_type::PaymentId, address_id: &str, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, @@ -131,7 +131,7 @@ mod storage { &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, - payment_id: &str, + payment_id: &id_type::PaymentId, address_id: &str, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, @@ -185,7 +185,7 @@ mod storage { state: &KeyManagerState, this: domain::PaymentAddress, address_update: domain::AddressUpdate, - _payment_id: String, + _payment_id: id_type::PaymentId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult { @@ -214,7 +214,7 @@ mod storage { async fn insert_address_for_payments( &self, state: &KeyManagerState, - _payment_id: &str, + _payment_id: &id_type::PaymentId, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, @@ -359,7 +359,7 @@ mod storage { &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, - payment_id: &str, + payment_id: &id_type::PaymentId, address_id: &str, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, @@ -444,7 +444,7 @@ mod storage { state: &KeyManagerState, this: domain::PaymentAddress, address_update: domain::AddressUpdate, - payment_id: String, + payment_id: id_type::PaymentId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult { @@ -528,7 +528,7 @@ mod storage { async fn insert_address_for_payments( &self, state: &KeyManagerState, - payment_id: &str, + payment_id: &id_type::PaymentId, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, @@ -733,7 +733,7 @@ impl AddressInterface for MockDb { &self, state: &KeyManagerState, _merchant_id: &id_type::MerchantId, - _payment_id: &str, + _payment_id: &id_type::PaymentId, address_id: &str, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, @@ -802,7 +802,7 @@ impl AddressInterface for MockDb { state: &KeyManagerState, this: domain::PaymentAddress, address_update: domain::AddressUpdate, - _payment_id: String, + _payment_id: id_type::PaymentId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult { @@ -837,7 +837,7 @@ impl AddressInterface for MockDb { async fn insert_address_for_payments( &self, state: &KeyManagerState, - _payment_id: &str, + _payment_id: &id_type::PaymentId, address_new: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, diff --git a/crates/router/src/db/authorization.rs b/crates/router/src/db/authorization.rs index 40902ce888..2440cbf83e 100644 --- a/crates/router/src/db/authorization.rs +++ b/crates/router/src/db/authorization.rs @@ -19,7 +19,7 @@ pub trait AuthorizationInterface { async fn find_all_authorizations_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult, errors::StorageError>; async fn update_authorization_by_merchant_id_authorization_id( @@ -48,7 +48,7 @@ impl AuthorizationInterface for Store { async fn find_all_authorizations_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Authorization::find_by_merchant_id_payment_id(&conn, merchant_id, payment_id) @@ -110,12 +110,12 @@ impl AuthorizationInterface for MockDb { async fn find_all_authorizations_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult, errors::StorageError> { let authorizations = self.authorizations.lock().await; let authorizations_found: Vec = authorizations .iter() - .filter(|a| a.merchant_id == *merchant_id && a.payment_id == payment_id) + .filter(|a| a.merchant_id == *merchant_id && a.payment_id == *payment_id) .cloned() .collect(); diff --git a/crates/router/src/db/capture.rs b/crates/router/src/db/capture.rs index 34ef1bfddf..16b18a873d 100644 --- a/crates/router/src/db/capture.rs +++ b/crates/router/src/db/capture.rs @@ -17,7 +17,7 @@ pub trait CaptureInterface { async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &self, merchant_id: &common_utils::id_type::MerchantId, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, authorized_attempt_id: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult, errors::StorageError>; @@ -81,7 +81,7 @@ mod storage { async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &self, merchant_id: &common_utils::id_type::MerchantId, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, authorized_attempt_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult, errors::StorageError> { @@ -152,7 +152,7 @@ mod storage { async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &self, merchant_id: &common_utils::id_type::MerchantId, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, authorized_attempt_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult, errors::StorageError> { @@ -216,7 +216,7 @@ impl CaptureInterface for MockDb { async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &self, _merchant_id: &common_utils::id_type::MerchantId, - _payment_id: &str, + _payment_id: &common_utils::id_type::PaymentId, _authorized_attempt_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult, errors::StorageError> { diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs index 686de8c223..abe469dc32 100644 --- a/crates/router/src/db/dispute.rs +++ b/crates/router/src/db/dispute.rs @@ -18,7 +18,7 @@ pub trait DisputeInterface { async fn find_by_merchant_id_payment_id_connector_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, connector_dispute_id: &str, ) -> CustomResult, errors::StorageError>; @@ -37,7 +37,7 @@ pub trait DisputeInterface { async fn find_disputes_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult, errors::StorageError>; async fn update_dispute( @@ -65,7 +65,7 @@ impl DisputeInterface for Store { async fn find_by_merchant_id_payment_id_connector_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, connector_dispute_id: &str, ) -> CustomResult, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; @@ -107,7 +107,7 @@ impl DisputeInterface for Store { async fn find_disputes_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Dispute::find_by_merchant_id_payment_id(&conn, merchant_id, payment_id) @@ -180,7 +180,7 @@ impl DisputeInterface for MockDb { async fn find_by_merchant_id_payment_id_connector_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, connector_dispute_id: &str, ) -> CustomResult, errors::StorageError> { Ok(self @@ -190,7 +190,7 @@ impl DisputeInterface for MockDb { .iter() .find(|d| { d.merchant_id == *merchant_id - && d.payment_id == payment_id + && d.payment_id == *payment_id && d.connector_dispute_id == connector_dispute_id }) .cloned()) @@ -285,13 +285,13 @@ impl DisputeInterface for MockDb { async fn find_disputes_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult, errors::StorageError> { let locked_disputes = self.disputes.lock().await; Ok(locked_disputes .iter() - .filter(|d| d.merchant_id == *merchant_id && d.payment_id == payment_id) + .filter(|d| d.merchant_id == *merchant_id && d.payment_id == *payment_id) .cloned() .collect()) } @@ -380,7 +380,7 @@ mod tests { pub struct DisputeNewIds { dispute_id: String, - payment_id: String, + payment_id: common_utils::id_type::PaymentId, attempt_id: String, merchant_id: common_utils::id_type::MerchantId, connector_dispute_id: String, @@ -426,7 +426,10 @@ mod tests { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), - payment_id: "payment_1".into(), + payment_id: common_utils::id_type::PaymentId::try_from(Cow::Borrowed( + "payment_1", + )) + .unwrap(), connector_dispute_id: "connector_dispute_1".into(), })) .await @@ -459,7 +462,10 @@ mod tests { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), - payment_id: "payment_1".into(), + payment_id: common_utils::id_type::PaymentId::try_from(Cow::Borrowed( + "payment_1", + )) + .unwrap(), connector_dispute_id: "connector_dispute_1".into(), })) .await @@ -470,7 +476,10 @@ mod tests { dispute_id: "dispute_2".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), - payment_id: "payment_1".into(), + payment_id: common_utils::id_type::PaymentId::try_from(Cow::Borrowed( + "payment_1", + )) + .unwrap(), connector_dispute_id: "connector_dispute_2".into(), })) .await @@ -479,7 +488,8 @@ mod tests { let found_dispute = mockdb .find_by_merchant_id_payment_id_connector_dispute_id( &merchant_id, - "payment_1", + &common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")) + .unwrap(), "connector_dispute_1", ) .await @@ -495,6 +505,9 @@ mod tests { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); + let payment_id = + common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); + let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create Mock store"); @@ -504,7 +517,7 @@ mod tests { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), - payment_id: "payment_1".into(), + payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await @@ -515,7 +528,7 @@ mod tests { dispute_id: "dispute_2".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), - payment_id: "payment_1".into(), + payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await @@ -534,6 +547,9 @@ mod tests { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_2")).unwrap(); + let payment_id = + common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); + let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create Mock store"); @@ -543,7 +559,7 @@ mod tests { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), - payment_id: "payment_1".into(), + payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await @@ -554,7 +570,7 @@ mod tests { dispute_id: "dispute_2".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), - payment_id: "payment_1".into(), + payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await @@ -590,6 +606,9 @@ mod tests { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); + let payment_id = + common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); + let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create Mock store"); @@ -599,7 +618,7 @@ mod tests { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), - payment_id: "payment_1".into(), + payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await @@ -610,14 +629,14 @@ mod tests { dispute_id: "dispute_2".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), - payment_id: "payment_1".into(), + payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let found_disputes = mockdb - .find_disputes_by_merchant_id_payment_id(&merchant_id, "payment_1") + .find_disputes_by_merchant_id_payment_id(&merchant_id, &payment_id) .await .unwrap(); @@ -650,6 +669,9 @@ mod tests { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); + let payment_id = + common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); + let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); @@ -659,7 +681,7 @@ mod tests { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), - payment_id: "payment_1".into(), + payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await @@ -731,6 +753,9 @@ mod tests { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); + let payment_id = + common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); + let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); @@ -740,7 +765,7 @@ mod tests { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), - payment_id: "payment_1".into(), + payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await @@ -807,6 +832,9 @@ mod tests { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); + let payment_id = + common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); + let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); @@ -816,7 +844,7 @@ mod tests { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), - payment_id: "payment_1".into(), + payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs index 6aae49f1bd..651c2ece61 100644 --- a/crates/router/src/db/events.rs +++ b/crates/router/src/db/events.rs @@ -794,7 +794,10 @@ mod tests { response: None, delivery_attempt: Some(enums::WebhookDeliveryAttempt::InitialAttempt), metadata: Some(EventMetadata::Payment { - payment_id: payment_id.into(), + payment_id: common_utils::id_type::PaymentId::try_from( + std::borrow::Cow::Borrowed(payment_id), + ) + .unwrap(), }), }, &merchant_key_store, diff --git a/crates/router/src/db/fraud_check.rs b/crates/router/src/db/fraud_check.rs index 20e3bfb32a..af4c4bdcff 100644 --- a/crates/router/src/db/fraud_check.rs +++ b/crates/router/src/db/fraud_check.rs @@ -24,13 +24,13 @@ pub trait FraudCheckInterface { async fn find_fraud_check_by_payment_id( &self, - payment_id: String, + payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult; async fn find_fraud_check_by_payment_id_if_present( &self, - payment_id: String, + payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult, errors::StorageError>; } @@ -63,7 +63,7 @@ impl FraudCheckInterface for Store { #[instrument(skip_all)] async fn find_fraud_check_by_payment_id( &self, - payment_id: String, + payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult { let conn = connection::pg_connection_write(self).await?; @@ -75,7 +75,7 @@ impl FraudCheckInterface for Store { #[instrument(skip_all)] async fn find_fraud_check_by_payment_id_if_present( &self, - payment_id: String, + payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; @@ -102,7 +102,7 @@ impl FraudCheckInterface for MockDb { } async fn find_fraud_check_by_payment_id( &self, - _payment_id: String, + _payment_id: common_utils::id_type::PaymentId, _merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult { Err(errors::StorageError::MockDbError)? @@ -110,7 +110,7 @@ impl FraudCheckInterface for MockDb { async fn find_fraud_check_by_payment_id_if_present( &self, - _payment_id: String, + _payment_id: common_utils::id_type::PaymentId, _merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult, errors::StorageError> { Err(errors::StorageError::MockDbError)? diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 316e8106c9..f7b15cdb3a 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -131,7 +131,7 @@ impl AddressInterface for KafkaStore { state: &KeyManagerState, this: domain::PaymentAddress, address: domain::AddressUpdate, - payment_id: String, + payment_id: id_type::PaymentId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult { @@ -150,7 +150,7 @@ impl AddressInterface for KafkaStore { async fn insert_address_for_payments( &self, state: &KeyManagerState, - payment_id: &str, + payment_id: &id_type::PaymentId, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, @@ -164,7 +164,7 @@ impl AddressInterface for KafkaStore { &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, - payment_id: &str, + payment_id: &id_type::PaymentId, address_id: &str, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, @@ -544,7 +544,7 @@ impl DisputeInterface for KafkaStore { async fn find_by_merchant_id_payment_id_connector_dispute_id( &self, merchant_id: &id_type::MerchantId, - payment_id: &str, + payment_id: &id_type::PaymentId, connector_dispute_id: &str, ) -> CustomResult, errors::StorageError> { self.diesel_store @@ -599,7 +599,7 @@ impl DisputeInterface for KafkaStore { async fn find_disputes_by_merchant_id_payment_id( &self, merchant_id: &id_type::MerchantId, - payment_id: &str, + payment_id: &id_type::PaymentId, ) -> CustomResult, errors::StorageError> { self.diesel_store .find_disputes_by_merchant_id_payment_id(merchant_id, payment_id) @@ -1349,7 +1349,7 @@ impl PaymentAttemptInterface for KafkaStore { async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, connector_transaction_id: &str, - payment_id: &str, + payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult { @@ -1380,7 +1380,7 @@ impl PaymentAttemptInterface for KafkaStore { async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, - payment_id: &str, + payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, attempt_id: &str, storage_scheme: MerchantStorageScheme, @@ -1408,7 +1408,7 @@ impl PaymentAttemptInterface for KafkaStore { async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, - payment_id: &str, + payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult { @@ -1423,7 +1423,7 @@ impl PaymentAttemptInterface for KafkaStore { async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, - payment_id: &str, + payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult { @@ -1493,7 +1493,7 @@ impl PaymentAttemptInterface for KafkaStore { async fn find_attempts_by_merchant_id_payment_id( &self, merchant_id: &id_type::MerchantId, - payment_id: &str, + payment_id: &id_type::PaymentId, storage_scheme: MerchantStorageScheme, ) -> CustomResult, errors::DataStorageError> { self.diesel_store @@ -1561,7 +1561,7 @@ impl PaymentIntentInterface for KafkaStore { async fn find_payment_intent_by_payment_id_merchant_id( &self, state: &KeyManagerState, - payment_id: &str, + payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, @@ -2131,7 +2131,7 @@ impl CaptureInterface for KafkaStore { async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &self, merchant_id: &id_type::MerchantId, - payment_id: &str, + payment_id: &id_type::PaymentId, authorized_attempt_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult, errors::StorageError> { @@ -2165,7 +2165,7 @@ impl RefundInterface for KafkaStore { async fn find_refund_by_payment_id_merchant_id( &self, - payment_id: &str, + payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult, errors::StorageError> { @@ -3121,7 +3121,7 @@ impl AuthorizationInterface for KafkaStore { async fn find_all_authorizations_by_merchant_id_payment_id( &self, merchant_id: &id_type::MerchantId, - payment_id: &str, + payment_id: &id_type::PaymentId, ) -> CustomResult, errors::StorageError> { self.diesel_store .find_all_authorizations_by_merchant_id_payment_id(merchant_id, payment_id) diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index 408c649560..e6b46c5af5 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -25,7 +25,7 @@ pub trait RefundInterface { async fn find_refund_by_payment_id_merchant_id( &self, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult, errors::StorageError>; @@ -201,7 +201,7 @@ mod storage { #[instrument(skip_all)] async fn find_refund_by_payment_id_merchant_id( &self, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult, errors::StorageError> { @@ -706,7 +706,7 @@ mod storage { #[instrument(skip_all)] async fn find_refund_by_payment_id_merchant_id( &self, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult, errors::StorageError> { @@ -946,7 +946,7 @@ impl RefundInterface for MockDb { async fn find_refund_by_payment_id_merchant_id( &self, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult, errors::StorageError> { @@ -954,7 +954,7 @@ impl RefundInterface for MockDb { Ok(refunds .iter() - .filter(|refund| refund.merchant_id == *merchant_id && refund.payment_id == payment_id) + .filter(|refund| refund.merchant_id == *merchant_id && refund.payment_id == *payment_id) .cloned() .collect::>()) } diff --git a/crates/router/src/events/outgoing_webhook_logs.rs b/crates/router/src/events/outgoing_webhook_logs.rs index 0f7ca4a234..b2a8202e0e 100644 --- a/crates/router/src/events/outgoing_webhook_logs.rs +++ b/crates/router/src/events/outgoing_webhook_logs.rs @@ -27,7 +27,7 @@ pub struct OutgoingWebhookEvent { #[serde(tag = "outgoing_webhook_event_type", rename_all = "snake_case")] pub enum OutgoingWebhookEventContent { Payment { - payment_id: String, + payment_id: common_utils::id_type::PaymentId, content: Value, }, Payout { @@ -35,12 +35,12 @@ pub enum OutgoingWebhookEventContent { content: Value, }, Refund { - payment_id: String, + payment_id: common_utils::id_type::PaymentId, refund_id: String, content: Value, }, Dispute { - payment_id: String, + payment_id: common_utils::id_type::PaymentId, attempt_id: String, dispute_id: String, content: Value, diff --git a/crates/router/src/routes/dummy_connector.rs b/crates/router/src/routes/dummy_connector.rs index a0c85f90ef..26c32776d7 100644 --- a/crates/router/src/routes/dummy_connector.rs +++ b/crates/router/src/routes/dummy_connector.rs @@ -101,11 +101,11 @@ pub async fn dummy_connector_refund( state: web::Data, req: actix_web::HttpRequest, json_payload: web::Json, - path: web::Path, + path: web::Path, ) -> impl actix_web::Responder { let flow = types::Flow::DummyRefundCreate; let mut payload = json_payload.into_inner(); - payload.payment_id = Some(path.to_string()); + payload.payment_id = Some(path.into_inner()); api::server_wrap( flow, state, diff --git a/crates/router/src/routes/dummy_connector/consts.rs b/crates/router/src/routes/dummy_connector/consts.rs index e872ce2120..ffd89fc9e9 100644 --- a/crates/router/src/routes/dummy_connector/consts.rs +++ b/crates/router/src/routes/dummy_connector/consts.rs @@ -1,4 +1,3 @@ -pub const PAYMENT_ID_PREFIX: &str = "dummy_pay"; pub const ATTEMPT_ID_PREFIX: &str = "dummy_attempt"; pub const REFUND_ID_PREFIX: &str = "dummy_ref"; pub const THREE_DS_CSS: &str = include_str!("threeds_page.css"); diff --git a/crates/router/src/routes/dummy_connector/core.rs b/crates/router/src/routes/dummy_connector/core.rs index 513a586d19..f8e500e5b2 100644 --- a/crates/router/src/routes/dummy_connector/core.rs +++ b/crates/router/src/routes/dummy_connector/core.rs @@ -32,7 +32,7 @@ pub async fn payment( .await?; utils::store_data_in_redis( &state, - payment_data.payment_id.clone(), + payment_data.payment_id.get_string_repr().to_owned(), payment_data.clone(), state.conf.dummy_connector.payment_ttl, ) @@ -116,7 +116,7 @@ pub async fn payment_complete( }; utils::store_data_in_redis( &state, - updated_payment_data.payment_id.clone(), + updated_payment_data.payment_id.get_string_repr().to_owned(), updated_payment_data.clone(), state.conf.dummy_connector.payment_ttl, ) @@ -162,7 +162,8 @@ pub async fn refund_payment( })?; let mut payment_data = - utils::get_payment_data_from_payment_id(&state, payment_id.clone()).await?; + utils::get_payment_data_from_payment_id(&state, payment_id.get_string_repr().to_owned()) + .await?; payment_data.is_eligible_for_refund(req.amount)?; @@ -171,7 +172,7 @@ pub async fn refund_payment( utils::store_data_in_redis( &state, - payment_id, + payment_id.get_string_repr().to_owned(), payment_data.to_owned(), state.conf.dummy_connector.payment_ttl, ) diff --git a/crates/router/src/routes/dummy_connector/types.rs b/crates/router/src/routes/dummy_connector/types.rs index fb20cd4c27..fa84ab1f55 100644 --- a/crates/router/src/routes/dummy_connector/types.rs +++ b/crates/router/src/routes/dummy_connector/types.rs @@ -70,14 +70,14 @@ pub enum DummyConnectorStatus { pub struct DummyConnectorPaymentAttempt { pub timestamp: PrimitiveDateTime, pub attempt_id: String, - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub payment_request: DummyConnectorPaymentRequest, } impl From for DummyConnectorPaymentAttempt { fn from(payment_request: DummyConnectorPaymentRequest) -> Self { let timestamp = common_utils::date_time::now(); - let payment_id = generate_id_with_default_len(consts::PAYMENT_ID_PREFIX); + let payment_id = common_utils::id_type::PaymentId::default(); let attempt_id = generate_id_with_default_len(consts::ATTEMPT_ID_PREFIX); Self { timestamp, @@ -248,7 +248,7 @@ impl GetPaymentMethodDetails for DummyConnectorPayLater { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)] pub struct DummyConnectorPaymentData { pub attempt_id: String, - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub status: DummyConnectorStatus, pub amount: i64, pub eligible_amount: i64, @@ -286,7 +286,7 @@ pub enum DummyConnectorNextAction { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DummyConnectorPaymentResponse { pub status: DummyConnectorStatus, - pub id: String, + pub id: common_utils::id_type::PaymentId, pub amount: i64, pub currency: Currency, #[serde(with = "common_utils::custom_serde::iso8601")] @@ -333,7 +333,7 @@ pub struct DummyConnectorPaymentCompleteBody { #[derive(Default, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] pub struct DummyConnectorRefundRequest { pub amount: i64, - pub payment_id: Option, + pub payment_id: Option, } #[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] diff --git a/crates/router/src/routes/payment_link.rs b/crates/router/src/routes/payment_link.rs index 7e25156c9a..be6ef9009b 100644 --- a/crates/router/src/routes/payment_link.rs +++ b/crates/router/src/routes/payment_link.rs @@ -54,7 +54,10 @@ pub async fn payment_link_retrieve( pub async fn initiate_payment_link( state: web::Data, req: actix_web::HttpRequest, - path: web::Path<(common_utils::id_type::MerchantId, String)>, + path: web::Path<( + common_utils::id_type::MerchantId, + common_utils::id_type::PaymentId, + )>, ) -> impl Responder { let flow = Flow::PaymentLinkInitiate; let (merchant_id, payment_id) = path.into_inner(); @@ -88,7 +91,10 @@ pub async fn initiate_payment_link( pub async fn initiate_secure_payment_link( state: web::Data, req: actix_web::HttpRequest, - path: web::Path<(common_utils::id_type::MerchantId, String)>, + path: web::Path<( + common_utils::id_type::MerchantId, + common_utils::id_type::PaymentId, + )>, ) -> impl Responder { let flow = Flow::PaymentSecureLinkInitiate; let (merchant_id, payment_id) = path.into_inner(); @@ -164,7 +170,10 @@ pub async fn payments_link_list( pub async fn payment_link_status( state: web::Data, req: actix_web::HttpRequest, - path: web::Path<(common_utils::id_type::MerchantId, String)>, + path: web::Path<( + common_utils::id_type::MerchantId, + common_utils::id_type::PaymentId, + )>, ) -> impl Responder { let flow = Flow::PaymentLinkStatus; let (merchant_id, payment_id) = path.into_inner(); diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 60ecbe0a2b..95b65e5be5 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -16,7 +16,6 @@ use crate::{ core::{ errors::{self, http_not_implemented}, payments::{self, PaymentRedirectFlow}, - utils as core_utils, }, routes::lock_utils, services::{api, authentication as auth}, @@ -121,6 +120,8 @@ pub async fn payments_create( .map(|payment_id_type| payment_id_type.get_payment_intent_id()) .transpose() .unwrap_or_default() + .as_ref() + .map(|id| id.get_string_repr()) .unwrap_or_default(), ); @@ -178,7 +179,11 @@ pub async fn payments_create( pub async fn payments_start( state: web::Data, req: actix_web::HttpRequest, - path: web::Path<(String, common_utils::id_type::MerchantId, String)>, + path: web::Path<( + common_utils::id_type::PaymentId, + common_utils::id_type::MerchantId, + String, + )>, ) -> impl Responder { let flow = Flow::PaymentsStart; let (payment_id, merchant_id, attempt_id) = path.into_inner(); @@ -189,7 +194,7 @@ pub async fn payments_start( }; let locking_action = payload.get_locking_input(flow.clone()); - tracing::Span::current().record("payment_id", &payment_id); + tracing::Span::current().record("payment_id", payment_id.get_string_repr()); Box::pin(api::server_wrap( flow, @@ -246,15 +251,18 @@ pub async fn payments_start( pub async fn payments_retrieve( state: web::Data, req: actix_web::HttpRequest, - path: web::Path, + path: web::Path, json_payload: web::Query, ) -> impl Responder { let flow = match json_payload.force_sync { Some(true) => Flow::PaymentsRetrieveForceSync, _ => Flow::PaymentsRetrieve, }; + let payment_id = path.into_inner(); + tracing::Span::current().record("payment_id", payment_id.get_string_repr()); + let payload = payment_types::PaymentsRetrieveRequest { - resource_id: payment_types::PaymentIdType::PaymentIntentId(path.to_string()), + resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id), merchant_id: json_payload.merchant_id.clone(), force_sync: json_payload.force_sync.unwrap_or(false), client_secret: json_payload.client_secret.clone(), @@ -269,7 +277,6 @@ pub async fn payments_retrieve( } }; - tracing::Span::current().record("payment_id", path.to_string()); tracing::Span::current().record("flow", flow.to_string()); let (auth_type, auth_flow) = @@ -335,21 +342,22 @@ pub async fn payments_retrieve_with_gateway_creds( Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; + + tracing::Span::current().record("payment_id", json_payload.payment_id.get_string_repr()); + let payload = payment_types::PaymentsRetrieveRequest { - resource_id: payment_types::PaymentIdType::PaymentIntentId( - json_payload.payment_id.to_string(), - ), + resource_id: payment_types::PaymentIdType::PaymentIntentId(json_payload.payment_id.clone()), merchant_id: json_payload.merchant_id.clone(), force_sync: json_payload.force_sync.unwrap_or(false), merchant_connector_details: json_payload.merchant_connector_details.clone(), ..Default::default() }; + let flow = match json_payload.force_sync { Some(true) => Flow::PaymentsRetrieveForceSync, _ => Flow::PaymentsRetrieve, }; - tracing::Span::current().record("payment_id", &json_payload.payment_id); tracing::Span::current().record("flow", flow.to_string()); let locking_action = payload.get_locking_input(flow.clone()); @@ -403,7 +411,7 @@ pub async fn payments_update( state: web::Data, req: actix_web::HttpRequest, json_payload: web::Json, - path: web::Path, + path: web::Path, ) -> impl Responder { let flow = Flow::PaymentsUpdate; let mut payload = json_payload.into_inner(); @@ -414,7 +422,7 @@ pub async fn payments_update( let payment_id = path.into_inner(); - tracing::Span::current().record("payment_id", &payment_id); + tracing::Span::current().record("payment_id", payment_id.get_string_repr()); payload.payment_id = Some(payment_types::PaymentIdType::PaymentIntentId(payment_id)); @@ -472,7 +480,7 @@ pub async fn payments_confirm( state: web::Data, req: actix_web::HttpRequest, json_payload: web::Json, - path: web::Path, + path: web::Path, ) -> impl Responder { let flow = Flow::PaymentsConfirm; let mut payload = json_payload.into_inner(); @@ -486,7 +494,7 @@ pub async fn payments_confirm( } let payment_id = path.into_inner(); - tracing::Span::current().record("payment_id", &payment_id); + tracing::Span::current().record("payment_id", payment_id.get_string_repr()); payload.payment_id = Some(payment_types::PaymentIdType::PaymentIntentId(payment_id)); payload.confirm = Some(true); let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { @@ -551,10 +559,10 @@ pub async fn payments_capture( state: web::Data, req: actix_web::HttpRequest, json_payload: web::Json, - path: web::Path, + path: web::Path, ) -> impl Responder { let payment_id = path.into_inner(); - tracing::Span::current().record("payment_id", &payment_id); + tracing::Span::current().record("payment_id", payment_id.get_string_repr()); let flow = Flow::PaymentsCapture; let payload = payment_types::PaymentsCaptureRequest { @@ -624,7 +632,7 @@ pub async fn payments_connector_session( } }; - tracing::Span::current().record("payment_id", &payload.payment_id); + tracing::Span::current().record("payment_id", payload.payment_id.get_string_repr()); let locking_action = payload.get_locking_input(flow.clone()); @@ -682,13 +690,17 @@ pub async fn payments_redirect_response( state: web::Data, req: actix_web::HttpRequest, json_payload: Option>, - path: web::Path<(String, common_utils::id_type::MerchantId, String)>, + path: web::Path<( + common_utils::id_type::PaymentId, + common_utils::id_type::MerchantId, + String, + )>, ) -> impl Responder { let flow = Flow::PaymentsRedirect; let (payment_id, merchant_id, connector) = path.into_inner(); let param_string = req.query_string(); - tracing::Span::current().record("payment_id", &payment_id); + tracing::Span::current().record("payment_id", payment_id.get_string_repr()); let payload = payments::PaymentsRedirectResponseData { resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id), @@ -744,12 +756,17 @@ pub async fn payments_redirect_response( pub async fn payments_redirect_response_with_creds_identifier( state: web::Data, req: actix_web::HttpRequest, - path: web::Path<(String, common_utils::id_type::MerchantId, String, String)>, + path: web::Path<( + common_utils::id_type::PaymentId, + common_utils::id_type::MerchantId, + String, + String, + )>, ) -> impl Responder { let (payment_id, merchant_id, connector, creds_identifier) = path.into_inner(); let param_string = req.query_string(); - tracing::Span::current().record("payment_id", &payment_id); + tracing::Span::current().record("payment_id", payment_id.get_string_repr()); let payload = payments::PaymentsRedirectResponseData { resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id), @@ -788,13 +805,17 @@ pub async fn payments_complete_authorize_redirect( state: web::Data, req: actix_web::HttpRequest, json_payload: Option>, - path: web::Path<(String, common_utils::id_type::MerchantId, String)>, + path: web::Path<( + common_utils::id_type::PaymentId, + common_utils::id_type::MerchantId, + String, + )>, ) -> impl Responder { let flow = Flow::PaymentsRedirect; let (payment_id, merchant_id, connector) = path.into_inner(); let param_string = req.query_string(); - tracing::Span::current().record("payment_id", &payment_id); + tracing::Span::current().record("payment_id", payment_id.get_string_repr()); let payload = payments::PaymentsRedirectResponseData { resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id), @@ -835,7 +856,7 @@ pub async fn payments_complete_authorize( state: web::Data, req: actix_web::HttpRequest, json_payload: web::Json, - path: web::Path, + path: web::Path, ) -> impl Responder { let flow = Flow::PaymentsCompleteAuthorize; let mut payload = json_payload.into_inner(); @@ -843,7 +864,7 @@ pub async fn payments_complete_authorize( let payment_id = path.into_inner(); payload.payment_id.clone_from(&payment_id); - tracing::Span::current().record("payment_id", &payment_id); + tracing::Span::current().record("payment_id", payment_id.get_string_repr()); let payment_confirm_req = payment_types::PaymentsRequest { payment_id: Some(payment_types::PaymentIdType::PaymentIntentId( @@ -912,18 +933,17 @@ pub async fn payments_complete_authorize( security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCancel, payment_id))] -// #[post("/{payment_id}/cancel")] pub async fn payments_cancel( state: web::Data, req: actix_web::HttpRequest, json_payload: web::Json, - path: web::Path, + path: web::Path, ) -> impl Responder { let flow = Flow::PaymentsCancel; let mut payload = json_payload.into_inner(); let payment_id = path.into_inner(); - tracing::Span::current().record("payment_id", &payment_id); + tracing::Span::current().record("payment_id", payment_id.get_string_repr()); payload.payment_id = payment_id; let locking_action = payload.get_locking_input(flow.clone()); @@ -1212,17 +1232,16 @@ pub async fn get_payments_aggregates( #[cfg(feature = "oltp")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsApprove, payment_id))] -// #[post("/{payment_id}/approve")] pub async fn payments_approve( state: web::Data, http_req: actix_web::HttpRequest, json_payload: web::Json, - path: web::Path, + path: web::Path, ) -> impl Responder { let mut payload = json_payload.into_inner(); let payment_id = path.into_inner(); - tracing::Span::current().record("payment_id", &payment_id); + tracing::Span::current().record("payment_id", payment_id.get_string_repr()); payload.payment_id = payment_id; let flow = Flow::PaymentsApprove; @@ -1272,12 +1291,12 @@ pub async fn payments_reject( state: web::Data, http_req: actix_web::HttpRequest, json_payload: web::Json, - path: web::Path, + path: web::Path, ) -> impl Responder { let mut payload = json_payload.into_inner(); let payment_id = path.into_inner(); - tracing::Span::current().record("payment_id", &payment_id); + tracing::Span::current().record("payment_id", payment_id.get_string_repr()); payload.payment_id = payment_id; let flow = Flow::PaymentsReject; @@ -1421,13 +1440,13 @@ pub async fn payments_incremental_authorization( state: web::Data, req: actix_web::HttpRequest, json_payload: web::Json, - path: web::Path, + path: web::Path, ) -> impl Responder { let flow = Flow::PaymentsIncrementalAuthorization; let mut payload = json_payload.into_inner(); let payment_id = path.into_inner(); - tracing::Span::current().record("payment_id", &payment_id); + tracing::Span::current().record("payment_id", payment_id.get_string_repr()); payload.payment_id = payment_id; let locking_action = payload.get_locking_input(flow.clone()); @@ -1486,13 +1505,13 @@ pub async fn payments_external_authentication( state: web::Data, req: actix_web::HttpRequest, json_payload: web::Json, - path: web::Path, + path: web::Path, ) -> impl Responder { let flow = Flow::PaymentsExternalAuthentication; let mut payload = json_payload.into_inner(); let payment_id = path.into_inner(); - tracing::Span::current().record("payment_id", &payment_id); + tracing::Span::current().record("payment_id", payment_id.get_string_repr()); payload.payment_id = payment_id; let locking_action = payload.get_locking_input(flow.clone()); @@ -1535,12 +1554,16 @@ pub async fn post_3ds_payments_authorize( state: web::Data, req: actix_web::HttpRequest, json_payload: Option>, - path: web::Path<(String, common_utils::id_type::MerchantId, String)>, + path: web::Path<( + common_utils::id_type::PaymentId, + common_utils::id_type::MerchantId, + String, + )>, ) -> impl Responder { let flow = Flow::PaymentsAuthorize; let (payment_id, merchant_id, connector) = path.into_inner(); - tracing::Span::current().record("payment_id", &payment_id); + tracing::Span::current().record("payment_id", payment_id.get_string_repr()); let param_string = req.query_string(); let payload = payments::PaymentsRedirectResponseData { resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id), @@ -1580,7 +1603,7 @@ pub async fn payments_manual_update( state: web::Data, req: actix_web::HttpRequest, json_payload: web::Json, - path: web::Path, + path: web::Path, ) -> impl Responder { let flow = Flow::PaymentsManualUpdate; let mut payload = json_payload.into_inner(); @@ -1588,7 +1611,7 @@ pub async fn payments_manual_update( let locking_action = payload.get_locking_input(flow.clone()); - tracing::Span::current().record("payment_id", &payment_id); + tracing::Span::current().record("payment_id", payment_id.get_string_repr()); payload.payment_id = payment_id; @@ -1609,7 +1632,7 @@ pub async fn payments_manual_update( pub async fn retrieve_extended_card_info( state: web::Data, req: actix_web::HttpRequest, - path: web::Path, + path: web::Path, ) -> impl Responder { let flow = Flow::GetExtendedCardInfo; let payment_id = path.into_inner(); @@ -1645,7 +1668,7 @@ pub fn get_or_generate_payment_id( }) .transpose()?; - let payment_id = core_utils::get_or_generate_id("payment_id", &given_payment_id, "pay")?; + let payment_id = given_payment_id.unwrap_or(common_utils::id_type::PaymentId::default()); payload.payment_id = Some(api_models::payments::PaymentIdType::PaymentIntentId( payment_id, @@ -1664,7 +1687,7 @@ impl GetLockingInput for payment_types::PaymentsRequest { Some(payment_types::PaymentIdType::PaymentIntentId(ref id)) => { api_locking::LockAction::Hold { input: api_locking::LockingInput { - unique_locking_key: id.to_owned(), + unique_locking_key: id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, @@ -1683,7 +1706,7 @@ impl GetLockingInput for payment_types::PaymentsStartRequest { { api_locking::LockAction::Hold { input: api_locking::LockingInput { - unique_locking_key: self.payment_id.to_owned(), + unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, @@ -1701,7 +1724,7 @@ impl GetLockingInput for payment_types::PaymentsRetrieveRequest { payment_types::PaymentIdType::PaymentIntentId(ref id) if self.force_sync => { api_locking::LockAction::Hold { input: api_locking::LockingInput { - unique_locking_key: id.to_owned(), + unique_locking_key: id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, @@ -1720,7 +1743,7 @@ impl GetLockingInput for payment_types::PaymentsSessionRequest { { api_locking::LockAction::Hold { input: api_locking::LockingInput { - unique_locking_key: self.payment_id.to_owned(), + unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, @@ -1738,7 +1761,7 @@ impl GetLockingInput for payments::PaymentsRedirectResponseData { payment_types::PaymentIdType::PaymentIntentId(ref id) => { api_locking::LockAction::Hold { input: api_locking::LockingInput { - unique_locking_key: id.to_owned(), + unique_locking_key: id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, @@ -1757,7 +1780,7 @@ impl GetLockingInput for payment_types::PaymentsCompleteAuthorizeRequest { { api_locking::LockAction::Hold { input: api_locking::LockingInput { - unique_locking_key: self.payment_id.to_owned(), + unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, @@ -1773,7 +1796,7 @@ impl GetLockingInput for payment_types::PaymentsCancelRequest { { api_locking::LockAction::Hold { input: api_locking::LockingInput { - unique_locking_key: self.payment_id.to_owned(), + unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, @@ -1789,7 +1812,7 @@ impl GetLockingInput for payment_types::PaymentsCaptureRequest { { api_locking::LockAction::Hold { input: api_locking::LockingInput { - unique_locking_key: self.payment_id.to_owned(), + unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, @@ -1809,7 +1832,7 @@ impl<'a> GetLockingInput for FPaymentsApproveRequest<'a> { { api_locking::LockAction::Hold { input: api_locking::LockingInput { - unique_locking_key: self.0.payment_id.to_owned(), + unique_locking_key: self.0.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, @@ -1829,7 +1852,7 @@ impl<'a> GetLockingInput for FPaymentsRejectRequest<'a> { { api_locking::LockAction::Hold { input: api_locking::LockingInput { - unique_locking_key: self.0.payment_id.to_owned(), + unique_locking_key: self.0.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, @@ -1845,7 +1868,7 @@ impl GetLockingInput for payment_types::PaymentsIncrementalAuthorizationRequest { api_locking::LockAction::Hold { input: api_locking::LockingInput { - unique_locking_key: self.payment_id.to_owned(), + unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, @@ -1861,7 +1884,7 @@ impl GetLockingInput for payment_types::PaymentsExternalAuthenticationRequest { { api_locking::LockAction::Hold { input: api_locking::LockingInput { - unique_locking_key: self.payment_id.to_owned(), + unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, @@ -1877,7 +1900,7 @@ impl GetLockingInput for payment_types::PaymentsManualUpdateRequest { { api_locking::LockAction::Hold { input: api_locking::LockingInput { - unique_locking_key: self.payment_id.to_owned(), + unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, diff --git a/crates/router/src/services/conversion_impls.rs b/crates/router/src/services/conversion_impls.rs index e5d39bab83..f1aec19bd3 100644 --- a/crates/router/src/services/conversion_impls.rs +++ b/crates/router/src/services/conversion_impls.rs @@ -31,7 +31,9 @@ fn get_default_router_data( customer_id: None, connector_customer: None, connector: get_irrelevant_id_string("connector", flow_name), - payment_id: get_irrelevant_id_string("payment_id", flow_name), + payment_id: common_utils::id_type::PaymentId::get_irrelevant_id(flow_name) + .get_string_repr() + .to_owned(), attempt_id: get_irrelevant_id_string("attempt_id", flow_name), status: common_enums::AttemptStatus::default(), payment_method: common_enums::PaymentMethod::default(), @@ -564,8 +566,13 @@ impl RouterDataConversion for MandateR ); router_data.merchant_id = merchant_id; router_data.customer_id = Some(customer_id); - router_data.payment_id = - payment_id.unwrap_or_else(|| get_irrelevant_id_string("payment_id", "mandate revoke")); + router_data.payment_id = payment_id + .unwrap_or_else(|| { + common_utils::id_type::PaymentId::get_irrelevant_id("mandate revoke") + .get_string_repr() + .to_owned() + }) + .to_owned(); Ok(router_data) } } diff --git a/crates/router/src/services/kafka/authentication.rs b/crates/router/src/services/kafka/authentication.rs index 0dfda622d3..67e488d6c8 100644 --- a/crates/router/src/services/kafka/authentication.rs +++ b/crates/router/src/services/kafka/authentication.rs @@ -36,7 +36,7 @@ pub struct KafkaAuthentication<'a> { pub acs_trans_id: Option<&'a String>, pub acs_signed_content: Option<&'a String>, pub profile_id: &'a common_utils::id_type::ProfileId, - pub payment_id: Option<&'a String>, + pub payment_id: Option<&'a common_utils::id_type::PaymentId>, pub merchant_connector_id: &'a common_utils::id_type::MerchantConnectorAccountId, pub ds_trans_id: Option<&'a String>, pub directory_server_id: Option<&'a String>, diff --git a/crates/router/src/services/kafka/authentication_event.rs b/crates/router/src/services/kafka/authentication_event.rs index 8d48e56a61..7c8b77a384 100644 --- a/crates/router/src/services/kafka/authentication_event.rs +++ b/crates/router/src/services/kafka/authentication_event.rs @@ -37,7 +37,7 @@ pub struct KafkaAuthenticationEvent<'a> { pub acs_trans_id: Option<&'a String>, pub acs_signed_content: Option<&'a String>, pub profile_id: &'a common_utils::id_type::ProfileId, - pub payment_id: Option<&'a String>, + pub payment_id: Option<&'a common_utils::id_type::PaymentId>, pub merchant_connector_id: &'a common_utils::id_type::MerchantConnectorAccountId, pub ds_trans_id: Option<&'a String>, pub directory_server_id: Option<&'a String>, diff --git a/crates/router/src/services/kafka/dispute.rs b/crates/router/src/services/kafka/dispute.rs index 9374c42cbe..2afb41cc86 100644 --- a/crates/router/src/services/kafka/dispute.rs +++ b/crates/router/src/services/kafka/dispute.rs @@ -12,7 +12,7 @@ pub struct KafkaDispute<'a> { pub currency: &'a String, pub dispute_stage: &'a storage_enums::DisputeStage, pub dispute_status: &'a storage_enums::DisputeStatus, - pub payment_id: &'a String, + pub payment_id: &'a id_type::PaymentId, pub attempt_id: &'a String, pub merchant_id: &'a id_type::MerchantId, pub connector_status: &'a String, @@ -70,7 +70,7 @@ impl<'a> super::KafkaMessage for KafkaDispute<'a> { format!( "{}_{}_{}", self.merchant_id.get_string_repr(), - self.payment_id, + self.payment_id.get_string_repr(), self.dispute_id ) } diff --git a/crates/router/src/services/kafka/dispute_event.rs b/crates/router/src/services/kafka/dispute_event.rs index ac72af0cd9..057a060dec 100644 --- a/crates/router/src/services/kafka/dispute_event.rs +++ b/crates/router/src/services/kafka/dispute_event.rs @@ -12,7 +12,7 @@ pub struct KafkaDisputeEvent<'a> { pub currency: &'a String, pub dispute_stage: &'a storage_enums::DisputeStage, pub dispute_status: &'a storage_enums::DisputeStatus, - pub payment_id: &'a String, + pub payment_id: &'a common_utils::id_type::PaymentId, pub attempt_id: &'a String, pub merchant_id: &'a common_utils::id_type::MerchantId, pub connector_status: &'a String, @@ -70,7 +70,7 @@ impl<'a> super::KafkaMessage for KafkaDisputeEvent<'a> { format!( "{}_{}_{}", self.merchant_id.get_string_repr(), - self.payment_id, + self.payment_id.get_string_repr(), self.dispute_id ) } diff --git a/crates/router/src/services/kafka/fraud_check.rs b/crates/router/src/services/kafka/fraud_check.rs index cf67ac14dd..26fa9e6b4e 100644 --- a/crates/router/src/services/kafka/fraud_check.rs +++ b/crates/router/src/services/kafka/fraud_check.rs @@ -9,7 +9,7 @@ use time::OffsetDateTime; #[derive(serde::Serialize, Debug)] pub struct KafkaFraudCheck<'a> { pub frm_id: &'a String, - pub payment_id: &'a String, + pub payment_id: &'a common_utils::id_type::PaymentId, pub merchant_id: &'a common_utils::id_type::MerchantId, pub attempt_id: &'a String, #[serde(with = "time::serde::timestamp")] @@ -58,7 +58,7 @@ impl<'a> super::KafkaMessage for KafkaFraudCheck<'a> { format!( "{}_{}_{}_{}", self.merchant_id.get_string_repr(), - self.payment_id, + self.payment_id.get_string_repr(), self.attempt_id, self.frm_id ) diff --git a/crates/router/src/services/kafka/fraud_check_event.rs b/crates/router/src/services/kafka/fraud_check_event.rs index 88d1465ce1..f35748cb1c 100644 --- a/crates/router/src/services/kafka/fraud_check_event.rs +++ b/crates/router/src/services/kafka/fraud_check_event.rs @@ -8,7 +8,7 @@ use time::OffsetDateTime; #[derive(serde::Serialize, Debug)] pub struct KafkaFraudCheckEvent<'a> { pub frm_id: &'a String, - pub payment_id: &'a String, + pub payment_id: &'a common_utils::id_type::PaymentId, pub merchant_id: &'a common_utils::id_type::MerchantId, pub attempt_id: &'a String, #[serde(default, with = "time::serde::timestamp::milliseconds")] @@ -57,7 +57,7 @@ impl<'a> super::KafkaMessage for KafkaFraudCheckEvent<'a> { format!( "{}_{}_{}_{}", self.merchant_id.get_string_repr(), - self.payment_id, + self.payment_id.get_string_repr(), self.attempt_id, self.frm_id ) diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rs index b92728196d..b3827450a8 100644 --- a/crates/router/src/services/kafka/payment_attempt.rs +++ b/crates/router/src/services/kafka/payment_attempt.rs @@ -8,7 +8,7 @@ use time::OffsetDateTime; #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentAttempt<'a> { - pub payment_id: &'a String, + pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a id_type::MerchantId, pub attempt_id: &'a String, pub status: storage_enums::AttemptStatus, @@ -123,7 +123,7 @@ impl<'a> super::KafkaMessage for KafkaPaymentAttempt<'a> { format!( "{}_{}_{}", self.merchant_id.get_string_repr(), - self.payment_id, + self.payment_id.get_string_repr(), self.attempt_id ) } diff --git a/crates/router/src/services/kafka/payment_attempt_event.rs b/crates/router/src/services/kafka/payment_attempt_event.rs index e9f8fbdfc5..13ab031981 100644 --- a/crates/router/src/services/kafka/payment_attempt_event.rs +++ b/crates/router/src/services/kafka/payment_attempt_event.rs @@ -9,7 +9,7 @@ use time::OffsetDateTime; #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentAttemptEvent<'a> { - pub payment_id: &'a String, + pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a id_type::MerchantId, pub attempt_id: &'a String, pub status: storage_enums::AttemptStatus, @@ -124,7 +124,7 @@ impl<'a> super::KafkaMessage for KafkaPaymentAttemptEvent<'a> { format!( "{}_{}_{}", self.merchant_id.get_string_repr(), - self.payment_id, + self.payment_id.get_string_repr(), self.attempt_id ) } diff --git a/crates/router/src/services/kafka/payment_intent.rs b/crates/router/src/services/kafka/payment_intent.rs index 31f424b2a2..6e8e795442 100644 --- a/crates/router/src/services/kafka/payment_intent.rs +++ b/crates/router/src/services/kafka/payment_intent.rs @@ -7,7 +7,7 @@ use time::OffsetDateTime; #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentIntent<'a> { - pub payment_id: &'a String, + pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, @@ -90,7 +90,11 @@ impl<'a> KafkaPaymentIntent<'a> { impl<'a> super::KafkaMessage for KafkaPaymentIntent<'a> { fn key(&self) -> String { - format!("{}_{}", self.merchant_id.get_string_repr(), self.payment_id) + format!( + "{}_{}", + self.merchant_id.get_string_repr(), + self.payment_id.get_string_repr(), + ) } fn event_type(&self) -> crate::events::EventType { diff --git a/crates/router/src/services/kafka/payment_intent_event.rs b/crates/router/src/services/kafka/payment_intent_event.rs index f92f3fa932..1d450c35cf 100644 --- a/crates/router/src/services/kafka/payment_intent_event.rs +++ b/crates/router/src/services/kafka/payment_intent_event.rs @@ -8,7 +8,7 @@ use time::OffsetDateTime; #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentIntentEvent<'a> { - pub payment_id: &'a String, + pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, @@ -91,7 +91,11 @@ impl<'a> KafkaPaymentIntentEvent<'a> { impl<'a> super::KafkaMessage for KafkaPaymentIntentEvent<'a> { fn key(&self) -> String { - format!("{}_{}", self.merchant_id.get_string_repr(), self.payment_id) + format!( + "{}_{}", + self.merchant_id.get_string_repr(), + self.payment_id.get_string_repr(), + ) } fn event_type(&self) -> crate::events::EventType { diff --git a/crates/router/src/services/kafka/refund.rs b/crates/router/src/services/kafka/refund.rs index 09537812e5..c4fb4a43dd 100644 --- a/crates/router/src/services/kafka/refund.rs +++ b/crates/router/src/services/kafka/refund.rs @@ -6,7 +6,7 @@ use time::OffsetDateTime; pub struct KafkaRefund<'a> { pub internal_reference_id: &'a String, pub refund_id: &'a String, //merchant_reference id - pub payment_id: &'a String, + pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a id_type::MerchantId, pub connector_transaction_id: &'a String, pub connector: &'a String, @@ -68,7 +68,7 @@ impl<'a> super::KafkaMessage for KafkaRefund<'a> { format!( "{}_{}_{}_{}", self.merchant_id.get_string_repr(), - self.payment_id, + self.payment_id.get_string_repr(), self.attempt_id, self.refund_id ) diff --git a/crates/router/src/services/kafka/refund_event.rs b/crates/router/src/services/kafka/refund_event.rs index 764146f808..f2150020c9 100644 --- a/crates/router/src/services/kafka/refund_event.rs +++ b/crates/router/src/services/kafka/refund_event.rs @@ -7,7 +7,7 @@ use time::OffsetDateTime; pub struct KafkaRefundEvent<'a> { pub internal_reference_id: &'a String, pub refund_id: &'a String, //merchant_reference id - pub payment_id: &'a String, + pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a id_type::MerchantId, pub connector_transaction_id: &'a String, pub connector: &'a String, @@ -69,7 +69,7 @@ impl<'a> super::KafkaMessage for KafkaRefundEvent<'a> { format!( "{}_{}_{}_{}", self.merchant_id.get_string_repr(), - self.payment_id, + self.payment_id.get_string_repr(), self.attempt_id, self.refund_id ) diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 2bd6e27aca..d71d0b2f50 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -493,7 +493,7 @@ pub struct AuthenticatePaymentFlowResponse { pub struct ConnectorResponse { pub merchant_id: common_utils::id_type::MerchantId, pub connector: String, - pub payment_id: String, + pub payment_id: common_utils::id_type::PaymentId, pub amount: i64, pub connector_transaction_id: String, pub return_url: Option, diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index ab25332a5c..3b342c5c7d 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -38,11 +38,15 @@ use crate::core::errors; impl super::Router for PaymentsRequest {} pub trait PaymentIdTypeExt { - fn get_payment_intent_id(&self) -> errors::CustomResult; + fn get_payment_intent_id( + &self, + ) -> errors::CustomResult; } impl PaymentIdTypeExt for PaymentIdType { - fn get_payment_intent_id(&self) -> errors::CustomResult { + fn get_payment_intent_id( + &self, + ) -> errors::CustomResult { match self { Self::PaymentIntentId(id) => Ok(id.clone()), Self::ConnectorTransactionId(_) @@ -127,7 +131,12 @@ mod payments_test { // Intended to test the serialization and deserialization of the enum PaymentIdType #[test] fn test_connector_id_type() { - let sample_1 = PaymentIdType::PaymentIntentId("test_234565430uolsjdnf48i0".to_string()); + let sample_1 = PaymentIdType::PaymentIntentId( + common_utils::id_type::PaymentId::try_from(std::borrow::Cow::Borrowed( + "test_234565430uolsjdnf48i0", + )) + .unwrap(), + ); let s_sample_1 = serde_json::to_string(&sample_1).unwrap(); let ds_sample_1 = serde_json::from_str::(&s_sample_1).unwrap(); assert_eq!(ds_sample_1, sample_1) diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index e54ee8706f..1b3162a354 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -97,9 +97,9 @@ impl VerifyConnectorData { payment_method_status: None, connector_request_reference_id: attempt_id, address: types::PaymentAddress::new(None, None, None, None), - payment_id: common_utils::generate_id_with_default_len( - consts::VERIFY_CONNECTOR_ID_PREFIX, - ), + payment_id: common_utils::id_type::PaymentId::default() + .get_string_repr() + .to_owned(), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] diff --git a/crates/router/src/types/domain/address.rs b/crates/router/src/types/domain/address.rs index 680e26e1f6..5d9af527cd 100644 --- a/crates/router/src/types/domain/address.rs +++ b/crates/router/src/types/domain/address.rs @@ -46,7 +46,7 @@ pub struct Address { #[derive(Debug, Clone)] pub struct PaymentAddress { pub address: Address, - pub payment_id: String, + pub payment_id: id_type::PaymentId, // This is present in `PaymentAddress` because even `payouts` uses `PaymentAddress` pub customer_id: Option, } diff --git a/crates/router/src/types/fraud_check.rs b/crates/router/src/types/fraud_check.rs index 4995cc59cd..a861aca67d 100644 --- a/crates/router/src/types/fraud_check.rs +++ b/crates/router/src/types/fraud_check.rs @@ -20,6 +20,7 @@ pub type FrmSaleType = pub struct FrmRouterData { pub merchant_id: common_utils::id_type::MerchantId, pub connector: String, + // TODO: change this to PaymentId type pub payment_id: String, pub attempt_id: String, pub request: FrmRequest, diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs index 6775f9a81a..950a666dd6 100644 --- a/crates/router/src/types/storage/payment_attempt.rs +++ b/crates/router/src/types/storage/payment_attempt.rs @@ -121,7 +121,8 @@ mod tests { #[tokio::test] async fn test_payment_attempt_insert() { let state = create_single_connection_test_transaction_pool().await; - let payment_id = Uuid::new_v4().to_string(); + let payment_id = + 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 { @@ -204,7 +205,8 @@ mod tests { async fn test_find_payment_attempt() { let state = create_single_connection_test_transaction_pool().await; let current_time = common_utils::date_time::now(); - let payment_id = Uuid::new_v4().to_string(); + let payment_id = + common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data(); let attempt_id = Uuid::new_v4().to_string(); let merchant_id = common_utils::id_type::MerchantId::new_from_unix_timestamp(); let connector = types::Connector::DummyConnector1.to_string(); @@ -302,11 +304,14 @@ mod tests { let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("merchant1")) .unwrap(); + + let payment_id = + 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 { - payment_id: uuid.clone(), + payment_id: payment_id.clone(), merchant_id: merchant_id.clone(), connector: Some(connector), created_at: current_time.into(), @@ -376,7 +381,7 @@ mod tests { let response = store .find_payment_attempt_by_payment_id_merchant_id_attempt_id( - &uuid, + &payment_id, &merchant_id, &uuid, enums::MerchantStorageScheme::PostgresOnly, diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index ce8419ad3c..abdfb680a7 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -163,8 +163,8 @@ impl ConnectorResponseExt } #[inline] -pub fn get_payment_attempt_id(payment_id: impl std::fmt::Display, attempt_count: i16) -> String { - format!("{payment_id}_{attempt_count}") +pub fn get_payout_attempt_id(payout_id: impl std::fmt::Display, attempt_count: i16) -> String { + format!("{payout_id}_{attempt_count}") } #[derive(Debug)] pub struct QrImage { @@ -1174,7 +1174,7 @@ where &cloned_key_store, event_type, diesel_models::enums::EventClass::Payments, - payment_id, + payment_id.get_string_repr().to_owned(), diesel_models::enums::EventObjectType::PaymentDetails, webhooks::OutgoingWebhookContent::PaymentDetails( payments_response_json, diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index 94890a41ad..95d00c6220 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -172,12 +172,9 @@ pub async fn generate_sample_data( .change_context(SampleDataError::InternalServerError)?; for num in 1..=sample_data_size { - let payment_id = common_utils::generate_id_with_default_len("test"); - let attempt_id = crate::utils::get_payment_attempt_id(&payment_id, 1); - let client_secret = common_utils::generate_id( - consts::ID_LENGTH, - format!("{}_secret", payment_id.clone()).as_str(), - ); + let payment_id = id_type::PaymentId::generate_test_payment_id_for_sample_data(); + let attempt_id = payment_id.get_attempt_id(1); + let client_secret = payment_id.generate_client_secret(); let amount = thread_rng().gen_range(min_amount..=max_amount); let created_at @ modified_at @ last_synced = diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rs index 19ef82c121..b5a7a89811 100644 --- a/crates/router/src/workflows/outgoing_webhook_retry.rs +++ b/crates/router/src/workflows/outgoing_webhook_retry.rs @@ -201,7 +201,7 @@ impl ProcessTrackerWorkflow for OutgoingWebhookRetryWorkflow { _ => { logger::warn!( %event.event_id, - "The current status of the resource `{}` (event type: {:?}) and the status of \ + "The current status of the resource `{:?}` (event type: {:?}) and the status of \ the resource when the event was created (event type: {:?}) differ, finishing task", tracking_data.primary_object_id, event_type, @@ -359,6 +359,15 @@ async fn get_outgoing_webhook_content_and_event_type( match tracking_data.event_class { diesel_models::enums::EventClass::Payments => { let payment_id = tracking_data.primary_object_id.clone(); + let payment_id = + common_utils::id_type::PaymentId::try_from(std::borrow::Cow::Owned(payment_id)) + .map_err(|payment_id_parsing_error| { + logger::error!( + ?payment_id_parsing_error, + "Failed to parse payment ID from tracking data" + ); + errors::ProcessTrackerError::DeserializationFailed + })?; let request = PaymentsRetrieveRequest { resource_id: PaymentIdType::PaymentIntentId(payment_id), merchant_id: Some(tracking_data.merchant_id.clone()), diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index 66f99dd085..19a4489c44 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -313,10 +313,11 @@ async fn payments_create_core() { .await .unwrap(); + let payment_id = + id_type::PaymentId::try_from(Cow::Borrowed("pay_mbabizu24mvu3mela5njyhpit10")).unwrap(); + let req = api::PaymentsRequest { - payment_id: Some(api::PaymentIdType::PaymentIntentId( - "pay_mbabizu24mvu3mela5njyhpit10".to_string(), - )), + payment_id: Some(api::PaymentIdType::PaymentIntentId(payment_id.clone())), merchant_id: Some(merchant_id.clone()), amount: Some(MinorUnit::new(6540).into()), currency: Some(api_enums::Currency::USD), @@ -364,7 +365,7 @@ async fn payments_create_core() { }; let expected_response = api::PaymentsResponse { - payment_id: "pay_mbabizu24mvu3mela5njyhpit10".to_string(), + payment_id, status: api_enums::IntentStatus::Succeeded, amount: MinorUnit::new(6540), amount_capturable: MinorUnit::new(0), @@ -548,9 +549,11 @@ async fn payments_create_core_adyen_no_redirect() { .get_session_state("public", || {}) .unwrap(); + let payment_id = + id_type::PaymentId::try_from(Cow::Borrowed("pay_mbabizu24mvu3mela5njyhpit10")).unwrap(); + let customer_id = format!("cust_{}", Uuid::new_v4()); let merchant_id = id_type::MerchantId::try_from(Cow::from("juspay_merchant")).unwrap(); - let payment_id = "pay_mbabizu24mvu3mela5njyhpit10".to_string(); let key_manager_state = &(&state).into(); let key_store = state .store diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index 7899abf72a..430ea0c14b 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -73,10 +73,11 @@ async fn payments_create_core() { .await .unwrap(); + let payment_id = + id_type::PaymentId::try_from(Cow::Borrowed("pay_mbabizu24mvu3mela5njyhpit10")).unwrap(); + let req = api::PaymentsRequest { - payment_id: Some(api::PaymentIdType::PaymentIntentId( - "pay_mbabizu24mvu3mela5njyhpit10".to_string(), - )), + payment_id: Some(api::PaymentIdType::PaymentIntentId(payment_id.clone())), merchant_id: Some(merchant_id.clone()), amount: Some(MinorUnit::new(6540).into()), currency: Some(api_enums::Currency::USD), @@ -124,7 +125,7 @@ async fn payments_create_core() { }; let expected_response = api::PaymentsResponse { - payment_id: "pay_mbabizu24mvu3mela5njyhpit10".to_string(), + payment_id, status: api_enums::IntentStatus::Succeeded, amount: MinorUnit::new(6540), amount_capturable: MinorUnit::new(0), @@ -317,7 +318,9 @@ async fn payments_create_core_adyen_no_redirect() { let customer_id = format!("cust_{}", Uuid::new_v4()); let merchant_id = id_type::MerchantId::try_from(Cow::from("juspay_merchant")).unwrap(); - let payment_id = "pay_mbabizu24mvu3mela5njyhpit10".to_string(); + let payment_id = + id_type::PaymentId::try_from(Cow::Borrowed("pay_mbabizu24mvu3mela5njyhpit10")).unwrap(); + let key_manager_state = &(&state).into(); let key_store = state .store diff --git a/crates/router/tests/refunds.rs b/crates/router/tests/refunds.rs index dce0838df4..3359117d14 100644 --- a/crates/router/tests/refunds.rs +++ b/crates/router/tests/refunds.rs @@ -16,7 +16,7 @@ async fn refund_create_fail_stripe() { let user_client = client.user("321"); - let payment_id = format!("test_{}", uuid::Uuid::new_v4()); + let payment_id = common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data(); let refund: serde_json::Value = user_client.create_refund(&app, &payment_id, 10).await; assert_eq!(refund.get("error").unwrap().get("message").unwrap(), "Access forbidden, invalid API key was used. Please create your new API key from the Dashboard Settings section."); @@ -30,7 +30,7 @@ async fn refund_create_fail_adyen() { let user_client = client.user("321"); - let payment_id = format!("test_{}", uuid::Uuid::new_v4()); + let payment_id = common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data(); let refund: serde_json::Value = user_client.create_refund(&app, &payment_id, 10).await; assert_eq!(refund.get("error").unwrap().get("message").unwrap(), "Access forbidden, invalid API key was used. Please create your new API key from the Dashboard Settings section."); diff --git a/crates/router/tests/utils.rs b/crates/router/tests/utils.rs index c6632798ab..eb8ed7090d 100644 --- a/crates/router/tests/utils.rs +++ b/crates/router/tests/utils.rs @@ -146,7 +146,7 @@ impl AppClient { pub async fn create_refund( &self, app: &S, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, amount: usize, ) -> T where @@ -337,7 +337,7 @@ fn _mk_payment_confirm() -> Value { }) } -fn mk_refund(payment_id: &str, amount: usize) -> Value { +fn mk_refund(payment_id: &common_utils::id_type::PaymentId, amount: usize) -> Value { let timestamp = common_utils::date_time::now().to_string(); json!({ @@ -407,7 +407,7 @@ pub struct Message { #[derive(Deserialize, Deref)] pub struct PaymentId { - payment_id: String, + payment_id: common_utils::id_type::PaymentId, } #[derive(Deserialize, Deref)] diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs index d4eadd4437..995f11b9cc 100644 --- a/crates/storage_impl/src/lib.rs +++ b/crates/storage_impl/src/lib.rs @@ -334,7 +334,7 @@ impl UniqueConstraints for diesel_models::PaymentIntent { vec![format!( "pi_{}_{}", self.merchant_id.get_string_repr(), - self.payment_id + self.payment_id.get_string_repr() )] } fn table_name(&self) -> &str { @@ -347,7 +347,7 @@ impl UniqueConstraints for diesel_models::PaymentAttempt { vec![format!( "pa_{}_{}_{}", self.merchant_id.get_string_repr(), - self.payment_id, + self.payment_id.get_string_repr(), self.attempt_id )] } diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index 67840636de..9cdc1e87ce 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -15,7 +15,7 @@ use crate::DataModelExt; impl PaymentAttemptInterface for MockDb { async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, - _payment_id: &str, + _payment_id: &common_utils::id_type::PaymentId, _merchant_id: &common_utils::id_type::MerchantId, _attempt_id: &str, _storage_scheme: storage_enums::MerchantStorageScheme, @@ -83,7 +83,7 @@ impl PaymentAttemptInterface for MockDb { async fn find_attempts_by_merchant_id_payment_id( &self, _merchant_id: &common_utils::id_type::MerchantId, - _payment_id: &str, + _payment_id: &common_utils::id_type::PaymentId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult, StorageError> { // [#172]: Implement function for `MockDb` @@ -192,7 +192,7 @@ impl PaymentAttemptInterface for MockDb { async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, _connector_transaction_id: &str, - _payment_id: &str, + _payment_id: &common_utils::id_type::PaymentId, _merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult { @@ -204,7 +204,7 @@ impl PaymentAttemptInterface for MockDb { #[allow(clippy::unwrap_used)] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult { @@ -213,7 +213,7 @@ impl PaymentAttemptInterface for MockDb { Ok(payment_attempts .iter() .find(|payment_attempt| { - payment_attempt.payment_id == payment_id + payment_attempt.payment_id == *payment_id && payment_attempt.merchant_id.eq(merchant_id) }) .cloned() @@ -222,7 +222,7 @@ impl PaymentAttemptInterface for MockDb { #[allow(clippy::unwrap_used)] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult { @@ -231,7 +231,7 @@ impl PaymentAttemptInterface for MockDb { Ok(payment_attempts .iter() .find(|payment_attempt| { - payment_attempt.payment_id == payment_id + payment_attempt.payment_id == *payment_id && payment_attempt.merchant_id.eq(merchant_id) && (payment_attempt.status == storage_enums::AttemptStatus::PartialCharged || payment_attempt.status == storage_enums::AttemptStatus::Charged) diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs index 4fb06bc169..f5db60da3f 100644 --- a/crates/storage_impl/src/mock_db/payment_intent.rs +++ b/crates/storage_impl/src/mock_db/payment_intent.rs @@ -125,7 +125,7 @@ impl PaymentIntentInterface for MockDb { async fn find_payment_intent_by_payment_id_merchant_id( &self, _state: &KeyManagerState, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, @@ -135,7 +135,7 @@ impl PaymentIntentInterface for MockDb { Ok(payment_intents .iter() .find(|payment_intent| { - payment_intent.payment_id == payment_id + payment_intent.payment_id == *payment_id && payment_intent.merchant_id.eq(merchant_id) }) .cloned() diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 63b10cf01b..7edf5fd5a7 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -79,7 +79,7 @@ impl PaymentAttemptInterface for RouterStore { async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, connector_transaction_id: &str, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult { @@ -101,7 +101,7 @@ impl PaymentAttemptInterface for RouterStore { #[instrument(skip_all)] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult { @@ -122,7 +122,7 @@ impl PaymentAttemptInterface for RouterStore { #[instrument(skip_all)] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult { @@ -164,7 +164,7 @@ impl PaymentAttemptInterface for RouterStore { #[instrument(skip_all)] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, attempt_id: &str, _storage_scheme: MerchantStorageScheme, @@ -251,7 +251,7 @@ impl PaymentAttemptInterface for RouterStore { async fn find_attempts_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult, errors::StorageError> { let conn = pg_connection_read(self).await?; @@ -600,7 +600,7 @@ impl PaymentAttemptInterface for KVRouterStore { async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, connector_transaction_id: &str, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result { @@ -654,7 +654,7 @@ impl PaymentAttemptInterface for KVRouterStore { #[instrument(skip_all)] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result { @@ -708,7 +708,7 @@ impl PaymentAttemptInterface for KVRouterStore { #[instrument(skip_all)] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result { @@ -829,7 +829,7 @@ impl PaymentAttemptInterface for KVRouterStore { #[instrument(skip_all)] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, attempt_id: &str, storage_scheme: MerchantStorageScheme, @@ -1004,7 +1004,7 @@ impl PaymentAttemptInterface for KVRouterStore { async fn find_attempts_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result, errors::StorageError> { let storage_scheme = diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index f7127761af..4624f33eec 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -74,7 +74,7 @@ impl PaymentIntentInterface for KVRouterStore { ) -> error_stack::Result { let merchant_id = payment_intent.merchant_id.clone(); let payment_id = payment_intent.payment_id.clone(); - let field = format!("pi_{}", payment_intent.payment_id); + let field = payment_intent.payment_id.get_hash_key_for_kv_store(); let key = PartitionKey::MerchantIdPaymentId { merchant_id: &merchant_id, payment_id: &payment_id, @@ -153,7 +153,7 @@ impl PaymentIntentInterface for KVRouterStore { merchant_id: &merchant_id, payment_id: &payment_id, }; - let field = format!("pi_{}", this.payment_id); + let field = format!("pi_{}", this.payment_id.get_string_repr()); let storage_scheme = decide_storage_scheme::<_, DieselPaymentIntent>( self, storage_scheme, @@ -229,7 +229,7 @@ impl PaymentIntentInterface for KVRouterStore { async fn find_payment_intent_by_payment_id_merchant_id( &self, state: &KeyManagerState, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, @@ -253,7 +253,7 @@ impl PaymentIntentInterface for KVRouterStore { merchant_id, payment_id, }; - let field = format!("pi_{payment_id}"); + let field = payment_id.get_hash_key_for_kv_store(); Box::pin(utils::try_redis_get_else_try_database_get( async { kv_wrapper::( @@ -463,7 +463,7 @@ impl PaymentIntentInterface for crate::RouterStore { async fn find_payment_intent_by_payment_id_merchant_id( &self, state: &KeyManagerState, - payment_id: &str, + payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs index 5b2194c58a..8b5674084a 100644 --- a/crates/storage_impl/src/redis/kv_store.rs +++ b/crates/storage_impl/src/redis/kv_store.rs @@ -25,7 +25,7 @@ pub trait KvStorePartition { pub enum PartitionKey<'a> { MerchantIdPaymentId { merchant_id: &'a common_utils::id_type::MerchantId, - payment_id: &'a str, + payment_id: &'a common_utils::id_type::PaymentId, }, CombinationKey { combination: &'a str, @@ -64,8 +64,9 @@ impl<'a> std::fmt::Display for PartitionKey<'a> { merchant_id, payment_id, } => f.write_str(&format!( - "mid_{}_pid_{payment_id}", - merchant_id.get_string_repr() + "mid_{}_pid_{}", + merchant_id.get_string_repr(), + payment_id.get_string_repr() )), PartitionKey::CombinationKey { combination } => f.write_str(combination), PartitionKey::MerchantIdCustomerId {