Skip to content

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

feat: remove client_secret from payment_intent and update related code (#7648)

Gaurav Rawat5730ddfc8893
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index f420b3cce5..c252c5a6ab 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -17193,7 +17193,7 @@
"client_secret": {
"type": "string",
"description": "It's a token used for client side verification.",
- "example": "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo"
+ "example": "cs_0195b34da95d75239c6a4bf514458896"
},
"profile_id": {
"type": "string",
@@ -17791,7 +17791,6 @@
"status",
"amount",
"customer_id",
- "client_secret",
"created"
],
"properties": {
@@ -17821,10 +17820,6 @@
"example": "stripe",
"nullable": true
},
- "client_secret": {
- "type": "string",
- "description": "It's a token used for client side verification."
- },
"created": {
"type": "string",
"format": "date-time",
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 57c6ab7db1..ad11cc06b9 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -483,8 +483,8 @@ pub struct PaymentsIntentResponse {
pub amount_details: AmountDetailsResponse,
/// It's a token used for client side verification.
- #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")]
- pub client_secret: common_utils::types::ClientSecret,
+ #[schema(value_type = String, example = "cs_0195b34da95d75239c6a4bf514458896")]
+ pub client_secret: Option<Secret<String>>,
/// The identifier for the profile. This is inferred from the `x-profile-id` header
#[schema(value_type = String)]
@@ -5607,10 +5607,6 @@ pub struct PaymentsResponse {
#[schema(example = "stripe")]
pub connector: Option<String>,
- /// It's a token used for client side verification.
- #[schema(value_type = String)]
- pub client_secret: common_utils::types::ClientSecret,
-
/// Time when the payment was created
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(with = "common_utils::custom_serde::iso8601")]
diff --git a/crates/common_utils/src/id_type/global_id/payment.rs b/crates/common_utils/src/id_type/global_id/payment.rs
index 5de836cd48..22ac0d4c0a 100644
--- a/crates/common_utils/src/id_type/global_id/payment.rs
+++ b/crates/common_utils/src/id_type/global_id/payment.rs
@@ -28,11 +28,6 @@ impl GlobalPaymentId {
Self(global_id)
}
- /// Generate a new ClientId from self
- pub fn generate_client_secret(&self) -> types::ClientSecret {
- types::ClientSecret::new(self.clone(), generate_time_ordered_id_without_prefix())
- }
-
/// Generate the id for revenue recovery Execute PT workflow
pub fn get_execute_revenue_recovery_id(
&self,
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs
index 11c9b17fae..b9d245d48c 100644
--- a/crates/common_utils/src/types.rs
+++ b/crates/common_utils/src/types.rs
@@ -686,261 +686,6 @@ where
}
}
-#[cfg(feature = "v2")]
-pub use client_secret_type::ClientSecret;
-#[cfg(feature = "v2")]
-mod client_secret_type {
- use std::fmt;
-
- use masking::PeekInterface;
- use router_env::logger;
-
- use super::*;
- use crate::id_type;
-
- /// A domain type that can be used to represent a client secret
- /// Client secret is generated for a payment and is used to authenticate the client side api calls
- #[derive(Debug, PartialEq, Clone, AsExpression)]
- #[diesel(sql_type = sql_types::Text)]
- pub struct ClientSecret {
- /// The payment id of the payment
- pub payment_id: id_type::GlobalPaymentId,
- /// The secret string
- pub secret: masking::Secret<String>,
- }
-
- impl ClientSecret {
- pub(crate) fn get_string_repr(&self) -> String {
- format!(
- "{}_secret_{}",
- self.payment_id.get_string_repr(),
- self.secret.peek()
- )
- }
-
- /// Create a new client secret
- pub(crate) fn new(payment_id: id_type::GlobalPaymentId, secret: String) -> Self {
- Self {
- payment_id,
- secret: masking::Secret::new(secret),
- }
- }
- }
-
- impl FromStr for ClientSecret {
- type Err = ParsingError;
-
- fn from_str(str_value: &str) -> Result<Self, Self::Err> {
- let (payment_id, secret) =
- str_value
- .rsplit_once("_secret_")
- .ok_or(ParsingError::EncodeError(
- "Expected a string in the format '{payment_id}_secret_{secret}'",
- ))?;
-
- let payment_id = id_type::GlobalPaymentId::try_from(Cow::Owned(payment_id.to_owned()))
- .map_err(|err| {
- logger::error!(global_payment_id_error=?err);
- ParsingError::EncodeError("Error while constructing GlobalPaymentId")
- })?;
-
- Ok(Self {
- payment_id,
- secret: masking::Secret::new(secret.to_owned()),
- })
- }
- }
-
- impl<'de> Deserialize<'de> for ClientSecret {
- fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
- where
- D: Deserializer<'de>,
- {
- struct ClientSecretVisitor;
-
- impl Visitor<'_> for ClientSecretVisitor {
- type Value = ClientSecret;
-
- fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
- formatter.write_str("a string in the format '{payment_id}_secret_{secret}'")
- }
-
- fn visit_str<E>(self, value: &str) -> Result<ClientSecret, E>
- where
- E: serde::de::Error,
- {
- let (payment_id, secret) = value.rsplit_once("_secret_").ok_or_else(|| {
- E::invalid_value(
- serde::de::Unexpected::Str(value),
- &"a string with '_secret_'",
- )
- })?;
-
- let payment_id =
- id_type::GlobalPaymentId::try_from(Cow::Owned(payment_id.to_owned()))
- .map_err(serde::de::Error::custom)?;
-
- Ok(ClientSecret {
- payment_id,
- secret: masking::Secret::new(secret.to_owned()),
- })
- }
- }
-
- deserializer.deserialize_str(ClientSecretVisitor)
- }
- }
-
- impl Serialize for ClientSecret {
- fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where
- S: serde::ser::Serializer,
- {
- serializer.serialize_str(self.get_string_repr().as_str())
- }
- }
-
- impl ToSql<sql_types::Text, diesel::pg::Pg> for ClientSecret
- where
- String: ToSql<sql_types::Text, diesel::pg::Pg>,
- {
- fn to_sql<'b>(
- &'b self,
- out: &mut Output<'b, '_, diesel::pg::Pg>,
- ) -> diesel::serialize::Result {
- let string_repr = self.get_string_repr();
- <String as ToSql<sql_types::Text, diesel::pg::Pg>>::to_sql(
- &string_repr,
- &mut out.reborrow(),
- )
- }
- }
-
- impl<DB> FromSql<sql_types::Text, DB> for ClientSecret
- where
- DB: Backend,
- String: FromSql<sql_types::Text, DB>,
- {
- fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> {
- let string_repr = String::from_sql(value)?;
- let (payment_id, secret) =
- string_repr
- .rsplit_once("_secret_")
- .ok_or(ParsingError::EncodeError(
- "Expected a string in the format '{payment_id}_secret_{secret}'",
- ))?;
-
- let payment_id = id_type::GlobalPaymentId::try_from(Cow::Owned(payment_id.to_owned()))
- .map_err(|err| {
- logger::error!(global_payment_id_error=?err);
- ParsingError::EncodeError("Error while constructing GlobalPaymentId")
- })?;
-
- Ok(Self {
- payment_id,
- secret: masking::Secret::new(secret.to_owned()),
- })
- }
- }
-
- impl<DB> Queryable<sql_types::Text, DB> for ClientSecret
- where
- DB: Backend,
- Self: FromSql<sql_types::Text, DB>,
- {
- type Row = Self;
-
- fn build(row: Self::Row) -> deserialize::Result<Self> {
- Ok(row)
- }
- }
- crate::impl_serializable_secret_id_type!(ClientSecret);
- #[cfg(test)]
- mod client_secret_tests {
- #![allow(clippy::expect_used)]
- #![allow(clippy::unwrap_used)]
-
- use serde_json;
-
- use super::*;
- use crate::id_type::GlobalPaymentId;
-
- #[test]
- fn test_serialize_client_secret() {
- let global_payment_id = "12345_pay_1a961ed9093c48b09781bf8ab17ba6bd";
- let secret = "fc34taHLw1ekPgNh92qr".to_string();
-
- let expected_client_secret_string = format!("\"{global_payment_id}_secret_{secret}\"");
-
- let client_secret1 = ClientSecret {
- payment_id: GlobalPaymentId::try_from(Cow::Borrowed(global_payment_id)).unwrap(),
- secret: masking::Secret::new(secret),
- };
-
- let parsed_client_secret =
- serde_json::to_string(&client_secret1).expect("Failed to serialize client_secret1");
-
- assert_eq!(expected_client_secret_string, parsed_client_secret);
- }
-
- #[test]
- fn test_deserialize_client_secret() {
- // This is a valid global id
- let global_payment_id_str = "12345_pay_1a961ed9093c48b09781bf8ab17ba6bd";
- let secret = "fc34taHLw1ekPgNh92qr".to_string();
-
- let valid_payment_global_id =
- GlobalPaymentId::try_from(Cow::Borrowed(global_payment_id_str))
- .expect("Failed to create valid global payment id");
-
- // This is an invalid global id because of the cell id being in invalid length
- let invalid_global_payment_id = "123_pay_1a961ed9093c48b09781bf8ab17ba6bd";
-
- // Create a client secret string which is valid
- let valid_client_secret = format!(r#""{global_payment_id_str}_secret_{secret}""#);
-
- dbg!(&valid_client_secret);
-
- // Create a client secret string which is invalid
- let invalid_client_secret_because_of_invalid_payment_id =
- format!(r#""{invalid_global_payment_id}_secret_{secret}""#);
-
- // Create a client secret string which is invalid because of invalid secret
- let invalid_client_secret_because_of_invalid_secret =
- format!(r#""{invalid_global_payment_id}""#);
-
- let valid_client_secret = serde_json::from_str::<ClientSecret>(&valid_client_secret)
- .expect("Failed to deserialize client_secret_str1");
-
- let invalid_deser1 = serde_json::from_str::<ClientSecret>(
- &invalid_client_secret_because_of_invalid_payment_id,
- );
-
- dbg!(&invalid_deser1);
-
- let invalid_deser2 = serde_json::from_str::<ClientSecret>(
- &invalid_client_secret_because_of_invalid_secret,
- );
-
- dbg!(&invalid_deser2);
-
- assert_eq!(valid_client_secret.payment_id, valid_payment_global_id);
-
- assert_eq!(valid_client_secret.secret.peek(), &secret);
-
- assert_eq!(
- invalid_deser1.err().unwrap().to_string(),
- "Incorrect value provided for field: payment_id at line 1 column 70"
- );
-
- assert_eq!(
- invalid_deser2.err().unwrap().to_string(),
- "invalid value: string \"123_pay_1a961ed9093c48b09781bf8ab17ba6bd\", expected a string with '_secret_' at line 1 column 42"
- );
- }
- }
-}
-
/// A type representing a range of time for filtering, including a mandatory start time and an optional end time.
#[derive(
Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, ToSchema,
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index 634626a4b1..7476639a47 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -33,7 +33,6 @@ pub struct PaymentIntent {
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
- pub client_secret: common_utils::types::ClientSecret,
pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>,
#[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)]
pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>,
@@ -300,7 +299,6 @@ pub struct PaymentIntentNew {
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
- pub client_secret: common_utils::types::ClientSecret,
pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>,
#[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)]
pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>,
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index ad2766c242..b9ca1c5da4 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -921,8 +921,6 @@ diesel::table! {
modified_at -> Timestamp,
last_synced -> Nullable<Timestamp>,
setup_future_usage -> Nullable<FutureUsage>,
- #[max_length = 128]
- client_secret -> Varchar,
#[max_length = 64]
active_attempt_id -> Nullable<Varchar>,
order_details -> Nullable<Array<Nullable<Jsonb>>>,
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index 4020bfbbe2..3c6a253d4b 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -405,8 +405,6 @@ pub struct PaymentIntent {
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub setup_future_usage: storage_enums::FutureUsage,
- /// The client secret that is generated for the payment. This is used to authenticate the payment from client facing apis.
- pub client_secret: common_utils::types::ClientSecret,
/// The active attempt for the payment intent. This is the payment attempt that is currently active for the payment intent.
pub active_attempt_id: Option<id_type::GlobalAttemptId>,
/// The order details for the payment.
@@ -531,22 +529,6 @@ impl PaymentIntent {
.unwrap_or(Ok(common_enums::RequestIncrementalAuthorization::default()))
}
- /// Check if the client secret is associated with the payment and if it has been expired
- pub fn validate_client_secret(
- &self,
- client_secret: &common_utils::types::ClientSecret,
- ) -> Result<(), errors::api_error_response::ApiErrorResponse> {
- common_utils::fp_utils::when(self.client_secret != *client_secret, || {
- Err(errors::api_error_response::ApiErrorResponse::ClientSecretInvalid)
- })?;
-
- common_utils::fp_utils::when(self.session_expiry < common_utils::date_time::now(), || {
- Err(errors::api_error_response::ApiErrorResponse::ClientSecretExpired)
- })?;
-
- Ok(())
- }
-
pub async fn create_domain_model_from_request(
payment_id: &id_type::GlobalPaymentId,
merchant_account: &merchant_account::MerchantAccount,
@@ -571,7 +553,6 @@ impl PaymentIntent {
.unwrap_or(common_utils::consts::DEFAULT_SESSION_EXPIRY),
),
));
- let client_secret = payment_id.generate_client_secret();
let order_details = request.order_details.map(|order_details| {
order_details
.into_iter()
@@ -595,7 +576,6 @@ impl PaymentIntent {
modified_at: common_utils::date_time::now(),
last_synced: None,
setup_future_usage: request.setup_future_usage.unwrap_or_default(),
- client_secret,
active_attempt_id: None,
order_details,
allowed_payment_method_types,
@@ -712,7 +692,6 @@ pub struct HeaderPayload {
pub locale: Option<String>,
pub x_app_id: Option<String>,
pub x_redirect_uri: Option<String>,
- pub client_secret: Option<common_utils::types::ClientSecret>,
}
impl HeaderPayload {
@@ -733,6 +712,7 @@ where
pub flow: PhantomData<F>,
pub payment_intent: PaymentIntent,
pub sessions_token: Vec<SessionToken>,
+ pub client_secret: Option<Secret<String>>,
}
// TODO: Check if this can be merged with existing payment data
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index e041effba4..a55b1b62fa 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -1573,7 +1573,6 @@ impl behaviour::Conversion for PaymentIntent {
modified_at,
last_synced,
setup_future_usage,
- client_secret,
active_attempt_id,
order_details,
allowed_payment_method_types,
@@ -1625,7 +1624,6 @@ impl behaviour::Conversion for PaymentIntent {
modified_at,
last_synced,
setup_future_usage: Some(setup_future_usage),
- client_secret,
active_attempt_id,
order_details: order_details.map(|order_details| {
order_details
@@ -1776,7 +1774,6 @@ impl behaviour::Conversion for PaymentIntent {
modified_at: storage_model.modified_at,
last_synced: storage_model.last_synced,
setup_future_usage: storage_model.setup_future_usage.unwrap_or_default(),
- client_secret: storage_model.client_secret,
active_attempt_id: storage_model.active_attempt_id,
order_details: storage_model.order_details.map(|order_details| {
order_details
@@ -1854,7 +1851,6 @@ impl behaviour::Conversion for PaymentIntent {
modified_at: self.modified_at,
last_synced: self.last_synced,
setup_future_usage: Some(self.setup_future_usage),
- client_secret: self.client_secret,
active_attempt_id: self.active_attempt_id,
order_details: self.order_details,
allowed_payment_method_types: self
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 38f4823e06..a81e88bf95 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -2041,9 +2041,6 @@ pub(crate) async fn payments_create_and_confirm_intent(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unexpected response from payments core")?;
- // Adding client secret to ensure client secret validation passes during confirm intent step
- header_payload.client_secret = Some(create_intent_response.client_secret.clone());
-
let payload = payments_api::PaymentsConfirmIntentRequest::from(&request);
let confirm_intent_response = decide_authorize_or_setup_intent_flow(
@@ -8013,6 +8010,8 @@ impl<F: Clone> PaymentMethodChecker<F> for PaymentData<F> {
pub trait OperationSessionGetters<F> {
fn get_payment_attempt(&self) -> &storage::PaymentAttempt;
fn get_payment_intent(&self) -> &storage::PaymentIntent;
+ #[cfg(feature = "v2")]
+ fn get_client_secret(&self) -> &Option<Secret<String>>;
fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod>;
fn get_mandate_id(&self) -> Option<&payments_api::MandateIds>;
fn get_address(&self) -> &PaymentAddress;
@@ -8054,6 +8053,8 @@ pub trait OperationSessionGetters<F> {
pub trait OperationSessionSetters<F> {
// Setter functions for PaymentData
fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent);
+ #[cfg(feature = "v2")]
+ fn set_client_secret(&mut self, client_secret: Option<Secret<String>>);
fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt);
fn set_payment_method_data(&mut self, payment_method_data: Option<domain::PaymentMethodData>);
fn set_email_if_not_present(&mut self, email: pii::Email);
@@ -8361,6 +8362,10 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentIntentData<F> {
todo!()
}
+ fn get_client_secret(&self) -> &Option<Secret<String>> {
+ &self.client_secret
+ }
+
fn get_payment_intent(&self) -> &storage::PaymentIntent {
&self.payment_intent
}
@@ -8493,7 +8498,9 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> {
fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) {
self.payment_intent = payment_intent;
}
-
+ fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) {
+ self.client_secret = client_secret;
+ }
fn set_payment_attempt(&mut self, _payment_attempt: storage::PaymentAttempt) {
todo!()
}
@@ -8577,6 +8584,9 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentConfirmData<F> {
fn get_payment_attempt(&self) -> &storage::PaymentAttempt {
&self.payment_attempt
}
+ fn get_client_secret(&self) -> &Option<Secret<String>> {
+ todo!()
+ }
fn get_payment_intent(&self) -> &storage::PaymentIntent {
&self.payment_intent
@@ -8709,7 +8719,9 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentConfirmData<F> {
fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) {
self.payment_intent = payment_intent;
}
-
+ fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) {
+ todo!()
+ }
fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) {
self.payment_attempt = payment_attempt;
}
@@ -8795,7 +8807,9 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentStatusData<F> {
fn get_payment_attempt(&self) -> &storage::PaymentAttempt {
todo!()
}
-
+ fn get_client_secret(&self) -> &Option<Secret<String>> {
+ todo!()
+ }
fn get_payment_intent(&self) -> &storage::PaymentIntent {
&self.payment_intent
}
@@ -8926,7 +8940,9 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentStatusData<F> {
fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) {
self.payment_intent = payment_intent;
}
-
+ fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) {
+ todo!()
+ }
fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) {
self.payment_attempt = Some(payment_attempt);
}
@@ -9012,7 +9028,9 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentCaptureData<F> {
fn get_payment_attempt(&self) -> &storage::PaymentAttempt {
&self.payment_attempt
}
-
+ fn get_client_secret(&self) -> &Option<Secret<String>> {
+ todo!()
+ }
fn get_payment_intent(&self) -> &storage::PaymentIntent {
&self.payment_intent
}
@@ -9145,7 +9163,9 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentCaptureData<F> {
fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) {
self.payment_intent = payment_intent;
}
-
+ fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) {
+ todo!()
+ }
fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) {
self.payment_attempt = payment_attempt;
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 5d6513c765..bdf7e9ec83 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -3587,30 +3587,6 @@ pub fn authenticate_client_secret(
}
}
-#[cfg(feature = "v2")]
-// A function to manually authenticate the client secret with intent fulfillment time
-pub fn authenticate_client_secret(
- request_client_secret: Option<&common_utils::types::ClientSecret>,
- payment_intent: &PaymentIntent,
-) -> Result<(), errors::ApiErrorResponse> {
- match (request_client_secret, &payment_intent.client_secret) {
- (Some(req_cs), pi_cs) => {
- if req_cs != pi_cs {
- Err(errors::ApiErrorResponse::ClientSecretInvalid)
- } else {
- let current_timestamp = common_utils::date_time::now();
-
- let session_expiry = payment_intent.session_expiry;
-
- fp_utils::when(current_timestamp > session_expiry, || {
- Err(errors::ApiErrorResponse::ClientSecretExpired)
- })
- }
- }
- _ => Ok(()),
- }
-}
-
pub(crate) fn validate_payment_status_against_allowed_statuses(
intent_status: storage_enums::IntentStatus,
allowed_statuses: &[storage_enums::IntentStatus],
diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rs
index 11e5093cf0..a997aab457 100644
--- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs
@@ -169,11 +169,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, PaymentsConfir
// TODO (#7195): Add platform merchant account validation once publishable key auth is solved
self.validate_status_for_operation(payment_intent.status)?;
- let client_secret = header_payload
- .client_secret
- .as_ref()
- .get_required_value("client_secret header")?;
- payment_intent.validate_client_secret(client_secret)?;
let cell_id = state.conf.cell_information.id.clone();
diff --git a/crates/router/src/core/payments/operations/payment_create_intent.rs b/crates/router/src/core/payments/operations/payment_create_intent.rs
index 755c4e153c..92572602ad 100644
--- a/crates/router/src/core/payments/operations/payment_create_intent.rs
+++ b/crates/router/src/core/payments/operations/payment_create_intent.rs
@@ -5,7 +5,7 @@ use async_trait::async_trait;
use common_utils::{
errors::CustomResult,
ext_traits::{AsyncExt, Encode, ValueExt},
- types::keymanager::ToEncryptable,
+ types::{authentication, keymanager::ToEncryptable},
};
use error_stack::ResultExt;
use masking::PeekInterface;
@@ -158,9 +158,19 @@ impl<F: Send + Clone + Sync>
})
.attach_printable("failed while inserting new payment intent")?;
+ let client_secret = helpers::create_client_secret(
+ state,
+ merchant_account.get_id(),
+ authentication::ResourceId::Payment(payment_id.clone()),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to create client secret")?;
+
let payment_data = payments::PaymentIntentData {
flow: PhantomData,
payment_intent,
+ client_secret: Some(client_secret.secret),
sessions_token: vec![],
};
diff --git a/crates/router/src/core/payments/operations/payment_get_intent.rs b/crates/router/src/core/payments/operations/payment_get_intent.rs
index 05f939ee31..2e00b19c75 100644
--- a/crates/router/src/core/payments/operations/payment_get_intent.rs
+++ b/crates/router/src/core/payments/operations/payment_get_intent.rs
@@ -106,6 +106,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentIntentData<F>, Payme
let payment_data = payments::PaymentIntentData {
flow: PhantomData,
payment_intent,
+ // todo : add a way to fetch client secret if required
+ client_secret: None,
sessions_token: vec![],
};
diff --git a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs
index 4e62899546..d90dba639b 100644
--- a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs
+++ b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs
@@ -74,7 +74,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsPostSess
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
// TODO (#7195): Add platform merchant account validation once publishable key auth is solved
-
helpers::authenticate_client_secret(Some(request.client_secret.peek()), &payment_intent)?;
let mut payment_attempt = db
diff --git a/crates/router/src/core/payments/operations/payment_session_intent.rs b/crates/router/src/core/payments/operations/payment_session_intent.rs
index 79348e6e23..8b8bbae292 100644
--- a/crates/router/src/core/payments/operations/payment_session_intent.rs
+++ b/crates/router/src/core/payments/operations/payment_session_intent.rs
@@ -138,15 +138,10 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentIntentData<F>, Payme
self.validate_status_for_operation(payment_intent.status)?;
- let client_secret = header_payload
- .client_secret
- .as_ref()
- .get_required_value("client_secret header")?;
- payment_intent.validate_client_secret(client_secret)?;
-
let payment_data = payments::PaymentIntentData {
flow: PhantomData,
payment_intent,
+ client_secret: None,
sessions_token: vec![],
};
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index 455f288432..49de2c77ec 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -83,6 +83,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsStartReq
payment_intent.client_secret.as_ref(),
&payment_intent,
)?;
+
payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 0baa0829fc..baacbb9d47 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -112,7 +112,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
],
"update",
)?;
-
helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?;
payment_intent.order_details = request
diff --git a/crates/router/src/core/payments/operations/payment_update_intent.rs b/crates/router/src/core/payments/operations/payment_update_intent.rs
index 98a3713605..5a283409ed 100644
--- a/crates/router/src/core/payments/operations/payment_update_intent.rs
+++ b/crates/router/src/core/payments/operations/payment_update_intent.rs
@@ -291,6 +291,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentIntentData<F>, PaymentsUpda
let payment_data = payments::PaymentIntentData {
flow: PhantomData,
payment_intent,
+ client_secret: None,
sessions_token: vec![],
};
diff --git a/crates/router/src/core/payments/payment_methods.rs b/crates/router/src/core/payments/payment_methods.rs
index df100d2e9b..94c4341dee 100644
--- a/crates/router/src/core/payments/payment_methods.rs
+++ b/crates/router/src/core/payments/payment_methods.rs
@@ -36,16 +36,6 @@ pub async fn list_payment_methods(
validate_payment_status_for_payment_method_list(payment_intent.status)?;
- let client_secret = header_payload
- .client_secret
- .as_ref()
- .get_required_value("client_secret header")
- .change_context(errors::ApiErrorResponse::MissingRequiredField {
- field_name: "client_secret header",
- })?;
-
- payment_intent.validate_client_secret(client_secret)?;
-
let payment_connector_accounts = db
.list_enabled_connector_accounts_by_profile_id(
key_manager_state,
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 2e2cda7afe..077a288c16 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -1523,6 +1523,7 @@ where
_merchant_account: &domain::MerchantAccount,
) -> RouterResponse<Self> {
let payment_intent = payment_data.get_payment_intent();
+ let client_secret = payment_data.get_client_secret();
Ok(services::ApplicationResponse::JsonWithHeaders((
Self {
id: payment_intent.id.clone(),
@@ -1531,7 +1532,7 @@ where
amount_details: api_models::payments::AmountDetailsResponse::foreign_from(
payment_intent.amount_details.clone(),
),
- client_secret: payment_intent.client_secret.clone(),
+ client_secret: client_secret.clone(),
merchant_reference_id: payment_intent.merchant_reference_id.clone(),
routing_algorithm_id: payment_intent.routing_algorithm_id.clone(),
capture_method: payment_intent.capture_method,
@@ -1662,7 +1663,6 @@ where
amount,
customer_id: payment_intent.customer_id.clone(),
connector: Some(connector),
- client_secret: payment_intent.client_secret.clone(),
created: payment_intent.created_at,
payment_method_data,
payment_method_type: Some(payment_attempt.payment_method_type),
@@ -1760,7 +1760,6 @@ where
.cloned()
.map(From::from),
shipping: self.payment_address.get_shipping().cloned().map(From::from),
- client_secret: payment_intent.client_secret.clone(),
created: payment_intent.created_at,
payment_method_data,
payment_method_type: self
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 3b9fcfc0d8..e3b71f6f4f 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -2200,23 +2200,38 @@ where
get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)?
.get_required_value(headers::X_PROFILE_ID)?;
- match db_client_secret.resource_id {
- common_utils::types::authentication::ResourceId::Payment(global_payment_id) => {
- return Err(errors::ApiErrorResponse::Unauthorized.into())
+ match (&self.0, &db_client_secret.resource_id) {
+ (
+ common_utils::types::authentication::ResourceId::Payment(self_id),
+ common_utils::types::authentication::ResourceId::Payment(db_id),
+ ) => {
+ fp_utils::when(self_id != db_id, || {
+ Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized)
+ });
}
- common_utils::types::authentication::ResourceId::Customer(global_customer_id) => {
- if global_customer_id.get_string_repr() != self.0.to_str() {
- return Err(errors::ApiErrorResponse::Unauthorized.into());
- }
+
+ (
+ common_utils::types::authentication::ResourceId::Customer(self_id),
+ common_utils::types::authentication::ResourceId::Customer(db_id),
+ ) => {
+ fp_utils::when(self_id != db_id, || {
+ Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized)
+ });
}
- common_utils::types::authentication::ResourceId::PaymentMethodSession(
- global_payment_method_session_id,
+
+ (
+ common_utils::types::authentication::ResourceId::PaymentMethodSession(self_id),
+ common_utils::types::authentication::ResourceId::PaymentMethodSession(db_id),
) => {
- if global_payment_method_session_id.get_string_repr() != self.0.to_str() {
- return Err(errors::ApiErrorResponse::Unauthorized.into());
- }
+ fp_utils::when(self_id != db_id, || {
+ Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized)
+ });
}
- };
+
+ _ => {
+ return Err(errors::ApiErrorResponse::Unauthorized.into());
+ }
+ }
let (merchant_account, key_store) = state
.store()
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 0469046546..0d890599ea 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -1654,14 +1654,6 @@ impl ForeignTryFrom<&HeaderMap> for hyperswitch_domain_models::payments::HeaderP
let x_redirect_uri =
get_header_value_by_key(X_REDIRECT_URI.into(), headers)?.map(|val| val.to_string());
- // TODO: combine publishable key and client secret when we unify the auth
- let client_secret = get_header_value_by_key(X_CLIENT_SECRET.into(), headers)?
- .map(common_utils::types::ClientSecret::from_str)
- .transpose()
- .change_context(errors::ApiErrorResponse::InvalidRequestData {
- message: "Invalid data received in client_secret header".into(),
- })?;
-
Ok(Self {
payment_confirm_source,
// client_source,
@@ -1673,7 +1665,6 @@ impl ForeignTryFrom<&HeaderMap> for hyperswitch_domain_models::payments::HeaderP
locale,
x_app_id,
x_redirect_uri,
- client_secret,
})
}
}
diff --git a/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/down.sql b/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/down.sql
new file mode 100644
index 0000000000..215c3bf412
--- /dev/null
+++ b/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_intent
+ADD COLUMN client_secret VARCHAR(128);
\ No newline at end of file
diff --git a/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/up.sql b/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/up.sql
new file mode 100644
index 0000000000..7463ea0cbc
--- /dev/null
+++ b/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE payment_intent DROP COLUMN client_secret;
\ No newline at end of file