Skip to content

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

feat(router): Add new api for delete tokenization record (#8361)

Prasunna Soppa0e957854372f
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index 6b7fa4eae9..02dbdddf4a 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -3613,6 +3613,63 @@
}
]
}
+ },
+ "/v2/tokenize/{id}": {
+ "delete": {
+ "tags": [
+ "Tokenization"
+ ],
+ "summary": "Tokenization - Delete",
+ "description": "Delete a token entry with customer_id and session_id",
+ "operationId": "delete_tokenized_data_api",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/DeleteTokenDataRequest"
+ },
+ "examples": {
+ "Delete a token entry with customer_id and session_id": {
+ "value": {
+ "customer_id": "12345_cus_0196d94b9c207333a297cbcf31f2e8c8",
+ "session_id": "12345_pms_01926c58bc6e77c09e809964e72af8c8"
+ }
+ }
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Token deleted successfully",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/DeleteTokenDataResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid request"
+ },
+ "401": {
+ "description": "Unauthorized"
+ },
+ "500": {
+ "description": "Internal server error"
+ }
+ },
+ "security": [
+ {
+ "ephemeral_key": []
+ },
+ {
+ "api_key": []
+ }
+ ]
+ }
}
},
"components": {
@@ -10210,6 +10267,38 @@
"frictionless"
]
},
+ "DeleteTokenDataRequest": {
+ "type": "object",
+ "required": [
+ "customer_id",
+ "session_id"
+ ],
+ "properties": {
+ "customer_id": {
+ "type": "string",
+ "description": "Customer ID for which the tokenization is requested",
+ "example": "12345_cus_01926c58bc6e77c09e809964e72af8c8"
+ },
+ "session_id": {
+ "type": "string",
+ "description": "Session ID associated with the tokenization request",
+ "example": "12345_pms_01926c58bc6e77c09e809964e72af8c8"
+ }
+ }
+ },
+ "DeleteTokenDataResponse": {
+ "type": "object",
+ "required": [
+ "id"
+ ],
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "Unique identifier returned by the tokenization service",
+ "example": "12345_tok_01926c58bc6e77c09e809964e72af8c8"
+ }
+ }
+ },
"DeviceChannel": {
"type": "string",
"description": "Device Channel indicating whether request is coming from App or Browser",
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index dd54cd6322..b97d77a4a8 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -238,3 +238,9 @@ impl ApiEventMetric for tokenization::GenericTokenizationRequest {}
#[cfg(feature = "tokenization_v2")]
impl ApiEventMetric for tokenization::GenericTokenizationResponse {}
+
+#[cfg(feature = "tokenization_v2")]
+impl ApiEventMetric for tokenization::DeleteTokenDataResponse {}
+
+#[cfg(feature = "tokenization_v2")]
+impl ApiEventMetric for tokenization::DeleteTokenDataRequest {}
diff --git a/crates/api_models/src/tokenization.rs b/crates/api_models/src/tokenization.rs
index 131b0804fd..914a8110a6 100644
--- a/crates/api_models/src/tokenization.rs
+++ b/crates/api_models/src/tokenization.rs
@@ -1,5 +1,5 @@
use common_enums;
-use common_utils::id_type::{GlobalCustomerId, GlobalTokenId};
+use common_utils::id_type;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::{schema, ToSchema};
@@ -9,7 +9,7 @@ use utoipa::{schema, ToSchema};
pub struct GenericTokenizationResponse {
/// Unique identifier returned by the tokenization service
#[schema(value_type = String, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")]
- pub id: GlobalTokenId,
+ pub id: id_type::GlobalTokenId,
/// Created time of the tokenization id
#[schema(value_type = PrimitiveDateTime,example = "2024-02-24T11:04:09.922Z")]
pub created_at: PrimitiveDateTime,
@@ -22,8 +22,26 @@ pub struct GenericTokenizationResponse {
pub struct GenericTokenizationRequest {
/// Customer ID for which the tokenization is requested
#[schema(value_type = String, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")]
- pub customer_id: GlobalCustomerId,
+ pub customer_id: id_type::GlobalCustomerId,
/// Request for tokenization which contains the data to be tokenized
#[schema(value_type = Object,example = json!({ "city": "NY", "unit": "245" }))]
pub token_request: masking::Secret<serde_json::Value>,
}
+
+#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+pub struct DeleteTokenDataRequest {
+ /// Customer ID for which the tokenization is requested
+ #[schema(value_type = String, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")]
+ pub customer_id: id_type::GlobalCustomerId,
+ /// Session ID associated with the tokenization request
+ #[schema(value_type = String, example = "12345_pms_01926c58bc6e77c09e809964e72af8c8")]
+ pub session_id: id_type::GlobalPaymentMethodSessionId,
+}
+
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+pub struct DeleteTokenDataResponse {
+ /// Unique identifier returned by the tokenization service
+ #[schema(value_type = String, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")]
+ pub id: id_type::GlobalTokenId,
+}
diff --git a/crates/diesel_models/src/query/tokenization.rs b/crates/diesel_models/src/query/tokenization.rs
index 8f20b903d7..2991b89ecf 100644
--- a/crates/diesel_models/src/query/tokenization.rs
+++ b/crates/diesel_models/src/query/tokenization.rs
@@ -1,10 +1,12 @@
#[cfg(feature = "v2")]
use diesel::associations::HasTable;
+#[cfg(feature = "v2")]
+use diesel::ExpressionMethods;
#[cfg(feature = "v2")]
use crate::{
- query::generics, schema_v2::tokenization, tokenization as tokenization_diesel, PgPooledConn,
- StorageResult,
+ errors, query::generics, schema_v2::tokenization, tokenization as tokenization_diesel,
+ PgPooledConn, StorageResult,
};
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
@@ -17,11 +19,35 @@ impl tokenization_diesel::Tokenization {
conn: &PgPooledConn,
id: &common_utils::id_type::GlobalTokenId,
) -> StorageResult<Self> {
- use diesel::ExpressionMethods;
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
tokenization::dsl::id.eq(id.to_owned()),
)
.await
}
+
+ pub async fn update_with_id(
+ self,
+ conn: &PgPooledConn,
+ tokenization_record: tokenization_diesel::TokenizationUpdateInternal,
+ ) -> StorageResult<Self> {
+ match generics::generic_update_with_unique_predicate_get_result::<
+ <Self as HasTable>::Table,
+ _,
+ _,
+ _,
+ >(
+ conn,
+ tokenization::dsl::id.eq(self.id.to_owned()),
+ tokenization_record,
+ )
+ .await
+ {
+ Err(error) => match error.current_context() {
+ errors::DatabaseError::NoFieldsToUpdate => Ok(self),
+ _ => Err(error),
+ },
+ result => result,
+ }
+ }
}
diff --git a/crates/diesel_models/src/tokenization.rs b/crates/diesel_models/src/tokenization.rs
index e7ab2a4b13..62fecdcf5e 100644
--- a/crates/diesel_models/src/tokenization.rs
+++ b/crates/diesel_models/src/tokenization.rs
@@ -1,8 +1,12 @@
#[cfg(feature = "v2")]
use common_enums;
#[cfg(feature = "v2")]
+use common_utils::id_type;
+#[cfg(feature = "v2")]
use diesel::{AsChangeset, Identifiable, Insertable, Queryable};
#[cfg(feature = "v2")]
+use serde::{Deserialize, Serialize};
+#[cfg(feature = "v2")]
use time::PrimitiveDateTime;
#[cfg(feature = "v2")]
@@ -12,9 +16,9 @@ use crate::schema_v2::tokenization;
#[derive(Clone, Debug, Identifiable, Insertable, Queryable)]
#[diesel(table_name = tokenization)]
pub struct Tokenization {
- pub id: common_utils::id_type::GlobalTokenId,
- pub merchant_id: common_utils::id_type::MerchantId,
- pub customer_id: common_utils::id_type::GlobalCustomerId,
+ pub id: id_type::GlobalTokenId,
+ pub merchant_id: id_type::MerchantId,
+ pub customer_id: id_type::GlobalCustomerId,
pub created_at: PrimitiveDateTime,
pub updated_at: PrimitiveDateTime,
pub locker_id: String,
@@ -26,9 +30,9 @@ pub struct Tokenization {
#[derive(Clone, Debug, Insertable)]
#[diesel(table_name = tokenization)]
pub struct TokenizationNew {
- pub id: common_utils::id_type::GlobalTokenId,
- pub merchant_id: common_utils::id_type::MerchantId,
- pub customer_id: common_utils::id_type::GlobalCustomerId,
+ pub id: id_type::GlobalTokenId,
+ pub merchant_id: id_type::MerchantId,
+ pub customer_id: id_type::GlobalCustomerId,
pub locker_id: String,
pub created_at: PrimitiveDateTime,
pub updated_at: PrimitiveDateTime,
@@ -39,8 +43,7 @@ pub struct TokenizationNew {
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
#[derive(Clone, Debug, AsChangeset)]
#[diesel(table_name = tokenization)]
-pub struct TokenizationUpdate {
- pub updated_at: Option<PrimitiveDateTime>,
- pub version: Option<common_enums::enums::ApiVersion>,
+pub struct TokenizationUpdateInternal {
+ pub updated_at: PrimitiveDateTime,
pub flag: Option<common_enums::enums::TokenizationFlag>,
}
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 5b1732657a..cadfd62e37 100644
--- a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
+++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
@@ -319,6 +319,8 @@ pub enum ApiErrorResponse {
field_names: String,
connector_transaction_id: Option<String>,
},
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Tokenization record not found for the given token_id {id}")]
+ TokenizationRecordNotFound { id: String },
}
#[derive(Clone)]
@@ -705,6 +707,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon
Self::InvalidPlatformOperation => {
AER::Unauthorized(ApiError::new("IR", 44, "Invalid platform account operation", None))
}
+ Self::TokenizationRecordNotFound{ id } => {
+ AER::NotFound(ApiError::new("HE", 2, format!("Tokenization record not found for the given token_id '{id}' "), None))
+ }
}
}
}
diff --git a/crates/hyperswitch_domain_models/src/tokenization.rs b/crates/hyperswitch_domain_models/src/tokenization.rs
index 918e647b6c..20d283a5f1 100644
--- a/crates/hyperswitch_domain_models/src/tokenization.rs
+++ b/crates/hyperswitch_domain_models/src/tokenization.rs
@@ -1,6 +1,6 @@
use common_enums;
use common_utils::{
- self,
+ self, date_time,
errors::{CustomResult, ValidationError},
types::keymanager,
};
@@ -21,6 +21,12 @@ pub struct Tokenization {
pub version: common_enums::ApiVersion,
}
+impl Tokenization {
+ pub fn is_disabled(&self) -> bool {
+ self.flag == common_enums::TokenizationFlag::Disabled
+ }
+}
+
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TokenizationNew {
@@ -50,6 +56,14 @@ impl From<Tokenization> for TokenizationResponse {
}
}
+#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub enum TokenizationUpdate {
+ DeleteTokenizationRecordUpdate {
+ flag: Option<common_enums::enums::TokenizationFlag>,
+ },
+}
+
#[async_trait::async_trait]
impl super::behaviour::Conversion for Tokenization {
type DstType = diesel_models::tokenization::Tokenization;
@@ -99,3 +113,15 @@ impl super::behaviour::Conversion for Tokenization {
})
}
}
+
+impl From<TokenizationUpdate> for diesel_models::tokenization::TokenizationUpdateInternal {
+ fn from(value: TokenizationUpdate) -> Self {
+ let now = date_time::now();
+ match value {
+ TokenizationUpdate::DeleteTokenizationRecordUpdate { flag } => Self {
+ updated_at: now,
+ flag,
+ },
+ }
+ }
+}
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 2995375c01..69de6450c9 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -160,6 +160,7 @@ Never share your secret api keys. Keep them guarded and secure.
// Route for tokenization
routes::tokenization::create_token_vault_api,
+ routes::tokenization::delete_tokenized_data_api,
),
components(schemas(
common_utils::types::MinorUnit,
@@ -794,6 +795,8 @@ Never share your secret api keys. Keep them guarded and secure.
routes::payments::ForceSync,
api_models::tokenization::GenericTokenizationRequest,
api_models::tokenization::GenericTokenizationResponse,
+ api_models::tokenization::DeleteTokenDataRequest,
+ api_models::tokenization::DeleteTokenDataResponse,
)),
modifiers(&SecurityAddon)
)]
diff --git a/crates/openapi/src/routes/tokenization.rs b/crates/openapi/src/routes/tokenization.rs
index d69008911c..0e60862a28 100644
--- a/crates/openapi/src/routes/tokenization.rs
+++ b/crates/openapi/src/routes/tokenization.rs
@@ -34,3 +34,32 @@ use utoipa::OpenApi;
security(("ephemeral_key" = []),("api_key" = []))
)]
pub async fn create_token_vault_api() {}
+
+/// Tokenization - Delete
+///
+/// Delete a token entry with customer_id and session_id
+#[cfg(feature = "v2")]
+#[utoipa::path(
+ delete,
+ path = "/v2/tokenize/{id}",
+ request_body(
+ content = DeleteTokenDataRequest,
+ examples(("Delete a token entry with customer_id and session_id" = (
+ value = json!({
+ "customer_id": "12345_cus_0196d94b9c207333a297cbcf31f2e8c8",
+ "session_id": "12345_pms_01926c58bc6e77c09e809964e72af8c8",
+ })
+ )))
+ ),
+ responses(
+ (status = 200, description = "Token deleted successfully", body = DeleteTokenDataResponse),
+ (status = 400, description = "Invalid request"),
+ (status = 401, description = "Unauthorized"),
+ (status = 500, description = "Internal server error")
+ ),
+ tag = "Tokenization",
+ operation_id = "delete_tokenized_data_api",
+ security(("ephemeral_key" = []),("api_key" = []))
+)]
+
+pub async fn delete_tokenized_data_api() {}
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs
index 83f7fe6905..a30f8d4c56 100644
--- a/crates/router/src/compatibility/stripe/errors.rs
+++ b/crates/router/src/compatibility/stripe/errors.rs
@@ -693,6 +693,10 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {
errors::ApiErrorResponse::ProfileAcquirerNotFound { .. } => {
Self::ProfileAcquirerNotFound
}
+ errors::ApiErrorResponse::TokenizationRecordNotFound { id } => Self::ResourceMissing {
+ object: "tokenization record".to_owned(),
+ id,
+ },
}
}
}
diff --git a/crates/router/src/core/tokenization.rs b/crates/router/src/core/tokenization.rs
index 87d94dd9ee..b2b878e41c 100644
--- a/crates/router/src/core/tokenization.rs
+++ b/crates/router/src/core/tokenization.rs
@@ -1,6 +1,3 @@
-#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
-use std::sync::Arc;
-
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use actix_web::{web, HttpRequest, HttpResponse};
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
@@ -12,6 +9,7 @@ use common_utils::{
crypto::{DecodeMessage, EncodeMessage, GcmAes256},
errors::CustomResult,
ext_traits::{BytesExt, Encode, StringExt},
+ fp_utils::when,
id_type,
};
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
@@ -19,8 +17,6 @@ use error_stack::ResultExt;
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use hyperswitch_domain_models;
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
-use masking::{JsonMaskStrategy, Secret};
-#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use router_env::{instrument, logger, tracing, Flow};
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use serde::Serialize;
@@ -30,8 +26,8 @@ use crate::{
core::{
errors::{self, RouterResponse, RouterResult},
payment_methods::vault as pm_vault,
- tokenization,
},
+ db::errors::StorageErrorExt,
routes::{app::StorageInterface, AppState, SessionState},
services::{self, api as api_service, authentication as auth},
types::{api, domain, payment_methods as pm_types},
@@ -106,6 +102,79 @@ pub async fn create_vault_token_core(
))
}
+#[cfg(feature = "v2")]
+#[instrument(skip_all)]
+pub async fn delete_tokenized_data_core(
+ state: SessionState,
+ merchant_context: domain::MerchantContext,
+ token_id: &id_type::GlobalTokenId,
+ payload: api_models::tokenization::DeleteTokenDataRequest,
+) -> RouterResponse<api_models::tokenization::DeleteTokenDataResponse> {
+ let db = &*state.store;
+ let key_manager_state = &(&state).into();
+
+ // Retrieve the tokenization record
+ let tokenization_record = db
+ .get_entity_id_vault_id_by_token_id(
+ token_id,
+ merchant_context.get_merchant_key_store(),
+ key_manager_state,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::TokenizationRecordNotFound {
+ id: token_id.get_string_repr().to_string(),
+ })
+ .attach_printable("Failed to get tokenization record")?;
+
+ when(
+ tokenization_record.customer_id != payload.customer_id,
+ || {
+ Err(errors::ApiErrorResponse::UnprocessableEntity {
+ message: "Tokenization record does not belong to the customer".to_string(),
+ })
+ },
+ )?;
+
+ when(tokenization_record.is_disabled(), || {
+ Err(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "Tokenization is already disabled for the id".to_string(),
+ })
+ })?;
+
+ //fetch locker id
+ let vault_id = domain::VaultId::generate(tokenization_record.locker_id.clone());
+ //delete card from vault
+ pm_vault::delete_payment_method_data_from_vault_internal(
+ &state,
+ &merchant_context,
+ vault_id,
+ &tokenization_record.customer_id,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to delete payment method from vault")?;
+
+ //update the status with Disabled
+ let tokenization_update = hyperswitch_domain_models::tokenization::TokenizationUpdate::DeleteTokenizationRecordUpdate {
+ flag: Some(enums::TokenizationFlag::Disabled),
+ };
+ db.update_tokenization_record(
+ tokenization_record,
+ tokenization_update,
+ merchant_context.get_merchant_key_store(),
+ key_manager_state,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update tokenization record")?;
+
+ Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
+ api_models::tokenization::DeleteTokenDataResponse {
+ id: token_id.clone(),
+ },
+ ))
+}
+
#[instrument(skip_all)]
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
pub async fn get_token_vault_core(
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index ed9d140d22..43be476f68 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -4289,6 +4289,24 @@ impl TokenizationInterface for KafkaStore {
.get_entity_id_vault_id_by_token_id(token, merchant_key_store, key_manager_state)
.await
}
+
+ async fn update_tokenization_record(
+ &self,
+ tokenization: hyperswitch_domain_models::tokenization::Tokenization,
+ tokenization_update: hyperswitch_domain_models::tokenization::TokenizationUpdate,
+ merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
+ key_manager_state: &KeyManagerState,
+ ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>
+ {
+ self.diesel_store
+ .update_tokenization_record(
+ tokenization,
+ tokenization_update,
+ merchant_key_store,
+ key_manager_state,
+ )
+ .await
+ }
}
#[cfg(not(all(feature = "v2", feature = "tokenization_v2")))]
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 91f35de891..01455e9e17 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1502,11 +1502,16 @@ pub struct Tokenization;
#[cfg(all(feature = "v2", feature = "oltp"))]
impl Tokenization {
pub fn server(state: AppState) -> Scope {
- let mut token_route = web::scope("/v2/tokenize").app_data(web::Data::new(state));
- token_route = token_route.service(
- web::resource("").route(web::post().to(tokenization_routes::create_token_vault_api)),
- );
- token_route
+ web::scope("/v2/tokenize")
+ .app_data(web::Data::new(state))
+ .service(
+ web::resource("")
+ .route(web::post().to(tokenization_routes::create_token_vault_api)),
+ )
+ .service(
+ web::resource("/{id}")
+ .route(web::delete().to(tokenization_routes::delete_tokenized_data_api)),
+ )
}
}
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 67943da57f..62d6521105 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -373,7 +373,9 @@ impl From<Flow> for ApiIdentifier {
Flow::ProfileAcquirerCreate | Flow::ProfileAcquirerUpdate => Self::ProfileAcquirer,
Flow::ThreeDsDecisionRuleExecute => Self::ThreeDsDecisionRule,
- Flow::TokenizationCreate | Flow::TokenizationRetrieve => Self::GenericTokenization,
+ Flow::TokenizationCreate | Flow::TokenizationRetrieve | Flow::TokenizationDelete => {
+ Self::GenericTokenization
+ }
}
}
}
diff --git a/crates/router/src/routes/tokenization.rs b/crates/router/src/routes/tokenization.rs
index 6becca19df..cf74d8dd06 100644
--- a/crates/router/src/routes/tokenization.rs
+++ b/crates/router/src/routes/tokenization.rs
@@ -72,3 +72,42 @@ pub async fn create_token_vault_api(
))
.await
}
+
+#[instrument(skip_all, fields(flow = ?Flow::TokenizationDelete))]
+#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
+pub async fn delete_tokenized_data_api(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<id_type::GlobalTokenId>,
+ json_payload: web::Json<api_models::tokenization::DeleteTokenDataRequest>,
+) -> HttpResponse {
+ let flow = Flow::TokenizationDelete;
+ let payload = json_payload.into_inner();
+ let session_id = payload.session_id.clone();
+ let token_id = path.into_inner();
+
+ Box::pin(api_service::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: auth::AuthenticationData, req, _| {
+ let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
+ domain::Context(auth.merchant_account, auth.key_store),
+ ));
+ tokenization::delete_tokenized_data_core(state, merchant_context, &token_id, req)
+ },
+ auth::api_or_client_auth(
+ &auth::V2ApiKeyAuth {
+ is_connected_allowed: false,
+ is_platform_allowed: false,
+ },
+ &auth::V2ClientAuth(
+ common_utils::types::authentication::ResourceId::PaymentMethodSession(session_id),
+ ),
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index de402b026f..e6651c3c52 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -642,6 +642,8 @@ pub enum Flow {
DecisionEngineGatewayFeedbackCall,
/// Recovery payments create flow.
RecoveryPaymentsCreate,
+ /// Tokenization delete flow
+ TokenizationDelete,
}
/// Trait for providing generic behaviour to flow metric
diff --git a/crates/storage_impl/src/tokenization.rs b/crates/storage_impl/src/tokenization.rs
index 9a824e9126..8fd299e79f 100644
--- a/crates/storage_impl/src/tokenization.rs
+++ b/crates/storage_impl/src/tokenization.rs
@@ -1,6 +1,8 @@
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState};
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
+use diesel_models::tokenization as tokenization_diesel;
+#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use error_stack::{report, ResultExt};
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use hyperswitch_domain_models::{
@@ -32,6 +34,14 @@ pub trait TokenizationInterface {
merchant_key_store: &MerchantKeyStore,
key_manager_state: &KeyManagerState,
) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>;
+
+ async fn update_tokenization_record(
+ &self,
+ tokenization: hyperswitch_domain_models::tokenization::Tokenization,
+ tokenization_update: hyperswitch_domain_models::tokenization::TokenizationUpdate,
+ merchant_key_store: &MerchantKeyStore,
+ key_manager_state: &KeyManagerState,
+ ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>;
}
#[async_trait::async_trait]
@@ -71,7 +81,7 @@ impl<T: DatabaseStore> TokenizationInterface for RouterStore<T> {
{
let conn = connection::pg_connection_read(self).await?;
- let tokenization = diesel_models::tokenization::Tokenization::find_by_id(&conn, token)
+ let tokenization = tokenization_diesel::Tokenization::find_by_id(&conn, token)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?;
@@ -86,6 +96,30 @@ impl<T: DatabaseStore> TokenizationInterface for RouterStore<T> {
Ok(domain)
}
+
+ async fn update_tokenization_record(
+ &self,
+ tokenization_record: hyperswitch_domain_models::tokenization::Tokenization,
+ tokenization_update: hyperswitch_domain_models::tokenization::TokenizationUpdate,
+ merchant_key_store: &MerchantKeyStore,
+ key_manager_state: &KeyManagerState,
+ ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>
+ {
+ let conn = connection::pg_connection_write(self).await?;
+
+ let tokenization_record = Conversion::convert(tokenization_record)
+ .await
+ .change_context(errors::StorageError::DecryptionError)?;
+ self.call_database(
+ key_manager_state,
+ merchant_key_store,
+ tokenization_record.update_with_id(
+ &conn,
+ tokenization_diesel::TokenizationUpdateInternal::from(tokenization_update),
+ ),
+ )
+ .await
+ }
}
#[async_trait::async_trait]
@@ -114,6 +148,24 @@ impl<T: DatabaseStore> TokenizationInterface for KVRouterStore<T> {
.get_entity_id_vault_id_by_token_id(token, merchant_key_store, key_manager_state)
.await
}
+
+ async fn update_tokenization_record(
+ &self,
+ tokenization_record: hyperswitch_domain_models::tokenization::Tokenization,
+ tokenization_update: hyperswitch_domain_models::tokenization::TokenizationUpdate,
+ merchant_key_store: &MerchantKeyStore,
+ key_manager_state: &KeyManagerState,
+ ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>
+ {
+ self.router_store
+ .update_tokenization_record(
+ tokenization_record,
+ tokenization_update,
+ merchant_key_store,
+ key_manager_state,
+ )
+ .await
+ }
}
#[async_trait::async_trait]
@@ -137,6 +189,17 @@ impl TokenizationInterface for MockDb {
{
Err(errors::StorageError::MockDbError)?
}
+
+ async fn update_tokenization_record(
+ &self,
+ tokenization_record: hyperswitch_domain_models::tokenization::Tokenization,
+ tokenization_update: hyperswitch_domain_models::tokenization::TokenizationUpdate,
+ merchant_key_store: &MerchantKeyStore,
+ key_manager_state: &KeyManagerState,
+ ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>
+ {
+ Err(errors::StorageError::MockDbError)?
+ }
}
#[cfg(not(all(feature = "v2", feature = "tokenization_v2")))]