Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
fix(network_tokenization): Save network token data for saved payment methods (#11152)
Sarthak Soni2994c6d92c42
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rsindex baf5c6de6d..2cc67bacec 100644--- a/crates/diesel_models/src/payment_method.rs+++ b/crates/diesel_models/src/payment_method.rs@@ -259,6 +259,9 @@ pub enum PaymentMethodUpdate {network_token_locker_id: Option<String>,network_token_payment_method_data: Option<Encryption>,last_modified_by: Option<String>,+ metadata: Option<serde_json::Value>,+ last_used_at: Option<PrimitiveDateTime>,+ connector_mandate_details: Option<serde_json::Value>,},ConnectorMandateDetailsUpdate {connector_mandate_details: Option<serde_json::Value>,@@ -678,16 +681,19 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {network_token_locker_id,network_token_payment_method_data,last_modified_by,+ metadata,+ last_used_at,+ connector_mandate_details,} => Self {- metadata: None,+ metadata,payment_method_data,- last_used_at: None,+ last_used_at,network_transaction_id: None,status,locker_id,network_token_requestor_reference_id,payment_method,- connector_mandate_details: None,+ connector_mandate_details,updated_by: None,payment_method_issuer,payment_method_type,diff --git a/crates/payment_methods/src/core/errors.rs b/crates/payment_methods/src/core/errors.rsindex 35da124b90..ffc4dbab32 100644--- a/crates/payment_methods/src/core/errors.rs+++ b/crates/payment_methods/src/core/errors.rs@@ -31,7 +31,7 @@ pub enum VaultError {#[error("The card vault returned an unexpected response: {0:?}")]UnexpectedResponseError(bytes::Bytes),#[error("Failed to update in PMD table")]- UpdateInPaymentMethodDataTableFailed,+ UpdateInPaymentMethodTableFailed,#[error("Failed to fetch payment method in vault")]FetchPaymentMethodFailed,#[error("Failed to save payment method in vault")]diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex 10e1e2f62e..920ec7a7f9 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -1680,6 +1680,9 @@ pub async fn add_payment_method_data(network_token_locker_id: None,network_token_payment_method_data: None,last_modified_by: None,+ metadata: None,+ last_used_at: None,+ connector_mandate_details: None,};db.update_payment_method(@@ -2325,21 +2328,60 @@ where}#[cfg(feature = "v1")]-pub async fn update_payment_method_metadata_and_last_used(+#[allow(clippy::too_many_arguments)]+pub async fn update_payment_method_metadata_and_network_token_data_and_last_used(key_store: &domain::MerchantKeyStore,db: &dyn db::StorageInterface,pm: domain::PaymentMethod,pm_metadata: Option<serde_json::Value>,+ network_token_requestor_reference_id: Option<String>,+ network_token_locker_id: Option<String>,+ pm_network_token_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>>,storage_scheme: MerchantStorageScheme,) -> errors::CustomResult<(), errors::VaultError> {- let pm_update = payment_method::PaymentMethodUpdate::MetadataUpdateAndLastUsed {+ let pm_update = payment_method::PaymentMethodUpdate::AdditionalDataUpdate {+ locker_id: None,+ payment_method_data: None,+ status: None,+ payment_method: None,+ payment_method_type: None,+ payment_method_issuer: None,+ network_token_requestor_reference_id,+ network_token_locker_id,+ network_token_payment_method_data: pm_network_token_data_encrypted.map(Into::into),+ last_modified_by: None,metadata: pm_metadata,- last_used_at: common_utils::date_time::now(),+ last_used_at: Some(common_utils::date_time::now()),+ connector_mandate_details: None,+ };++ db.update_payment_method(key_store, pm, pm_update, storage_scheme)+ .await+ .change_context(errors::VaultError::UpdateInPaymentMethodTableFailed)?;+ Ok(())+}++#[cfg(feature = "v1")]+#[allow(clippy::too_many_arguments)]+pub async fn update_payment_method_network_token_data(+ key_store: &domain::MerchantKeyStore,+ db: &dyn db::StorageInterface,+ pm: domain::PaymentMethod,+ network_token_requestor_reference_id: Option<String>,+ network_token_locker_id: Option<String>,+ pm_network_token_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>>,+ storage_scheme: MerchantStorageScheme,+) -> errors::CustomResult<(), errors::VaultError> {+ let pm_update = payment_method::PaymentMethodUpdate::NetworkTokenDataUpdate {+ network_token_requestor_reference_id,+ network_token_locker_id,+ network_token_payment_method_data: pm_network_token_data_encrypted.map(Into::into),last_modified_by: None,};+db.update_payment_method(key_store, pm, pm_update, storage_scheme).await- .change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;+ .change_context(errors::VaultError::UpdateInPaymentMethodTableFailed)?;Ok(())}@@ -2359,7 +2401,7 @@ pub async fn update_payment_method_and_last_used(};db.update_payment_method(key_store, pm, pm_update, storage_scheme).await- .change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;+ .change_context(errors::VaultError::UpdateInPaymentMethodTableFailed)?;Ok(())}@@ -2379,7 +2421,7 @@ pub async fn update_payment_method_connector_mandate_details(db.update_payment_method(key_store, pm, pm_update, storage_scheme).await- .change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;+ .change_context(errors::VaultError::UpdateInPaymentMethodTableFailed)?;Ok(())}@@ -2395,7 +2437,7 @@ pub async fn update_payment_method_connector_mandate_details(.map(|common_mandate| {common_mandate.get_mandate_details_value().map_err(|err| {router_env::logger::error!("Failed to get get_mandate_details_value : {:?}", err);- errors::VaultError::UpdateInPaymentMethodDataTableFailed+ errors::VaultError::UpdateInPaymentMethodTableFailed})}).transpose()?;@@ -2407,7 +2449,49 @@ pub async fn update_payment_method_connector_mandate_details(db.update_payment_method(key_store, pm, pm_update, storage_scheme).await- .change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;+ .change_context(errors::VaultError::UpdateInPaymentMethodTableFailed)?;+ Ok(())+}++#[cfg(feature = "v1")]+#[allow(clippy::too_many_arguments)]+pub async fn update_payment_method_connector_mandate_details_and_network_token_data(+ key_store: &domain::MerchantKeyStore,+ db: &dyn db::StorageInterface,+ pm: domain::PaymentMethod,+ connector_mandate_details: Option<CommonMandateReference>,+ network_token_requestor_reference_id: Option<String>,+ network_token_locker_id: Option<String>,+ pm_network_token_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>>,+ storage_scheme: MerchantStorageScheme,+) -> errors::CustomResult<(), errors::VaultError> {+ let connector_mandate_details_value = connector_mandate_details+ .map(|common_mandate| {+ common_mandate.get_mandate_details_value().map_err(|err| {+ router_env::logger::error!("Failed to get get_mandate_details_value : {:?}", err);+ errors::VaultError::UpdateInPaymentMethodTableFailed+ })+ })+ .transpose()?;+ let pm_update = payment_method::PaymentMethodUpdate::AdditionalDataUpdate {+ locker_id: None,+ payment_method_data: None,+ status: None,+ payment_method: None,+ payment_method_type: None,+ payment_method_issuer: None,+ network_token_requestor_reference_id,+ network_token_locker_id,+ network_token_payment_method_data: pm_network_token_data_encrypted.map(Into::into),+ last_modified_by: None,+ metadata: None,+ last_used_at: None,+ connector_mandate_details: connector_mandate_details_value,+ };++ db.update_payment_method(key_store, pm, pm_update, storage_scheme)+ .await+ .change_context(errors::VaultError::UpdateInPaymentMethodTableFailed)?;Ok(())}#[instrument(skip_all)]diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rsindex b3b726459c..1fe13bfd29 100644--- a/crates/router/src/core/payments/tokenization.rs+++ b/crates/router/src/core/payments/tokenization.rs@@ -55,6 +55,40 @@ use crate::{utils::{generate_id, OptionExt},};+#[cfg(feature = "v1")]+pub async fn save_network_token_details_in_nt_mapper(+ state: &SessionState,+ platform: &domain::Platform,+ customer_id: &id_type::CustomerId,+ payment_method_id: String,+ network_token_requestor_ref_id: String,+) -> RouterResult<()> {+ let db = &*state.store;++ //Insert the network token reference ID along with merchant id, customer id in CallbackMapper table for its respective webooks+ let callback_mapper_data = CallbackMapperData::NetworkTokenWebhook {+ merchant_id: platform.get_processor().get_account().get_id().clone(),+ customer_id: customer_id.to_owned(),+ payment_method_id: payment_method_id.clone(),+ };+ let callback_mapper = CallbackMapper::new(+ network_token_requestor_ref_id,+ common_enums::CallbackMapperIdType::NetworkTokenRequestorReferenceID,+ callback_mapper_data,+ common_utils::date_time::now(),+ common_utils::date_time::now(),+ );++ db.insert_call_back_mapper(callback_mapper)+ .await+ .inspect_err(|err| {+ logger::error!("Failed to insert in Callback Mapper table: {:?}", err);+ })+ .attach_printable("Failed to insert in Callback Mapper table")+ .ok();+ Ok(())+}+#[cfg(feature = "v1")]async fn save_in_locker(state: &SessionState,@@ -456,16 +490,34 @@ wherepm.metadata.as_ref(),connector_token,)?;- payment_methods::cards::update_payment_method_metadata_and_last_used(+ payment_methods::cards::update_payment_method_metadata_and_network_token_data_and_last_used(platform.get_provider().get_key_store(),db,pm.clone(),pm_metadata,+ network_token_requestor_ref_id.clone(),+ network_token_locker_id,+ pm_network_token_data_encrypted,platform.get_provider().get_account().storage_scheme,).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to add payment method in db")?;++ if let Some(nt_ref_id) = network_token_requestor_ref_id {+ //Insert the network token reference ID along with merchant id, customer id in CallbackMapper table for its respective webooks+ save_network_token_details_in_nt_mapper(+ state,+ platform,+ &customer_id,+ resp.payment_method_id.clone(),+ nt_ref_id,+ )+ .await+ .attach_printable(+ "Failed to save network token details in callback_mapper table",+ )?;+ };}Err(err) => {if err.current_context().is_db_not_found() {@@ -567,26 +619,50 @@ where.transpose().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to deserialize to Payment Mandate Reference ")?;- if let Some((mandate_details, merchant_connector_id)) =- mandate_details.zip(merchant_connector_id)- {- let connector_mandate_details =+ let connector_mandate_details =+ if let Some((mandate_details, merchant_connector_id)) =+ mandate_details.zip(merchant_connector_id)+ {update_connector_mandate_details_status(merchant_connector_id,mandate_details,ConnectorMandateStatus::Inactive,- )?;- payment_methods::cards::update_payment_method_connector_mandate_details(+ )?+ } else {+ None+ };+ payment_methods::cards::update_payment_method_connector_mandate_details_and_network_token_data(platform.get_provider().get_key_store(),db,pm.clone(),connector_mandate_details,+ network_token_requestor_ref_id.clone(),+ network_token_locker_id,+ pm_network_token_data_encrypted,platform.get_provider().get_account().storage_scheme,).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to add payment method in db")?;- }++ network_token_requestor_ref_id+ .as_ref()+ .async_map(|nt_ref_id| {+ //Insert the network token reference ID along with merchant id, customer id in CallbackMapper table for its respective webooks+ save_network_token_details_in_nt_mapper(+ state,+ platform,+ &customer_id,+ resp.payment_method_id.clone(),+ nt_ref_id.clone(),+ )+ })+ .await+ .transpose()+ .attach_printable(+ "Failed to save network token details in callback_mapper table",+ )?;+Ok(pm)}Err(err) => {@@ -847,32 +923,17 @@ wherematch network_token_requestor_ref_id {Some(network_token_requestor_ref_id) => {//Insert the network token reference ID along with merchant id, customer id in CallbackMapper table for its respective webooks- let callback_mapper_data =- CallbackMapperData::NetworkTokenWebhook {- merchant_id: platform- .get_processor()- .get_account()- .get_id()- .clone(),- customer_id,- payment_method_id: resp.payment_method_id.clone(),- };- let callback_mapper = CallbackMapper::new(+ save_network_token_details_in_nt_mapper(+ state,+ platform,+ &customer_id,+ resp.payment_method_id.clone(),network_token_requestor_ref_id,- common_enums::CallbackMapperIdType::NetworkTokenRequestorReferenceID,- callback_mapper_data,- common_utils::date_time::now(),- common_utils::date_time::now(),- );-- db.insert_call_back_mapper(callback_mapper)- .await- .change_context(- errors::ApiErrorResponse::InternalServerError,- )- .attach_printable(- "Failed to insert in Callback Mapper table",- )?;+ )+ .await+ .attach_printable(+ "Failed to save network token details in callback_mapper table",+ )?;}None => {logger::info!("Network token requestor reference ID is not available, skipping callback mapper insertion");@@ -884,6 +945,32 @@ whereSome(resp.payment_method_id)} else {+ // generate Network token and update payment method if not already done when+ // network tokenization is enabled for the profile+ let is_network_tokenization_enabled =+ business_profile.is_network_tokenization_enabled;+ let is_payment_method_saved = payment_method_info.is_some();++ if is_network_tokenization_enabled && is_payment_method_saved {+ generate_network_token_and_update_payment_method(+ state,+ platform,+ &save_payment_method_data.request.get_payment_method_data(),+ save_payment_method_data.payment_method,+ payment_method_type,+ customer_id,+ billing_name,+ payment_method_billing_address,+ payment_method_info,+ )+ .await+ .inspect_err(|err| {+ logger::error!("Failed to process network tokenization: {:?}", err);+ })+ .attach_printable("Failed to process network tokenization")+ .ok();+ }+None};// check if there needs to be a config if yes then remove it to a different place@@ -1967,3 +2054,120 @@ pub async fn save_card_and_network_token_in_locker(}}}++#[cfg(feature = "v1")]+#[allow(clippy::too_many_arguments)]+async fn generate_network_token_and_update_payment_method(+ state: &SessionState,+ platform: &domain::Platform,+ payment_method_data: &domain::PaymentMethodData,+ payment_method: PaymentMethod,+ payment_method_type: Option<storage_enums::PaymentMethodType>,+ customer_id: Option<id_type::CustomerId>,+ billing_name: Option<Secret<String>>,+ payment_method_billing_address: Option<&hyperswitch_domain_models::address::Address>,+ payment_method_info: Option<domain::PaymentMethod>,+) -> RouterResult<()> {+ // check if payment method already has a network token associated+ if let Some(true) = payment_method_info.as_ref().map(|pm| {+ pm.network_token_requestor_reference_id.is_some()+ || pm.status != common_enums::PaymentMethodStatus::Active+ }) {+ logger::info!(+ "Payment method already has a network token associated or the payment method is inactive, skipping network tokenization"+ );+ Ok(())+ } else {+ // Extract card data and attempt network tokenization+ if let domain::PaymentMethodData::Card(card_data) = &payment_method_data {+ let payment_method_create_request = payment_methods::get_payment_method_create_request(+ Some(payment_method_data),+ Some(payment_method),+ payment_method_type,+ &customer_id.clone(),+ billing_name,+ payment_method_billing_address,+ )+ .await?;++ // Call save_network_token_in_locker - it will handle tokenization if network_token_data is None+ let (network_token_resp, _dc, network_token_requestor_ref_id) =+ Box::pin(save_network_token_in_locker(+ state,+ platform,+ card_data,+ None,+ payment_method_create_request.clone(),+ ))+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Add Network Token In Locker Failed")?;++ // Update payment method with network token details if available+ if let (Some(token_resp), Some(pm_info)) = (network_token_resp, payment_method_info) {+ let network_token_locker_id = network_token_requestor_ref_id+ .as_ref()+ .map(|_| token_resp.payment_method_id.clone());++ // Create encrypted network token data+ let key_manager_state = state.into();+ let pm_network_token_data_encrypted: Option<+ Encryptable<Secret<serde_json::Value>>,+ > = {+ let pm_token_details = token_resp.card.as_ref().map(|card| {+ domain::PaymentMethodsData::Card(domain::CardDetailsPaymentMethod::from((+ card.clone(),+ None,+ )))+ });++ pm_token_details+ .async_map(|pm_card| {+ create_encrypted_data(+ &key_manager_state,+ platform.get_provider().get_key_store(),+ pm_card,+ )+ })+ .await+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encrypt payment method data")?+ };++ // Update the payment method with network token details+ let db = &*state.store;+ payment_methods::cards::update_payment_method_network_token_data(+ platform.get_provider().get_key_store(),+ db,+ pm_info.clone(),+ network_token_requestor_ref_id.clone(),+ network_token_locker_id,+ pm_network_token_data_encrypted,+ platform.get_provider().get_account().storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to update payment method with network token details")?;++ // Save network token details in callback_mapper table if network_token_requestor_ref_id is present+ if let (Some(nt_ref_id), Some(cust_id)) =+ (network_token_requestor_ref_id, customer_id.clone())+ {+ save_network_token_details_in_nt_mapper(+ state,+ platform,+ &cust_id,+ pm_info.payment_method_id.clone(),+ nt_ref_id,+ )+ .await+ .attach_printable(+ "Failed to save network token details in callback_mapper table",+ )?;+ }+ }+ }+ Ok(())+ }+}diff --git a/crates/router/src/core/webhooks/network_tokenization_incoming.rs b/crates/router/src/core/webhooks/network_tokenization_incoming.rsindex 1d28241f29..292f2df133 100644--- a/crates/router/src/core/webhooks/network_tokenization_incoming.rs+++ b/crates/router/src/core/webhooks/network_tokenization_incoming.rs@@ -337,6 +337,9 @@ pub async fn handle_metadata_update(network_token_locker_id: None,network_token_payment_method_data: None,last_modified_by: None,+ metadata: None,+ last_used_at: None,+ connector_mandate_details: None,}} else {storage::PaymentMethodUpdate::AdditionalDataUpdate {@@ -350,6 +353,9 @@ pub async fn handle_metadata_update(network_token_locker_id: Some(res.payment_method_id),network_token_payment_method_data: pm_data_encrypted.map(Into::into),last_modified_by: None,+ metadata: None,+ last_used_at: None,+ connector_mandate_details: None,}};let db = &*state.store;