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(router): decrypt the wallet token before the debit routing call (#8598)
Shankar Singh Cbf8dc4959eab
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rsindex 0a5ca7705b..167cc7a2f0 100644--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs@@ -75,6 +75,14 @@ impl PaymentMethodData {}}+ pub fn get_wallet_data(&self) -> Option<&WalletData> {+ if let Self::Wallet(wallet_data) = self {+ Some(wallet_data)+ } else {+ None+ }+ }+pub fn is_network_token_payment_method_data(&self) -> bool {matches!(self, Self::NetworkToken(_))}@@ -263,6 +271,32 @@ pub enum WalletData {RevolutPay(RevolutPayData),}+impl WalletData {+ pub fn get_paze_wallet_data(&self) -> Option<&PazeWalletData> {+ if let Self::Paze(paze_wallet_data) = self {+ Some(paze_wallet_data)+ } else {+ None+ }+ }++ pub fn get_apple_pay_wallet_data(&self) -> Option<&ApplePayWalletData> {+ if let Self::ApplePay(apple_pay_wallet_data) = self {+ Some(apple_pay_wallet_data)+ } else {+ None+ }+ }++ pub fn get_google_pay_wallet_data(&self) -> Option<&GooglePayWalletData> {+ if let Self::GooglePay(google_pay_wallet_data) = self {+ Some(google_pay_wallet_data)+ } else {+ None+ }+ }+}+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]pub struct MifinityData {pub date_of_birth: Secret<Date>,diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex cf45d15a5a..e5772c323d 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -613,6 +613,17 @@ where).await?;+ let payment_method_token = get_decrypted_wallet_payment_method_token(+ &operation,+ state,+ merchant_context,+ &mut payment_data,+ connector.as_ref(),+ )+ .await?;++ payment_method_token.map(|token| payment_data.set_payment_method_token(Some(token)));+let (connector, debit_routing_output) = debit_routing::perform_debit_routing(&operation,state,@@ -3522,6 +3533,101 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {}}+#[cfg(feature = "v1")]+pub async fn get_decrypted_wallet_payment_method_token<F, Req, D>(+ operation: &BoxedOperation<'_, F, Req, D>,+ state: &SessionState,+ merchant_context: &domain::MerchantContext,+ payment_data: &mut D,+ connector_call_type_optional: Option<&ConnectorCallType>,+) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse>+where+ F: Send + Clone + Sync,+ D: OperationSessionGetters<F> + Send + Sync + Clone,+{+ if is_operation_confirm(operation) {+ let wallet_type = payment_data+ .get_payment_attempt()+ .payment_method_type+ .get_required_value("payment_method_type")?;++ let wallet: Box<dyn WalletFlow<F, D>> = match wallet_type {+ storage_enums::PaymentMethodType::ApplePay => Box::new(ApplePayWallet),+ storage_enums::PaymentMethodType::Paze => Box::new(PazeWallet),+ storage_enums::PaymentMethodType::GooglePay => Box::new(GooglePayWallet),+ _ => return Ok(None),+ };++ let merchant_connector_account =+ get_merchant_connector_account_for_wallet_decryption_flow::<F, D>(+ state,+ merchant_context,+ payment_data,+ connector_call_type_optional,+ )+ .await?;++ let decide_wallet_flow = &wallet+ .decide_wallet_flow(state, payment_data, &merchant_connector_account)+ .attach_printable("Failed to decide wallet flow")?+ .async_map(|payment_proce_data| async move {+ wallet+ .decrypt_wallet_token(&payment_proce_data, payment_data)+ .await+ })+ .await+ .transpose()+ .attach_printable("Failed to decrypt Wallet token")?;+ Ok(decide_wallet_flow.clone())+ } else {+ Ok(None)+ }+}++#[cfg(feature = "v1")]+pub async fn get_merchant_connector_account_for_wallet_decryption_flow<F, D>(+ state: &SessionState,+ merchant_context: &domain::MerchantContext,+ payment_data: &mut D,+ connector_call_type_optional: Option<&ConnectorCallType>,+) -> RouterResult<helpers::MerchantConnectorAccountType>+where+ F: Send + Clone + Sync,+ D: OperationSessionGetters<F> + Send + Sync + Clone,+{+ let connector_call_type = connector_call_type_optional+ .get_required_value("connector_call_type")+ .change_context(errors::ApiErrorResponse::InternalServerError)?;+ let connector_routing_data = match connector_call_type {+ ConnectorCallType::PreDetermined(connector_routing_data) => connector_routing_data,+ ConnectorCallType::Retryable(connector_routing_datas) => connector_routing_datas+ .first()+ .ok_or(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Found no connector routing data in retryable call")?,+ ConnectorCallType::SessionMultiple(_session_connector_datas) => {+ return Err(errors::ApiErrorResponse::InternalServerError).attach_printable(+ "SessionMultiple connector call type is invalid in confirm calls",+ );+ }+ };++ construct_profile_id_and_get_mca(+ state,+ merchant_context,+ payment_data,+ &connector_routing_data+ .connector_data+ .connector_name+ .to_string(),+ connector_routing_data+ .connector_data+ .merchant_connector_id+ .as_ref(),+ false,+ )+ .await+}+#[cfg(feature = "v1")]#[allow(clippy::too_many_arguments)]#[instrument(skip_all)]@@ -3610,13 +3716,7 @@ whererouter_data.connector_customer = Some(connector_customer_id);}- router_data.payment_method_token = if let Some(decrypted_token) =- add_decrypted_payment_method_token(tokenization_action.clone(), payment_data).await?- {- Some(decrypted_token)- } else {- router_data.payment_method_token- };+ router_data.payment_method_token = payment_data.get_payment_method_token().cloned();let payment_method_token_response = router_data.add_payment_method_token(@@ -3832,7 +3932,6 @@ whereoperation,payment_data,validate_result,- &merchant_connector_account,merchant_context.get_merchant_key_store(),customer,business_profile,@@ -4801,134 +4900,273 @@ whereOk(router_data)}+struct ApplePayWallet;+struct PazeWallet;+struct GooglePayWallet;-pub async fn add_decrypted_payment_method_token<F, D>(- tokenization_action: TokenizationAction,- payment_data: &D,-) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse>+#[async_trait::async_trait]+pub trait WalletFlow<F, D>: Send + Syncwhere- F: Send + Clone + Sync,+ F: Send + Clone,D: OperationSessionGetters<F> + Send + Sync + Clone,{- // Tokenization Action will be DecryptApplePayToken, only when payment method type is Apple Pay- // and the connector supports Apple Pay predecrypt- match &tokenization_action {- TokenizationAction::DecryptApplePayToken(payment_processing_details)- | TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(- payment_processing_details,- ) => {- let apple_pay_data = match payment_data.get_payment_method_data() {- Some(domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(- wallet_data,- ))) => Some(- ApplePayData::token_json(domain::WalletData::ApplePay(wallet_data.clone()))- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("failed to parse apple pay token to json")?- .decrypt(- &payment_processing_details.payment_processing_certificate,- &payment_processing_details.payment_processing_certificate_key,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("failed to decrypt apple pay token")?,- ),- _ => None,- };+ fn decide_wallet_flow(+ &self,+ state: &SessionState,+ payment_data: &D,+ merchant_connector_account: &helpers::MerchantConnectorAccountType,+ ) -> CustomResult<Option<DecideWalletFlow>, errors::ApiErrorResponse>;- let apple_pay_predecrypt = apple_pay_data- .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptData>(- "ApplePayPredecryptData",- )- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(- "failed to parse decrypted apple pay response to ApplePayPredecryptData",+ async fn decrypt_wallet_token(+ &self,+ wallet_flow: &DecideWalletFlow,+ payment_data: &D,+ ) -> CustomResult<PaymentMethodToken, errors::ApiErrorResponse>;+}++#[async_trait::async_trait]+impl<F, D> WalletFlow<F, D> for PazeWallet+where+ F: Send + Clone,+ D: OperationSessionGetters<F> + Send + Sync + Clone,+{+ fn decide_wallet_flow(+ &self,+ state: &SessionState,+ _payment_data: &D,+ _merchant_connector_account: &helpers::MerchantConnectorAccountType,+ ) -> CustomResult<Option<DecideWalletFlow>, errors::ApiErrorResponse> {+ let paze_keys = state+ .conf+ .paze_decrypt_keys+ .as_ref()+ .get_required_value("Paze decrypt keys")+ .attach_printable("Paze decrypt keys not found in the configuration")?;++ let wallet_flow = DecideWalletFlow::PazeDecrypt(PazePaymentProcessingDetails {+ paze_private_key: paze_keys.get_inner().paze_private_key.clone(),+ paze_private_key_passphrase: paze_keys.get_inner().paze_private_key_passphrase.clone(),+ });+ Ok(Some(wallet_flow))+ }++ async fn decrypt_wallet_token(+ &self,+ wallet_flow: &DecideWalletFlow,+ payment_data: &D,+ ) -> CustomResult<PaymentMethodToken, errors::ApiErrorResponse> {+ let paze_payment_processing_details = wallet_flow+ .get_paze_payment_processing_details()+ .get_required_value("Paze payment processing details")+ .attach_printable(+ "Paze payment processing details not found in Paze decryption flow",+ )?;++ let paze_wallet_data = payment_data+ .get_payment_method_data()+ .and_then(|payment_method_data| payment_method_data.get_wallet_data())+ .and_then(|wallet_data| wallet_data.get_paze_wallet_data())+ .get_required_value("Paze wallet token").attach_printable(+ "Paze wallet data not found in the payment method data during the Paze decryption flow",)?;- Ok(Some(PaymentMethodToken::ApplePayDecrypt(Box::new(- apple_pay_predecrypt,- ))))- }- TokenizationAction::DecryptPazeToken(payment_processing_details) => {- let paze_data = match payment_data.get_payment_method_data() {- Some(domain::PaymentMethodData::Wallet(domain::WalletData::Paze(wallet_data))) => {- Some(- decrypt_paze_token(- wallet_data.clone(),- payment_processing_details.paze_private_key.clone(),- payment_processing_details- .paze_private_key_passphrase- .clone(),- )- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("failed to decrypt paze token")?,- )- }- _ => None,- };- let paze_decrypted_data = paze_data- .parse_value::<hyperswitch_domain_models::router_data::PazeDecryptedData>(- "PazeDecryptedData",+ let paze_data = decrypt_paze_token(+ paze_wallet_data.clone(),+ paze_payment_processing_details.paze_private_key.clone(),+ paze_payment_processing_details+ .paze_private_key_passphrase+ .clone(),+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("failed to decrypt paze token")?;++ let paze_decrypted_data = paze_data+ .parse_value::<hyperswitch_domain_models::router_data::PazeDecryptedData>(+ "PazeDecryptedData",+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("failed to parse PazeDecryptedData")?;+ Ok(PaymentMethodToken::PazeDecrypt(Box::new(+ paze_decrypted_data,+ )))+ }+}++#[async_trait::async_trait]+impl<F, D> WalletFlow<F, D> for ApplePayWallet+where+ F: Send + Clone,+ D: OperationSessionGetters<F> + Send + Sync + Clone,+{+ fn decide_wallet_flow(+ &self,+ state: &SessionState,+ payment_data: &D,+ merchant_connector_account: &helpers::MerchantConnectorAccountType,+ ) -> CustomResult<Option<DecideWalletFlow>, errors::ApiErrorResponse> {+ let apple_pay_metadata = check_apple_pay_metadata(state, Some(merchant_connector_account));++ add_apple_pay_flow_metrics(+ &apple_pay_metadata,+ payment_data.get_payment_attempt().connector.clone(),+ payment_data.get_payment_attempt().merchant_id.clone(),+ );++ let wallet_flow = match apple_pay_metadata {+ Some(domain::ApplePayFlow::Simplified(payment_processing_details)) => Some(+ DecideWalletFlow::ApplePayDecrypt(payment_processing_details),+ ),+ Some(domain::ApplePayFlow::Manual) | None => None,+ };+ Ok(wallet_flow)+ }++ async fn decrypt_wallet_token(+ &self,+ wallet_flow: &DecideWalletFlow,+ payment_data: &D,+ ) -> CustomResult<PaymentMethodToken, errors::ApiErrorResponse> {+ let apple_pay_payment_processing_details = wallet_flow+ .get_apple_pay_payment_processing_details()+ .get_required_value("Apple Pay payment processing details")+ .attach_printable(+ "Apple Pay payment processing details not found in Apple Pay decryption flow",+ )?;+ let apple_pay_wallet_data = payment_data+ .get_payment_method_data()+ .and_then(|payment_method_data| payment_method_data.get_wallet_data())+ .and_then(|wallet_data| wallet_data.get_apple_pay_wallet_data())+ .get_required_value("Paze wallet token").attach_printable(+ "Apple Pay wallet data not found in the payment method data during the Apple Pay decryption flow",+ )?;+ let apple_pay_data =+ ApplePayData::token_json(domain::WalletData::ApplePay(apple_pay_wallet_data.clone()))+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("failed to parse apple pay token to json")?+ .decrypt(+ &apple_pay_payment_processing_details.payment_processing_certificate,+ &apple_pay_payment_processing_details.payment_processing_certificate_key,)+ .await.change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("failed to parse PazeDecryptedData")?;- Ok(Some(PaymentMethodToken::PazeDecrypt(Box::new(- paze_decrypted_data,- ))))- }- TokenizationAction::DecryptGooglePayToken(payment_processing_details) => {- let google_pay_data = match payment_data.get_payment_method_data() {- Some(domain::PaymentMethodData::Wallet(domain::WalletData::GooglePay(- wallet_data,- ))) => {- let decryptor = helpers::GooglePayTokenDecryptor::new(- payment_processing_details- .google_pay_root_signing_keys- .clone(),- payment_processing_details.google_pay_recipient_id.clone(),- payment_processing_details.google_pay_private_key.clone(),- )- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("failed to create google pay token decryptor")?;+ .attach_printable("failed to decrypt apple pay token")?;- // should_verify_token is set to false to disable verification of token- Some(- decryptor- .decrypt_token(wallet_data.tokenization_data.token.clone(), false)- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("failed to decrypt google pay token")?,- )- }- Some(payment_method_data) => {- logger::info!(- "Invalid payment_method_data found for Google Pay Decrypt Flow: {:?}",- payment_method_data.get_payment_method()- );- None- }- None => {- logger::info!("No payment_method_data found for Google Pay Decrypt Flow");- None- }- };+ let apple_pay_predecrypt = apple_pay_data+ .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptData>(+ "ApplePayPredecryptData",+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "failed to parse decrypted apple pay response to ApplePayPredecryptData",+ )?;- let google_pay_predecrypt = google_pay_data- .ok_or(errors::ApiErrorResponse::InternalServerError)- .attach_printable("failed to get GooglePayDecryptedData in response")?;+ Ok(PaymentMethodToken::ApplePayDecrypt(Box::new(+ apple_pay_predecrypt,+ )))+ }+}++#[async_trait::async_trait]+impl<F, D> WalletFlow<F, D> for GooglePayWallet+where+ F: Send + Clone,+ D: OperationSessionGetters<F> + Send + Sync + Clone,+{+ fn decide_wallet_flow(+ &self,+ state: &SessionState,+ _payment_data: &D,+ merchant_connector_account: &helpers::MerchantConnectorAccountType,+ ) -> CustomResult<Option<DecideWalletFlow>, errors::ApiErrorResponse> {+ Ok(+ get_google_pay_connector_wallet_details(state, merchant_connector_account)+ .map(DecideWalletFlow::GooglePayDecrypt),+ )+ }- Ok(Some(PaymentMethodToken::GooglePayDecrypt(Box::new(- google_pay_predecrypt,- ))))+ async fn decrypt_wallet_token(+ &self,+ wallet_flow: &DecideWalletFlow,+ payment_data: &D,+ ) -> CustomResult<PaymentMethodToken, errors::ApiErrorResponse> {+ let google_pay_payment_processing_details = wallet_flow+ .get_google_pay_payment_processing_details()+ .get_required_value("Google Pay payment processing details")+ .attach_printable(+ "Google Pay payment processing details not found in Google Pay decryption flow",+ )?;++ let google_pay_wallet_data = payment_data+ .get_payment_method_data()+ .and_then(|payment_method_data| payment_method_data.get_wallet_data())+ .and_then(|wallet_data| wallet_data.get_google_pay_wallet_data())+ .get_required_value("Paze wallet token").attach_printable(+ "Google Pay wallet data not found in the payment method data during the Google Pay decryption flow",+ )?;++ let decryptor = helpers::GooglePayTokenDecryptor::new(+ google_pay_payment_processing_details+ .google_pay_root_signing_keys+ .clone(),+ google_pay_payment_processing_details+ .google_pay_recipient_id+ .clone(),+ google_pay_payment_processing_details+ .google_pay_private_key+ .clone(),+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("failed to create google pay token decryptor")?;++ // should_verify_token is set to false to disable verification of token+ let google_pay_data = decryptor+ .decrypt_token(+ google_pay_wallet_data.tokenization_data.token.clone(),+ false,+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("failed to decrypt google pay token")?;++ Ok(PaymentMethodToken::GooglePayDecrypt(Box::new(+ google_pay_data,+ )))+ }+}++#[derive(Debug, Clone)]+pub enum DecideWalletFlow {+ ApplePayDecrypt(payments_api::PaymentProcessingDetails),+ PazeDecrypt(PazePaymentProcessingDetails),+ GooglePayDecrypt(GooglePayPaymentProcessingDetails),+ SkipDecryption,+}++impl DecideWalletFlow {+ fn get_paze_payment_processing_details(&self) -> Option<&PazePaymentProcessingDetails> {+ if let Self::PazeDecrypt(details) = self {+ Some(details)+ } else {+ None}- TokenizationAction::ConnectorToken(_) => {- logger::info!("Invalid tokenization action found for decryption flow: ConnectorToken");- Ok(None)+ }++ fn get_apple_pay_payment_processing_details(+ &self,+ ) -> Option<&payments_api::PaymentProcessingDetails> {+ if let Self::ApplePayDecrypt(details) = self {+ Some(details)+ } else {+ None}- token_action => {- logger::info!(- "Invalid tokenization action found for decryption flow: {:?}",- token_action- );- Ok(None)+ }++ fn get_google_pay_payment_processing_details(+ &self,+ ) -> Option<&GooglePayPaymentProcessingDetails> {+ if let Self::GooglePayDecrypt(details) = self {+ Some(details)+ } else {+ None}}}@@ -5926,7 +6164,7 @@ fn is_payment_method_tokenization_enabled_for_connector(connector_name: &str,payment_method: storage::enums::PaymentMethod,payment_method_type: Option<storage::enums::PaymentMethodType>,- apple_pay_flow: &Option<domain::ApplePayFlow>,+ payment_method_token: Option<&PaymentMethodToken>,) -> RouterResult<bool> {let connector_tokenization_filter = state.conf.tokenization.0.get(connector_name);@@ -5942,7 +6180,7 @@ fn is_payment_method_tokenization_enabled_for_connector()&& is_apple_pay_pre_decrypt_type_connector_tokenization(payment_method_type,- apple_pay_flow,+ payment_method_token,connector_filter.apple_pay_pre_decrypt_flow.clone(),)})@@ -5951,13 +6189,13 @@ fn is_payment_method_tokenization_enabled_for_connector(fn is_apple_pay_pre_decrypt_type_connector_tokenization(payment_method_type: Option<storage::enums::PaymentMethodType>,- apple_pay_flow: &Option<domain::ApplePayFlow>,+ payment_method_token: Option<&PaymentMethodToken>,apple_pay_pre_decrypt_flow_filter: Option<ApplePayPreDecryptFlow>,) -> bool {- match (payment_method_type, apple_pay_flow) {+ match (payment_method_type, payment_method_token) {(Some(storage::enums::PaymentMethodType::ApplePay),- Some(domain::ApplePayFlow::Simplified(_)),+ Some(PaymentMethodToken::ApplePayDecrypt(..)),) => !matches!(apple_pay_pre_decrypt_flow_filter,Some(ApplePayPreDecryptFlow::NetworkTokenization)@@ -6142,58 +6380,20 @@ async fn decide_payment_method_tokenize_action(payment_intent_data: payments::PaymentIntent,pm_parent_token: Option<&str>,is_connector_tokenization_enabled: bool,- apple_pay_flow: Option<domain::ApplePayFlow>,- payment_method_type: Option<storage_enums::PaymentMethodType>,- merchant_connector_account: &helpers::MerchantConnectorAccountType,) -> RouterResult<TokenizationAction> {- if let Some(storage_enums::PaymentMethodType::Paze) = payment_method_type {- // Paze generates a one time use network token which should not be tokenized in the connector or router.- match &state.conf.paze_decrypt_keys {- Some(paze_keys) => Ok(TokenizationAction::DecryptPazeToken(- PazePaymentProcessingDetails {- paze_private_key: paze_keys.get_inner().paze_private_key.clone(),- paze_private_key_passphrase: paze_keys- .get_inner()- .paze_private_key_passphrase- .clone(),- },- )),- None => Err(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to fetch Paze configs"),- }- } else if let Some(storage_enums::PaymentMethodType::GooglePay) = payment_method_type {- let google_pay_details =- get_google_pay_connector_wallet_details(state, merchant_connector_account);-- match google_pay_details {- Some(wallet_details) => Ok(TokenizationAction::DecryptGooglePayToken(wallet_details)),- None => {- if is_connector_tokenization_enabled {- Ok(TokenizationAction::TokenizeInConnectorAndRouter)- } else {- Ok(TokenizationAction::TokenizeInRouter)- }- }- }- } else if matches!(+ if matches!(payment_intent_data.split_payments,Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(_))) {Ok(TokenizationAction::TokenizeInConnector)} else {match pm_parent_token {- None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) {- (true, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => {- TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(- payment_processing_details,- )- }- (true, _) => TokenizationAction::TokenizeInConnectorAndRouter,- (false, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => {- TokenizationAction::DecryptApplePayToken(payment_processing_details)- }- (false, _) => TokenizationAction::TokenizeInRouter,+ None => Ok(if is_connector_tokenization_enabled {+ TokenizationAction::TokenizeInConnectorAndRouter+ } else {+ TokenizationAction::TokenizeInRouter}),+Some(token) => {let redis_conn = state.store@@ -6218,19 +6418,10 @@ async fn decide_payment_method_tokenize_action(Some(connector_token) => {Ok(TokenizationAction::ConnectorToken(connector_token))}- None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) {- (- true,- Some(domain::ApplePayFlow::Simplified(payment_processing_details)),- ) => TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(- payment_processing_details,- ),- (true, _) => TokenizationAction::TokenizeInConnectorAndRouter,- (- false,- Some(domain::ApplePayFlow::Simplified(payment_processing_details)),- ) => TokenizationAction::DecryptApplePayToken(payment_processing_details),- (false, _) => TokenizationAction::TokenizeInRouter,+ None => Ok(if is_connector_tokenization_enabled {+ TokenizationAction::TokenizeInConnectorAndRouter+ } else {+ TokenizationAction::TokenizeInRouter}),}}@@ -6258,10 +6449,6 @@ pub enum TokenizationAction {TokenizeInConnectorAndRouter,ConnectorToken(String),SkipConnectorTokenization,- DecryptApplePayToken(payments_api::PaymentProcessingDetails),- TokenizeInConnectorAndApplepayPreDecrypt(payments_api::PaymentProcessingDetails),- DecryptPazeToken(PazePaymentProcessingDetails),- DecryptGooglePayToken(GooglePayPaymentProcessingDetails),}#[cfg(feature = "v2")]@@ -6271,7 +6458,6 @@ pub async fn get_connector_tokenization_action_when_confirm_true<F, Req, D>(_operation: &BoxedOperation<'_, F, Req, D>,payment_data: &mut D,_validate_result: &operations::ValidateResult,- _merchant_connector_account: &helpers::MerchantConnectorAccountType,_merchant_key_store: &domain::MerchantKeyStore,_customer: &Option<domain::Customer>,_business_profile: &domain::Profile,@@ -6292,7 +6478,6 @@ pub async fn get_connector_tokenization_action_when_confirm_true<F, Req, D>(operation: &BoxedOperation<'_, F, Req, D>,payment_data: &mut D,validate_result: &operations::ValidateResult,- merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_key_store: &domain::MerchantKeyStore,customer: &Option<domain::Customer>,business_profile: &domain::Profile,@@ -6327,24 +6512,15 @@ where.get_required_value("payment_method")?;let payment_method_type = payment_data.get_payment_attempt().payment_method_type;- let apple_pay_flow =- decide_apple_pay_flow(state, payment_method_type, Some(merchant_connector_account));-let is_connector_tokenization_enabled =is_payment_method_tokenization_enabled_for_connector(state,&connector,payment_method,payment_method_type,- &apple_pay_flow,+ payment_data.get_payment_method_token(),)?;- add_apple_pay_flow_metrics(- &apple_pay_flow,- payment_data.get_payment_attempt().connector.clone(),- payment_data.get_payment_attempt().merchant_id.clone(),- );-let payment_method_action = decide_payment_method_tokenize_action(state,&connector,@@ -6352,9 +6528,6 @@ wherepayment_data.get_payment_intent().clone(),payment_data.get_token(),is_connector_tokenization_enabled,- apple_pay_flow,- payment_method_type,- merchant_connector_account,).await?;@@ -6377,7 +6550,6 @@ whereTokenizationAction::SkipConnectorTokenization}-TokenizationAction::TokenizeInConnector => TokenizationAction::TokenizeInConnector,TokenizationAction::TokenizeInConnectorAndRouter => {let (_operation, payment_method_data, pm_id) = operation@@ -6404,22 +6576,6 @@ whereTokenizationAction::SkipConnectorTokenization => {TokenizationAction::SkipConnectorTokenization}- TokenizationAction::DecryptApplePayToken(payment_processing_details) => {- TokenizationAction::DecryptApplePayToken(payment_processing_details)- }- TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(- payment_processing_details,- ) => TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(- payment_processing_details,- ),- TokenizationAction::DecryptPazeToken(paze_payment_processing_details) => {- TokenizationAction::DecryptPazeToken(paze_payment_processing_details)- }- TokenizationAction::DecryptGooglePayToken(- google_pay_payment_processing_details,- ) => {- TokenizationAction::DecryptGooglePayToken(google_pay_payment_processing_details)- }};(payment_data.to_owned(), connector_tokenization_action)}@@ -6520,6 +6676,7 @@ wherepub force_sync: Option<bool>,pub all_keys_required: Option<bool>,pub payment_method_data: Option<domain::PaymentMethodData>,+ pub payment_method_token: Option<PaymentMethodToken>,pub payment_method_info: Option<domain::PaymentMethod>,pub refunds: Vec<diesel_refund::Refund>,pub disputes: Vec<storage::Dispute>,@@ -9405,6 +9562,7 @@ pub trait OperationSessionGetters<F> {#[cfg(feature = "v2")]fn get_client_secret(&self) -> &Option<Secret<String>>;fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod>;+ fn get_payment_method_token(&self) -> Option<&PaymentMethodToken>;fn get_mandate_id(&self) -> Option<&payments_api::MandateIds>;fn get_address(&self) -> &PaymentAddress;fn get_creds_identifier(&self) -> Option<&str>;@@ -9470,6 +9628,7 @@ pub trait OperationSessionSetters<F> {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_payment_method_token(&mut self, payment_method_token: Option<PaymentMethodToken>);fn set_email_if_not_present(&mut self, email: pii::Email);fn set_payment_method_id_in_attempt(&mut self, payment_method_id: Option<String>);fn set_pm_token(&mut self, token: String);@@ -9553,6 +9712,10 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentData<F> {self.payment_method_info.as_ref()}+ fn get_payment_method_token(&self) -> Option<&PaymentMethodToken> {+ self.payment_method_token.as_ref()+ }+fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> {self.mandate_id.as_ref()}@@ -9717,6 +9880,10 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentData<F> {self.payment_method_data = payment_method_data;}+ fn set_payment_method_token(&mut self, payment_method_token: Option<PaymentMethodToken>) {+ self.payment_method_token = payment_method_token;+ }+fn set_payment_method_id_in_attempt(&mut self, payment_method_id: Option<String>) {self.payment_attempt.payment_method_id = payment_method_id;}@@ -9878,6 +10045,10 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentIntentData<F> {todo!()}+ fn get_payment_method_token(&self) -> Option<&PaymentMethodToken> {+ todo!()+ }+fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> {todo!()}@@ -10042,6 +10213,10 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> {todo!()}+ fn set_payment_method_token(&mut self, _payment_method_token: Option<PaymentMethodToken>) {+ todo!()+ }+fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) {todo!()}@@ -10179,6 +10354,10 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentConfirmData<F> {todo!()}+ fn get_payment_method_token(&self) -> Option<&PaymentMethodToken> {+ todo!()+ }+fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> {todo!()}@@ -10340,6 +10519,10 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentConfirmData<F> {todo!()}+ fn set_payment_method_token(&mut self, _payment_method_token: Option<PaymentMethodToken>) {+ todo!()+ }+fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) {todo!()}@@ -10478,6 +10661,10 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentStatusData<F> {todo!()}+ fn get_payment_method_token(&self) -> Option<&PaymentMethodToken> {+ todo!()+ }+fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> {todo!()}@@ -10635,6 +10822,10 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentStatusData<F> {todo!()}+ fn set_payment_method_token(&mut self, _payment_method_token: Option<PaymentMethodToken>) {+ todo!()+ }+fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) {todo!()}@@ -10772,6 +10963,10 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentCaptureData<F> {todo!()}+ fn get_payment_method_token(&self) -> Option<&PaymentMethodToken> {+ todo!()+ }+fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> {todo!()}@@ -10931,6 +11126,10 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentCaptureData<F> {todo!()}+ fn set_payment_method_token(&mut self, _payment_method_token: Option<PaymentMethodToken>) {+ todo!()+ }+fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) {todo!()}@@ -11063,6 +11262,10 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentAttemptListData<F> {todo!()}+ fn get_payment_method_token(&self) -> Option<&PaymentMethodToken> {+ todo!()+ }+fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> {todo!()}diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rsindex a16c2cd433..8beac4097a 100644--- a/crates/router/src/core/payments/operations/payment_approve.rs+++ b/crates/router/src/core/payments/operations/payment_approve.rs@@ -173,6 +173,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCaptureR),confirm: None,payment_method_data: None,+ payment_method_token: None,payment_method_info: None,force_sync: None,all_keys_required: None,diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rsindex 343c1f98a9..dfe3657b0f 100644--- a/crates/router/src/core/payments/operations/payment_cancel.rs+++ b/crates/router/src/core/payments/operations/payment_cancel.rs@@ -184,6 +184,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelRe),confirm: None,payment_method_data: None,+ payment_method_token: None,payment_method_info: None,force_sync: None,all_keys_required: None,diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rsindex 8e3a765b8a..6108ed3658 100644--- a/crates/router/src/core/payments/operations/payment_capture.rs+++ b/crates/router/src/core/payments/operations/payment_capture.rs@@ -235,6 +235,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, api::Paymen),confirm: None,payment_method_data: None,+ payment_method_token: None,payment_method_info: None,refunds: vec![],disputes: vec![],diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rsindex 3ce888e657..38a189e50f 100644--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs@@ -332,6 +332,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>.payment_method_data.as_ref().and_then(|pmd| pmd.payment_method_data.clone().map(Into::into)),+ payment_method_token: None,payment_method_info,force_sync: None,all_keys_required: None,diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex 2aa1a72e73..abbdc1f5c7 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -795,6 +795,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>token_data,confirm: request.confirm,payment_method_data: payment_method_data_after_card_bin_call.map(Into::into),+ payment_method_token: None,payment_method_info,force_sync: None,all_keys_required: None,diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rsindex a73796075a..1c3a8a0be9 100644--- a/crates/router/src/core/payments/operations/payment_create.rs+++ b/crates/router/src/core/payments/operations/payment_create.rs@@ -598,6 +598,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>token_data: None,confirm: request.confirm,payment_method_data: payment_method_data_after_card_bin_call.map(Into::into),+ payment_method_token: None,payment_method_info,refunds: vec![],disputes: 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.rsindex 3df1da1827..b1543be154 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@@ -145,6 +145,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsPostSess),confirm: None,payment_method_data: None,+ payment_method_token: None,payment_method_info: None,force_sync: None,all_keys_required: None,diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rsindex 33ec9a0d59..f963baa87c 100644--- a/crates/router/src/core/payments/operations/payment_reject.rs+++ b/crates/router/src/core/payments/operations/payment_reject.rs@@ -171,6 +171,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequesttoken_data: None,confirm: None,payment_method_data: None,+ payment_method_token: None,payment_method_info: None,force_sync: None,all_keys_required: None,diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rsindex b0a5f2fc13..8a7c22376a 100644--- a/crates/router/src/core/payments/operations/payment_session.rs+++ b/crates/router/src/core/payments/operations/payment_session.rs@@ -193,6 +193,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsSessionR),confirm: None,payment_method_data: None,+ payment_method_token: None,payment_method_info: None,force_sync: None,all_keys_required: None,diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rsindex e702ba1ef5..9727fb399d 100644--- a/crates/router/src/core/payments/operations/payment_start.rs+++ b/crates/router/src/core/payments/operations/payment_start.rs@@ -181,6 +181,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsStartReqconfirm: Some(payment_attempt.confirm),payment_attempt,payment_method_data: None,+ payment_method_token: None,payment_method_info: None,force_sync: None,all_keys_required: None,diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rsindex ac2a7b923f..c6488bdb75 100644--- a/crates/router/src/core/payments/operations/payment_status.rs+++ b/crates/router/src/core/payments/operations/payment_status.rs@@ -517,6 +517,7 @@ async fn get_tracker_for_sync<token_data: None,confirm: Some(request.force_sync),payment_method_data: None,+ payment_method_token: None,payment_method_info,force_sync: Some(request.force_syncdiff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rsindex 2299acbe30..0b77e5c31c 100644--- a/crates/router/src/core/payments/operations/payment_update.rs+++ b/crates/router/src/core/payments/operations/payment_update.rs@@ -475,6 +475,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>.payment_method_data.as_ref().and_then(|pmd| pmd.payment_method_data.clone().map(Into::into)),+ payment_method_token: None,payment_method_info,force_sync: None,all_keys_required: None,diff --git a/crates/router/src/core/payments/operations/payment_update_metadata.rs b/crates/router/src/core/payments/operations/payment_update_metadata.rsindex 2c6841c44a..23a300c3c8 100644--- a/crates/router/src/core/payments/operations/payment_update_metadata.rs+++ b/crates/router/src/core/payments/operations/payment_update_metadata.rs@@ -131,6 +131,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsUpdateMeaddress: payments::PaymentAddress::new(None, None, None, None),confirm: None,payment_method_data: None,+ payment_method_token: None,payment_method_info: None,force_sync: None,all_keys_required: None,diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rsindex e5262d092c..a32f89ef4d 100644--- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs+++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs@@ -145,6 +145,7 @@ impl<F: Send + Clone + Sync>address: PaymentAddress::new(None, None, None, None),confirm: None,payment_method_data: None,+ payment_method_token: None,payment_method_info: None,force_sync: None,all_keys_required: None,diff --git a/crates/router/src/core/payments/operations/tax_calculation.rs b/crates/router/src/core/payments/operations/tax_calculation.rsindex 85ad5fb1cb..9f0863e676 100644--- a/crates/router/src/core/payments/operations/tax_calculation.rs+++ b/crates/router/src/core/payments/operations/tax_calculation.rs@@ -160,6 +160,7 @@ impl<F: Send + Clone + Sync>),confirm: None,payment_method_data: None,+ payment_method_token: None,payment_method_info: None,force_sync: None,all_keys_required: None,diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rsindex f4389bc173..d6578ad36c 100644--- a/crates/router/src/core/payments/tokenization.rs+++ b/crates/router/src/core/payments/tokenization.rs@@ -1253,8 +1253,7 @@ pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>() -> RouterResult<types::PaymentMethodTokenResult> {if should_continue_payment {match tokenization_action {- payments::TokenizationAction::TokenizeInConnector- | payments::TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(_) => {+ payments::TokenizationAction::TokenizeInConnector => {let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<api::PaymentMethodToken,types::PaymentMethodTokenizationData,