Skip to content

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

refactor(payment_methods): add async network tokenization process tracker job (#13430)

Prasunna Soppa272715a8471d
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index ef6c071f75..aa3559dcf4 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -10592,6 +10592,7 @@ pub enum ProcessTrackerRunner {
InvoiceSyncflow,
PayoutSyncWorkFlow,
BatchBlocklistUpload,
+ NetworkTokenizationWorkflow,
}
#[derive(
diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs
index 7e303f9776..c87650635c 100644
--- a/crates/router/src/bin/scheduler.rs
+++ b/crates/router/src/bin/scheduler.rs
@@ -367,6 +367,9 @@ impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner {
)
}
}
+ storage::ProcessTrackerRunner::NetworkTokenizationWorkflow => Ok(Box::new(
+ workflows::network_tokenization::NetworkTokenizationWorkflow,
+ )),
}
};
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index c335e38d8e..4f25dd2abf 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -126,6 +126,10 @@ const PAYMENT_METHOD_MODULAR_COMPAT_PROCESS_TRACKER_ID_MAX_LENGTH: usize = 126;
const PAYMENT_METHOD_MODULAR_COMPAT_PROCESS_TRACKER_ID_SUFFIX_LENGTH: usize = 8;
#[cfg(feature = "v2")]
const PAYMENT_METHOD_REDACTED_FINGERPRINT_ID: &str = "FINGERPRINT_ID_REDACTED";
+#[cfg(feature = "v1")]
+const NETWORK_TOKENIZATION_TASK: &str = "NETWORK_TOKENIZATION";
+#[cfg(feature = "v1")]
+const NETWORK_TOKENIZATION_TAG: &str = "NETWORK_TOKENIZATION";
#[instrument(skip_all)]
pub async fn retrieve_payment_method_core(
@@ -710,6 +714,45 @@ pub async fn add_payment_method_modular_forward_compat_task(
Ok(())
}
+#[cfg(feature = "v1")]
+pub async fn add_network_tokenization_task(
+ db: &dyn StorageInterface,
+ tracking_data: storage::NetworkTokenizationTrackingData,
+ application_source: common_enums::ApplicationSource,
+) -> Result<(), ProcessTrackerError> {
+ let payment_method_id = tracking_data.payment_method_id.clone();
+
+ let runner = storage::ProcessTrackerRunner::NetworkTokenizationWorkflow;
+ let task = NETWORK_TOKENIZATION_TASK;
+ let tag = [NETWORK_TOKENIZATION_TAG];
+ let process_tracker_id = format!("{runner}_{task}_{payment_method_id}");
+
+ let process_tracker_entry = storage::ProcessTrackerNew::new(
+ process_tracker_id,
+ task,
+ runner,
+ tag,
+ tracking_data,
+ None,
+ common_utils::date_time::now(),
+ common_enums::ApiVersion::V1,
+ application_source,
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to construct NETWORK_TOKENIZATION process tracker task")?;
+
+ db.insert_process(process_tracker_entry)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable_lazy(|| {
+ format!(
+ "Failed while inserting NETWORK_TOKENIZATION task to process_tracker for payment_method_id: {payment_method_id}"
+ )
+ })?;
+
+ Ok(())
+}
+
#[cfg(feature = "v2")]
pub async fn add_payment_method_modular_backward_compat_task(
db: &dyn StorageInterface,
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 9bb4dd1f53..1f18739f19 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -24,7 +24,7 @@ use hyperswitch_domain_models::{
transformers::ForeignFrom as _,
};
use hyperswitch_interfaces::api::gateway;
-use hyperswitch_masking::{ExposeInterface, Secret};
+use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
use router_env::{instrument, tracing};
use super::helpers;
@@ -88,6 +88,35 @@ pub async fn save_network_token_details_in_nt_mapper(
Ok(())
}
+#[cfg(feature = "v1")]
+/// Inserts the network token reference ID along with merchant id and customer id in the
+/// CallbackMapper table (for its respective webhooks), when a reference ID is available.
+///
+/// No-op when `network_token_requestor_ref_id` is `None`.
+pub async fn save_optional_network_token_details_in_nt_mapper(
+ state: &SessionState,
+ provider: &domain::Provider,
+ customer_id: &id_type::CustomerId,
+ payment_method_id: String,
+ network_token_requestor_ref_id: Option<String>,
+) -> RouterResult<()> {
+ network_token_requestor_ref_id
+ .async_map(|nt_ref_id| {
+ save_network_token_details_in_nt_mapper(
+ state,
+ provider,
+ customer_id,
+ payment_method_id,
+ nt_ref_id,
+ )
+ })
+ .await
+ .transpose()
+ .attach_printable("Failed to save network token details in callback_mapper table")?;
+
+ Ok(())
+}
+
#[cfg(feature = "v1")]
async fn save_in_locker(
state: &SessionState,
@@ -286,6 +315,21 @@ where
_ => (None, None, None),
};
+ // Details retained for scheduling the asynchronous network tokenization task,
+ // since `billing_name` / `customer_id` are consumed within the branches below.
+ let billing_name_for_network_tokenization = billing_name.clone();
+ let customer_id_for_network_tokenization = customer_id.clone();
+ // The card read back from the locker does not carry the brand, so capture the card
+ // network here, while the original card data is still available.
+ let card_network_for_network_tokenization = save_payment_method_data
+ .request
+ .get_payment_method_data()
+ .get_card_data()
+ .and_then(|card| card.card_network.clone());
+ // Payment method that was saved without a network token, and therefore still needs
+ // one to be generated asynchronously by the process tracker.
+ let mut payment_method_pending_network_tokenization: Option<String> = None;
+
let pm_id = if let Some(existing_pm) = payment_method_info.clone().filter(|_| {
matches!(
save_payment_method_data.request.get_payment_method_data(),
@@ -498,6 +542,10 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to create vault source details")?;
+ // Whether a network token was generated for this card during this save flow.
+ // Read after the match below to decide if generation must be deferred.
+ let network_token_generated = network_token_requestor_ref_id.is_some();
+
match duplication_check {
Some(duplication_check) => match duplication_check {
payment_methods::transformers::DataDuplicationCheck::Duplicated => {
@@ -573,20 +621,14 @@ where
.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.get_provider(),
- &customer_id,
- resp.payment_method_id.clone(),
- nt_ref_id,
- )
- .await
- .attach_printable(
- "Failed to save network token details in callback_mapper table",
- )?;
- };
+ save_optional_network_token_details_in_nt_mapper(
+ state,
+ platform.get_provider(),
+ &customer_id,
+ resp.payment_method_id.clone(),
+ network_token_requestor_ref_id,
+ )
+ .await?;
}
Err(err) => {
if err.current_context().is_db_not_found() {
@@ -725,23 +767,14 @@ where
.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.get_provider(),
- &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",
- )?;
+ save_optional_network_token_details_in_nt_mapper(
+ state,
+ platform.get_provider(),
+ &customer_id,
+ resp.payment_method_id.clone(),
+ network_token_requestor_ref_id.clone(),
+ )
+ .await?;
Ok(pm)
}
@@ -1037,7 +1070,6 @@ where
match 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
save_network_token_details_in_nt_mapper(
state,
platform.get_provider(),
@@ -1058,36 +1090,71 @@ where
}
}
+ // A card can be saved without a network token in any of the duplication
+ // branches above (fresh, duplicated or metadata-changed) — e.g. an unsupported
+ // network or a failed tokenization service call. In every such case, defer
+ // generation to the process tracker. The workflow skips payment methods that are
+ // already tokenized, so this is safe for duplicated cards as well.
+ if save_payment_method_data.payment_method == PaymentMethod::Card
+ && !network_token_generated
+ {
+ payment_method_pending_network_tokenization =
+ Some(resp.payment_method_id.clone());
+ }
+
Some(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();
+ // No customer acceptance was provided in this transaction, so no new payment
+ // method is created. But the payment method may already have been saved earlier
+ // (e.g. recurring / MIT flow reusing a stored card). If that saved payment method
+ // still lacks a network token, defer generation to the process tracker.
+ payment_method_pending_network_tokenization = payment_method_info
+ .as_ref()
+ .filter(|pm_info| pm_info.network_token_requestor_reference_id.is_none())
+ .map(|pm_info| pm_info.payment_method_id.clone());
+ None
+ };
- 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,
+ // If network tokenization is enabled for the profile, trigger the process tracker
+ // workflow, which fetches the card, generates the network token and updates the
+ // payment method.
+ if business_profile.is_network_tokenization_enabled {
+ if let (Some(pending_pm_id), Some(nt_customer_id)) = (
+ payment_method_pending_network_tokenization,
+ customer_id_for_network_tokenization,
+ ) {
+ payment_methods::add_network_tokenization_task(
+ db,
+ types::storage::NetworkTokenizationTrackingData {
+ payment_method_id: pending_pm_id.clone(),
+ merchant_id: platform.get_provider().get_account().get_id().clone(),
+ profile_id: business_profile.get_id().clone(),
+ customer_id: nt_customer_id,
+ payment_method: save_payment_method_data.payment_method,
+ payment_method_type,
+ billing_name: billing_name_for_network_tokenization,
+ card_network: card_network_for_network_tokenization,
+ },
+ state.conf.application_source,
)
.await
- .inspect_err(|err| {
- logger::error!("Failed to process network tokenization: {:?}", err);
- })
- .attach_printable("Failed to process network tokenization")
- .ok();
+ .map_or_else(
+ |err| {
+ logger::error!(
+ payment_method_id=%pending_pm_id,
+ ?err,
+ "Failed to schedule NetworkTokenizationWorkflow process tracker task"
+ );
+ },
+ |()| {
+ logger::info!(
+ payment_method_id=%pending_pm_id,
+ "Scheduled NetworkTokenizationWorkflow process tracker task"
+ );
+ },
+ );
}
-
- None
- };
+ }
// check if there needs to be a config if yes then remove it to a different place
let connector_mandate_reference_id = if connector_mandate_id.is_some() {
if let Some(ref mut record) = original_connector_mandate_reference_id {
@@ -1597,7 +1664,11 @@ pub async fn save_network_token_in_locker(
.filter(|cn| network_tokenization_supported_card_networks.contains(cn))
.is_some()
{
- let optional_card_cvc = Some(card_data.card_cvc.clone());
+ // The CVC is never stored in the locker, so cards read back from it carry an
+ // empty CVC. Send no card security code at all in that case, rather than an
+ // empty one.
+ let optional_card_cvc =
+ Some(card_data.card_cvc.clone()).filter(|cvc| !cvc.peek().is_empty());
match network_tokenization::make_card_network_tokenization_request(
state,
&domain::CardDetail::from(card_data),
@@ -2021,12 +2092,12 @@ pub async fn save_card_and_network_token_in_locker(
state: &SessionState,
customer_id: id_type::CustomerId,
payment_method_status: common_enums::PaymentMethodStatus,
- payment_method_data: domain::PaymentMethodData,
+ _payment_method_data: domain::PaymentMethodData,
vault_operation: Option<hyperswitch_domain_models::payments::VaultOperation>,
payment_method_info: Option<domain::PaymentMethod>,
platform: &domain::Platform,
payment_method_create_request: api::PaymentMethodCreate,
- is_network_tokenization_enabled: bool,
+ _is_network_tokenization_enabled: bool,
business_profile: &domain::Profile,
) -> RouterResult<(
(
@@ -2159,32 +2230,10 @@ pub async fn save_card_and_network_token_in_locker(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Card In Locker Failed")?;
- if is_network_tokenization_enabled {
- match &payment_method_data {
- domain::PaymentMethodData::Card(card) => {
- let (
- network_token_resp,
- _network_token_duplication_check, //the duplication check is discarded, since each card has only one token, handling card duplication check will be suffice
- network_token_requestor_ref_id,
- ) = Box::pin(save_network_token_in_locker(
- state,
- platform.get_provider(),
- card,
- None,
- payment_method_create_request.clone(),
- ))
- .await?;
-
- Ok((
- (res, dc, network_token_requestor_ref_id),
- network_token_resp,
- ))
- }
- _ => Ok(((res, dc, None), None)), //network_token_resp is None in case of other payment methods
- }
- } else {
- Ok(((res, dc, None), None))
- }
+ // Network token generation is deferred to an async background task in save_payment_method()
+ // after the payment method is inserted into DB (so pm_id is available for the update).
+ // We return None here regardless of is_network_tokenization_enabled.
+ Ok(((res, dc, None), None))
}
}
}
@@ -2237,6 +2286,16 @@ async fn generate_network_token_and_update_payment_method(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Network Token In Locker Failed")?;
+ logger::info!(
+ card_network = ?card_data.card_network,
+ network_token_resp_present = network_token_resp.is_some(),
+ network_token_locker_id = ?network_token_resp
+ .as_ref()
+ .map(|resp| &resp.payment_method_id),
+ ?network_token_requestor_ref_id,
+ "NT response: received result from save_network_token_in_locker"
+ );
+
// 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
@@ -2297,23 +2356,131 @@ async fn generate_network_token_and_update_payment_method(
.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(
+ if let Some(cust_id) = customer_id.as_ref() {
+ save_optional_network_token_details_in_nt_mapper(
state,
platform.get_provider(),
- &cust_id,
+ cust_id,
pm_info.payment_method_id.clone(),
- nt_ref_id,
+ network_token_requestor_ref_id,
)
- .await
- .attach_printable(
- "Failed to save network token details in callback_mapper table",
- )?;
+ .await?;
}
}
}
Ok(())
}
}
+
+#[cfg(feature = "v1")]
+/// Inputs used to build the card sent for network token generation from the process tracker.
+///
+/// This exists as a named type rather than a tuple because `domain::Card` is defined in
+/// another crate, so the orphan rule requires a local type as the conversion source.
+pub struct NetworkTokenizationCardData<'a> {
+ pub locker_card: &'a api_models::payment_methods::Card,
+ pub tracking_data: &'a types::storage::NetworkTokenizationTrackingData,
+}
+
+#[cfg(feature = "v1")]
+impl From<NetworkTokenizationCardData<'_>> for domain::Card {
+ /// Builds the card used for network token generation from the card fetched out of the
+ /// locker, falling back to the process tracker tracking data for details the locker does
+ /// not return.
+ fn from(card_data: NetworkTokenizationCardData<'_>) -> Self {
+ let NetworkTokenizationCardData {
+ locker_card,
+ tracking_data,
+ } = card_data;
+
+ Self {
+ card_number: locker_card.card_number.clone(),
+ card_exp_month: locker_card.card_exp_month.clone(),
+ card_exp_year: locker_card.card_exp_year.clone(),
+ // The CVC is never stored in the locker, so there is none to send with the
+ // network tokenization request.
+ card_cvc: Secret::new(String::new()),
+ card_issuer: None,
+ // Card details always come from the locker. The card read back from it does not
+ // currently carry the brand, so fall back to the card network captured at payment
+ // time and carried through the process tracker tracking data.
+ card_network: locker_card
+ .card_brand
+ .as_deref()
+ .and_then(|card_brand| card_brand.parse::<common_enums::CardNetwork>().ok())
+ .or_else(|| tracking_data.card_network.clone()),
+ card_type: None,
+ card_issuing_country: None,
+ card_issuing_country_code: None,
+ bank_code: None,
+ card_holder_name: tracking_data.billing_name.clone(),
+ nick_name: locker_card.nick_name.clone().map(Secret::new),
+ co_badged_card_data: None,
+ }
+ }
+}
+
+#[cfg(feature = "v1")]
+/// Called from the `NetworkTokenizationWorkflow` process tracker job.
+///
+/// Fetches the card from the locker for the given payment method and delegates to
+/// `generate_network_token_and_update_payment_method`, which performs the actual
+/// network token generation and updates the payment method record.
+pub async fn generate_network_token_for_payment_method(
+ state: &SessionState,
+ platform: &domain::Platform,
+ tracking_data: &types::storage::NetworkTokenizationTrackingData,
+ payment_method: domain::PaymentMethod,
+) -> RouterResult<()> {
+ let customer_id = &tracking_data.customer_id;
+ let locker_id = payment_method
+ .locker_id
+ .as_ref()
+ .unwrap_or(&payment_method.payment_method_id);
+
+ // Fetch the raw card from the locker
+ let card_from_locker = payment_methods::cards::get_card_from_locker(
+ state,
+ customer_id,
+ &tracking_data.merchant_id,
+ locker_id,
+ )
+ .await
+ .inspect_err(|err| {
+ logger::error!(
+ ?err,
+ payment_method_id=%payment_method.payment_method_id,
+ "Failed to fetch card from locker for network token generation"
+ );
+ })?;
+
+ let locker_card = card_from_locker.get_card();
+
+ let card_data = domain::Card::from(NetworkTokenizationCardData {
+ locker_card: &locker_card,
+ tracking_data,
+ });
+
+ logger::info!(
+ payment_method_id = %payment_method.payment_method_id,
+ locker_id = %locker_id,
+ card_network = ?card_data.card_network,
+ locker_card_brand = ?locker_card.card_brand,
+ "NT request: card fetched from locker, initiating network token generation"
+ );
+
+ let payment_method_data = domain::PaymentMethodData::Card(card_data);
+
+ generate_network_token_and_update_payment_method(
+ state,
+ platform,
+ &payment_method_data,
+ tracking_data.payment_method,
+ tracking_data.payment_method_type,
+ Some(customer_id.clone()),
+ tracking_data.billing_name.clone(),
+ None,
+ Some(payment_method),
+ )
+ .await
+}
diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs
index 2029426b74..e8b2e00ee3 100644
--- a/crates/router/src/types/storage/payment_method.rs
+++ b/crates/router/src/types/storage/payment_method.rs
@@ -238,3 +238,24 @@ pub struct PaymentMethodModularCompatTrackingData {
pub organization_id: common_utils::id_type::OrganizationId,
pub last_modified_by: Option<String>,
}
+
+#[cfg(feature = "v1")]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
+pub struct NetworkTokenizationTrackingData {
+ pub payment_method_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
+ /// Profile the payment was made against. Network tokenization is configured per profile,
+ /// so this must come from the payment rather than the merchant's default profile.
+ pub profile_id: common_utils::id_type::ProfileId,
+ pub customer_id: common_utils::id_type::CustomerId,
+ pub payment_method: common_enums::PaymentMethod,
+ pub payment_method_type: Option<common_enums::PaymentMethodType>,
+ pub billing_name: Option<hyperswitch_masking::Secret<String>>,
+ /// Card network captured at payment time, used as a fallback when the card fetched from
+ /// the locker does not carry the brand (see `mk_get_card_response`).
+ ///
+ /// Only non-sensitive card metadata may be stored here: `tracking_data` is persisted
+ /// unencrypted and is included in process tracker log spans, so card number and CVC must
+ /// always be fetched from the locker instead.
+ pub card_network: Option<common_enums::CardNetwork>,
+}
diff --git a/crates/router/src/workflows.rs b/crates/router/src/workflows.rs
index 441cb8a3a8..42bead7483 100644
--- a/crates/router/src/workflows.rs
+++ b/crates/router/src/workflows.rs
@@ -26,3 +26,5 @@ pub mod payout_sync;
#[cfg(feature = "v1")]
pub mod batch_blocklist_upload;
+
+pub mod network_tokenization;
diff --git a/crates/router/src/workflows/network_tokenization.rs b/crates/router/src/workflows/network_tokenization.rs
new file mode 100644
index 0000000000..750e8455af
--- /dev/null
+++ b/crates/router/src/workflows/network_tokenization.rs
@@ -0,0 +1,161 @@
+#[cfg(feature = "v1")]
+use common_utils::ext_traits::ValueExt;
+use scheduler::workflows::ProcessTrackerWorkflow;
+#[cfg(feature = "v1")]
+use scheduler::{consumer::types::process_data, utils as pt_utils};
+
+use crate::{errors, logger, routes::SessionState, types::storage};
+
+pub struct NetworkTokenizationWorkflow;
+
+#[async_trait::async_trait]
+impl ProcessTrackerWorkflow<SessionState> for NetworkTokenizationWorkflow {
+ #[cfg(feature = "v1")]
+ async fn execute_workflow<'a>(
+ &'a self,
+ state: &'a SessionState,
+ process: storage::ProcessTracker,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ use crate::{
+ core::payments::tokenization, types::storage::NetworkTokenizationTrackingData,
+ };
+
+ let db = &*state.store;
+
+ let tracking_data: NetworkTokenizationTrackingData = process
+ .tracking_data
+ .clone()
+ .parse_value("NetworkTokenizationTrackingData")?;
+
+ let retry_count = process.retry_count;
+ let merchant_id = tracking_data.merchant_id.clone();
+
+ let key_store = state
+ .store
+ .get_merchant_key_store_by_merchant_id(
+ &merchant_id,
+ &state.store.get_master_key().to_vec().into(),
+ )
+ .await?;
+
+ let merchant_account = db
+ .find_merchant_account_by_merchant_id(&merchant_id, &key_store)
+ .await?;
+
+ let business_profile = db
+ .find_business_profile_by_merchant_id_profile_id(
+ &key_store,
+ &merchant_id,
+ &tracking_data.profile_id,
+ )
+ .await?;
+
+ if !business_profile.is_network_tokenization_enabled {
+ logger::info!(
+ payment_method_id=%tracking_data.payment_method_id,
+ "Network tokenization is disabled for this profile, skipping"
+ );
+ return db
+ .as_scheduler()
+ .finish_process_with_business_status(process, "SKIPPED_NT_DISABLED")
+ .await
+ .map_err(Into::<errors::ProcessTrackerError>::into);
+ }
+
+ let payment_method = db
+ .find_payment_method(
+ &key_store,
+ &tracking_data.payment_method_id,
+ merchant_account.storage_scheme,
+ )
+ .await?;
+
+ // Skip if already tokenized
+ if payment_method
+ .network_token_requestor_reference_id
+ .is_some()
+ {
+ logger::info!(
+ payment_method_id=%tracking_data.payment_method_id,
+ "Payment method already has a network token, skipping"
+ );
+ return db
+ .as_scheduler()
+ .finish_process_with_business_status(process, "ALREADY_TOKENIZED")
+ .await
+ .map_err(Into::<errors::ProcessTrackerError>::into);
+ }
+
+ let platform = crate::types::domain::Platform::new(
+ merchant_account.clone(),
+ key_store.clone(),
+ merchant_account,
+ key_store,
+ None,
+ );
+
+ let result = Box::pin(tokenization::generate_network_token_for_payment_method(
+ state,
+ &platform,
+ &tracking_data,
+ payment_method,
+ ))
+ .await;
+
+ match result {
+ Ok(()) => {
+ db.as_scheduler()
+ .finish_process_with_business_status(process, "COMPLETED_BY_PT")
+ .await
+ .map_err(Into::<errors::ProcessTrackerError>::into)?;
+ }
+ Err(err) => {
+ logger::error!(
+ payment_method_id=%tracking_data.payment_method_id,
+ ?err,
+ "Failed to generate network token in process tracker workflow"
+ );
+ let mapping = process_data::PaymentMethodsPTMapping::default();
+ let time_delta = if retry_count == 0 {
+ Some(mapping.default_mapping.start_after)
+ } else {
+ pt_utils::get_delay(retry_count + 1, &mapping.default_mapping.frequencies)
+ };
+ let schedule_time = pt_utils::get_time_from_delta(time_delta);
+ match schedule_time {
+ Some(s_time) => db
+ .as_scheduler()
+ .retry_process(process, s_time)
+ .await
+ .map_err(Into::<errors::ProcessTrackerError>::into)?,
+ None => db
+ .as_scheduler()
+ .finish_process_with_business_status(process, "RETRIES_EXCEEDED")
+ .await
+ .map_err(Into::<errors::ProcessTrackerError>::into)?,
+ };
+ }
+ }
+
+ Ok(())
+ }
+
+ #[cfg(feature = "v2")]
+ async fn execute_workflow<'a>(
+ &'a self,
+ _state: &'a SessionState,
+ _process: storage::ProcessTracker,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ todo!()
+ }
+
+ async fn error_handler<'a>(
+ &'a self,
+ _state: &'a SessionState,
+ process: storage::ProcessTracker,
+ _error: errors::ProcessTrackerError,
+ ) -> errors::CustomResult<(), errors::ProcessTrackerError> {
+ logger::error!(%process.id, "Failed while executing NetworkTokenizationWorkflow");
+ Ok(())
+ }
+}