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

feat(payment_methods): add and integrate modular pm update service into payments flow (#11091)

Kashif9d7d67f2feba
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 118cfd373d..cb51ca0642 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -243,6 +243,39 @@ impl AttemptStatus {
pub fn is_success(self) -> bool {
matches!(self, Self::Charged | Self::PartialCharged)
}
+
+ pub fn should_update_payment_method(self) -> bool {
+ match self {
+ Self::Charged
+ | Self::PartialCharged
+ | Self::Authorized
+ | Self::PartiallyAuthorized
+ | Self::AuthenticationSuccessful
+ | Self::PartialChargedAndChargeable => true,
+ Self::Started
+ | Self::AuthenticationFailed
+ | Self::RouterDeclined
+ | Self::AuthenticationPending
+ | Self::AuthorizationFailed
+ | Self::Authorizing
+ | Self::CodInitiated
+ | Self::Voided
+ | Self::VoidedPostCharge
+ | Self::VoidInitiated
+ | Self::CaptureInitiated
+ | Self::CaptureFailed
+ | Self::VoidFailed
+ | Self::AutoRefunded
+ | Self::Unresolved
+ | Self::Pending
+ | Self::Failure
+ | Self::PaymentMethodAwaited
+ | Self::ConfirmationAwaited
+ | Self::DeviceDataCollectionPending
+ | Self::IntegrityFailure
+ | Self::Expired => false,
+ }
+ }
}
#[derive(
diff --git a/crates/payment_methods/src/client.rs b/crates/payment_methods/src/client.rs
index c111e02df9..428e94561e 100644
--- a/crates/payment_methods/src/client.rs
+++ b/crates/payment_methods/src/client.rs
@@ -24,7 +24,10 @@ use hyperswitch_interfaces::micro_service::MicroserviceClient;
pub use retrieve::{RetrievePaymentMethod, RetrievePaymentMethodV1Request};
use router_env::RequestIdentifier;
#[cfg(feature = "v1")]
-pub use update::{UpdatePaymentMethod, UpdatePaymentMethodV1Request};
+pub use update::{
+ CardDetailUpdate, PaymentMethodUpdateData, UpdatePaymentMethod, UpdatePaymentMethodV1Payload,
+ UpdatePaymentMethodV1Request,
+};
use crate::configs::ModularPaymentMethodServiceUrl;
diff --git a/crates/payment_methods/src/client/update.rs b/crates/payment_methods/src/client/update.rs
index 46aa08e8d8..1d6cb9ab79 100644
--- a/crates/payment_methods/src/client/update.rs
+++ b/crates/payment_methods/src/client/update.rs
@@ -1,47 +1,107 @@
-use common_utils::request::{Method, RequestContent};
-use hyperswitch_interfaces::micro_service::MicroserviceClientError;
+//! Update payment method flow types and modular models.
+
+use api_models::payment_methods::NetworkTokenResponse;
+use common_enums::{PaymentMethod, PaymentMethodType, StorageType};
+use common_utils::{
+ id_type,
+ request::{Method, RequestContent},
+};
+use hyperswitch_interfaces::micro_service::{MicroserviceClientError, MicroserviceClientErrorKind};
use masking::Secret;
use serde::{Deserialize, Serialize};
+use time::PrimitiveDateTime;
-use crate::client::create::{ConnectorTokenDetails, ModularPaymentMethodResponse};
+use crate::types::{
+ CardCVCTokenStorageDetails, ConnectorTokenDetails, ModularPMRetrieveResponse,
+ PaymentMethodResponseData,
+};
+/// V1-facing update flow type.
#[derive(Debug)]
pub struct UpdatePaymentMethod;
+/// V1-facing update request payload.
#[derive(Debug)]
pub struct UpdatePaymentMethodV1Request {
/// Identifier for the payment method to update.
- /// Type String is used throughout v1 payment methods
pub payment_method_id: String,
+ /// Typed update payload derived from aggregated data.
+ pub payload: UpdatePaymentMethodV1Payload,
+ pub modular_service_prefix: String,
+}
+
+/// V1-facing update payload.
+#[derive(Clone, Debug, Serialize)]
+pub struct UpdatePaymentMethodV1Payload {
+ /// Payment method details to update.
pub payment_method_data: Option<PaymentMethodUpdateData>,
+ /// Connector token details to update.
pub connector_token_details: Option<ConnectorTokenDetails>,
+ /// Network transaction ID for off-session updates.
pub network_transaction_id: Option<Secret<String>>,
- pub modular_service_prefix: String,
}
-#[derive(Debug, Clone, Serialize)]
+/// Modular service update request payload.
+#[derive(Clone, Debug, Serialize)]
pub struct ModularPMUpdateRequest {
+ /// Payment method details to update.
pub payment_method_data: Option<PaymentMethodUpdateData>,
+ /// Connector token details to update.
pub connector_token_details: Option<ConnectorTokenDetails>,
+ /// Network transaction ID for off-session updates.
pub network_transaction_id: Option<Secret<String>>,
}
-#[derive(Debug, Clone, Serialize)]
+/// Payment method update data.
+#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "snake_case")]
+#[serde(rename = "payment_method_data")]
pub enum PaymentMethodUpdateData {
Card(CardDetailUpdate),
}
-#[derive(Debug, Clone, Serialize)]
+/// Card update payload for the modular service.
+#[derive(Debug, Serialize, Clone)]
pub struct CardDetailUpdate {
+ /// Card holder name.
pub card_holder_name: Option<Secret<String>>,
+ /// Card holder nickname.
pub nick_name: Option<Secret<String>>,
+ /// Card CVC (optional).
pub card_cvc: Option<Secret<String>>,
}
-#[derive(Clone, Debug, Deserialize)]
+/// V1-facing update response.
+#[derive(Debug, Deserialize)]
pub struct UpdatePaymentMethodResponse {
- pub payment_method_id: String,
+ /// The unique identifier of the payment method.
+ pub id: String,
+ /// Unique identifier for a merchant.
+ pub merchant_id: id_type::MerchantId,
+ /// The unique identifier of the customer.
+ pub customer_id: Option<id_type::CustomerId>,
+ /// The type of payment method.
+ pub payment_method_type: PaymentMethod,
+ /// The payment method subtype.
+ pub payment_method_subtype: PaymentMethodType,
+ /// Indicates whether recurring is enabled.
+ pub recurring_enabled: Option<bool>,
+ /// Timestamp for creation time.
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub created: Option<PrimitiveDateTime>,
+ /// Timestamp for last usage.
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub last_used_at: Option<PrimitiveDateTime>,
+ /// Payment method details.
+ pub payment_method_data: Option<PaymentMethodResponseData>,
+ /// Connector token details if available.
+ pub connector_tokens: Option<Vec<ConnectorTokenDetails>>,
+ /// Network token details if available.
+ pub network_token: Option<NetworkTokenResponse>,
+ /// Storage type.
+ pub storage_type: Option<StorageType>,
+ /// Stored card CVC token details.
+ pub card_cvc_token_storage: Option<CardCVCTokenStorageDetails>,
}
impl TryFrom<&UpdatePaymentMethodV1Request> for ModularPMUpdateRequest {
@@ -49,25 +109,51 @@ impl TryFrom<&UpdatePaymentMethodV1Request> for ModularPMUpdateRequest {
fn try_from(value: &UpdatePaymentMethodV1Request) -> Result<Self, Self::Error> {
Ok(Self {
- // payment_method_id: value.payment_method_id.clone(),
- payment_method_data: value.payment_method_data.clone(),
- connector_token_details: value.connector_token_details.clone(),
- network_transaction_id: value.network_transaction_id.clone(),
+ payment_method_data: value.payload.payment_method_data.clone(),
+ connector_token_details: value.payload.connector_token_details.clone(),
+ network_transaction_id: value.payload.network_transaction_id.clone(),
})
}
}
-impl TryFrom<ModularPaymentMethodResponse> for UpdatePaymentMethodResponse {
+impl TryFrom<ModularPMRetrieveResponse> for UpdatePaymentMethodResponse {
type Error = MicroserviceClientError;
- fn try_from(resp: ModularPaymentMethodResponse) -> Result<Self, Self::Error> {
+ fn try_from(value: ModularPMRetrieveResponse) -> Result<Self, Self::Error> {
Ok(Self {
- payment_method_id: resp.id,
+ id: value.id,
+ merchant_id: value.merchant_id,
+ customer_id: value.customer_id,
+ payment_method_type: value.payment_method_type,
+ payment_method_subtype: value.payment_method_subtype,
+ recurring_enabled: value.recurring_enabled,
+ created: value.created,
+ last_used_at: value.last_used_at,
+ payment_method_data: value.payment_method_data,
+ connector_tokens: value.connector_tokens,
+ network_token: value.network_token,
+ storage_type: value.storage_type,
+ card_cvc_token_storage: value.card_cvc_token_storage,
})
}
}
impl UpdatePaymentMethod {
+ fn validate_request(
+ &self,
+ request: &UpdatePaymentMethodV1Request,
+ ) -> Result<(), MicroserviceClientError> {
+ common_utils::fp_utils::when(request.payment_method_id.trim().is_empty(), || {
+ Err(MicroserviceClientError {
+ operation: std::any::type_name::<Self>().to_string(),
+ kind: MicroserviceClientErrorKind::InvalidRequest(
+ "Payment method ID cannot be empty".to_string(),
+ ),
+ })
+ })?;
+ Ok(())
+ }
+
fn build_path_params(
&self,
request: &UpdatePaymentMethodV1Request,
@@ -89,9 +175,10 @@ hyperswitch_interfaces::impl_microservice_flow!(
path = "/{prefix}/payment-methods/{id}/update-saved-payment-method",
v1_request = UpdatePaymentMethodV1Request,
v2_request = ModularPMUpdateRequest,
- v2_response = ModularPaymentMethodResponse,
+ v2_response = ModularPMRetrieveResponse,
v1_response = UpdatePaymentMethodResponse,
client = crate::client::PaymentMethodClient<'_>,
body = UpdatePaymentMethod::build_body,
- path_params = UpdatePaymentMethod::build_path_params
+ path_params = UpdatePaymentMethod::build_path_params,
+ validate = UpdatePaymentMethod::validate_request
);
diff --git a/crates/payment_methods/src/core/errors.rs b/crates/payment_methods/src/core/errors.rs
index 1c8823c11b..35da124b90 100644
--- a/crates/payment_methods/src/core/errors.rs
+++ b/crates/payment_methods/src/core/errors.rs
@@ -47,3 +47,15 @@ pub enum VaultError {
#[error("Failed while calling locker API")]
ApiError,
}
+
+#[derive(Debug, thiserror::Error)]
+pub enum ModularPaymentMethodError {
+ #[error("Failed to create payment method")]
+ CreateFailed,
+ #[error("Failed to retrieve payment method")]
+ RetrieveFailed,
+ #[error("Failed to update payment method")]
+ UpdateFailed,
+ #[error("Internal Server Error")]
+ InternalServerError,
+}
diff --git a/crates/payment_methods/src/lib.rs b/crates/payment_methods/src/lib.rs
index d373a56601..30381201ac 100644
--- a/crates/payment_methods/src/lib.rs
+++ b/crates/payment_methods/src/lib.rs
@@ -6,3 +6,5 @@ pub mod helpers;
pub mod state;
#[cfg(feature = "v1")]
pub mod types;
+
+pub use crate::core::errors;
diff --git a/crates/payment_methods/src/types.rs b/crates/payment_methods/src/types.rs
index c61cad4af4..9c0c7dd0b6 100644
--- a/crates/payment_methods/src/types.rs
+++ b/crates/payment_methods/src/types.rs
@@ -1,7 +1,7 @@
use api_models::payment_methods::{CardDetailFromLocker, NetworkTokenResponse};
use common_enums::{PaymentMethod, PaymentMethodType};
use common_utils::{id_type, pii};
-use serde::Deserialize;
+use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::client::create::CardDetail;
@@ -75,7 +75,7 @@ pub enum RawPaymentMethodData {
}
/// V2 ConnectorTokenDetails (for deserialization, ignored in transformation)
-#[derive(Clone, Debug, Deserialize)]
+#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ConnectorTokenDetails {
pub connector_id: id_type::MerchantConnectorAccountId,
pub token_type: common_enums::TokenizationType,
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index c7ee5af23b..a2aba5b9ee 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -3,6 +3,8 @@ use api_models::payment_methods::Card;
#[cfg(feature = "v2")]
use api_models::{enums as api_enums, payment_methods::PaymentMethodResponseItem};
use common_enums::CardNetwork;
+#[cfg(feature = "v1")]
+use common_utils::request::Headers;
use common_utils::{
ext_traits::{Encode, StringExt},
id_type,
@@ -13,7 +15,17 @@ use error_stack::ResultExt;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payment_method_data;
use josekit::jwe;
+#[cfg(feature = "v1")]
+use masking::Mask;
+use masking::{ExposeInterface, PeekInterface};
+#[cfg(feature = "v1")]
+use payment_methods::client::{
+ PaymentMethodClient, UpdatePaymentMethod, UpdatePaymentMethodV1Payload,
+ UpdatePaymentMethodV1Request,
+};
use router_env::RequestId;
+#[cfg(feature = "v1")]
+use router_env::{logger, RequestIdentifier};
use serde::{Deserialize, Serialize};
use crate::{
@@ -23,7 +35,7 @@ use crate::{
payment_methods::cards::call_vault_service,
},
headers,
- pii::{prelude::*, Secret},
+ pii::Secret,
routes,
services::{api as services, encryption, EncryptionAlgorithm},
types::{api, domain},
@@ -1114,3 +1126,56 @@ impl transformers::ForeignFrom<&payment_method_data::SingleUsePaymentMethodToken
}
}
}
+
+#[cfg(feature = "v1")]
+pub async fn call_modular_payment_method_update(
+ state: &routes::SessionState,
+ merchant_id: &id_type::MerchantId,
+ profile_id: &id_type::ProfileId,
+ payment_method_id: &str,
+ payload: UpdatePaymentMethodV1Payload,
+) -> CustomResult<(), ::payment_methods::errors::ModularPaymentMethodError> {
+ let mut parent_headers = Headers::new();
+ parent_headers.insert((
+ headers::X_PROFILE_ID.to_string(),
+ profile_id.get_string_repr().to_string().into(),
+ ));
+ parent_headers.insert((
+ headers::X_MERCHANT_ID.to_string(),
+ merchant_id.get_string_repr().to_string().into(),
+ ));
+ parent_headers.insert((
+ headers::X_INTERNAL_API_KEY.to_string(),
+ state
+ .conf
+ .internal_merchant_id_profile_id_auth
+ .internal_api_key
+ .clone()
+ .expose()
+ .to_string()
+ .into_masked(),
+ ));
+ let trace = RequestIdentifier::new(&state.conf.trace_header.header_name)
+ .use_incoming_id(state.conf.trace_header.id_reuse_strategy);
+ let client = PaymentMethodClient::new(
+ &state.conf.micro_services.payment_methods_base_url,
+ &parent_headers,
+ &trace,
+ );
+
+ UpdatePaymentMethod::call(
+ state,
+ &client,
+ UpdatePaymentMethodV1Request {
+ payment_method_id: payment_method_id.to_string(),
+ payload,
+ modular_service_prefix: state.conf.micro_services.payment_methods_prefix.0.clone(),
+ },
+ )
+ .await
+ .map_err(|err| {
+ logger::error!(error=?err, "modular payment method update failed");
+ ::payment_methods::errors::ModularPaymentMethodError::UpdateFailed
+ })?;
+ Ok(())
+}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index c46af9da4c..a3b8bd4555 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -641,6 +641,10 @@ where
.validate_request(&req, platform.get_processor())?;
tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id));
+
+ // Create feature_set early to avoid passing entire payment_data to get_trackers
+ let feature_set = core_utils::get_feature_set(state, platform).await;
+
// get profile from headers
let operations::GetTrackerResponse {
operation,
@@ -967,16 +971,17 @@ where
//add connector http status code metrics
add_connector_http_status_code_metrics(connector_http_status_code);
- operation
- .to_post_update_tracker()?
- .save_pm_and_mandate(
- state,
- &router_data,
- platform,
- &mut payment_data,
- &business_profile,
- )
- .await?;
+ handle_pm_and_mandate_post_update(
+ state,
+ operation.as_ref(),
+ &router_data,
+ platform,
+ &mut payment_data,
+ &business_profile,
+ req.get_payment_method_data(),
+ &feature_set,
+ )
+ .await?;
let router_data_for_pm_mandate = router_data.clone();
let mut payment_data = operation
@@ -1001,6 +1006,7 @@ where
platform.get_provider(),
&payment_data,
&router_data_for_pm_mandate,
+ &feature_set,
)
.await?;
@@ -1169,16 +1175,17 @@ where
//add connector http status code metrics
add_connector_http_status_code_metrics(connector_http_status_code);
- operation
- .to_post_update_tracker()?
- .save_pm_and_mandate(
- state,
- &router_data,
- platform,
- &mut payment_data,
- &business_profile,
- )
- .await?;
+ handle_pm_and_mandate_post_update(
+ state,
+ operation.as_ref(),
+ &router_data,
+ platform,
+ &mut payment_data,
+ &business_profile,
+ req.get_payment_method_data(),
+ &feature_set,
+ )
+ .await?;
let router_data_for_pm_mandate = router_data.clone();
let mut payment_data = operation
@@ -1203,6 +1210,7 @@ where
platform.get_provider(),
&payment_data,
&router_data_for_pm_mandate,
+ &feature_set,
)
.await?;
@@ -1409,6 +1417,8 @@ where
tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id));
+ let feature_set = core_utils::get_feature_set(state, &platform).await;
+
let operations::GetTrackerResponse {
operation,
customer_details,
@@ -1548,6 +1558,7 @@ where
platform.get_provider(),
&payment_data,
&router_data_for_pm_mandate,
+ &feature_set,
)
.await?;
@@ -2241,6 +2252,58 @@ pub async fn call_surcharge_decision_management_for_session_flow(
}
}
+#[cfg(feature = "v1")]
+#[allow(clippy::too_many_arguments)]
+async fn handle_pm_and_mandate_post_update<F, R, Op, D>(
+ state: &SessionState,
+ operation: &Op,
+ router_data: &RouterData<F, R, router_types::PaymentsResponseData>,
+ platform: &domain::Platform,
+ payment_data: &mut D,
+ business_profile: &domain::Profile,
+ request_payment_method_data: Option<api_models::payments::PaymentMethodData>,
+ feature_set: &core_utils::FeatureSet,
+) -> CustomResult<(), errors::ApiErrorResponse>
+where
+ F: Clone + Send + Sync,
+ R: Send,
+ D: OperationSessionGetters<F> + Send + Sync,
+ Op: Operation<F, R, Data = D> + Send + Sync,
+{
+ if feature_set.is_modular_merchant {
+ logger::debug!(
+ payment_id = ?payment_data.get_payment_attempt().payment_id,
+ "Modular merchant detected; calling update_modular_pm_and_mandate"
+ );
+
+ let domain_payment_method_data =
+ request_payment_method_data.map(domain::PaymentMethodData::from);
+
+ operation
+ .to_post_update_tracker()?
+ .update_modular_pm_and_mandate(
+ state,
+ router_data,
+ platform,
+ payment_data,
+ business_profile,
+ domain_payment_method_data.as_ref(),
+ )
+ .await?;
+ } else {
+ logger::debug!(
+ payment_id = ?payment_data.get_payment_attempt().payment_id,
+ "Non-modular merchant; calling save_pm_and_mandate"
+ );
+ operation
+ .to_post_update_tracker()?
+ .save_pm_and_mandate(state, router_data, platform, payment_data, business_profile)
+ .await?;
+ }
+
+ Ok(())
+}
+
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn payments_core<F, Res, Req, Op, FData, D>(
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index 8b8742419f..72ad9aae85 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -100,7 +100,10 @@ use super::{helpers, CustomerDetails, OperationSessionGetters, OperationSessionS
#[cfg(feature = "v2")]
use crate::core::payments;
use crate::{
- core::errors::{self, CustomResult, RouterResult},
+ core::{
+ errors::{self, CustomResult, RouterResult},
+ utils as core_utils,
+ },
routes::{app::ReqState, SessionState},
services,
types::{
@@ -585,12 +588,31 @@ 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,
) -> RouterResult<()>
where
F: 'b + Clone + Send + Sync,
{
Ok(())
}
+
+ #[cfg(feature = "v1")]
+ async fn update_modular_pm_and_mandate<'b>(
+ &self,
+ _state: &SessionState,
+ _resp: &types::RouterData<F, R, PaymentsResponseData>,
+ _platform: &domain::Platform,
+ // `PaymentData` is kept mutable for updating `payment_attempt.connector_mandate_detail`
+ // Ideally, this update should be moved to `update_trackers`
+ _payment_data: &mut D,
+ _business_profile: &domain::Profile,
+ _request_payment_method_data: Option<&domain::PaymentMethodData>,
+ ) -> CustomResult<(), errors::ApiErrorResponse>
+ where
+ F: 'b + Clone + Send + Sync,
+ {
+ Ok(())
+ }
}
#[cfg(feature = "v1")]
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 4a7ff48fbf..56ccf3ce99 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -1,10 +1,16 @@
use std::{collections::HashMap, ops::Deref};
+#[cfg(feature = "v1")]
+use ::payment_methods::client::{
+ CardDetailUpdate, PaymentMethodUpdateData, UpdatePaymentMethodV1Payload,
+};
use api_models::payments::{ConnectorMandateReferenceId, MandateReferenceId};
#[cfg(feature = "dynamic_routing")]
use api_models::routing::RoutableConnectorChoice;
use async_trait::async_trait;
use common_enums::AuthorizationStatus;
+#[cfg(feature = "v1")]
+use common_enums::{ConnectorTokenStatus, TokenizationType};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use common_utils::ext_traits::ValueExt;
use common_utils::{
@@ -22,9 +28,12 @@ use hyperswitch_domain_models::{behaviour::Conversion, payments::payment_attempt
use masking::PeekInterface;
use router_derive;
use router_env::{instrument, logger, tracing};
+#[cfg(feature = "v1")]
use tracing_futures::Instrument;
use super::{Operation, OperationSessionSetters, PostUpdateTracker};
+#[cfg(feature = "v1")]
+use crate::core::payment_methods::transformers::call_modular_payment_method_update;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use crate::core::routing::helpers as routing_helpers;
#[cfg(feature = "v2")]
@@ -58,6 +67,134 @@ use crate::{
utils,
};
+/// This implementation executes the flow only when
+/// 1. Payment was created with supported payment methods
+/// 2. Payment attempt's status was not a terminal failure
+#[cfg(feature = "v1")]
+async fn update_modular_pm_and_mandate_impl<F, T>(
+ state: &SessionState,
+ resp: &types::RouterData<F, T, types::PaymentsResponseData>,
+ request_payment_method_data: Option<&domain::PaymentMethodData>,
+ payment_data: &mut PaymentData<F>,
+) -> CustomResult<(), ::payment_methods::errors::ModularPaymentMethodError>
+where
+ F: Clone + Send + Sync,
+{
+ if matches!(
+ payment_data.payment_attempt.payment_method,
+ Some(enums::PaymentMethod::Card)
+ ) && resp.status.should_update_payment_method()
+ {
+ // #1 - Retrieve payment_method_id from payment_method_info.
+ let payment_method_id = payment_data
+ .payment_method_info
+ .as_ref()
+ .map(|info| info.get_id().clone())
+ .ok_or_else(|| {
+ logger::error!("Missing required Param payment_method_id");
+ ::payment_methods::errors::ModularPaymentMethodError::RetrieveFailed
+ })?;
+
+ // #2 - Derive network transaction ID from the connector response.
+ let network_transaction_id = resp
+ .response
+ .as_ref()
+ .map_err(|err| {
+ logger::debug!(error=?err, "Failed to obtain the network_transaction_id from payment response in modular payment method update call");
+ })
+ .ok()
+ .and_then(types::PaymentsResponseData::get_network_transaction_id);
+
+ // #3 - Fill payment method data for cards (update card holder name, nick_name & cvc).
+ // Use request payment method data for card_holder_name and nick_name
+ let payment_method_data =
+ request_payment_method_data.and_then(|method_data| match method_data {
+ domain::PaymentMethodData::Card(card) => {
+ Some(PaymentMethodUpdateData::Card(CardDetailUpdate {
+ card_holder_name: card.card_holder_name.clone(),
+ nick_name: card.nick_name.clone(),
+ card_cvc: None,
+ }))
+ }
+ _ => None,
+ });
+
+ // #4 - Build connector token details only when a mandate reference is available.
+ let connector_token_details = match resp
+ .response
+ .as_ref()
+ .ok()
+ .and_then(types::PaymentsResponseData::get_mandate_reference)
+ {
+ Some(mandate_reference) => {
+ let connector_id = payment_data
+ .payment_attempt
+ .merchant_connector_id
+ .clone()
+ .ok_or_else(|| {
+ logger::error!("Missing required Param merchant_connector_id");
+ ::payment_methods::errors::ModularPaymentMethodError::RetrieveFailed
+ })?;
+ update_connector_mandate_details_for_the_flow(
+ mandate_reference.connector_mandate_id.clone(),
+ mandate_reference.mandate_metadata.clone(),
+ mandate_reference
+ .connector_mandate_request_reference_id
+ .clone(),
+ payment_data,
+ )
+ .change_context(
+ ::payment_methods::errors::ModularPaymentMethodError::UpdateFailed,
+ )?;
+ mandate_reference
+ .connector_mandate_id
+ .map(
+ |connector_mandate_id| ::payment_methods::types::ConnectorTokenDetails {
+ connector_id,
+ token_type: TokenizationType::MultiUse,
+ status: ConnectorTokenStatus::Active,
+ connector_token_request_reference_id: mandate_reference
+ .connector_mandate_request_reference_id,
+ original_payment_authorized_amount: Some(
+ payment_data.payment_attempt.net_amount.get_total_amount(),
+ ),
+ original_payment_authorized_currency: payment_data
+ .payment_attempt
+ .currency,
+ metadata: mandate_reference.mandate_metadata,
+ token: masking::Secret::new(connector_mandate_id),
+ },
+ )
+ }
+ None => None,
+ };
+
+ let payload = UpdatePaymentMethodV1Payload {
+ payment_method_data,
+ connector_token_details,
+ network_transaction_id: network_transaction_id.map(masking::Secret::new),
+ };
+
+ // #5 - Execute the modular payment-method update call if there is something to be updated
+ if payload.payment_method_data.is_some()
+ || payload.connector_token_details.is_some()
+ || payload.network_transaction_id.is_some()
+ {
+ call_modular_payment_method_update(
+ state,
+ &payment_data.payment_attempt.merchant_id,
+ &payment_data.payment_attempt.profile_id,
+ &payment_method_id,
+ payload,
+ )
+ .await?;
+ payment_data.payment_attempt.payment_method_id = Some(payment_method_id);
+ }
+ }
+
+ Ok(())
+}
+
/// Helper function to update payment method connector mandate details.
/// This is called after a successful payment to activate/update the connector mandate.
#[cfg(feature = "v1")]
@@ -526,11 +663,35 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
+ feature_set: &core_utils::FeatureSet,
) -> RouterResult<()>
where
F: 'b + Clone + Send + Sync,
{
- update_pm_connector_mandate_details(state, provider, payment_data, router_data).await
+ if !feature_set.is_modular_merchant {
+ update_pm_connector_mandate_details(state, provider, payment_data, router_data).await
+ } else {
+ Ok(())
+ }
+ }
+
+ #[cfg(feature = "v1")]
+ async fn update_modular_pm_and_mandate<'b>(
+ &self,
+ state: &SessionState,
+ resp: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
+ _platform: &domain::Platform,
+ payment_data: &mut PaymentData<F>,
+ _business_profile: &domain::Profile,
+ request_payment_method_data: Option<&domain::PaymentMethodData>,
+ ) -> CustomResult<(), errors::ApiErrorResponse>
+ where
+ F: 'b + Clone + Send + Sync,
+ {
+ update_modular_pm_and_mandate_impl(state, resp, request_payment_method_data, payment_data)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update modular payment method and mandate")
}
}
@@ -793,11 +954,35 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSyncData> for
provider: &domain::Provider,
payment_data: &PaymentData<F>,
router_data: &types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>,
+ feature_set: &core_utils::FeatureSet,
) -> RouterResult<()>
where
F: 'b + Clone + Send + Sync,
{
- update_pm_connector_mandate_details(state, provider, payment_data, router_data).await
+ if !feature_set.is_modular_merchant {
+ update_pm_connector_mandate_details(state, provider, payment_data, router_data).await
+ } else {
+ Ok(())
+ }
+ }
+
+ #[cfg(feature = "v1")]
+ async fn update_modular_pm_and_mandate<'b>(
+ &self,
+ state: &SessionState,
+ resp: &types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>,
+ _platform: &domain::Platform,
+ payment_data: &mut PaymentData<F>,
+ _business_profile: &domain::Profile,
+ request_payment_method_data: Option<&domain::PaymentMethodData>,
+ ) -> CustomResult<(), errors::ApiErrorResponse>
+ where
+ F: 'b + Clone + Send + Sync,
+ {
+ update_modular_pm_and_mandate_impl(state, resp, request_payment_method_data, payment_data)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update modular payment method and mandate")
}
}
@@ -1503,12 +1688,31 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestDa
types::SetupMandateRequestData,
types::PaymentsResponseData,
>,
+ _feature_set: &core_utils::FeatureSet,
) -> RouterResult<()>
where
F: 'b + Clone + Send + Sync,
{
update_pm_connector_mandate_details(state, provider, payment_data, router_data).await
}
+ #[cfg(feature = "v1")]
+ async fn update_modular_pm_and_mandate<'b>(
+ &self,
+ state: &SessionState,
+ resp: &types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData>,
+ _platform: &domain::Platform,
+ payment_data: &mut PaymentData<F>,
+ _business_profile: &domain::Profile,
+ request_payment_method_data: Option<&domain::PaymentMethodData>,
+ ) -> CustomResult<(), errors::ApiErrorResponse>
+ where
+ F: 'b + Clone + Send + Sync,
+ {
+ update_modular_pm_and_mandate_impl(state, resp, request_payment_method_data, payment_data)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update modular payment method and mandate")
+ }
}
#[cfg(feature = "v1")]
@@ -1607,11 +1811,35 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::CompleteAuthorizeData
types::CompleteAuthorizeData,
types::PaymentsResponseData,
>,
+ feature_set: &core_utils::FeatureSet,
) -> RouterResult<()>
where
F: 'b + Clone + Send + Sync,
{
- update_pm_connector_mandate_details(state, provider, payment_data, router_data).await
+ if !feature_set.is_modular_merchant {
+ update_pm_connector_mandate_details(state, provider, payment_data, router_data).await
+ } else {
+ Ok(())
+ }
+ }
+
+ #[cfg(feature = "v1")]
+ async fn update_modular_pm_and_mandate<'b>(
+ &self,
+ state: &SessionState,
+ resp: &types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>,
+ _platform: &domain::Platform,
+ payment_data: &mut PaymentData<F>,
+ _business_profile: &domain::Profile,
+ request_payment_method_data: Option<&domain::PaymentMethodData>,
+ ) -> CustomResult<(), errors::ApiErrorResponse>
+ where
+ F: 'b + Clone + Send + Sync,
+ {
+ update_modular_pm_and_mandate_impl(state, resp, request_payment_method_data, payment_data)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update modular payment method and mandate")
}
}
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index a5ba943593..0d508643b5 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -60,6 +60,24 @@ use crate::{
utils::{generate_id, OptionExt, ValueExt},
};
+#[cfg(feature = "v1")]
+#[derive(Debug, Clone, Default)]
+pub struct FeatureSet {
+ pub is_modular_merchant: 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(
+ state.store.as_ref(),
+ &platform.get_processor().get_account().organization_id,
+ )
+ .await;
+ FeatureSet {
+ is_modular_merchant,
+ }
+}
+
pub const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_DISPUTE_FLOW: &str =
"irrelevant_connector_request_reference_id_in_dispute_flow";
const IRRELEVANT_ATTEMPT_ID_IN_DISPUTE_FLOW: &str = "irrelevant_attempt_id_in_dispute_flow";
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 84c64c5756..1694b02333 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -689,6 +689,10 @@ pub trait Authenticate {
fn is_external_three_ds_data_passed_by_merchant(&self) -> bool {
false
}
+
+ fn get_payment_method_data(&self) -> Option<api_models::payments::PaymentMethodData> {
+ None
+ }
}
#[cfg(feature = "v2")]
@@ -718,6 +722,12 @@ impl Authenticate for api_models::payments::PaymentsRequest {
fn is_external_three_ds_data_passed_by_merchant(&self) -> bool {
self.three_ds_data.is_some()
}
+
+ fn get_payment_method_data(&self) -> Option<api_models::payments::PaymentMethodData> {
+ self.payment_method_data
+ .as_ref()
+ .and_then(|pmd| pmd.payment_method_data.clone())
+ }
}
#[cfg(feature = "v1")]