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
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
Refactor(payment_methods_v2): Refactor Update saved PM session API to enable cvc only update (#10855)
Sarthak Soni51044bad90fd
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex bc38ae53d1..c82b89e92d 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -19755,13 +19755,13 @@"PaymentMethodSessionDeleteSavedPaymentMethod": {"type": "object","required": [- "payment_method_id"+ "payment_method_token"],"properties": {- "payment_method_id": {+ "payment_method_token": {"type": "string",- "description": "The payment method id of the payment method to be updated",- "example": "12345_pm_01926c58bc6e77c09e809964e72af8c8"+ "description": "The payment method token associated with the payment method to be updated",+ "example": "token_9wcXDRVkfEtLEsSnYKgQ"}}},diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex 269d0a22d5..74cc4ff7c6 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -2395,6 +2395,17 @@ pub struct PaymentMethodDeleteResponse {pub id: id_type::GlobalPaymentMethodId,}+#[cfg(feature = "v2")]+#[derive(Debug, serde::Serialize, ToSchema)]+pub struct PaymentMethodDeleteSessionResponse {+ /// The unique identifier of the Payment method+ #[schema(value_type = String, example = "token_9wcXDRVkfEtLEsSnYKgQ")]+ pub payment_method_token: String,+}++#[cfg(feature = "v2")]+impl common_utils::events::ApiEventMetric for PaymentMethodDeleteSessionResponse {}+#[cfg(feature = "v1")]#[derive(Debug, serde::Serialize, ToSchema)]pub struct CustomerDefaultPaymentMethodResponse {@@ -3415,12 +3426,31 @@ pub struct PaymentMethodSessionUpdateSavedPaymentMethod {pub payment_method_update_request: PaymentMethodUpdate,}+#[cfg(feature = "v2")]+impl PaymentMethodSessionUpdateSavedPaymentMethod {+ pub fn fetch_card_cvc_update(&self) -> Option<masking::Secret<String>> {+ match &self.payment_method_update_request.payment_method_data {+ Some(PaymentMethodUpdateData::Card(card_update)) => card_update.card_cvc.clone(),+ _ => None,+ }+ }++ pub fn is_payment_method_metadata_update(&self) -> bool {+ match &self.payment_method_update_request.payment_method_data {+ Some(PaymentMethodUpdateData::Card(card_update)) => {+ card_update.card_holder_name.is_some() || card_update.nick_name.is_some()+ }+ _ => false,+ }+ }+}+#[cfg(feature = "v2")]#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)]pub struct PaymentMethodSessionDeleteSavedPaymentMethod {- /// The payment method id of the payment method to be updated- #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")]- pub payment_method_id: id_type::GlobalPaymentMethodId,+ /// The payment method token associated with the payment method to be updated+ #[schema(value_type = String, example = "token_9wcXDRVkfEtLEsSnYKgQ")]+ pub payment_method_token: String,}#[cfg(feature = "v2")]diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex 41ec1794dc..25a356bbda 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -3808,6 +3808,7 @@ pub async fn payment_methods_session_retrieve(}).attach_printable("Failed to retrieve payment methods session from db")?;+ // Only one associated payment method is supported for nowlet associated_pm_token = payment_method_session_domain_model.associated_payment_methods.as_ref()@@ -3818,8 +3819,15 @@ pub async fn payment_methods_session_retrieve(});let expiry = associated_pm_token- .async_map(|token_string| {- vault::retrieve_key_and_ttl_for_cvc_from_payment_method_token(&state, token_string)+ .async_map(|pm_token| {+ utils::retrieve_payment_method_id_from_payment_method_token_data(&state, pm_token)+ })+ .await+ .transpose()+ .ok()+ .flatten()+ .async_map(|pm_id| {+ vault::retrieve_key_and_ttl_for_cvc_from_payment_method_id(&state, pm_id.to_owned())}).await.transpose()@@ -3877,31 +3885,29 @@ pub async fn payment_methods_session_update_payment_method(message: "No associated payment method found in the session".to_string(),})?;- let payment_method_token_data =- utils::retrieve_payment_token_data(&state, request.payment_method_token.clone())- .await- .attach_printable("Failed to retrieve payment method token data")?;-- let payment_method_id = match payment_method_token_data {- storage::payment_method::PaymentTokenData::PermanentCard(card) => {- Some(card.payment_method_id)- }- _ => None,- }- .get_required_value("payment_method_id from payment method token data")- .attach_printable("Failed to get payment method id from payment method token data")?;-- let payment_method_update_request = request.payment_method_update_request.clone();-- Box::pin(update_payment_method_core(+ let payment_method_id = utils::retrieve_payment_method_id_from_payment_method_token_data(&state,- &platform,- &profile,- payment_method_update_request,- &payment_method_id,- ))+ request.payment_method_token.clone(),+ ).await- .attach_printable("Failed to update saved payment method")?;+ .attach_printable("Failed to retrieve payment method id from payment method token data")?;++ // Stage 1: Update CVC in redis if provided+ let card_cvc = request.fetch_card_cvc_update();+ let card_cvc_token_details = card_cvc+ .async_map(|cvc| {+ vault::insert_cvc_using_payment_token(+ &state,+ &payment_method_id,+ cvc,+ common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME,+ platform.get_provider().get_key_store(),+ )+ })+ .await+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to insert encrypted cvc in redis")?;// Update payment method session with associated payment methodslet update_payment_method_session = hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum::UpdateAssociatedPaymentMethods {@@ -3921,29 +3927,20 @@ pub async fn payment_methods_session_update_payment_method("Failed to update payment method session with associated payment methods",)?;- let card_cvc_token = if let Some(api::PaymentMethodUpdateData::Card(ref card_data)) =- request.payment_method_update_request.payment_method_data- {- let token = if let Some(cvc) = card_data.card_cvc.clone() {- Some(- vault::insert_cvc_using_payment_token(- &state,- &request.payment_method_token,- cvc,- common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME,- platform.get_provider().get_key_store(),- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to insert encrypted cvc in redis")?,- )- } else {- None- };- token- } else {- None- };+ // Stage 2: Update saved payment method if there is any metadata update+ if request.is_payment_method_metadata_update() {+ let payment_method_update_request = request.payment_method_update_request.clone();++ Box::pin(update_payment_method_core(+ &state,+ &platform,+ &profile,+ payment_method_update_request,+ &payment_method_id,+ ))+ .await+ .attach_printable("Failed to update saved payment method")?;+ }let response = transformers::generate_payment_method_session_response(updated_payment_method_session,@@ -3951,7 +3948,7 @@ pub async fn payment_methods_session_update_payment_method(None, // TODO: send associated payments response based on the expandable paramNone,None,- card_cvc_token,+ card_cvc_token_details,);Ok(services::ApplicationResponse::Json(response))@@ -3962,9 +3959,9 @@ pub async fn payment_methods_session_delete_payment_method(state: SessionState,platform: domain::Platform,profile: domain::Profile,- pm_id: id_type::GlobalPaymentMethodId,+ pm_token: String,payment_method_session_id: id_type::GlobalPaymentMethodSessionId,-) -> RouterResponse<api::PaymentMethodDeleteResponse> {+) -> RouterResponse<payment_methods::PaymentMethodDeleteSessionResponse> {let db = state.store.as_ref();// Validate if the session still exists@@ -3978,11 +3975,22 @@ pub async fn payment_methods_session_delete_payment_method(}).attach_printable("Failed to retrieve payment methods session from db")?;- let response = delete_payment_method_core(&state, pm_id, &platform, &profile)+ let payment_method_id =+ utils::retrieve_payment_method_id_from_payment_method_token_data(&state, pm_token.clone())+ .await+ .attach_printable(+ "Failed to retrieve payment method id from payment method token data",+ )?;++ delete_payment_method_core(&state, payment_method_id, &platform, &profile).await.attach_printable("Failed to delete saved payment method")?;- Ok(services::ApplicationResponse::Json(response))+ Ok(services::ApplicationResponse::Json(+ payment_methods::PaymentMethodDeleteSessionResponse {+ payment_method_token: pm_token,+ },+ ))}#[cfg(feature = "v2")]@@ -4141,7 +4149,7 @@ pub async fn payment_methods_session_confirm(.async_map(|cvc| {vault::insert_cvc_using_payment_token(&state,- &parent_payment_method_token,+ &payment_method_response.id,cvc,intent_fulfillment_time,platform.get_provider().get_key_store(),diff --git a/crates/router/src/core/payment_methods/utils.rs b/crates/router/src/core/payment_methods/utils.rsindex 7518f967ab..f82dbb2c45 100644--- a/crates/router/src/core/payment_methods/utils.rs+++ b/crates/router/src/core/payment_methods/utils.rs@@ -25,6 +25,7 @@ use crate::{errors,storage::{self, enums as storage_enums},},+ routes::payment_methods as pm_routes,services::logger,};@@ -879,6 +880,32 @@ pub(super) async fn retrieve_payment_token_data(.attach_printable("failed to deserialize hyperswitch token data")}+#[cfg(feature = "v2")]+pub(super) async fn retrieve_payment_method_id_from_payment_method_token_data(+ state: &SessionState,+ token: String,+) -> errors::RouterResult<common_utils::id_type::GlobalPaymentMethodId> {+ let payment_method_token_data =+ pm_routes::ParentPaymentMethodToken::create_key_for_token(&token)+ .get_data_for_token(state)+ .await+ .attach_printable("Failed to retrieve payment method token data")?;++ let payment_method_id = match payment_method_token_data {+ storage::payment_method::PaymentTokenData::PermanentCard(card) => {+ Some(card.payment_method_id)+ }+ _ => None,+ }+ .get_required_value("payment_method_id from payment method token data")+ .change_context(errors::ApiErrorResponse::GenericNotFoundError {+ message: "payment_method_id".to_string(),+ })+ .attach_printable("Failed to get payment method id from payment method token data")?;++ Ok(payment_method_id)+}+#[cfg(feature = "v2")]pub(super) async fn delete_payment_token_data(state: &SessionState,diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rsindex 0ae3a64d8e..2d23f30b85 100644--- a/crates/router/src/core/payment_methods/vault.rs+++ b/crates/router/src/core/payment_methods/vault.rs@@ -1773,7 +1773,7 @@ pub struct TemporaryVaultCvc {#[instrument(skip_all)]pub async fn insert_cvc_using_payment_token(state: &routes::SessionState,- payment_method_token: &String,+ payment_method_id: &id_type::GlobalPaymentMethodId,card_cvc: masking::Secret<String>,fulfillment_time: i64,key_store: &domain::MerchantKeyStore,@@ -1784,7 +1784,10 @@ pub async fn insert_cvc_using_payment_token(.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to get redis connection")?;- let key = format!("pm_token_{payment_method_token}_hyperswitch_cvc");+ let key = format!(+ "pm_token_{}_hyperswitch_cvc",+ payment_method_id.get_string_repr()+ );let payload_to_be_encrypted = TemporaryVaultCvc { card_cvc };@@ -1867,9 +1870,9 @@ pub async fn retrieve_and_delete_cvc_from_payment_token(#[cfg(feature = "v2")]#[instrument(skip_all)]-pub async fn retrieve_key_and_ttl_for_cvc_from_payment_method_token(+pub async fn retrieve_key_and_ttl_for_cvc_from_payment_method_id(state: &routes::SessionState,- payment_method_token: String,+ payment_method_id: id_type::GlobalPaymentMethodId,) -> RouterResult<i64> {let redis_conn = state.store@@ -1877,7 +1880,10 @@ pub async fn retrieve_key_and_ttl_for_cvc_from_payment_method_token(.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to get redis connection")?;- let key = format!("pm_token_{payment_method_token}_hyperswitch_cvc",);+ let key = format!(+ "pm_token_{}_hyperswitch_cvc",+ payment_method_id.get_string_repr()+ );// check if key exists and get ttlredis_conndiff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rsindex 548a484874..80be6240f5 100644--- a/crates/router/src/routes/payment_methods.rs+++ b/crates/router/src/routes/payment_methods.rs@@ -1642,7 +1642,7 @@ pub async fn payment_method_session_delete_saved_payment_method(state,auth.platform,auth.profile,- request.request.payment_method_id,+ request.request.payment_method_token,request.payment_method_session_id,)},