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): Add cvc token PM V2 APIs (#10787)
Sarthak Soni4df077919dc8
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex e808c04fae..d59f5ae31a 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -8176,6 +8176,26 @@}}},+ "CardCVCTokenStorageDetails": {+ "type": "object",+ "required": [+ "is_stored"+ ],+ "properties": {+ "is_stored": {+ "type": "boolean",+ "description": "Indicates whether the card cvc is stored or not",+ "example": true+ },+ "expires_at": {+ "type": "string",+ "format": "date-time",+ "description": "A timestamp (ISO 8601 code) that determines expiry for stored card cvc token",+ "example": "2024-02-24T11:04:09.922Z",+ "nullable": true+ }+ }+ },"CardDetail": {"type": "object","required": [@@ -8324,6 +8344,12 @@"description": "Card Holder's Nick Name","example": "John Doe","nullable": true+ },+ "card_cvc": {+ "type": "string",+ "description": "The CVC number for the card",+ "example": "242",+ "nullable": true}},"additionalProperties": false@@ -10535,8 +10561,7 @@"CustomerPaymentMethodResponseItem": {"type": "object","required": [- "id",- "payment_token",+ "payment_method_token","customer_id","payment_method_type","payment_method_subtype",@@ -10547,12 +10572,7 @@"is_default"],"properties": {- "id": {- "type": "string",- "description": "The unique identifier of the payment method.",- "example": "12345_pm_01926c58bc6e77c09e809964e72af8c8"- },- "payment_token": {+ "payment_method_token": {"type": "string","description": "Temporary Token for payment method in vault which gets refreshed for every payment","example": "7ebf443f-a050-4067-84e5-e6f6d4800aef"@@ -19516,6 +19536,14 @@}],"nullable": true+ },+ "card_cvc_token_storage": {+ "allOf": [+ {+ "$ref": "#/components/schemas/CardCVCTokenStorageDetails"+ }+ ],+ "nullable": true}}},@@ -19827,6 +19855,14 @@}],"nullable": true+ },+ "card_cvc_token_storage": {+ "allOf": [+ {+ "$ref": "#/components/schemas/CardCVCTokenStorageDetails"+ }+ ],+ "nullable": true}}},@@ -19838,13 +19874,13 @@{"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 session",+ "example": "token_9wcXDRVkfEtLEsSnYKgQ"}}}diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex 4643f8c447..a432a8d656 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -871,6 +871,10 @@ pub struct CardDetailUpdate {/// Card Holder's Nick Name#[schema(value_type = Option<String>,example = "John Doe")]pub nick_name: Option<masking::Secret<String>>,++ /// The CVC number for the card+ #[schema(value_type = Option<String>, example = "242")]+ pub card_cvc: Option<masking::Secret<String>>,}#[cfg(feature = "v2")]@@ -1117,6 +1121,34 @@ pub struct PaymentMethodResponse {/// The storage type for the payment method#[schema(value_type = Option<StorageType>)]pub storage_type: Option<common_enums::StorageType>,++ /// Card CVC token storage details+ pub card_cvc_token_storage: Option<CardCVCTokenStorageDetails>,+}++#[cfg(feature = "v2")]+#[derive(Clone, Copy, Debug, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]+pub struct CardCVCTokenStorageDetails {+ /// Indicates whether the card cvc is stored or not+ #[schema(example = true)]+ pub is_stored: bool,++ /// A timestamp (ISO 8601 code) that determines expiry for stored card cvc token+ #[schema(value_type = Option<PrimitiveDateTime>, example = "2024-02-24T11:04:09.922Z")]+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]+ pub expires_at: Option<time::PrimitiveDateTime>,+}++#[cfg(feature = "v2")]+impl CardCVCTokenStorageDetails {+ pub fn generate_expiry_timestamp(duration_in_secs: i64) -> Self {+ let current_time = common_utils::date_time::now();+ let expiry_time = current_time + time::Duration::seconds(duration_in_secs);+ Self {+ is_stored: true,+ expires_at: Some(expiry_time),+ }+ }}#[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)]@@ -2448,13 +2480,9 @@ pub struct PaymentMethodResponseItem {#[cfg(feature = "v2")]#[derive(Debug, Clone, serde::Serialize, ToSchema)]pub struct CustomerPaymentMethodResponseItem {- /// The unique identifier of the payment method.- #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")]- pub id: id_type::GlobalPaymentMethodId,-/// Temporary Token for payment method in vault which gets refreshed for every payment#[schema(example = "7ebf443f-a050-4067-84e5-e6f6d4800aef")]- pub payment_token: String,+ pub payment_method_token: String,/// The unique identifier of the customer.#[schema(@@ -3379,10 +3407,9 @@ pub struct PaymentMethodsSessionUpdateRequest {#[cfg(feature = "v2")]#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)]pub struct PaymentMethodSessionUpdateSavedPaymentMethod {- /// 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 session+ #[schema(value_type = String, example = "token_9wcXDRVkfEtLEsSnYKgQ")]+ pub payment_method_token: String,/// The update request for the payment method update#[serde(flatten)]pub payment_method_update_request: PaymentMethodUpdate,@@ -3470,7 +3497,8 @@ pub struct PaymentMethodSessionResponse {/// The payment method that was created using this payment method session#[schema(value_type = Option<Vec<String>>)]- pub associated_payment_methods: Option<Vec<String>>,+ pub associated_payment_methods:+ Option<Vec<common_types::payment_methods::AssociatedPaymentMethods>>,/// The token-id created if there is tokenization_data present#[schema(value_type = Option<String>, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")]@@ -3479,6 +3507,10 @@ pub struct PaymentMethodSessionResponse {/// The storage type for the payment method#[schema(value_type = Option<StorageType>)]pub storage_type: Option<common_enums::StorageType>,++ /// Card CVC token storage details+ #[schema(value_type = Option<CardCVCTokenStorageDetails>)]+ pub card_cvc_token_storage: Option<CardCVCTokenStorageDetails>,}#[cfg(feature = "v2")]diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex fb5b54d0fb..b69ad4caea 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -3282,6 +3282,15 @@ pub struct PaymentMethodDataRequest {pub billing: Option<Address>,}+impl PaymentMethodDataRequest {+ pub fn get_card(&self) -> Option<Card> {+ match &self.payment_method_data {+ Some(PaymentMethodData::Card(card)) => Some(card.clone()),+ _ => None,+ }+ }+}+#[cfg(feature = "v2")]#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]pub struct SplitPaymentMethodDataRequest {diff --git a/crates/common_types/src/payment_methods.rs b/crates/common_types/src/payment_methods.rsindex eff2a101eb..341a9c2113 100644--- a/crates/common_types/src/payment_methods.rs+++ b/crates/common_types/src/payment_methods.rs@@ -265,3 +265,19 @@ pub struct PspTokenization {#[schema(value_type = String)]pub connector_id: common_utils::id_type::MerchantConnectorAccountId,}++/// Token type for Payment Method Session associated payment methods+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)]+#[serde(tag = "type", content = "data", rename_all = "snake_case")]+pub enum AssociatedPaymentMethodTokenType {+ /// Payment Method Session Token+ #[schema(value_type = String)]+ PaymentMethodSessionToken(String),+}++/// Details of associated payment methods for Payment Methods Session+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)]+pub struct AssociatedPaymentMethods {+ /// token type for associated payment method+ pub payment_method_token: AssociatedPaymentMethodTokenType,+}diff --git a/crates/diesel_models/src/payment_methods_session.rs b/crates/diesel_models/src/payment_methods_session.rsindex 05a20ffd19..349012a6c1 100644--- a/crates/diesel_models/src/payment_methods_session.rs+++ b/crates/diesel_models/src/payment_methods_session.rs@@ -12,7 +12,8 @@ pub struct PaymentMethodSession {pub return_url: Option<common_utils::types::Url>,#[serde(with = "common_utils::custom_serde::iso8601")]pub expires_at: time::PrimitiveDateTime,- pub associated_payment_methods: Option<Vec<String>>,+ pub associated_payment_methods:+ Option<Vec<common_types::payment_methods::AssociatedPaymentMethods>>,pub associated_payment: Option<common_utils::id_type::GlobalPaymentId>,pub associated_token_id: Option<common_utils::id_type::GlobalTokenId>,}diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rsindex 7eb54a03d3..a443a052c6 100644--- a/crates/hyperswitch_domain_models/src/payment_methods.rs+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs@@ -753,7 +753,8 @@ pub struct PaymentMethodSession {pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,pub tokenization_data: Option<pii::SecretSerdeValue>,pub expires_at: PrimitiveDateTime,- pub associated_payment_methods: Option<Vec<String>>,+ pub associated_payment_methods:+ Option<Vec<common_types::payment_methods::AssociatedPaymentMethods>>,pub associated_payment: Option<id_type::GlobalPaymentId>,pub associated_token_id: Option<id_type::GlobalTokenId>,}@@ -994,7 +995,8 @@ pub enum PaymentMethodsSessionUpdateEnum {tokenization_data: Option<pii::SecretSerdeValue>,},UpdateAssociatedPaymentMethods {- associated_payment_methods: Option<Vec<String>>,+ associated_payment_methods:+ Option<Vec<common_types::payment_methods::AssociatedPaymentMethods>>,},}@@ -1067,7 +1069,8 @@ pub struct PaymentMethodsSessionUpdateInternal {pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>,pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,pub tokenization_data: Option<pii::SecretSerdeValue>,- pub associated_payment_methods: Option<Vec<String>>,+ pub associated_payment_methods:+ Option<Vec<common_types::payment_methods::AssociatedPaymentMethods>>,}#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]diff --git a/crates/hyperswitch_domain_models/src/vault.rs b/crates/hyperswitch_domain_models/src/vault.rsindex a8cf15f949..38783ca64e 100644--- a/crates/hyperswitch_domain_models/src/vault.rs+++ b/crates/hyperswitch_domain_models/src/vault.rs@@ -102,7 +102,12 @@ impl TryFrom<payment_methods::PaymentMethodCreateData> for PaymentMethodVaultingtype Error = error_stack::Report<errors::api_error_response::ApiErrorResponse>;fn try_from(item: payment_methods::PaymentMethodCreateData) -> Result<Self, Self::Error> {match item {- payment_methods::PaymentMethodCreateData::Card(card) => Ok(Self::Card(card)),+ payment_methods::PaymentMethodCreateData::Card(card) => {+ Ok(Self::Card(payment_methods::CardDetail {+ card_cvc: None, // card cvc should not be used for vaulting+ ..card+ }))+ }payment_methods::PaymentMethodCreateData::ProxyCard(card) => Err(errors::api_error_response::ApiErrorResponse::UnprocessableEntity {message: "Proxy Card for PaymentMethodCreateData".to_string(),diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rsindex e37cac17a4..89190b9cd2 100644--- a/crates/openapi/src/openapi_v2.rs+++ b/crates/openapi/src/openapi_v2.rs@@ -639,6 +639,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payment_methods::TokenizeCardRequest,api_models::payment_methods::TokenizeDataRequest,api_models::payment_methods::TokenizePaymentMethodRequest,+ api_models::payment_methods::CardCVCTokenStorageDetails,api_models::refunds::RefundListRequest,api_models::refunds::RefundListResponse,api_models::payments::AmountFilter,diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex 706cf4b7a6..beebe667f0 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -1178,6 +1178,7 @@ pub async fn create_payment_method_card_core(&payment_method,&None,req.storage_type,+ None,req.customer_id,)?;@@ -1307,6 +1308,7 @@ pub async fn create_volatile_payment_method_card_core(&domain_payment_method,&None,req.storage_type,+ None,req.customer_id,)?;@@ -1416,6 +1418,7 @@ pub async fn create_payment_method_proxy_card_core(&payment_method,&None,req.storage_type,+ None,req.customer_id,)?;@@ -1806,6 +1809,7 @@ pub async fn payment_method_intent_create(&payment_method,&None,None,+ None,Some(customer_id),)?;@@ -1856,13 +1860,40 @@ pub async fn list_payment_methods_for_session(.attach_printable("error when fetching merchant connector accounts")?;let customer_payment_methods = match payment_method_session.customer_id {- Some(customer_id) => {- list_customer_payment_methods_core(&state, platform.get_provider(), &customer_id)- .await?+ Some(ref customer_id) => {+ list_customer_payment_methods_core(&state, platform.get_provider(), customer_id).await?}None => Vec::new(),};+ // Create associated payment methods from customer payment methods+ let associated_payment_methods_vec: Vec<common_types::payment_methods::AssociatedPaymentMethods> = customer_payment_methods+ .iter()+ .map(|cpm| {+ common_types::payment_methods::AssociatedPaymentMethods {+ payment_method_token: common_types::payment_methods::AssociatedPaymentMethodTokenType::PaymentMethodSessionToken(cpm.payment_method_token.clone()),+ }+ })+ .collect();++ // Update payment method session with associated payment methods+ let update_payment_method_session = hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum::UpdateAssociatedPaymentMethods {+ associated_payment_methods: Some(associated_payment_methods_vec.clone())+ };++ let updated_payment_method_session = db+ .update_payment_method_session(+ platform.get_provider().get_key_store(),+ &payment_method_session_id,+ update_payment_method_session,+ payment_method_session,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to update payment method session with associated payment methods",+ )?;+let response =hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled::from_payment_connectors_list(payment_connector_accounts).perform_filtering()@@ -2351,8 +2382,7 @@ pub async fn get_external_vault_token() -> CustomResult<domain::ExternalVaultPaymentMethodData, errors::ApiErrorResponse> {let db = &*state.store;- let pm_token_data =- utils::retrieve_payment_token_data(state, payment_token, Some(payment_method_type)).await?;+ let pm_token_data = utils::retrieve_payment_token_data(state, payment_token).await?;let payment_method_id = match pm_token_data {storage::PaymentTokenData::PermanentCard(card_token_data) => {@@ -3233,6 +3263,7 @@ pub async fn retrieve_payment_method(&payment_method,&single_use_token_in_cache,Some(common_enums::StorageType::Persistent),+ None,payment_method.customer_id.clone(),).map(services::ApplicationResponse::Json)@@ -3328,9 +3359,12 @@ pub async fn update_payment_method_core(.attach_printable("Failed to retrieve payment method from vault")?.data;- let vault_request_data = request.payment_method_data.map(|payment_method_data| {- pm_transforms::generate_pm_vaulting_req_from_update_request(pmd, payment_method_data)- });+ let vault_request_data = request+ .payment_method_data+ .clone()+ .map(|payment_method_data| {+ pm_transforms::generate_pm_vaulting_req_from_update_request(pmd, payment_method_data)+ });let vaulting_response = match vault_request_data {// cannot use async map because of problems related to lifetimes@@ -3397,6 +3431,7 @@ pub async fn update_payment_method_core(&payment_method,&None,Some(common_enums::StorageType::Persistent),+ None,payment_method.customer_id.clone(),)?;@@ -3686,6 +3721,7 @@ pub async fn payment_methods_session_create(None,None,None,+ None,);Ok(services::ApplicationResponse::Json(response))@@ -3751,6 +3787,7 @@ pub async fn payment_methods_session_update(None, // TODO: send associated payments response based on the expandable paramNone,None,+ None,);Ok(services::ApplicationResponse::Json(response))@@ -3771,12 +3808,35 @@ pub async fn payment_methods_session_retrieve(}).attach_printable("Failed to retrieve payment methods session from db")?;+ let associated_pm_token = payment_method_session_domain_model+ .associated_payment_methods+ .as_ref()+ .and_then(|payment_methods| {+ payment_methods.iter().map(|pm| match &pm.payment_method_token {+ common_types::payment_methods::AssociatedPaymentMethodTokenType::PaymentMethodSessionToken(token) => token.clone(),+ }).next()+ });++ let expiry = associated_pm_token+ .async_map(|token_string| {+ vault::retrieve_key_and_ttl_for_cvc_from_payment_method_token(&state, token_string)+ })+ .await+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to retrieve cvc from redis")+ .ok()+ .flatten();+let response = transformers::generate_payment_method_session_response(payment_method_session_domain_model,Secret::new("CLIENT_SECRET_REDACTED".to_string()),None, // TODO: send associated payments response based on the expandable paramNone,None,+ expiry.map(|time| {+ payment_methods::CardCVCTokenStorageDetails::generate_expiry_timestamp(time)+ }),);Ok(services::ApplicationResponse::Json(response))@@ -3789,33 +3849,112 @@ pub async fn payment_methods_session_update_payment_method(profile: domain::Profile,payment_method_session_id: id_type::GlobalPaymentMethodSessionId,request: payment_methods::PaymentMethodSessionUpdateSavedPaymentMethod,-) -> RouterResponse<payment_methods::PaymentMethodResponse> {+) -> RouterResponse<payment_methods::PaymentMethodSessionResponse> {let db = state.store.as_ref();// Validate if the session still exists- db.get_payment_methods_session(- platform.get_provider().get_key_store(),- &payment_method_session_id,- )- .await- .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {- message: "payment methods session does not exist or has expired".to_string(),- })- .attach_printable("Failed to retrieve payment methods session from db")?;+ let payment_method_session = db+ .get_payment_methods_session(+ platform.get_provider().get_key_store(),+ &payment_method_session_id,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {+ message: "payment methods session does not exist or has expired".to_string(),+ })+ .attach_printable("Failed to retrieve payment methods session from db")?;- let payment_method_update_request = request.payment_method_update_request;+ // Get the associated_pm_token_details for the payment_method_token from the request+ let associated_pm_token_details = payment_method_session+ .associated_payment_methods+ .as_ref()+ .and_then(|payment_methods| {+ payment_methods.iter().find(|pm| match &pm.payment_method_token {+ common_types::payment_methods::AssociatedPaymentMethodTokenType::PaymentMethodSessionToken(token) => token == &request.payment_method_token+ })+ })+ .ok_or(errors::ApiErrorResponse::GenericNotFoundError {+ 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 updated_payment_method = Box::pin(update_payment_method_core(+ let payment_method_update_request = request.payment_method_update_request.clone();++ Box::pin(update_payment_method_core(&state,&platform,&profile,payment_method_update_request,- &request.payment_method_id,+ &payment_method_id,)).await.attach_printable("Failed to update saved payment method")?;- Ok(services::ApplicationResponse::Json(updated_payment_method))+ // Update payment method session with associated payment methods+ let update_payment_method_session = hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum::UpdateAssociatedPaymentMethods {+ associated_payment_methods: Some(vec![associated_pm_token_details.clone()])+ };++ let updated_payment_method_session = db+ .update_payment_method_session(+ platform.get_provider().get_key_store(),+ &payment_method_session_id,+ update_payment_method_session,+ payment_method_session,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "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+ };++ let response = transformers::generate_payment_method_session_response(+ updated_payment_method_session,+ Secret::new("CLIENT_SECRET_REDACTED".to_string()),+ None, // TODO: send associated payments response based on the expandable param+ None,+ None,+ card_cvc_token,+ );++ Ok(services::ApplicationResponse::Json(response))}#[cfg(feature = "v2")]@@ -3993,6 +4132,24 @@ pub async fn payment_methods_session_confirm(let intent_fulfillment_time = common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME;+ let card_cvc = request+ .payment_method_data+ .get_card()+ .map(|card| card.card_cvc.clone());++ let cvc_expiry_details = card_cvc+ .async_map(|cvc| {+ vault::insert_cvc_using_payment_token(+ &state,+ &parent_payment_method_token,+ cvc,+ intent_fulfillment_time,+ platform.get_provider().get_key_store(),+ )+ })+ .await+ .transpose()?;+// insert the token data into redisif let Some(token_data) = token_data {pm_routes::ParentPaymentMethodToken::create_key_for_token(&parent_payment_method_token)@@ -4000,19 +4157,13 @@ pub async fn payment_methods_session_confirm(.await?;};- let update_payment_method_session = hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum::UpdateAssociatedPaymentMethods {- associated_payment_methods: Some(vec![parent_payment_method_token.clone()])+ let associated_payment_methods = common_types::payment_methods::AssociatedPaymentMethods {+ payment_method_token: common_types::payment_methods::AssociatedPaymentMethodTokenType::PaymentMethodSessionToken(parent_payment_method_token),};- vault::insert_cvc_using_payment_token(- &state,- &parent_payment_method_token,- create_payment_method_request.payment_method_data.clone(),- request.payment_method_type,- intent_fulfillment_time,- platform.get_provider().get_key_store().key.get_inner(),- )- .await?;+ let update_payment_method_session = hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum::UpdateAssociatedPaymentMethods {+ associated_payment_methods: Some(vec![associated_payment_methods])+ };let payment_method_session = db.update_payment_method_session(@@ -4099,6 +4250,7 @@ pub async fn payment_methods_session_confirm(payments_response,(tokenization_response.flatten()),payment_method_response.storage_type,+ cvc_expiry_details,);Ok(services::ApplicationResponse::Json(diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rsindex 713a9e1d02..148fbb60dd 100644--- a/crates/router/src/core/payment_methods/transformers.rs+++ b/crates/router/src/core/payment_methods/transformers.rs@@ -540,6 +540,7 @@ pub fn generate_payment_method_response(payment_method: &domain::PaymentMethod,single_use_token: &Option<payment_method_data::SingleUsePaymentMethodToken>,storage_type: Option<common_enums::StorageType>,+ card_cvc_token_storage: Option<api_models::payment_methods::CardCVCTokenStorageDetails>,customer_id: Option<id_type::GlobalCustomerId>,) -> errors::RouterResult<api::PaymentMethodResponse> {let pmd = payment_method@@ -603,6 +604,7 @@ pub fn generate_payment_method_response(connector_tokens,network_token,storage_type,+ card_cvc_token_storage,};Ok(resp)@@ -838,7 +840,6 @@ impl transformers::ForeignTryFrom<(domain::PaymentMethod, String)>let recurring_enabled = true;Ok(Self {- id: item.id,customer_id: item.customer_id.get_required_value("GlobalCustomerId")@@ -855,7 +856,7 @@ impl transformers::ForeignTryFrom<(domain::PaymentMethod, String)>requires_cvv: true,is_default: false,billing: payment_method_billing,- payment_token,+ payment_method_token: payment_token,})}}@@ -959,6 +960,7 @@ pub fn generate_payment_method_session_response(associated_payment: Option<api_models::payments::PaymentsResponse>,tokenization_service_response: Option<api_models::tokenization::GenericTokenizationResponse>,storage_type: Option<common_enums::StorageType>,+ card_cvc_token_storage: Option<api_models::payment_methods::CardCVCTokenStorageDetails>,) -> api_models::payment_methods::PaymentMethodSessionResponse {let next_action = associated_payment.as_ref()@@ -994,6 +996,7 @@ pub fn generate_payment_method_session_response(authentication_details,associated_token_id: token_id,storage_type,+ card_cvc_token_storage,}}diff --git a/crates/router/src/core/payment_methods/utils.rs b/crates/router/src/core/payment_methods/utils.rsindex fee1ad11d9..7518f967ab 100644--- a/crates/router/src/core/payment_methods/utils.rs+++ b/crates/router/src/core/payment_methods/utils.rs@@ -852,7 +852,6 @@ pub async fn get_sdk_next_action_for_payment_method_list(pub(super) async fn retrieve_payment_token_data(state: &SessionState,token: String,- payment_method: Option<&storage_enums::PaymentMethod>,) -> errors::RouterResult<storage::PaymentTokenData> {let redis_conn = state.storediff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rsindex 14ff021fae..0ae3a64d8e 100644--- a/crates/router/src/core/payment_methods/vault.rs+++ b/crates/router/src/core/payment_methods/vault.rs@@ -40,7 +40,7 @@ use crate::{use crate::{core::{errors::StorageErrorExt,- payment_methods::{transformers as pm_transforms, utils},+ payment_methods::{cards as pm_cards, transformers as pm_transforms, utils},payments::{self as payments_core, helpers as payment_helpers},},headers, settings,@@ -1720,12 +1720,8 @@ pub async fn retrieve_payment_method_from_vault_using_payment_token(payment_token: &String,payment_method_type: &common_enums::PaymentMethod,) -> RouterResult<(domain::PaymentMethod, domain::PaymentMethodVaultingData)> {- let pm_token_data = utils::retrieve_payment_token_data(- state,- payment_token.to_string(),- Some(payment_method_type),- )- .await?;+ let pm_token_data =+ utils::retrieve_payment_token_data(state, payment_token.to_string()).await?;let payment_method_id = match pm_token_data {storage::PaymentTokenData::PermanentCard(card_token_data) => {@@ -1777,50 +1773,52 @@ pub struct TemporaryVaultCvc {#[instrument(skip_all)]pub async fn insert_cvc_using_payment_token(state: &routes::SessionState,- payment_token: &String,- payment_method_data: api_models::payment_methods::PaymentMethodCreateData,- payment_method: common_enums::PaymentMethod,+ payment_method_token: &String,+ card_cvc: masking::Secret<String>,fulfillment_time: i64,- encryption_key: &masking::Secret<Vec<u8>>,-) -> RouterResult<()> {- let card_cvc = domain::PaymentMethodVaultingData::try_from(payment_method_data)?- .get_card()- .and_then(|card| card.card_cvc.clone());-- if let Some(card_cvc) = card_cvc {- let redis_conn = state- .store- .get_redis_conn()- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to get redis connection")?;-- let key = format!("pm_token_{payment_token}_hyperswitch_cvc");+ key_store: &domain::MerchantKeyStore,+) -> RouterResult<api_models::payment_methods::CardCVCTokenStorageDetails> {+ let redis_conn = state+ .store+ .get_redis_conn()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to get redis connection")?;- let payload_to_be_encrypted = TemporaryVaultCvc { card_cvc };+ let key = format!("pm_token_{payment_method_token}_hyperswitch_cvc");- let payload = payload_to_be_encrypted- .encode_to_string_of_json()- .change_context(errors::ApiErrorResponse::InternalServerError)?;+ let payload_to_be_encrypted = TemporaryVaultCvc { card_cvc };- // Encrypt the CVC and store it in Redis- let encrypted_payload = GcmAes256- .encode_message(encryption_key.peek().as_ref(), payload.as_bytes())- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to encode TemporaryVaultCvc for vault")?;+ let payload = payload_to_be_encrypted+ .encode_to_string_of_json()+ .change_context(errors::ApiErrorResponse::InternalServerError)?;- redis_conn- .set_key_if_not_exists_with_expiry(- &key.as_str().into(),- bytes::Bytes::from(encrypted_payload),- Some(fulfillment_time),- )+ // Encrypt the CVC and store it in Redis+ let encrypted_payload =+ pm_cards::create_encrypted_data(&(state.into()), key_store, payload.as_bytes()).await- .change_context(errors::StorageError::KVError).change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to add token in redis")?;- };+ .attach_printable("Failed to encrypt TemporaryVaultCvc for vault")?+ .encode_to_vec()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to encode TemporaryVaultCvc to bytes for vault")?;- Ok(())+ redis_conn+ .set_key_with_expiry(+ &key.as_str().into(),+ bytes::Bytes::from(encrypted_payload),+ fulfillment_time,+ )+ .await+ .change_context(errors::StorageError::KVError)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to add encrypted cvc in redis")?;++ let card_token_cvc_storage =+ api_models::payment_methods::CardCVCTokenStorageDetails::generate_expiry_timestamp(+ fulfillment_time,+ );++ Ok(card_token_cvc_storage)}#[cfg(feature = "v2")]@@ -1867,6 +1865,36 @@ pub async fn retrieve_and_delete_cvc_from_payment_token(Ok(cvc_data.card_cvc)}+#[cfg(feature = "v2")]+#[instrument(skip_all)]+pub async fn retrieve_key_and_ttl_for_cvc_from_payment_method_token(+ state: &routes::SessionState,+ payment_method_token: String,+) -> RouterResult<i64> {+ let redis_conn = state+ .store+ .get_redis_conn()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to get redis connection")?;++ let key = format!("pm_token_{payment_method_token}_hyperswitch_cvc",);++ // check if key exists and get ttl+ redis_conn+ .get_key::<bytes::Bytes>(&key.clone().into())+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to fetch the payment_method_token from redis")?;++ let ttl = redis_conn+ .get_ttl(&key.clone().into())+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to fetch the payment_method_token ttl from redis")?;++ Ok(ttl)+}+#[cfg(feature = "v2")]#[instrument(skip_all)]pub async fn delete_payment_token(