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
fix(payment_methods): delete token when a payment reaches terminal state (#1818)
Shankar Singh C07020d01b5d0
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex b84d01a052..65d59bf156 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -42,6 +42,7 @@ use crate::{routes::{self,metrics::{self, request},+ payment_methods::ParentPaymentMethodToken,},services,types::{@@ -1792,37 +1793,19 @@ pub async fn list_customer_payment_method(};customer_pms.push(pma.to_owned());+ let intent_created = payment_intent.as_ref().map(|intent| intent.created_at);+let redis_conn = state.store.get_redis_conn().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to get redis connection")?;-- let key_for_hyperswitch_token = format!(- "pm_token_{}_{}_hyperswitch",- parent_payment_method_token, pma.payment_method- );-- let current_datetime_utc = common_utils::date_time::now();- let time_eslapsed = current_datetime_utc- - payment_intent- .as_ref()- .map(|intent| intent.created_at)- .unwrap_or_else(|| current_datetime_utc);- redis_conn- .set_key_with_expiry(- &key_for_hyperswitch_token,- hyperswitch_token,- consts::TOKEN_TTL - time_eslapsed.whole_seconds(),- )- .await- .map_err(|error| {- logger::error!(hyperswitch_token_kv_error=?error);- errors::StorageError::KVError- })- .into_report()- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to add data in redis")?;+ ParentPaymentMethodToken::create_key_for_token((+ &parent_payment_method_token,+ pma.payment_method,+ ))+ .insert(intent_created, hyperswitch_token, state)+ .await?;if let Some(metadata) = pma.metadata {let pm_metadata_vec: payment_methods::PaymentMethodMetadata = metadata@@ -1837,11 +1820,17 @@ pub async fn list_customer_payment_method("pm_token_{}_{}_{}",parent_payment_method_token, pma.payment_method, pm_metadata.0);+ let current_datetime_utc = common_utils::date_time::now();+ let time_elapsed = current_datetime_utc+ - payment_intent+ .as_ref()+ .map(|intent| intent.created_at)+ .unwrap_or_else(|| current_datetime_utc);redis_conn.set_key_with_expiry(&key,pm_metadata.1,- consts::TOKEN_TTL - time_eslapsed.whole_seconds(),+ consts::TOKEN_TTL - time_elapsed.whole_seconds(),).await.map_err(|error| {diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 9465bdf8a2..65d7bc41f3 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -9,7 +9,7 @@ pub mod transformers;use std::{collections::HashMap, fmt::Debug, marker::PhantomData, ops::Deref, time::Instant};use api_models::payments::FrmMessage;-use common_utils::pii;+use common_utils::{ext_traits::AsyncExt, pii};use diesel_models::ephemeral_key;use error_stack::{IntoReport, ResultExt};use futures::future::join_all;@@ -32,7 +32,7 @@ use crate::{core::errors::{self, CustomResult, RouterResponse, RouterResult},db::StorageInterface,logger,- routes::{metrics, AppState},+ routes::{metrics, payment_methods::ParentPaymentMethodToken, AppState},scheduler::{utils as pt_utils, workflows::payment_sync},services::{self, api::Authenticate},types::{@@ -197,6 +197,20 @@ where.await?}};+ payment_data+ .payment_attempt+ .payment_token+ .as_ref()+ .zip(payment_data.payment_attempt.payment_method)+ .map(ParentPaymentMethodToken::create_key_for_token)+ .async_map(|key_for_hyperswitch_token| async move {+ if key_for_hyperswitch_token+ .should_delete_payment_method_token(payment_data.payment_intent.status)+ {+ let _ = key_for_hyperswitch_token.delete(state).await;+ }+ })+ .await;} else {(_, payment_data) = operation.to_update_tracker()?diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 815a195ac8..e4ec1ae74b 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -27,7 +27,7 @@ use crate::{payments,},db::StorageInterface,- routes::{metrics, AppState},+ routes::{metrics, payment_methods::ParentPaymentMethodToken, AppState},scheduler::metrics as scheduler_metrics,services,types::{@@ -1174,6 +1174,7 @@ pub async fn make_pm_data<'a, F: Clone, R>() -> RouterResult<(BoxedOperation<'a, F, R>, Option<api::PaymentMethodData>)> {let request = &payment_data.payment_method_data;let token = payment_data.token.clone();+let hyperswitch_token = if let Some(token) = token {let redis_conn = state.store@@ -1191,13 +1192,16 @@ pub async fn make_pm_data<'a, F: Clone, R>(.get_required_value("payment_method")?,);- let hyperswitch_token_option = redis_conn+ let key = redis_conn.get_key::<Option<String>>(&key).await.change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to fetch the token from redis")?;+ .attach_printable("Failed to fetch the token from redis")?+ .ok_or(error_stack::Report::new(+ errors::ApiErrorResponse::UnprocessableEntity { entity: token },+ ))?;- hyperswitch_token_option.or(Some(token))+ Some(key)} else {None};@@ -1273,7 +1277,7 @@ pub async fn make_pm_data<'a, F: Clone, R>(})}(pm_opt @ Some(pm @ api::PaymentMethodData::Card(_)), _) => {- let token = vault::Vault::store_payment_method_data_in_locker(+ let hyperswitch_token = vault::Vault::store_payment_method_data_in_locker(state,None,pm,@@ -1281,7 +1285,30 @@ pub async fn make_pm_data<'a, F: Clone, R>(enums::PaymentMethod::Card,).await?;- payment_data.token = Some(token);++ let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token");+ let key_for_hyperswitch_token =+ payment_data+ .payment_attempt+ .payment_method+ .map(|payment_method| {+ ParentPaymentMethodToken::create_key_for_token((+ &parent_payment_method_token,+ payment_method,+ ))+ });+ if let Some(key_for_hyperswitch_token) = key_for_hyperswitch_token {+ key_for_hyperswitch_token+ .insert(+ Some(payment_data.payment_intent.created_at),+ hyperswitch_token,+ state,+ )+ .await?;+ };++ payment_data.token = Some(parent_payment_method_token);+Ok(pm_opt.to_owned())}(pm @ Some(api::PaymentMethodData::PayLater(_)), _) => Ok(pm.to_owned()),diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rsindex 0e6f5c0e24..589ae7d73d 100644--- a/crates/router/src/routes/payment_methods.rs+++ b/crates/router/src/routes/payment_methods.rs@@ -1,11 +1,17 @@use actix_web::{web, HttpRequest, HttpResponse};-use router_env::{instrument, tracing, Flow};+use common_utils::{consts::TOKEN_TTL, errors::CustomResult};+use error_stack::{IntoReport, ResultExt};+use router_env::{instrument, logger, tracing, Flow};+use time::PrimitiveDateTime;use super::app::AppState;use crate::{- core::payment_methods::cards,+ core::{errors, payment_methods::cards},services::{api, authentication as auth},- types::api::payment_methods::{self, PaymentMethodId},+ types::{+ api::payment_methods::{self, PaymentMethodId},+ storage::enums as storage_enums,+ },};/// PaymentMethods - Create@@ -354,3 +360,75 @@ mod tests {assert!(de_query.is_err())}}++#[derive(Clone)]+pub struct ParentPaymentMethodToken {+ key_for_token: String,+}++impl ParentPaymentMethodToken {+ pub fn create_key_for_token(+ (parent_pm_token, payment_method): (&String, api_models::enums::PaymentMethod),+ ) -> Self {+ Self {+ key_for_token: format!(+ "pm_token_{}_{}_hyperswitch",+ parent_pm_token, payment_method+ ),+ }+ }+ pub async fn insert(+ &self,+ intent_created_at: Option<PrimitiveDateTime>,+ token: String,+ state: &AppState,+ ) -> CustomResult<(), errors::ApiErrorResponse> {+ let redis_conn = state+ .store+ .get_redis_conn()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to get redis connection")?;+ let current_datetime_utc = common_utils::date_time::now();+ let time_elapsed = current_datetime_utc - intent_created_at.unwrap_or(current_datetime_utc);+ redis_conn+ .set_key_with_expiry(+ &self.key_for_token,+ token,+ TOKEN_TTL - time_elapsed.whole_seconds(),+ )+ .await+ .map_err(|error| {+ logger::error!(hyperswitch_token_kv_error=?error);+ errors::StorageError::KVError+ })+ .into_report()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to add data in redis")?;++ Ok(())+ }++ pub fn should_delete_payment_method_token(&self, status: storage_enums::IntentStatus) -> bool {+ !matches!(+ status,+ diesel_models::enums::IntentStatus::RequiresCustomerAction+ )+ }++ pub async fn delete(&self, state: &AppState) -> CustomResult<(), errors::ApiErrorResponse> {+ let redis_conn = state+ .store+ .get_redis_conn()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to get redis connection")?;+ match redis_conn.delete_key(&self.key_for_token).await {+ Ok(_) => Ok(()),+ Err(err) => {+ {+ logger::info!("Error while deleting redis key: {:?}", err)+ };+ Ok(())+ }+ }+ }+}