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
feat(router): Add pm mod support in payments operation core v1 (#11107)
Prasunna Soppa22a2a3a6d5b3
diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rsindex 52ffd7a264..a4c76bfac8 100644--- a/crates/hyperswitch_domain_models/src/merchant_account.rs+++ b/crates/hyperswitch_domain_models/src/merchant_account.rs@@ -216,6 +216,12 @@ impl MerchantAccount {&self.merchant_id}+ #[cfg(feature = "v1")]+ /// Get the unique identifier of MerchantAccount+ pub fn get_default_profile(&self) -> &Option<common_utils::id_type::ProfileId> {+ &self.default_profile+ }+#[cfg(feature = "v2")]/// Get the unique identifier of MerchantAccountpub fn get_id(&self) -> &common_utils::id_type::MerchantId {diff --git a/crates/payment_methods/src/client/create.rs b/crates/payment_methods/src/client/create.rsindex 050eff70a2..10e49dd4c9 100644--- a/crates/payment_methods/src/client/create.rs+++ b/crates/payment_methods/src/client/create.rs@@ -96,8 +96,8 @@ pub struct CreatePaymentMethodResponse {pub payment_method_id: String,pub merchant_id: id_type::MerchantId,pub customer_id: Option<id_type::CustomerId>,- pub payment_method_type: Option<common_enums::PaymentMethod>,- pub payment_method_subtype: Option<common_enums::PaymentMethodType>,+ pub payment_method: Option<common_enums::PaymentMethod>,+ pub payment_method_type: Option<common_enums::PaymentMethodType>,pub recurring_enabled: Option<bool>,pub created: Option<PrimitiveDateTime>,pub last_used_at: Option<PrimitiveDateTime>,@@ -176,8 +176,8 @@ impl TryFrom<ModularPaymentMethodResponse> for CreatePaymentMethodResponse {payment_method_id: response.id,merchant_id: response.merchant_id,customer_id: response.customer_id,- payment_method_type: response.payment_method_type,- payment_method_subtype: response.payment_method_subtype,+ payment_method: response.payment_method_type,+ payment_method_type: response.payment_method_subtype,recurring_enabled: response.recurring_enabled,created: response.created,last_used_at: response.last_used_at,diff --git a/crates/payment_methods/src/client/retrieve.rs b/crates/payment_methods/src/client/retrieve.rsindex 82e8d430e5..c345412740 100644--- a/crates/payment_methods/src/client/retrieve.rs+++ b/crates/payment_methods/src/client/retrieve.rs@@ -26,8 +26,8 @@ pub struct RetrievePaymentMethodResponse {pub payment_method_id: String,pub merchant_id: id_type::MerchantId,pub customer_id: Option<id_type::CustomerId>,- pub payment_method_type: common_enums::PaymentMethod,- pub payment_method_subtype: common_enums::PaymentMethodType,+ pub payment_method: common_enums::PaymentMethod,+ pub payment_method_type: common_enums::PaymentMethodType,pub recurring_enabled: Option<bool>,pub created: Option<PrimitiveDateTime>,pub last_used_at: Option<PrimitiveDateTime>,@@ -59,8 +59,8 @@ impl TryFrom<ModularPMRetrieveResponse> for RetrievePaymentMethodResponse {payment_method_id,merchant_id: v2_resp.merchant_id,customer_id,- payment_method_type: v2_resp.payment_method_type,- payment_method_subtype: v2_resp.payment_method_subtype,+ payment_method: v2_resp.payment_method_type,+ payment_method_type: v2_resp.payment_method_subtype,recurring_enabled: v2_resp.recurring_enabled,created: v2_resp.created,last_used_at: v2_resp.last_used_at,diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rsindex a2aba5b9ee..43eeac5a35 100644--- a/crates/router/src/core/payment_methods/transformers.rs+++ b/crates/router/src/core/payment_methods/transformers.rs@@ -20,8 +20,10 @@ use masking::Mask;use masking::{ExposeInterface, PeekInterface};#[cfg(feature = "v1")]use payment_methods::client::{- PaymentMethodClient, UpdatePaymentMethod, UpdatePaymentMethodV1Payload,- UpdatePaymentMethodV1Request,+ self as pm_client,+ create::{CreatePaymentMethodResponse, CreatePaymentMethodV1Request},+ retrieve::{RetrievePaymentMethodResponse, RetrievePaymentMethodV1Request},+ UpdatePaymentMethod, UpdatePaymentMethodV1Payload, UpdatePaymentMethodV1Request,};use router_env::RequestId;#[cfg(feature = "v1")]@@ -1157,7 +1159,7 @@ pub async fn call_modular_payment_method_update());let trace = RequestIdentifier::new(&state.conf.trace_header.header_name).use_incoming_id(state.conf.trace_header.id_reuse_strategy);- let client = PaymentMethodClient::new(+ let client = pm_client::PaymentMethodClient::new(&state.conf.micro_services.payment_methods_base_url,&parent_headers,&trace,@@ -1179,3 +1181,353 @@ pub async fn call_modular_payment_method_update(})?;Ok(())}++#[cfg(feature = "v1")]+#[derive(Clone, Debug)]+pub struct DomainPaymentMethodWrapper(pub domain::PaymentMethod);++#[cfg(feature = "v1")]+pub struct DomainPaymentMethodDataWrapper(pub domain::PaymentMethodData);++#[derive(Clone, Debug)]+#[cfg(feature = "v1")]+pub struct PaymentMethodWithRawData {+ pub payment_method: DomainPaymentMethodWrapper,+ pub raw_payment_method_data: Option<domain::PaymentMethodData>,+}++#[cfg(feature = "v1")]+// from to convert payment method response to domain payment method+impl TryFrom<&RetrievePaymentMethodResponse> for DomainPaymentMethodWrapper {+ type Error = error_stack::Report<errors::ApiErrorResponse>;+ fn try_from(response: &RetrievePaymentMethodResponse) -> Result<Self, Self::Error> {+ Ok(Self(domain::PaymentMethod {+ //for guest checkout, where customer id, this will fail.+ customer_id: response+ .customer_id+ .clone()+ .get_required_value("CustomerId")?,+ merchant_id: response.merchant_id.clone(),+ payment_method_id: response.payment_method_id.clone(),+ accepted_currency: None,+ scheme: None,+ token: None,+ cardholder_name: None,+ issuer_name: None,+ issuer_country: None,+ payer_country: None,+ is_stored: None,+ swift_code: None,+ direct_debit_token: None,+ created_at: response+ .created+ .unwrap_or_else(common_utils::date_time::now),+ last_modified: response+ .last_used_at+ .unwrap_or_else(common_utils::date_time::now),+ payment_method: Some(response.payment_method),+ payment_method_type: Some(response.payment_method_type),+ payment_method_issuer: None,+ payment_method_issuer_code: None,+ metadata: None,+ payment_method_data: None, //this is not required in any flow, hence None+ locker_id: None, //This id will always be with PM Service+ last_used_at: response+ .last_used_at+ .unwrap_or_else(common_utils::date_time::now),+ connector_mandate_details: None,+ customer_acceptance: None,+ status: common_enums::PaymentMethodStatus::Active, //should be sent from PM service+ network_transaction_id: None,+ client_secret: None,+ payment_method_billing_address: None, //Should be sent from PM service+ updated_by: None,+ version: common_enums::ApiVersion::V1, //to be updated later+ network_token_requestor_reference_id: None, //to be added later+ network_token_locker_id: None,+ network_token_payment_method_data: None,+ vault_source_details: domain::PaymentMethodVaultSourceDetails::InternalVault,+ created_by: None,+ last_modified_by: None,+ customer_details: None,+ }))+ }+}++#[cfg(feature = "v1")]+// from to convert payment method response to domain payment method+impl+ TryFrom<(+ payment_methods::types::RawPaymentMethodData,+ Option<domain::CardToken>,+ )> for DomainPaymentMethodDataWrapper+{+ type Error = error_stack::Report<errors::ApiErrorResponse>;++ fn try_from(+ (raw_data, card_token): (+ payment_methods::types::RawPaymentMethodData,+ Option<domain::CardToken>,+ ),+ ) -> Result<Self, Self::Error> {+ match raw_data {+ payment_methods::types::RawPaymentMethodData::Card(card_detail) => {+ // Use card_cvc from card_token if available, otherwise fall back to card_details.card_cvc+ let card_cvc = card_token+ .as_ref()+ .and_then(|token| token.card_cvc.clone())+ .or(card_detail.card_cvc.clone())+ .get_required_value("card_cvc")?;+ let card_holder_name = card_token+ .and_then(|token| token.card_holder_name.clone())+ .or(card_detail.card_holder_name.clone());++ Ok(Self(domain::PaymentMethodData::Card(+ hyperswitch_domain_models::payment_method_data::Card {+ card_number: card_detail.card_number,+ card_exp_month: card_detail.card_exp_month,+ card_exp_year: card_detail.card_exp_year,+ card_cvc,+ card_issuer: card_detail.card_issuer,+ card_network: card_detail.card_network,+ card_type: card_detail.card_type.map(|card_type| card_type.to_string()),+ card_issuing_country: card_detail.card_issuing_country,+ card_issuing_country_code: None,+ bank_code: None,+ nick_name: card_detail.nick_name,+ card_holder_name,+ co_badged_card_data: None,+ },+ )))+ }+ }+ }+}++#[cfg(feature = "v1")]+impl TryFrom<CreatePaymentMethodResponse> for DomainPaymentMethodWrapper {+ type Error = error_stack::Report<errors::ApiErrorResponse>;+ fn try_from(response: CreatePaymentMethodResponse) -> Result<Self, Self::Error> {+ Ok(Self(domain::PaymentMethod {+ //for guest checkout, where customer id, this will fail.+ customer_id: response.customer_id.get_required_value("CustomerId")?,+ merchant_id: response.merchant_id,+ payment_method_id: response.payment_method_id,+ accepted_currency: None,+ scheme: None,+ token: None,+ cardholder_name: None,+ issuer_name: None,+ issuer_country: None,+ payer_country: None,+ is_stored: None,+ swift_code: None,+ direct_debit_token: None,+ created_at: response+ .created+ .unwrap_or_else(common_utils::date_time::now),+ last_modified: response+ .last_used_at+ .unwrap_or_else(common_utils::date_time::now),+ payment_method: response.payment_method,+ payment_method_type: response.payment_method_type,+ payment_method_issuer: None,+ payment_method_issuer_code: None,+ metadata: None,+ payment_method_data: None, //use response.card to convert to OptionalEncryptableValue+ locker_id: None, //This id will always be with PM Service+ last_used_at: response+ .last_used_at+ .unwrap_or_else(common_utils::date_time::now),+ connector_mandate_details: None,+ customer_acceptance: None,+ status: common_enums::PaymentMethodStatus::Active, //should be sent from PM service+ network_transaction_id: None,+ client_secret: None,+ payment_method_billing_address: None, //Should be sent from PM service+ updated_by: None,+ version: common_enums::ApiVersion::V1,+ network_token_requestor_reference_id: None, //to be added later+ network_token_locker_id: None,+ network_token_payment_method_data: None,+ vault_source_details: domain::PaymentMethodVaultSourceDetails::InternalVault,+ created_by: None,+ last_modified_by: None,+ customer_details: None,+ }))+ }+}++//Fetch Payment Method from Modular Service+#[cfg(feature = "v1")]+pub async fn fetch_payment_method_from_modular_service(+ state: &routes::SessionState,+ merchant_id: &id_type::MerchantId,+ profile_id: &id_type::ProfileId,+ payment_method_id: &str, //Currently PM id is string in v1+ pmd_card_token: Option<domain::CardToken>,+) -> CustomResult<PaymentMethodWithRawData, errors::ApiErrorResponse> {+ let payment_method_fetch_req = RetrievePaymentMethodV1Request {+ payment_method_id: api_models::payment_methods::PaymentMethodId {+ payment_method_id: payment_method_id.to_owned(),+ },+ fetch_raw_detail: true,+ modular_service_prefix: state.conf.micro_services.payment_methods_prefix.0.clone(),+ };++ //Fetch modular service call+ let pm_response =+ retrieve_pm_modular_service_call(state, merchant_id, profile_id, payment_method_fetch_req)+ .await?;++ //Convert PMResponse to PaymentMethodWithRawData+ let payment_method = DomainPaymentMethodWrapper::try_from(&pm_response)?;++ //Convert RawPaymentMethodData to domain::PaymentMethodData+ let raw_payment_method_data = pm_response+ .raw_payment_method_data+ .map(|raw_data| {+ DomainPaymentMethodDataWrapper::try_from((raw_data, pmd_card_token.clone()))+ })+ .transpose()+ .attach_printable("Failed to convert raw payment method data")?;++ let pm_wrapper = PaymentMethodWithRawData {+ payment_method,+ raw_payment_method_data: raw_payment_method_data.map(|wrapper| wrapper.0),+ };+ Ok(pm_wrapper)+}++#[cfg(feature = "v1")]+pub async fn retrieve_pm_modular_service_call(+ state: &routes::SessionState,+ merchant_id: &id_type::MerchantId,+ profile_id: &id_type::ProfileId,+ payment_method_fetch_req: RetrievePaymentMethodV1Request,+) -> CustomResult<RetrievePaymentMethodResponse, errors::ApiErrorResponse> {+ let internal_api_key = &state+ .conf+ .internal_merchant_id_profile_id_auth+ .internal_api_key;+ let mut parent_headers = Headers::new();+ parent_headers.insert((+ headers::X_PROFILE_ID.to_string(),+ profile_id.get_string_repr().to_string().into_masked(),+ ));+ parent_headers.insert((+ headers::X_INTERNAL_API_KEY.to_string(),+ internal_api_key.clone().expose().to_string().into_masked(),+ ));+ parent_headers.insert((+ headers::X_MERCHANT_ID.to_string(),+ merchant_id.get_string_repr().to_string().into_masked(),+ ));++ let trace = RequestIdentifier::new(&state.conf.trace_header.header_name)+ .use_incoming_id(state.conf.trace_header.id_reuse_strategy);++ //pm client construction+ let client = pm_client::PaymentMethodClient::new(+ &state.conf.micro_services.payment_methods_base_url,+ &parent_headers,+ &trace,+ );++ //Modular service call+ let pm_response =+ pm_client::RetrievePaymentMethod::call(state, &client, payment_method_fetch_req)+ .await+ .map_err(|err| {+ logger::debug!("Error in retrieving payment method: {:?}", err);+ errors::ApiErrorResponse::InternalServerError+ })+ .attach_printable("Failed to retrieve payment method from modular service")?;++ Ok(pm_response)+}++//Create Payment Method from Modular Service+#[cfg(feature = "v1")]+#[allow(clippy::too_many_arguments)]+pub async fn create_payment_method_in_modular_service(+ state: &routes::SessionState,+ merchant_id: &id_type::MerchantId,+ profile_id: &id_type::ProfileId,+ payment_method: common_enums::PaymentMethod,+ payment_method_type: common_enums::PaymentMethodType,+ payment_method_data: domain::PaymentMethodData,+ _billing_address: Option<hyperswitch_domain_models::address::Address>,+ customer_id: id_type::CustomerId,+) -> CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {+ let payment_method_request = CreatePaymentMethodV1Request {+ merchant_id: merchant_id.clone(),+ payment_method,+ payment_method_type,+ metadata: None,+ customer_id,+ payment_method_data,+ billing: None,+ network_tokenization: None,+ storage_type: Some(common_enums::StorageType::Persistent),+ modular_service_prefix: state.conf.micro_services.payment_methods_prefix.0.clone(),+ };++ //Create modular service call+ let pm_response =+ create_pm_modular_service_call(state, merchant_id, profile_id, payment_method_request)+ .await?;++ //Convert PMResponse to PaymentMethodWithRawData+ let payment_method_with_raw_data = DomainPaymentMethodWrapper::try_from(pm_response)?;++ Ok(payment_method_with_raw_data.0)+}++#[cfg(feature = "v1")]+pub async fn create_pm_modular_service_call(+ state: &routes::SessionState,+ merchant_id: &id_type::MerchantId,+ profile_id: &id_type::ProfileId,+ payment_method_create_req: CreatePaymentMethodV1Request,+) -> CustomResult<CreatePaymentMethodResponse, errors::ApiErrorResponse> {+ let internal_api_key = &state+ .conf+ .internal_merchant_id_profile_id_auth+ .internal_api_key;+ let mut parent_headers = Headers::new();+ parent_headers.insert((+ headers::X_PROFILE_ID.to_string(),+ profile_id.get_string_repr().to_string().into_masked(),+ ));+ parent_headers.insert((+ headers::X_INTERNAL_API_KEY.to_string(),+ internal_api_key.clone().expose().to_string().into_masked(),+ ));+ parent_headers.insert((+ headers::X_MERCHANT_ID.to_string(),+ merchant_id.get_string_repr().to_string().into_masked(),+ ));++ let trace = RequestIdentifier::new(&state.conf.trace_header.header_name)+ .use_incoming_id(state.conf.trace_header.id_reuse_strategy);++ //pm client construction+ let client = pm_client::PaymentMethodClient::new(+ &state.conf.micro_services.payment_methods_base_url,+ &parent_headers,+ &trace,+ );++ //Modular service call+ let pm_response =+ pm_client::CreatePaymentMethod::call(state, &client, payment_method_create_req)+ .await+ .map_err(|err| {+ logger::debug!("Error in creating payment method: {:?}", err);+ errors::ApiErrorResponse::InternalServerError+ })+ .attach_printable("Failed to create payment method in modular service")?;++ Ok(pm_response)+}diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 6df476674a..ef43b4893b 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -130,7 +130,7 @@ use crate::{consts,core::{errors::{self, CustomResult, RouterResponse, RouterResult},- payment_methods::{cards, network_tokenization},+ payment_methods::{cards, network_tokenization, transformers as pm_transformers},payments::helpers::{get_applepay_metadata, is_applepay_predecrypted_flow_supported,is_googlepay_predecrypted_flow_supported,@@ -640,10 +640,15 @@ where.to_validate_request()?.validate_request(&req, platform.get_processor())?;- tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id));+ // Create feature_config+ let feature_config = core_utils::get_feature_config(state, platform).await;++ let payment_method_info = operation+ .to_domain()?+ .fetch_payment_method(state, &req, platform, &feature_config)+ .await?;- // Create feature_set early to avoid passing entire payment_data to get_trackers- let feature_set = core_utils::get_feature_set(state, platform).await;+ tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id));// get profile from headerslet operations::GetTrackerResponse {@@ -661,6 +666,7 @@ whereplatform,auth_flow,&header_payload,+ payment_method_info,).await?;@@ -674,6 +680,18 @@ where&payment_data.get_payment_intent().clone(),)?;+ operation+ .to_domain()?+ .create_payment_method(+ state,+ &req,+ platform,+ &mut payment_data,+ &business_profile,+ &feature_config,+ )+ .await?;+let (operation, customer) = operation.to_domain()?// get_customer_details@@ -931,6 +949,7 @@ where&business_profile,false,None,+ &feature_config,).await?;@@ -1004,7 +1023,7 @@ where&mut payment_data,&business_profile,req.get_payment_method_data(),- &feature_set,+ &feature_config,).await?;@@ -1031,7 +1050,7 @@ whereplatform.get_provider(),&payment_data,&router_data_for_pm_mandate,- &feature_set,+ &feature_config,).await?;@@ -1101,6 +1120,7 @@ where&business_profile,false,routing_decision,+ &feature_config,).await?;@@ -1186,6 +1206,7 @@ where#[cfg(not(feature = "frm"))]None,&business_profile,+ &feature_config,).await?;};@@ -1208,7 +1229,7 @@ where&mut payment_data,&business_profile,req.get_payment_method_data(),- &feature_set,+ &feature_config,).await?;@@ -1235,7 +1256,7 @@ whereplatform.get_provider(),&payment_data,&router_data_for_pm_mandate,- &feature_set,+ &feature_config,).await?;@@ -1442,7 +1463,7 @@ wheretracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id));- let feature_set = core_utils::get_feature_set(state, &platform).await;+ let feature_config = core_utils::get_feature_config(state, &platform).await;let operations::GetTrackerResponse {operation,@@ -1459,6 +1480,7 @@ where&platform,auth_flow,&header_payload,+ None,).await?;@@ -1583,7 +1605,7 @@ whereplatform.get_provider(),&payment_data,&router_data_for_pm_mandate,- &feature_set,+ &feature_config,).await?;@@ -2287,7 +2309,7 @@ async fn handle_pm_and_mandate_post_update<F, R, Op, D>(payment_data: &mut D,business_profile: &domain::Profile,request_payment_method_data: Option<api_models::payments::PaymentMethodData>,- feature_set: &core_utils::FeatureSet,+ feature_config: &core_utils::FeatureConfig,) -> CustomResult<(), errors::ApiErrorResponse>whereF: Clone + Send + Sync,@@ -2295,7 +2317,7 @@ whereD: OperationSessionGetters<F> + Send + Sync,Op: Operation<F, R, Data = D> + Send + Sync,{- if feature_set.is_modular_merchant {+ if feature_config.is_payment_method_modular_allowed {logger::debug!(payment_id = ?payment_data.get_payment_attempt().payment_id,"Modular merchant detected; calling update_modular_pm_and_mandate"@@ -4564,6 +4586,7 @@ pub async fn call_connector_service_prerequisites<F, RouterDReq, ApiRequest, D>(business_profile: &domain::Profile,should_retry_with_pan: bool,routing_decision: Option<routing_helpers::RoutingDecisionData>,+ feature_config: &core_utils::FeatureConfig,) -> RouterResult<(helpers::MerchantConnectorAccountType,RouterData<F, RouterDReq, router_types::PaymentsResponseData>,@@ -4667,6 +4690,7 @@ whereplatform,business_profile,should_retry_with_pan,+ feature_config,).await?;*payment_data = pd;@@ -7717,12 +7741,13 @@ async fn decide_payment_method_tokenize_action(payment_method,connector_name);-+ //this will throw error, in repeat cit, since pm token generate wont be of this keylet connector_token_option = redis_conn.get_key::<Option<String>>(&key.into()).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to fetch the token from redis")?;+ //new merchant,dont throw error??match connector_token_option {Some(connector_token) => {@@ -7778,6 +7803,7 @@ pub async fn get_connector_tokenization_action_when_confirm_true<F, Req, D>(platform: &domain::Platform,business_profile: &domain::Profile,should_retry_with_pan: bool,+ feature_config: &core_utils::FeatureConfig,) -> RouterResult<(D, TokenizationAction)>whereF: Send + Clone,@@ -7836,38 +7862,58 @@ wherelet connector_tokenization_action = match payment_method_action {TokenizationAction::TokenizeInRouter => {- let (_operation, payment_method_data, pm_id) = operation- .to_domain()?- .make_pm_data(- state,- payment_data,- validate_result.storage_scheme,- platform,- business_profile,- should_retry_with_pan,- )- .await?;- payment_data.set_payment_method_data(payment_method_data);- payment_data.set_payment_method_id_in_attempt(pm_id);+ if !feature_config.is_payment_method_modular_allowed {+ let (_operation, payment_method_data, pm_id) = operation+ .to_domain()?+ .make_pm_data(+ state,+ payment_data,+ validate_result.storage_scheme,+ platform,+ business_profile,+ should_retry_with_pan,+ )+ .await?;+ payment_data.set_payment_method_data(payment_method_data);+ payment_data.set_payment_method_id_in_attempt(pm_id);+ } else {+ logger::debug!("Organization is eligible for PM Modular service, skipping make_pm_data call since raw payment method data fetch is done");+ //Merchant enabled for PM Modular service+ let pm_id = payment_data+ .get_payment_method_info()+ .map(|pm| pm.payment_method_id.clone());+ //Payment method data is already set in get trackers flow if modular pm service is enabled+ payment_data.set_payment_method_id_in_attempt(pm_id);+ }TokenizationAction::SkipConnectorTokenization}TokenizationAction::TokenizeInConnector => TokenizationAction::TokenizeInConnector,TokenizationAction::TokenizeInConnectorAndRouter => {- let (_operation, payment_method_data, pm_id) = operation- .to_domain()?- .make_pm_data(- state,- payment_data,- validate_result.storage_scheme,- platform,- business_profile,- should_retry_with_pan,- )- .await?;+ if !feature_config.is_payment_method_modular_allowed {+ let (_operation, payment_method_data, pm_id) = operation+ .to_domain()?+ .make_pm_data(+ state,+ payment_data,+ validate_result.storage_scheme,+ platform,+ business_profile,+ should_retry_with_pan,+ )+ .await?;- payment_data.set_payment_method_data(payment_method_data);- payment_data.set_payment_method_id_in_attempt(pm_id);+ payment_data.set_payment_method_data(payment_method_data);+ payment_data.set_payment_method_id_in_attempt(pm_id);+ } else {+ //Merchant enabled for PM Modular service+ logger::debug!("Organization is eligible for PM Modular service, skipping make_pm_data call since raw payment method data fetch is done");+ let pm_id = payment_data+ .get_payment_method_info()+ .map(|pm| pm.payment_method_id.clone());+ //Payment method data is already set in get trackers flow if modular pm service is enabled+ payment_data.set_payment_method_id_in_attempt(pm_id);+ }TokenizationAction::TokenizeInConnector}TokenizationAction::ConnectorToken(token) => {@@ -11622,6 +11668,7 @@ pub trait OperationSessionSetters<F> {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_payment_method_info(&mut self, payment_method_info: Option<domain::PaymentMethod>);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);@@ -11884,6 +11931,10 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentData<F> {self.payment_method_token = payment_method_token;}+ fn set_payment_method_info(&mut self, payment_method_info: Option<domain::PaymentMethod>) {+ self.payment_method_info = payment_method_info;+ }+fn set_payment_method_id_in_attempt(&mut self, payment_method_id: Option<String>) {self.payment_attempt.payment_method_id = payment_method_id;}@@ -12223,6 +12274,10 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> {todo!()}+ fn set_payment_method_info(&mut self, payment_method_info: Option<domain::PaymentMethod>) {+ todo!()+ }+fn set_payment_method_token(&mut self, _payment_method_token: Option<PaymentMethodToken>) {todo!()}@@ -12529,6 +12584,10 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentConfirmData<F> {todo!()}+ fn set_payment_method_info(&mut self, payment_method_info: Option<domain::PaymentMethod>) {+ todo!()+ }+fn set_payment_method_token(&mut self, _payment_method_token: Option<PaymentMethodToken>) {todo!()}@@ -12836,6 +12895,10 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentStatusData<F> {todo!()}+ fn set_payment_method_info(&mut self, payment_method_info: Option<domain::PaymentMethod>) {+ todo!()+ }+fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) {todo!()}@@ -13140,6 +13203,10 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentCaptureData<F> {todo!()}+ fn set_payment_method_info(&mut self, payment_method_info: Option<domain::PaymentMethod>) {+ todo!()+ }+fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) {todo!()}@@ -13600,6 +13667,10 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentCancelData<F> {todo!()}+ fn set_payment_method_info(&mut self, payment_method_info: Option<domain::PaymentMethod>) {+ todo!()+ }+fn set_email_if_not_present(&mut self, _email: pii::Email) {todo!()}diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 45a9f8e683..a3447987dc 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -458,6 +458,7 @@ pub async fn get_token_pm_type_mandate_details(platform: &domain::Platform,payment_method_id: Option<String>,payment_intent_customer_id: Option<&id_type::CustomerId>,+ pm_info: Option<domain::PaymentMethod>,) -> RouterResult<MandateGenericData> {let mandate_data = request.mandate_data.clone().map(MandateData::foreign_from);let (@@ -546,17 +547,20 @@ pub async fn get_token_pm_type_mandate_details()}RecurringDetails::PaymentMethodId(payment_method_id) => {- let payment_method_info = state- .store- .find_payment_method(- platform.get_provider().get_key_store(),- payment_method_id,- platform.get_provider().get_account().storage_scheme,- )- .await- .to_not_found_response(- errors::ApiErrorResponse::PaymentMethodNotFound,- )?;+ let payment_method_info = match pm_info {+ Some(pm) => pm.clone(),+ None => state+ .store+ .find_payment_method(+ platform.get_provider().get_key_store(),+ payment_method_id,+ platform.get_provider().get_account().storage_scheme,+ )+ .await+ .to_not_found_response(+ errors::ApiErrorResponse::PaymentMethodNotFound,+ )?,+ };let customer_id = request.get_customer_id().get_required_value("customer_id")?;@@ -680,22 +684,26 @@ pub async fn get_token_pm_type_mandate_details()}} else {- let payment_method_info = payment_method_id- .async_map(|payment_method_id| async move {- state- .store- .find_payment_method(- platform.get_provider().get_key_store(),- &payment_method_id,- platform.get_provider().get_account().storage_scheme,- )- .await- .to_not_found_response(- errors::ApiErrorResponse::PaymentMethodNotFound,- )- })- .await- .transpose()?;+ let payment_method_info = match pm_info {+ Some(pm) => Some(pm.clone()),+ None => payment_method_id+ .async_map(|payment_method_id| async move {+ state+ .store+ .find_payment_method(+ platform.get_provider().get_key_store(),+ &payment_method_id,+ platform.get_provider().get_account().storage_scheme,+ )+ .await+ .to_not_found_response(+ errors::ApiErrorResponse::PaymentMethodNotFound,+ )+ })+ .await+ .transpose()?,+ };+(request.payment_token.to_owned(),request.payment_method,@@ -710,20 +718,23 @@ pub async fn get_token_pm_type_mandate_details(}}None => {- let payment_method_info = payment_method_id- .async_map(|payment_method_id| async move {- state- .store- .find_payment_method(- platform.get_provider().get_key_store(),- &payment_method_id,- platform.get_provider().get_account().storage_scheme,- )- .await- .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)- })- .await- .transpose()?;+ let payment_method_info = match pm_info {+ Some(pm) => Some(pm.clone()),+ None => payment_method_id+ .async_map(|payment_method_id| async move {+ state+ .store+ .find_payment_method(+ platform.get_provider().get_key_store(),+ &payment_method_id,+ platform.get_provider().get_account().storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)+ })+ .await+ .transpose()?,+ };(request.payment_token.to_owned(),request.payment_method,diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rsindex 72ad9aae85..f37f08e801 100644--- a/crates/router/src/core/payments/operations.rs+++ b/crates/router/src/core/payments/operations.rs@@ -99,6 +99,8 @@ pub use self::{use super::{helpers, CustomerDetails, OperationSessionGetters, OperationSessionSetters};#[cfg(feature = "v2")]use crate::core::payments;+#[cfg(feature = "v1")]+use crate::core::payments::pm_transformers::PaymentMethodWithRawData;use crate::{core::{errors::{self, CustomResult, RouterResult},@@ -216,6 +218,7 @@ pub trait GetTracker<F: Clone, D, R>: Send {platform: &domain::Platform,auth_flow: services::AuthFlow,header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ payment_method_with_raw_data: Option<PaymentMethodWithRawData>,) -> RouterResult<GetTrackerResponse<'a, F, R, D>>;#[cfg(feature = "v2")]@@ -303,6 +306,29 @@ pub trait Domain<F: Clone, R, D>: Send + Sync {) -> CustomResult<(), errors::ApiErrorResponse> {Ok(())}+ #[cfg(feature = "v1")]+ async fn create_payment_method(+ &self,+ _state: &SessionState,+ _request: &R,+ _platform: &domain::Platform,+ _payment_data: &mut D,+ _business_profile: &domain::Profile,+ _feature_config: &core_utils::FeatureConfig,+ ) -> RouterResult<()> {+ Ok(())+ }++ #[cfg(feature = "v1")]+ async fn fetch_payment_method(+ &self,+ _state: &SessionState,+ _request: &R,+ _platform: &domain::Platform,+ _feature_config: &core_utils::FeatureConfig,+ ) -> RouterResult<Option<PaymentMethodWithRawData>> {+ Ok(None)+ }#[allow(clippy::too_many_arguments)]async fn make_pm_data<'a>(@@ -588,7 +614,7 @@ pub trait PostUpdateTracker<F, D, R: Send>: Send {_provider: &domain::Provider,_payment_data: &D,_router_data: &types::RouterData<F, R, PaymentsResponseData>,- _feature_set: &core_utils::FeatureSet,+ _feature_set: &core_utils::FeatureConfig,) -> RouterResult<()>whereF: 'b + Clone + Send + Sync,diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rsindex 385991c4a0..50f7959135 100644--- a/crates/router/src/core/payments/operations/payment_approve.rs+++ b/crates/router/src/core/payments/operations/payment_approve.rs@@ -42,6 +42,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRplatform: &domain::Platform,_auth_flow: services::AuthFlow,_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ _payment_method_wrapper: Option<operations::PaymentMethodWithRawData>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsCaptureRequest, PaymentData<F>>,> {diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rsindex 78ff394843..b6a245a8a0 100644--- a/crates/router/src/core/payments/operations/payment_cancel.rs+++ b/crates/router/src/core/payments/operations/payment_cancel.rs@@ -44,6 +44,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelReplatform: &domain::Platform,_auth_flow: services::AuthFlow,_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ _payment_method_wrapper: Option<operations::PaymentMethodWithRawData>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsCancelRequest, PaymentData<F>>,> {diff --git a/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs b/crates/router/src/core/payments/operations/payment_cancel_post_capture.rsindex 15a82aead4..61f8b95653 100644--- a/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs+++ b/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs@@ -42,6 +42,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelPoplatform: &domain::Platform,_auth_flow: services::AuthFlow,_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ _payment_method_wrapper: Option<operations::PaymentMethodWithRawData>,) -> RouterResult<operations::GetTrackerResponse<'a,diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rsindex 149c160eaa..e871c78329 100644--- a/crates/router/src/core/payments/operations/payment_capture.rs+++ b/crates/router/src/core/payments/operations/payment_capture.rs@@ -44,6 +44,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, api::Paymenplatform: &domain::Platform,_auth_flow: services::AuthFlow,_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ _payment_method_wrapper: Option<operations::PaymentMethodWithRawData>,) -> RouterResult<operations::GetTrackerResponse<'a,diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rsindex f4731f3a2b..12d9a119dc 100644--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs@@ -44,6 +44,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>platform: &domain::Platform,_auth_flow: services::AuthFlow,_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ _payment_method_wrapper: Option<operations::PaymentMethodWithRawData>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>>{let db = &*state.store;@@ -133,6 +134,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>platform,payment_attempt.payment_method_id.clone(),payment_intent.customer_id.as_ref(),+ None,)).await?;let customer_acceptance: Option<CustomerAcceptance> =diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex 4ab818f4b4..203f593ab9 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -5,7 +5,7 @@ use api_models::payment_methods::PaymentMethodsData;use api_models::{admin::ExtendedCardInfoConfig,enums::FrmSuggestion,- payments::{ConnectorMandateReferenceId, ExtendedCardInfo, GetAddressFromPaymentMethodData},+ payments::{ConnectorMandateReferenceId, ExtendedCardInfo},};use async_trait::async_trait;use common_utils::ext_traits::{AsyncExt, Encode, StringExt, ValueExt};@@ -13,7 +13,9 @@ use diesel_models::payment_attempt::ConnectorMandateReferenceId as DieselConnectuse error_stack::{report, ResultExt};use futures::FutureExt;#[cfg(feature = "v1")]-use hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdateFields;+use hyperswitch_domain_models::payments::{+ self as domain_payments, payment_intent::PaymentIntentUpdateFields,+};use hyperswitch_domain_models::router_request_types::unified_authentication_service;use masking::{ExposeInterface, PeekInterface};use router_derive::PaymentOperation;@@ -35,10 +37,12 @@ use crate::{errors::{self, CustomResult, RouterResult, StorageErrorExt},mandate::helpers as m_helpers,metrics,+ payment_methods::{transformers as pm_transformers, utils as pm_utils},payments::{self, helpers, operations,operations::payment_confirm::unified_authentication_service::ThreeDsMetaData,- populate_surcharge_details, CustomerDetails, PaymentAddress, PaymentData,+ populate_surcharge_details, CustomerDetails, OperationSessionSetters, PaymentAddress,+ PaymentData,},three_ds_decision_rule,unified_authentication_service::{@@ -78,6 +82,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>platform: &domain::Platform,auth_flow: services::AuthFlow,header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ payment_method_with_raw_data: Option<pm_transformers::PaymentMethodWithRawData>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>>{let processor_merchant_id = platform.get_processor().get_account().get_id();@@ -513,10 +518,23 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>let n_payment_method_billing_address_id =payment_attempt.payment_method_billing_address_id.clone();+let n_request_payment_method_billing_address = request.payment_method_data.as_ref()- .and_then(|pmd| pmd.billing.clone());+ .and_then(|pmd| pmd.billing.clone())+ .or(payment_method_with_raw_data.clone().and_then(|pm| {+ pm.payment_method+ .0+ .payment_method_billing_address+ .clone()+ .map(|decrypted_data| decrypted_data.into_inner().expose())+ .and_then(|decrypted_value| {+ decrypted_value+ .parse_value("payment method billing address")+ .ok()+ })+ }));let m_payment_intent_customer_id = payment_intent.customer_id.clone();let m_payment_intent_payment_id = payment_intent.payment_id.clone();let m_key_store = platform.get_processor().get_key_store().clone();@@ -562,6 +580,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>let payment_intent_customer_id = payment_intent.customer_id.clone();+ let m_pm_wrapper = payment_method_with_raw_data.clone();let mandate_details_fut = tokio::spawn(async move {Box::pin(helpers::get_token_pm_type_mandate_details(@@ -571,6 +590,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>&m_platform,None,payment_intent_customer_id.as_ref(),+ m_pm_wrapper.map(|pm| pm.payment_method.0),)).await}@@ -610,25 +630,40 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>&request.ctp_service_details,)?;- let (token_data, payment_method_info) = if let Some(token) = token.clone() {- let token_data = helpers::retrieve_payment_token_data(- state,- token,- payment_method.or(payment_attempt.payment_method),- )- .await?;+ //fetch for repeat cit using payment token- let payment_method_info = helpers::retrieve_payment_method_from_db_with_token_data(- state,- platform.get_provider().get_key_store(),- &token_data,- storage_scheme,+ let (token_data, payment_method_info) =+ if pm_utils::get_organization_eligibility_config_for_pm_modular_service(+ &*state.store,+ &platform.get_processor().get_account().organization_id,)- .await?;- (Some(token_data), payment_method_info)- } else {- (None, payment_method_info)- };+ .await+ {+ (+ None,+ payment_method_with_raw_data+ .clone()+ .map(|pm| pm.payment_method.0),+ )+ } else if let Some(token) = token.clone() {+ let token_data = helpers::retrieve_payment_token_data(+ state,+ token,+ payment_method.or(payment_attempt.payment_method),+ )+ .await?;++ let payment_method_info = helpers::retrieve_payment_method_from_db_with_token_data(+ state,+ platform.get_provider().get_key_store(),+ &token_data,+ storage_scheme,+ )+ .await?;+ (Some(token_data), payment_method_info)+ } else {+ (None, payment_method_info)+ };let additional_pm_data_from_locker = if let Some(ref pm) = payment_method_info {let card_detail_from_locker: Option<api::CardDetailFromLocker> = pm.payment_method_data@@ -710,6 +745,11 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Card cobadge check failed due to an invalid card network regex")?;+ let payment_method_data = payment_method_with_raw_data+ .clone()+ .and_then(|pm| pm.raw_payment_method_data)+ .or(payment_method_data_after_card_bin_call.map(Into::into));+payment_attempt.payment_method_billing_address_id = payment_method_billing.as_ref().map(|payment_method_billing| payment_method_billing.address_id.clone());@@ -724,14 +764,22 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>let payment_method_data_billing = request.payment_method_data.as_ref()- .and_then(|pmd| pmd.payment_method_data.as_ref())- .and_then(|payment_method_data_billing| {- payment_method_data_billing.get_billing_address()- })- .map(From::from);+ .and_then(|pmd| pmd.billing.clone())+ .or(payment_method_with_raw_data.as_ref().and_then(|pm| {+ pm.payment_method+ .0+ .payment_method_billing_address+ .clone()+ .map(|decrypted_data| decrypted_data.into_inner().expose())+ .and_then(|decrypted_value| {+ decrypted_value+ .parse_value("payment method billing address")+ .ok()+ })+ }));- let unified_address =- address.unify_with_payment_method_data_billing(payment_method_data_billing);+ let unified_address = address+ .unify_with_payment_method_data_billing(payment_method_data_billing.map(From::from));// If processor_payment_token is passed in request then populating the same in PaymentDatalet mandate_id = request@@ -792,6 +840,17 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>)),);+ //setting vault operation to existing vault data if raw payment method data is present in pm_info+ let vault_operation =+ payment_method_with_raw_data.and_then(|pm| match pm.raw_payment_method_data {+ Some(domain::PaymentMethodData::Card(card)) => {+ Some(domain_payments::VaultOperation::ExistingVaultData(+ domain_payments::VaultData::Card(card),+ ))+ }+ _ => None,+ });+let payment_data = PaymentData {flow: PhantomData,payment_intent,@@ -807,7 +866,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>address: unified_address,token_data,confirm: request.confirm,- payment_method_data: payment_method_data_after_card_bin_call.map(Into::into),+ payment_method_data,payment_method_token: None,payment_method_info,force_sync: None,@@ -835,7 +894,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>session_id: None,service_details: request.ctp_service_details.clone(),card_testing_guard_data: None,- vault_operation: None,+ vault_operation,threeds_method_comp_ind: None,whole_connector_response: None,is_manual_retry_enabled: business_profile.is_manual_retry_enabled,@@ -977,6 +1036,157 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forOk(())}+ #[instrument(skip_all)]+ async fn create_payment_method(+ &self,+ state: &SessionState,+ req: &api::PaymentsRequest,+ platform: &domain::Platform,+ payment_data: &mut PaymentData<F>,+ business_profile: &domain::Profile,+ feature_config: &core_utils::FeatureConfig,+ ) -> RouterResult<()> {+ match feature_config.is_payment_method_modular_allowed {+ true => {+ logger::info!("Organization is eligible for PM Modular Service, proceeding to create payment method using PM Modular Service.");+ //check for req.payment_method_data, if card, create payment method with pm service+ let payment_method_info = match req+ .payment_method_data+ .as_ref()+ .and_then(|pmd| pmd.payment_method_data.as_ref())+ {+ Some(api_models::payments::PaymentMethodData::Card(_)) => {+ let payment_method = req.payment_method.ok_or(+ errors::ApiErrorResponse::MissingRequiredField {+ field_name: "payment_method",+ },+ )?;++ let payment_method_type = req.payment_method_type.ok_or(+ errors::ApiErrorResponse::MissingRequiredField {+ field_name: "payment_method_type",+ },+ )?;++ let payment_method_data = req+ .payment_method_data+ .as_ref()+ .and_then(|pmd| pmd.payment_method_data.clone())+ .map(Into::into)+ .ok_or(errors::ApiErrorResponse::MissingRequiredField {+ field_name: "payment_method_data",+ })?;++ match pm_transformers::create_payment_method_in_modular_service(+ state,+ platform.get_provider().get_account().get_id(),+ business_profile.get_id(),+ payment_method,+ payment_method_type,+ payment_method_data,+ payment_data+ .address+ .get_request_payment_method_billing()+ .cloned(),+ payment_data+ .payment_intent+ .customer_id+ .clone()+ .get_required_value("customer_id")?,+ )+ .await+ {+ Ok(pm_info) => {+ logger::info!(+ "Payment method created in PM Modular service successfully"+ );+ Some(pm_info)+ }+ Err(err) => {+ logger::error!(+ "Error creating payment method in PM Modular service: {:?}",+ err+ );+ None+ }+ }+ }+ _ => {+ logger::info!("No supported payment method data found for creating payment method in PM Modular service.");+ None+ }+ };+ //set payment_data.payment_method_info+ payment_data.set_payment_method_info(payment_method_info);+ Ok(())+ }+ false => {+ logger::info!("Organization is not eligible for PM Modular Service, skipping create payment method.");+ Ok(())+ }+ }+ }++ #[instrument(skip_all)]+ async fn fetch_payment_method(+ &self,+ state: &SessionState,+ req: &api::PaymentsRequest,+ platform: &domain::Platform,+ feature_config: &core_utils::FeatureConfig,+ ) -> RouterResult<Option<operations::PaymentMethodWithRawData>> {+ match feature_config.is_payment_method_modular_allowed {+ true => {+ let profile_id = req+ .profile_id+ .clone()+ .or(platform+ .get_provider()+ .get_account()+ .get_default_profile()+ .clone())+ .get_required_value("profile_id")?;++ let pm_info = if let Some(payment_token) = &req.payment_token {+ logger::info!("Organization is eligible for PM Modular Service, proceeding to fetch payment method using PM Modular Service.");+ //fetch req/payment_method_data, if CardToken, then send it in fetch call else None+ let pmd = req+ .payment_method_data+ .clone()+ .and_then(|pmd| pmd.payment_method_data)+ .map(Into::into);+ let payment_method_data =+ if let Some(domain::PaymentMethodData::CardToken(ref token)) = pmd {+ Some(token.clone())+ } else {+ None+ };+ // Fetch payment method using PM Modular Service+ let pm_info = pm_transformers::fetch_payment_method_from_modular_service(+ state,+ platform.get_provider().get_account().get_id(),+ &profile_id,+ payment_token,+ payment_method_data,+ )+ .await?;+ logger::info!("Payment method fetched from PM Modular Service.");++ Some(pm_info)+ } else {+ None+ };++ //the pm_info will be set in payment_data in get trackers+ Ok(pm_info)+ }+ false => {+ logger::info!("Organization is not eligible for PM Modular Service, skipping fetch payment method.");+ Ok(None)+ }+ }+ }+#[instrument(skip_all)]async fn make_pm_data<'a>(&'a self,diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rsindex afe30ec8e2..41def68dc7 100644--- a/crates/router/src/core/payments/operations/payment_create.rs+++ b/crates/router/src/core/payments/operations/payment_create.rs@@ -2,7 +2,6 @@ use std::marker::PhantomData;use api_models::{enums::FrmSuggestion, mandates::RecurringDetails, payment_methods::PaymentMethodsData,- payments::GetAddressFromPaymentMethodData,};use async_trait::async_trait;use common_types::payments as common_payments_types;@@ -33,6 +32,7 @@ use crate::{errors::{self, CustomResult, RouterResult, StorageErrorExt},mandate::helpers as m_helpers,payment_link,+ payment_methods::transformers as pm_transformers,payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},utils as core_utils,},@@ -72,6 +72,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>platform: &domain::Platform,_auth_flow: services::AuthFlow,header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ payment_method_with_raw_data: Option<pm_transformers::PaymentMethodWithRawData>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>>{let db = &*state.store;@@ -146,6 +147,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>reason: "Expected one out of recurring_details and mandate_data but got both".into(),})?;+ let m_pm_wrapper = payment_method_with_raw_data.clone();let m_helpers::MandateGenericData {token,payment_method,@@ -161,6 +163,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>platform,None,None,+ m_pm_wrapper.map(|pm| pm.payment_method.0),).await?;@@ -198,13 +201,27 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>).await?;+ let payment_method_data_billing = request+ .payment_method_data+ .as_ref()+ .and_then(|pmd| pmd.billing.clone())+ .or(payment_method_with_raw_data.as_ref().and_then(|pm| {+ pm.payment_method+ .0+ .payment_method_billing_address+ .clone()+ .map(|decrypted_data| decrypted_data.into_inner().expose())+ .and_then(|decrypted_value| {+ decrypted_value+ .parse_value("payment method billing address")+ .ok()+ })+ }));+let payment_method_billing_address =helpers::create_or_find_address_for_payment_by_request(state,- request- .payment_method_data- .as_ref()- .and_then(|pmd| pmd.billing.as_ref()),+ payment_method_data_billing.as_ref(),None,platform.get_processor().get_account().get_id(),customer_details.customer_id.as_ref(),@@ -443,6 +460,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>} else {mandate_id};+let operation = payments::if_not_create_change_operation::<_, F>(payment_intent.status,request.confirm,@@ -490,6 +508,11 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Card cobadge check failed due to an invalid card network regex")?;+ let payment_method_data = payment_method_with_raw_data+ .as_ref()+ .and_then(|pm| pm.raw_payment_method_data.clone())+ .or(payment_method_data_after_card_bin_call.map(Into::into));+let additional_pm_data_from_locker = if let Some(ref pm) = payment_method_info {let card_detail_from_locker: Option<api::CardDetailFromLocker> = pm.payment_method_data@@ -551,14 +574,22 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>let payment_method_data_billing = request.payment_method_data.as_ref()- .and_then(|pmd| pmd.payment_method_data.as_ref())- .and_then(|payment_method_data_billing| {- payment_method_data_billing.get_billing_address()- })- .map(From::from);+ .and_then(|pmd| pmd.billing.clone())+ .or(payment_method_with_raw_data.as_ref().and_then(|pm| {+ pm.payment_method+ .0+ .payment_method_billing_address+ .clone()+ .map(|decrypted_data| decrypted_data.into_inner().expose())+ .and_then(|decrypted_value| {+ decrypted_value+ .parse_value("payment method billing address")+ .ok()+ })+ }));- let unified_address =- address.unify_with_payment_method_data_billing(payment_method_data_billing);+ let unified_address = address+ .unify_with_payment_method_data_billing(payment_method_data_billing.map(From::from));let payment_data = PaymentData {flow: PhantomData,@@ -575,7 +606,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>address: unified_address,token_data: None,confirm: request.confirm,- payment_method_data: payment_method_data_after_card_bin_call.map(Into::into),+ payment_method_data,payment_method_token: None,payment_method_info,refunds: vec![],@@ -768,6 +799,54 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for}}+ #[instrument(skip_all)]+ async fn fetch_payment_method(+ &self,+ state: &SessionState,+ req: &api::PaymentsRequest,+ platform: &domain::Platform,+ feature_config: &core_utils::FeatureConfig,+ ) -> RouterResult<Option<pm_transformers::PaymentMethodWithRawData>> {+ match feature_config.is_payment_method_modular_allowed {+ true => {+ logger::info!("Organization is eligible for PM Modular Service, fetching payment method if payment_token is provided.");++ let profile_id = req+ .profile_id+ .clone()+ .or(platform+ .get_provider()+ .get_account()+ .get_default_profile()+ .clone())+ .get_required_value("profile_id")?;++ let pm_info = if let Some(payment_token) = &req.payment_token {+ // Fetch payment method using PM Modular Service+ let pm_info = pm_transformers::fetch_payment_method_from_modular_service(+ state,+ platform.get_provider().get_account().get_id(),+ &profile_id,+ payment_token,+ None, // CVC token data is not passed in create api+ )+ .await?;+ logger::info!("Payment method fetched from PM Modular Service.");++ Some(pm_info)+ } else {+ None+ };++ Ok(pm_info)+ }+ false => {+ logger::info!("Organization is not eligible for PM Modular Service, skipping fetch payment method.");+ Ok(None)+ }+ }+ }+#[instrument(skip_all)]async fn make_pm_data<'a>(&'a self,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 256566bb17..5a8ae3e404 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@@ -43,6 +43,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsPostSessplatform: &domain::Platform,_auth_flow: services::AuthFlow,_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ _payment_method_wrapper: Option<operations::PaymentMethodWithRawData>,) -> RouterResult<operations::GetTrackerResponse<'a,diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rsindex 79c3779559..ea9e917957 100644--- a/crates/router/src/core/payments/operations/payment_reject.rs+++ b/crates/router/src/core/payments/operations/payment_reject.rs@@ -41,6 +41,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequestplatform: &domain::Platform,_auth_flow: services::AuthFlow,_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ _payment_method_wrapper: Option<operations::PaymentMethodWithRawData>,) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsCancelRequest, PaymentData<F>>>{let db = &*state.store;diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rsindex f3ac4543cd..8f6f8c3b84 100644--- a/crates/router/src/core/payments/operations/payment_response.rs+++ b/crates/router/src/core/payments/operations/payment_response.rs@@ -671,12 +671,12 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthortypes::PaymentsAuthorizeData,types::PaymentsResponseData,>,- feature_set: &core_utils::FeatureSet,+ feature_set: &core_utils::FeatureConfig,) -> RouterResult<()>whereF: 'b + Clone + Send + Sync,{- if !feature_set.is_modular_merchant {+ if !feature_set.is_payment_method_modular_allowed {update_pm_connector_mandate_details(state, provider, payment_data, router_data).await} else {Ok(())@@ -962,12 +962,12 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSyncData> forprovider: &domain::Provider,payment_data: &PaymentData<F>,router_data: &types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>,- feature_set: &core_utils::FeatureSet,+ feature_set: &core_utils::FeatureConfig,) -> RouterResult<()>whereF: 'b + Clone + Send + Sync,{- if !feature_set.is_modular_merchant {+ if !feature_set.is_payment_method_modular_allowed {update_pm_connector_mandate_details(state, provider, payment_data, router_data).await} else {Ok(())@@ -1702,7 +1702,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestDatypes::SetupMandateRequestData,types::PaymentsResponseData,>,- _feature_set: &core_utils::FeatureSet,+ _feature_set: &core_utils::FeatureConfig,) -> RouterResult<()>whereF: 'b + Clone + Send + Sync,@@ -1825,12 +1825,12 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::CompleteAuthorizeDatatypes::CompleteAuthorizeData,types::PaymentsResponseData,>,- feature_set: &core_utils::FeatureSet,+ feature_set: &core_utils::FeatureConfig,) -> RouterResult<()>whereF: 'b + Clone + Send + Sync,{- if !feature_set.is_modular_merchant {+ if !feature_set.is_payment_method_modular_allowed {update_pm_connector_mandate_details(state, provider, payment_data, router_data).await} else {Ok(())diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rsindex 31445d40b8..30c641cdb6 100644--- a/crates/router/src/core/payments/operations/payment_session.rs+++ b/crates/router/src/core/payments/operations/payment_session.rs@@ -43,6 +43,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsSessionRplatform: &domain::Platform,_auth_flow: services::AuthFlow,_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ _payment_method_wrapper: Option<operations::PaymentMethodWithRawData>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsSessionRequest, PaymentData<F>>,> {diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rsindex 0fb1f8339c..27ebc1cba1 100644--- a/crates/router/src/core/payments/operations/payment_start.rs+++ b/crates/router/src/core/payments/operations/payment_start.rs@@ -42,6 +42,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsStartReqplatform: &domain::Platform,_auth_flow: services::AuthFlow,_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ _payment_method_wrapper: Option<operations::PaymentMethodWithRawData>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsStartRequest, PaymentData<F>>,> {diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rsindex 5e18f1ad44..d2f57acb6f 100644--- a/crates/router/src/core/payments/operations/payment_status.rs+++ b/crates/router/src/core/payments/operations/payment_status.rs@@ -228,6 +228,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveplatform: &domain::Platform,_auth_flow: services::AuthFlow,_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ _payment_method_wrapper: Option<operations::PaymentMethodWithRawData>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>,> {diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rsindex 9f98a67205..fe915f682f 100644--- a/crates/router/src/core/payments/operations/payment_update.rs+++ b/crates/router/src/core/payments/operations/payment_update.rs@@ -55,6 +55,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>platform: &domain::Platform,auth_flow: services::AuthFlow,_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ _payment_method_wrapper: Option<operations::PaymentMethodWithRawData>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>>{let (mut payment_intent, mut payment_attempt, currency): (_, _, storage_enums::Currency);@@ -162,6 +163,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>platform,None,payment_intent.customer_id.as_ref(),+ None,)).await?;helpers::validate_amount_to_capture_and_capture_method(Some(&payment_attempt), request)?;diff --git a/crates/router/src/core/payments/operations/payment_update_metadata.rs b/crates/router/src/core/payments/operations/payment_update_metadata.rsindex c412d389e5..31342128be 100644--- a/crates/router/src/core/payments/operations/payment_update_metadata.rs+++ b/crates/router/src/core/payments/operations/payment_update_metadata.rs@@ -43,6 +43,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsUpdateMeplatform: &domain::Platform,_auth_flow: services::AuthFlow,_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ _payment_method_wrapper: Option<operations::PaymentMethodWithRawData>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsUpdateMetadataRequest, PaymentData<F>>,> {diff --git a/crates/router/src/core/payments/operations/payments_extend_authorization.rs b/crates/router/src/core/payments/operations/payments_extend_authorization.rsindex d9fd41c615..bead031b8a 100644--- a/crates/router/src/core/payments/operations/payments_extend_authorization.rs+++ b/crates/router/src/core/payments/operations/payments_extend_authorization.rs@@ -42,6 +42,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsExtendAuplatform: &domain::Platform,_auth_flow: services::AuthFlow,_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ _payment_method_wrapper: Option<operations::PaymentMethodWithRawData>,) -> RouterResult<operations::GetTrackerResponse<'a,diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rsindex 4448053a1f..328774d660 100644--- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs+++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs@@ -47,6 +47,7 @@ impl<F: Send + Clone + Sync>platform: &domain::Platform,_auth_flow: services::AuthFlow,_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ _payment_method_wrapper: Option<operations::PaymentMethodWithRawData>,) -> RouterResult<operations::GetTrackerResponse<'a,diff --git a/crates/router/src/core/payments/operations/tax_calculation.rs b/crates/router/src/core/payments/operations/tax_calculation.rsindex 80ad3b299b..67b1e3fae0 100644--- a/crates/router/src/core/payments/operations/tax_calculation.rs+++ b/crates/router/src/core/payments/operations/tax_calculation.rs@@ -49,6 +49,7 @@ impl<F: Send + Clone + Sync>platform: &domain::Platform,_auth_flow: services::AuthFlow,_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ _payment_method_wrapper: Option<operations::PaymentMethodWithRawData>,) -> RouterResult<operations::GetTrackerResponse<'a,diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rsindex 990135ef95..b1709029b2 100644--- a/crates/router/src/core/payments/retry.rs+++ b/crates/router/src/core/payments/retry.rs@@ -19,6 +19,7 @@ use crate::{helpers as payments_helpers, operations,},routing::helpers as routing_helpers,+ utils as core_utils,},db::StorageInterface,routes::{@@ -47,6 +48,7 @@ pub async fn do_gsm_actions<'a, F, ApiRequest, FData, D>(schedule_time: Option<time::PrimitiveDateTime>,frm_suggestion: Option<storage_enums::FrmSuggestion>,business_profile: &domain::Profile,+ feature_config: &core_utils::FeatureConfig,) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>>whereF: Clone + Send + Sync + std::fmt::Debug + 'static,@@ -116,6 +118,7 @@ wherefalse, //should_retry_with_pan is not applicable for step-upNone,initial_gsm.clone(),+ feature_config,).await?;}@@ -222,6 +225,7 @@ whereshould_retry_with_pan,routing_decision,gsm.clone(),+ feature_config,).await?;@@ -370,6 +374,7 @@ pub async fn do_retry<'a, F, ApiRequest, FData, D>(should_retry_with_pan: bool,routing_decision: Option<routing_helpers::RoutingDecisionData>,initial_gsm: Option<hyperswitch_domain_models::gsm::GatewayStatusMap>,+ feature_config: &core_utils::FeatureConfig,) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>>whereF: Clone + Send + Sync + std::fmt::Debug + 'static,@@ -409,6 +414,7 @@ wherebusiness_profile,should_retry_with_pan,routing_decision,+ feature_config,).await?;diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rsindex f91ee420a5..ef65179091 100644--- a/crates/router/src/core/utils.rs+++ b/crates/router/src/core/utils.rs@@ -62,19 +62,22 @@ use crate::{#[cfg(feature = "v1")]#[derive(Debug, Clone, Default)]-pub struct FeatureSet {- pub is_modular_merchant: bool,+pub struct FeatureConfig {+ pub is_payment_method_modular_allowed: bool,}#[cfg(feature = "v1")]-pub async fn get_feature_set(state: &SessionState, platform: &domain::Platform) -> FeatureSet {- let is_modular_merchant = crate::core::payment_methods::utils::get_organization_eligibility_config_for_pm_modular_service(+pub async fn get_feature_config(+ state: &SessionState,+ platform: &domain::Platform,+) -> FeatureConfig {+ let is_payment_method_modular_allowed = crate::core::payment_methods::utils::get_organization_eligibility_config_for_pm_modular_service(state.store.as_ref(),&platform.get_processor().get_account().organization_id,).await;- FeatureSet {- is_modular_merchant,+ FeatureConfig {+ is_payment_method_modular_allowed,}}