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(router): Flow changes for split payments (v2) (#9239)

Anurag Thakur75290087ce78
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 66ff970c51..17124b047c 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -7265,7 +7265,7 @@ pub struct PaymentsListResponseItem {
//
/// Request for Payment Intent Confirm
#[cfg(feature = "v2")]
-#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct PaymentsConfirmIntentRequest {
/// The URL to which you want the user to be redirected after the completion of the payment operation
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index b6330145a0..cb3553257e 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2339,6 +2339,28 @@ pub enum PaymentMethod {
MobilePayment,
}
+impl PaymentMethod {
+ pub fn is_gift_card(&self) -> bool {
+ match self {
+ Self::GiftCard => true,
+ Self::Card
+ | Self::CardRedirect
+ | Self::PayLater
+ | Self::Wallet
+ | Self::BankRedirect
+ | Self::BankTransfer
+ | Self::Crypto
+ | Self::BankDebit
+ | Self::Reward
+ | Self::RealTimePayment
+ | Self::Upi
+ | Self::Voucher
+ | Self::OpenBanking
+ | Self::MobilePayment => false,
+ }
+ }
+}
+
/// Indicates the gateway system through which the payment is processed.
#[derive(
Clone,
@@ -3161,7 +3183,7 @@ pub enum SplitTxnsEnabled {
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum ActiveAttemptIDType {
- AttemptsGroupID,
+ GroupID,
#[default]
AttemptID,
}
diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs
index 4d57975b0f..ce5826dcbe 100644
--- a/crates/common_utils/src/id_type.rs
+++ b/crates/common_utils/src/id_type.rs
@@ -38,7 +38,7 @@ use thiserror::Error;
#[cfg(feature = "v2")]
pub use self::global_id::{
customer::GlobalCustomerId,
- payment::{GlobalAttemptId, GlobalPaymentId},
+ payment::{GlobalAttemptGroupId, GlobalAttemptId, GlobalPaymentId},
payment_methods::{GlobalPaymentMethodId, GlobalPaymentMethodSessionId},
refunds::GlobalRefundId,
token::GlobalTokenId,
diff --git a/crates/common_utils/src/id_type/global_id.rs b/crates/common_utils/src/id_type/global_id.rs
index 636e4ec61e..ff9f7d2286 100644
--- a/crates/common_utils/src/id_type/global_id.rs
+++ b/crates/common_utils/src/id_type/global_id.rs
@@ -25,6 +25,7 @@ pub(crate) enum GlobalEntity {
Customer,
Payment,
Attempt,
+ AttemptGroup,
PaymentMethod,
Refund,
PaymentMethodSession,
@@ -38,6 +39,7 @@ impl GlobalEntity {
Self::Payment => "pay",
Self::PaymentMethod => "pm",
Self::Attempt => "att",
+ Self::AttemptGroup => "atg",
Self::Refund => "ref",
Self::PaymentMethodSession => "pms",
Self::Token => "tok",
diff --git a/crates/common_utils/src/id_type/global_id/payment.rs b/crates/common_utils/src/id_type/global_id/payment.rs
index b6d62689ec..f86e3ed2f1 100644
--- a/crates/common_utils/src/id_type/global_id/payment.rs
+++ b/crates/common_utils/src/id_type/global_id/payment.rs
@@ -98,3 +98,37 @@ impl TryFrom<std::borrow::Cow<'static, str>> for GlobalAttemptId {
Ok(Self(global_attempt_id))
}
}
+
+crate::global_id_type!(
+ GlobalAttemptGroupId,
+ "A global id that can be used to identify a payment attempt group"
+);
+
+// Database related implementations so that this field can be used directly in the database tables
+crate::impl_queryable_id_type!(GlobalAttemptGroupId);
+crate::impl_to_sql_from_sql_global_id_type!(GlobalAttemptGroupId);
+
+impl GlobalAttemptGroupId {
+ /// Generate a new GlobalAttemptId from a cell id
+ pub fn generate(cell_id: &super::CellId) -> Self {
+ let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::AttemptGroup);
+ Self(global_id)
+ }
+
+ /// Get string representation of the id
+ pub fn get_string_repr(&self) -> &str {
+ self.0.get_string_repr()
+ }
+}
+
+impl TryFrom<std::borrow::Cow<'static, str>> for GlobalAttemptGroupId {
+ type Error = error_stack::Report<errors::ValidationError>;
+ fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> {
+ let global_attempt_group_id = super::GlobalId::from_string(value).change_context(
+ errors::ValidationError::IncorrectValueProvided {
+ field_name: "global_attempt_group_id",
+ },
+ )?;
+ Ok(Self(global_attempt_group_id))
+ }
+}
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index 9e1a2af7dd..5f6e8d4f5a 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -135,7 +135,7 @@ pub struct PaymentAttempt {
/// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better.
pub network_error_message: Option<String>,
/// A string indicating the group of the payment attempt. Used in split payments flow
- pub attempts_group_id: Option<String>,
+ pub attempts_group_id: Option<id_type::GlobalAttemptGroupId>,
}
#[cfg(feature = "v1")]
@@ -312,7 +312,7 @@ pub struct PaymentListFilters {
pub struct PaymentAttemptNew {
pub payment_id: id_type::GlobalPaymentId,
pub merchant_id: id_type::MerchantId,
- pub attempts_group_id: Option<String>,
+ pub attempts_group_id: Option<id_type::GlobalAttemptGroupId>,
pub status: storage_enums::AttemptStatus,
pub error_message: Option<String>,
pub surcharge_amount: Option<MinorUnit>,
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index 4b41a020c3..41dddd9917 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -101,7 +101,7 @@ pub struct PaymentIntent {
pub payment_link_config: Option<PaymentLinkConfigRequestForPayments>,
pub id: common_utils::id_type::GlobalPaymentId,
pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>,
- pub active_attempts_group_id: Option<String>,
+ pub active_attempts_group_id: Option<common_utils::id_type::GlobalAttemptGroupId>,
pub active_attempt_id_type: Option<common_enums::ActiveAttemptIDType>,
}
@@ -664,6 +664,8 @@ pub struct PaymentIntentUpdateInternal {
pub amount_captured: Option<MinorUnit>,
pub modified_at: PrimitiveDateTime,
pub active_attempt_id: Option<Option<common_utils::id_type::GlobalAttemptId>>,
+ pub active_attempts_group_id: Option<common_utils::id_type::GlobalAttemptGroupId>,
+ pub active_attempt_id_type: Option<common_enums::ActiveAttemptIDType>,
pub amount: Option<MinorUnit>,
pub currency: Option<storage_enums::Currency>,
pub shipping_cost: Option<MinorUnit>,
@@ -708,6 +710,8 @@ impl PaymentIntentUpdateInternal {
amount_captured,
modified_at: _, // This will be ignored from self
active_attempt_id,
+ active_attempts_group_id,
+ active_attempt_id_type,
amount,
currency,
shipping_cost,
@@ -752,6 +756,8 @@ impl PaymentIntentUpdateInternal {
Some(v_option) => v_option,
None => source.active_attempt_id,
},
+ active_attempt_id_type: active_attempt_id_type.or(source.active_attempt_id_type),
+ active_attempts_group_id: active_attempts_group_id.or(source.active_attempts_group_id),
amount: amount.unwrap_or(source.amount),
currency: currency.unwrap_or(source.currency),
shipping_cost: shipping_cost.or(source.shipping_cost),
@@ -821,8 +827,6 @@ impl PaymentIntentUpdateInternal {
enable_partial_authorization: source.enable_partial_authorization,
split_txns_enabled: source.split_txns_enabled,
enable_overcapture: None,
- active_attempt_id_type: source.active_attempt_id_type,
- active_attempts_group_id: source.active_attempts_group_id,
mit_category: None,
billing_descriptor: source.billing_descriptor,
}
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index c3dcbd77d4..8d01070bb3 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -31,6 +31,8 @@ use time::PrimitiveDateTime;
pub mod payment_attempt;
pub mod payment_intent;
+#[cfg(feature = "v2")]
+pub mod split_payments;
use common_enums as storage_enums;
#[cfg(feature = "v2")]
@@ -393,6 +395,44 @@ impl AmountDetails {
})
}
+ pub fn create_split_attempt_amount_details(
+ &self,
+ confirm_intent_request: &api_models::payments::PaymentsConfirmIntentRequest,
+ split_amount: MinorUnit,
+ ) -> payment_attempt::AttemptAmountDetails {
+ let net_amount = split_amount;
+
+ let surcharge_amount = match self.skip_surcharge_calculation {
+ common_enums::SurchargeCalculationOverride::Skip => self.surcharge_amount,
+ common_enums::SurchargeCalculationOverride::Calculate => None,
+ };
+
+ let tax_on_surcharge = match self.skip_surcharge_calculation {
+ common_enums::SurchargeCalculationOverride::Skip => self.tax_on_surcharge,
+ common_enums::SurchargeCalculationOverride::Calculate => None,
+ };
+
+ let order_tax_amount = match self.skip_external_tax_calculation {
+ common_enums::TaxCalculationOverride::Skip => {
+ self.tax_details.as_ref().and_then(|tax_details| {
+ tax_details.get_tax_amount(Some(confirm_intent_request.payment_method_subtype))
+ })
+ }
+ common_enums::TaxCalculationOverride::Calculate => None,
+ };
+
+ payment_attempt::AttemptAmountDetails::from(payment_attempt::AttemptAmountDetailsSetter {
+ net_amount,
+ amount_to_capture: None,
+ surcharge_amount,
+ tax_on_surcharge,
+ // This will be updated when we receive response from the connector
+ amount_capturable: MinorUnit::zero(),
+ shipping_cost: self.shipping_cost,
+ order_tax_amount,
+ })
+ }
+
pub fn proxy_create_attempt_amount_details(
&self,
_confirm_intent_request: &api_models::payments::ProxyPaymentsRequest,
@@ -495,7 +535,7 @@ pub struct PaymentIntent {
/// This field represents whether there are attempt groups for this payment intent. Used in split payments workflow
pub active_attempt_id_type: common_enums::ActiveAttemptIDType,
/// The ID of the active attempt group for the payment intent
- pub active_attempts_group_id: Option<String>,
+ pub active_attempts_group_id: Option<id_type::GlobalAttemptGroupId>,
/// The order details for the payment.
pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>,
/// This is the list of payment method types that are allowed for the payment intent.
@@ -852,9 +892,33 @@ impl PaymentIntent {
self.amount_details.currency
}
+ pub fn supports_split_payments(&self) -> bool {
+ self.split_txns_enabled == common_enums::SplitTxnsEnabled::Enable
+ }
+
pub fn is_split_payment(&self) -> bool {
self.split_txns_enabled == common_enums::SplitTxnsEnabled::Enable
- && self.active_attempt_id_type == common_enums::ActiveAttemptIDType::AttemptsGroupID
+ && self.active_attempt_id_type == common_enums::ActiveAttemptIDType::GroupID
+ }
+
+ pub fn is_succeeded(&self) -> bool {
+ match self.status {
+ common_enums::IntentStatus::Succeeded => true,
+ common_enums::IntentStatus::Failed
+ | common_enums::IntentStatus::Cancelled
+ | common_enums::IntentStatus::CancelledPostCapture
+ | common_enums::IntentStatus::PartiallyCaptured
+ | common_enums::IntentStatus::Expired
+ | common_enums::IntentStatus::Processing
+ | common_enums::IntentStatus::RequiresCustomerAction
+ | common_enums::IntentStatus::RequiresMerchantAction
+ | common_enums::IntentStatus::RequiresPaymentMethod
+ | common_enums::IntentStatus::RequiresConfirmation
+ | common_enums::IntentStatus::RequiresCapture
+ | common_enums::IntentStatus::PartiallyCapturedAndCapturable
+ | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
+ | common_enums::IntentStatus::Conflicted => false,
+ }
}
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index c49413800e..d4bbbb27d8 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -399,7 +399,7 @@ pub struct PaymentAttempt {
/// Merchant id for the payment attempt
pub merchant_id: id_type::MerchantId,
/// Group id for the payment attempt
- pub attempts_group_id: Option<String>,
+ pub attempts_group_id: Option<id_type::GlobalAttemptGroupId>,
/// Amount details for the payment attempt
pub amount_details: AttemptAmountDetails,
/// Status of the payment attempt. This is the status that is updated by the connector.
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index d297026f6d..387d263cf1 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -394,6 +394,15 @@ pub enum PaymentIntentUpdate {
status: common_enums::IntentStatus,
updated_by: String,
},
+ AttemptGroupUpdate {
+ active_attempts_group_id: id_type::GlobalAttemptGroupId,
+ active_attempt_id_type: common_enums::ActiveAttemptIDType,
+ updated_by: String,
+ },
+ SplitPaymentStatusUpdate {
+ status: common_enums::IntentStatus,
+ updated_by: String,
+ },
}
#[cfg(feature = "v2")]
@@ -471,6 +480,8 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal
} => Ok(Self {
status: Some(status),
active_attempt_id: Some(active_attempt_id),
+ active_attempt_id_type: None,
+ active_attempts_group_id: None,
prerouting_algorithm: None,
modified_at: common_utils::date_time::now(),
amount: None,
@@ -517,6 +528,9 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal
} => Ok(Self {
status: Some(status),
active_attempt_id: None,
+ active_attempt_id_type: None,
+ active_attempts_group_id: None,
+
prerouting_algorithm: None,
modified_at: common_utils::date_time::now(),
amount_captured,
@@ -561,6 +575,9 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal
} => Ok(Self {
status: Some(status),
active_attempt_id: None,
+ active_attempt_id_type: None,
+ active_attempts_group_id: None,
+
prerouting_algorithm: None,
modified_at: common_utils::date_time::now(),
amount: None,
@@ -606,6 +623,9 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal
status: Some(status),
amount_captured,
active_attempt_id: None,
+ active_attempt_id_type: None,
+ active_attempts_group_id: None,
+
prerouting_algorithm: None,
modified_at: common_utils::date_time::now(),
amount: None,
@@ -648,6 +668,9 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal
} => Ok(Self {
status: None,
active_attempt_id: None,
+ active_attempt_id_type: None,
+ active_attempts_group_id: None,
+
modified_at: common_utils::date_time::now(),
amount_captured: None,
prerouting_algorithm: Some(
@@ -721,6 +744,7 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal
frm_metadata,
request_external_three_ds_authentication,
active_attempt_id,
+
updated_by,
force_3ds_challenge,
is_iframe_redirection_enabled,
@@ -729,6 +753,9 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal
Ok(Self {
status: None,
active_attempt_id,
+ active_attempt_id_type: None,
+ active_attempts_group_id: None,
+
prerouting_algorithm: None,
modified_at: common_utils::date_time::now(),
amount_captured: None,
@@ -782,6 +809,9 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal
status: Some(status),
amount_captured: None,
active_attempt_id: Some(active_attempt_id),
+ active_attempt_id_type: None,
+ active_attempts_group_id: None,
+
modified_at: common_utils::date_time::now(),
amount: None,
currency: None,
@@ -822,6 +852,99 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal
status: Some(status),
amount_captured: None,
active_attempt_id: None,
+ active_attempt_id_type: None,
+ active_attempts_group_id: None,
+
+ prerouting_algorithm: None,
+ modified_at: common_utils::date_time::now(),
+ amount: None,
+ currency: None,
+ shipping_cost: None,
+ tax_details: None,
+ skip_external_tax_calculation: None,
+ surcharge_applicable: None,
+ surcharge_amount: None,
+ tax_on_surcharge: None,
+ routing_algorithm_id: None,
+ capture_method: None,
+ authentication_type: None,
+ billing_address: None,
+ shipping_address: None,
+ customer_present: None,
+ description: None,
+ return_url: None,
+ setup_future_usage: None,
+ apply_mit_exemption: None,
+ statement_descriptor: None,
+ order_details: None,
+ allowed_payment_method_types: None,
+ metadata: None,
+ connector_metadata: None,
+ feature_metadata: None,
+ payment_link_config: None,
+ request_incremental_authorization: None,
+ session_expiry: None,
+ frm_metadata: None,
+ request_external_three_ds_authentication: None,
+ updated_by,
+ force_3ds_challenge: None,
+ is_iframe_redirection_enabled: None,
+ enable_partial_authorization: None,
+ }),
+ PaymentIntentUpdate::AttemptGroupUpdate {
+ updated_by,
+ active_attempts_group_id,
+ active_attempt_id_type,
+ } => Ok(Self {
+ status: None,
+ amount_captured: None,
+ active_attempt_id: None,
+ active_attempt_id_type: Some(active_attempt_id_type),
+ active_attempts_group_id: Some(active_attempts_group_id),
+
+ prerouting_algorithm: None,
+ modified_at: common_utils::date_time::now(),
+ amount: None,
+ currency: None,
+ shipping_cost: None,
+ tax_details: None,
+ skip_external_tax_calculation: None,
+ surcharge_applicable: None,
+ surcharge_amount: None,
+ tax_on_surcharge: None,
+ routing_algorithm_id: None,
+ capture_method: None,
+ authentication_type: None,
+ billing_address: None,
+ shipping_address: None,
+ customer_present: None,
+ description: None,
+ return_url: None,
+ setup_future_usage: None,
+ apply_mit_exemption: None,
+ statement_descriptor: None,
+ order_details: None,
+ allowed_payment_method_types: None,
+ metadata: None,
+ connector_metadata: None,
+ feature_metadata: None,
+ payment_link_config: None,
+ request_incremental_authorization: None,
+ session_expiry: None,
+ frm_metadata: None,
+ request_external_three_ds_authentication: None,
+ updated_by,
+ force_3ds_challenge: None,
+ is_iframe_redirection_enabled: None,
+ enable_partial_authorization: None,
+ }),
+ PaymentIntentUpdate::SplitPaymentStatusUpdate { status, updated_by } => Ok(Self {
+ status: Some(status),
+ amount_captured: None,
+ active_attempt_id: None,
+ active_attempt_id_type: None,
+ active_attempts_group_id: None,
+
prerouting_algorithm: None,
modified_at: common_utils::date_time::now(),
amount: None,
diff --git a/crates/hyperswitch_domain_models/src/payments/split_payments.rs b/crates/hyperswitch_domain_models/src/payments/split_payments.rs
new file mode 100644
index 0000000000..9aed698983
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/payments/split_payments.rs
@@ -0,0 +1,8 @@
+use api_models::payments::PaymentMethodData;
+use common_utils::types::MinorUnit;
+
+/// There can be multiple gift-cards, but at most one non-gift card PM
+pub struct PaymentMethodAmountSplit {
+ pub balance_pm_split: Vec<(PaymentMethodData, MinorUnit)>,
+ pub non_balance_pm_split: Option<(PaymentMethodData, MinorUnit)>,
+}
diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs
index 863577cd8a..91b8d16c76 100644
--- a/crates/router/src/core.rs
+++ b/crates/router/src/core.rs
@@ -38,6 +38,10 @@ pub mod payment_link;
pub mod payment_method_balance;
pub mod payment_methods;
pub mod payments;
+
+#[cfg(feature = "v2")]
+pub mod split_payments;
+
#[cfg(feature = "payouts")]
pub mod payout_link;
#[cfg(feature = "payouts")]
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index c91051c3a7..8e94397635 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -2822,6 +2822,51 @@ where
)
}
+#[allow(clippy::too_many_arguments)]
+#[cfg(feature = "v2")]
+pub(crate) async fn payments_execute_wrapper(
+ state: SessionState,
+ req_state: ReqState,
+ merchant_context: domain::MerchantContext,
+ profile: domain::Profile,
+ request: payments_api::PaymentsConfirmIntentRequest,
+ header_payload: HeaderPayload,
+ payment_id: id_type::GlobalPaymentId,
+) -> RouterResponse<payments_api::PaymentsResponse> {
+ if request.split_payment_method_data.is_none() {
+ Box::pin(payments_core::<
+ api::Authorize,
+ api_models::payments::PaymentsResponse,
+ _,
+ _,
+ _,
+ PaymentConfirmData<api::Authorize>,
+ >(
+ state,
+ req_state,
+ merchant_context,
+ profile,
+ operations::PaymentIntentConfirm,
+ request,
+ payment_id,
+ CallConnectorAction::Trigger,
+ header_payload,
+ ))
+ .await
+ } else {
+ Box::pin(super::split_payments::split_payments_execute_core(
+ state,
+ req_state,
+ merchant_context,
+ profile,
+ request,
+ header_payload,
+ payment_id,
+ ))
+ .await
+ }
+}
+
#[allow(clippy::too_many_arguments)]
#[cfg(feature = "v2")]
pub(crate) async fn payments_create_and_confirm_intent(
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index 7ed0aa5813..7e3bee1d93 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -227,6 +227,27 @@ pub trait GetTracker<F: Clone, D, R>: Send {
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<GetTrackerResponse<D>>;
+ #[cfg(feature = "v2")]
+ #[allow(clippy::too_many_arguments)]
+ async fn get_trackers_for_split_payments<'a>(
+ &'a self,
+ _state: &'a SessionState,
+ _payment_id: &common_utils::id_type::GlobalPaymentId,
+ _request: &R,
+ _merchant_context: &domain::MerchantContext,
+ _profile: &domain::Profile,
+ _header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
+ _split_amount_data: (
+ api_models::payments::PaymentMethodData,
+ common_utils::types::MinorUnit,
+ ),
+ _attempts_group_id: &common_utils::id_type::GlobalAttemptGroupId,
+ ) -> RouterResult<GetTrackerResponse<D>> {
+ Err(errors::ApiErrorResponse::NotImplemented {
+ message: errors::NotImplementedMessage::Default,
+ })?
+ }
+
async fn validate_request_with_state(
&self,
_state: &SessionState,
diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rs
index f7db988b26..c49d83ad37 100644
--- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs
@@ -286,6 +286,132 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, PaymentsConfir
Ok(get_trackers_response)
}
+
+ #[instrument(skip_all)]
+ async fn get_trackers_for_split_payments<'a>(
+ &'a self,
+ state: &'a SessionState,
+ payment_id: &id_type::GlobalPaymentId,
+ request: &PaymentsConfirmIntentRequest,
+ merchant_context: &domain::MerchantContext,
+ profile: &domain::Profile,
+ header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
+ split_amount_data: (
+ api_models::payments::PaymentMethodData,
+ common_utils::types::MinorUnit,
+ ),
+ attempts_group_id: &id_type::GlobalAttemptGroupId,
+ ) -> RouterResult<operations::GetTrackerResponse<PaymentConfirmData<F>>> {
+ let db = &*state.store;
+ let key_manager_state = &state.into();
+
+ let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
+
+ let payment_intent = db
+ .find_payment_intent_by_id(
+ key_manager_state,
+ payment_id,
+ merchant_context.get_merchant_key_store(),
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ // TODO (#7195): Add platform merchant account validation once publishable key auth is solved
+
+ self.validate_status_for_operation(payment_intent.status)?;
+
+ let cell_id = state.conf.cell_information.id.clone();
+
+ let batch_encrypted_data = domain_types::crypto_operation(
+ key_manager_state,
+ common_utils::type_name!(hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt),
+ domain_types::CryptoOperation::BatchEncrypt(
+ hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::to_encryptable(
+ hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt {
+ payment_method_billing_address: request.payment_method_data.billing.as_ref().map(|address| address.clone().encode_to_value()).transpose().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to encode payment_method_billing address")?.map(masking::Secret::new),
+ },
+ ),
+ ),
+ common_utils::types::keymanager::Identifier::Merchant(merchant_context.get_merchant_account().get_id().to_owned()),
+ merchant_context.get_merchant_key_store().key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_batchoperation())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while encrypting payment intent details".to_string())?;
+
+ let encrypted_data =
+ hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::from_encryptable(batch_encrypted_data)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while encrypting payment intent details")?;
+
+ let payment_attempt_domain_model =
+ crate::core::split_payments::create_domain_model_for_split_payment(
+ &payment_intent,
+ cell_id,
+ storage_scheme,
+ request,
+ encrypted_data,
+ split_amount_data.1,
+ attempts_group_id,
+ )
+ .await?;
+
+ let payment_attempt: hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt =
+ db.insert_payment_attempt(
+ key_manager_state,
+ merchant_context.get_merchant_key_store(),
+ payment_attempt_domain_model,
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Could not insert payment attempt")?;
+
+ let payment_method_data =
+ hyperswitch_domain_models::payment_method_data::PaymentMethodData::from(
+ split_amount_data.0,
+ );
+
+ let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new(
+ payment_intent
+ .shipping_address
+ .clone()
+ .map(|address| address.into_inner()),
+ payment_intent
+ .billing_address
+ .clone()
+ .map(|address| address.into_inner()),
+ payment_attempt
+ .payment_method_billing_address
+ .clone()
+ .map(|address| address.into_inner()),
+ Some(true),
+ );
+
+ let merchant_connector_details = request.merchant_connector_details.clone();
+
+ let payment_data = PaymentConfirmData {
+ flow: std::marker::PhantomData,
+ payment_intent,
+ payment_attempt,
+ payment_method_data: Some(payment_method_data),
+ payment_address,
+ mandate_data: None,
+ payment_method: None,
+ merchant_connector_details,
+ external_vault_pmd: None,
+ webhook_url: request
+ .webhook_url
+ .as_ref()
+ .map(|url| url.get_string_repr().to_string()),
+ };
+
+ let get_trackers_response = operations::GetTrackerResponse { payment_data };
+
+ Ok(get_trackers_response)
+ }
}
#[async_trait]
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 0ec25fca0b..c183d02135 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -2730,6 +2730,165 @@ where
}
}
+#[cfg(feature = "v2")]
+impl GenerateResponse<api_models::payments::PaymentsResponse>
+ for crate::core::split_payments::SplitPaymentResponseData
+{
+ fn generate_response(
+ self,
+ state: &SessionState,
+ connector_http_status_code: Option<u16>,
+ external_latency: Option<u128>,
+ is_latency_header_enabled: Option<bool>,
+ merchant_context: &domain::MerchantContext,
+ profile: &domain::Profile,
+ connector_response_data: Option<common_types::domain::ConnectorResponseData>,
+ ) -> RouterResponse<api_models::payments::PaymentsResponse> {
+ let payment_intent = self.primary_payment_response_data.payment_intent.clone();
+ let payment_attempt = self.primary_payment_response_data.payment_attempt.clone();
+
+ let intent_amount_details = &payment_intent.amount_details;
+ let attempt_amount_details = &payment_attempt.amount_details;
+
+ let net_amount = intent_amount_details.calculate_net_amount();
+
+ let amount = api_models::payments::PaymentAmountDetailsResponse {
+ order_amount: intent_amount_details.order_amount,
+ currency: intent_amount_details.currency,
+ shipping_cost: attempt_amount_details.get_shipping_cost(),
+ order_tax_amount: attempt_amount_details.get_order_tax_amount(),
+ external_tax_calculation: intent_amount_details.skip_external_tax_calculation,
+ surcharge_calculation: intent_amount_details.skip_surcharge_calculation,
+ surcharge_amount: attempt_amount_details.get_surcharge_amount(),
+ tax_on_surcharge: attempt_amount_details.get_tax_on_surcharge(),
+ net_amount,
+ amount_to_capture: attempt_amount_details.get_amount_to_capture(),
+ amount_capturable: attempt_amount_details.get_amount_capturable(),
+ amount_captured: Some(net_amount),
+ };
+
+ let connector = payment_attempt
+ .connector
+ .clone()
+ .get_required_value("connector")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Connector is none when constructing response")?;
+
+ let merchant_connector_id = payment_attempt.merchant_connector_id.clone();
+
+ let error = payment_attempt
+ .error
+ .as_ref()
+ .map(api_models::payments::ErrorDetails::foreign_from);
+
+ let payment_address = self.primary_payment_response_data.payment_address;
+
+ let raw_connector_response =
+ connector_response_data.and_then(|data| data.raw_connector_response);
+
+ let payment_method_data =
+ Some(api_models::payments::PaymentMethodDataResponseWithBilling {
+ payment_method_data: None,
+ billing: payment_address
+ .get_request_payment_method_billing()
+ .cloned()
+ .map(From::from),
+ });
+
+ // TODO: Add support for other next actions, currently only supporting redirect to url
+ let redirect_to_url = payment_intent.create_start_redirection_url(
+ &state.base_url,
+ merchant_context
+ .get_merchant_account()
+ .publishable_key
+ .clone(),
+ )?;
+
+ let next_action = if payment_intent.status.is_in_terminal_state() {
+ None
+ } else {
+ let next_action_containing_wait_screen =
+ wait_screen_next_steps_check(payment_attempt.clone())?;
+
+ let next_action_containing_sdk_upi_intent =
+ extract_sdk_uri_information(payment_attempt.clone())?;
+
+ payment_attempt
+ .redirection_data
+ .as_ref()
+ .map(|_| api_models::payments::NextActionData::RedirectToUrl { redirect_to_url })
+ .or(next_action_containing_sdk_upi_intent.map(|sdk_uri_data| {
+ api_models::payments::NextActionData::SdkUpiIntentInformation {
+ sdk_uri: sdk_uri_data.sdk_uri,
+ }
+ }))
+ .or(next_action_containing_wait_screen.map(|wait_screen_data| {
+ api_models::payments::NextActionData::WaitScreenInformation {
+ display_from_timestamp: wait_screen_data.display_from_timestamp,
+ display_to_timestamp: wait_screen_data.display_to_timestamp,
+ poll_config: wait_screen_data.poll_config,
+ }
+ }))
+ };
+
+ let connector_token_details = payment_attempt
+ .connector_token_details
+ .and_then(Option::<api_models::payments::ConnectorTokenDetails>::foreign_from);
+
+ let return_url = payment_intent
+ .return_url
+ .clone()
+ .or(profile.return_url.clone());
+
+ let headers = connector_http_status_code
+ .map(|status_code| {
+ vec![(
+ X_CONNECTOR_HTTP_STATUS_CODE.to_string(),
+ Maskable::new_normal(status_code.to_string()),
+ )]
+ })
+ .unwrap_or_default();
+
+ let response = api_models::payments::PaymentsResponse {
+ id: payment_intent.id.clone(),
+ status: payment_intent.status,
+ amount,
+ customer_id: payment_intent.customer_id.clone(),
+ connector: Some(connector),
+ created: payment_intent.created_at,
+ modified_at: payment_intent.modified_at,
+ payment_method_data,
+ payment_method_type: Some(payment_attempt.payment_method_type),
+ payment_method_subtype: Some(payment_attempt.payment_method_subtype),
+ next_action,
+ connector_transaction_id: payment_attempt.connector_payment_id.clone(),
+ connector_reference_id: payment_attempt.connector_response_reference_id.clone(),
+ connector_token_details,
+ merchant_connector_id,
+ browser_info: None,
+ error,
+ return_url,
+ authentication_type: payment_intent.authentication_type,
+ authentication_type_applied: Some(payment_attempt.authentication_type),
+ payment_method_id: payment_attempt.payment_method_id,
+ attempts: None,
+ billing: None, //TODO: add this
+ shipping: None, //TODO: add this
+ is_iframe_redirection_enabled: None,
+ merchant_reference_id: payment_intent.merchant_reference_id.clone(),
+ raw_connector_response,
+ feature_metadata: payment_intent
+ .feature_metadata
+ .map(|feature_metadata| feature_metadata.convert_back()),
+ metadata: payment_intent.metadata,
+ };
+
+ Ok(services::ApplicationResponse::JsonWithHeaders((
+ response, headers,
+ )))
+ }
+}
+
#[cfg(feature = "v2")]
impl<F> GenerateResponse<api_models::payments::PaymentsResponse>
for hyperswitch_domain_models::payments::PaymentStatusData<F>
diff --git a/crates/router/src/core/split_payments.rs b/crates/router/src/core/split_payments.rs
new file mode 100644
index 0000000000..c14fdf65e7
--- /dev/null
+++ b/crates/router/src/core/split_payments.rs
@@ -0,0 +1,578 @@
+use api_models::{
+ enums,
+ payments::{
+ self as payments_api, GetPaymentMethodType, PaymentMethodData,
+ SplitPaymentMethodDataRequest,
+ },
+};
+use common_enums::CallConnectorAction;
+use common_utils::{
+ ext_traits::{OptionExt, ValueExt},
+ id_type,
+ types::MinorUnit,
+};
+use error_stack::{report, Report, ResultExt};
+use hyperswitch_domain_models::payments::{
+ split_payments, HeaderPayload, PaymentConfirmData, PaymentIntent,
+};
+use masking::ExposeInterface;
+
+use super::errors::StorageErrorExt;
+use crate::{
+ core::{
+ errors::{self, RouterResponse},
+ payment_method_balance,
+ payments::{
+ operations::{self, Operation, PaymentIntentConfirm},
+ payments_operation_core,
+ transformers::GenerateResponse,
+ },
+ },
+ db::errors::RouterResult,
+ routes::{app::ReqState, SessionState},
+ types::{api, domain},
+};
+
+pub(crate) struct SplitPaymentResponseData {
+ pub primary_payment_response_data: PaymentConfirmData<api::Authorize>,
+ pub secondary_payment_response_data: Vec<PaymentConfirmData<api::Authorize>>,
+}
+
+impl SplitPaymentResponseData {
+ fn get_intent_status(&self) -> common_enums::IntentStatus {
+ let primary_status = common_enums::IntentStatus::from(
+ self.primary_payment_response_data.payment_attempt.status,
+ );
+
+ let secondary_status_vec: Vec<common_enums::IntentStatus> = self
+ .secondary_payment_response_data
+ .iter()
+ .map(|elem| common_enums::IntentStatus::from(elem.payment_attempt.status))
+ .collect();
+
+ // If all statuses are the same, return that status
+ let all_same = secondary_status_vec
+ .iter()
+ .all(|status| *status == primary_status);
+
+ if all_same {
+ primary_status
+ } else {
+ // Return the last secondary status if array is not empty, otherwise primary status
+ secondary_status_vec
+ .last()
+ .copied()
+ .unwrap_or(primary_status)
+ }
+ }
+}
+
+/// This function has been written to support multiple gift cards + at most one non-gift card
+/// payment method.
+async fn get_payment_method_amount_split(
+ state: &SessionState,
+ payment_id: &id_type::GlobalPaymentId,
+ request: &payments_api::PaymentsConfirmIntentRequest,
+ payment_intent: &PaymentIntent,
+) -> RouterResult<split_payments::PaymentMethodAmountSplit> {
+ // This function is called inside split payments flow, so its mandatory to have split_payment_method_data
+ let split_payment_method_data = request
+ .split_payment_method_data
+ .clone()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("split_payment_method_data not found in split payments flow")?;
+
+ // The primary/secondary payment method distinction is decided on the backend. Its irrelevant whether a payment_method
+ // is received in the top level `payment_method_data` field or inside `split_payment_method_data`
+ // Add the outer payment_method_data to the PMs inside split_payment_method_data to create a combined Vec and then segregate.
+ let payment_method_data = SplitPaymentMethodDataRequest {
+ payment_method_data: request
+ .payment_method_data
+ .payment_method_data
+ .clone()
+ .ok_or(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "payment_method_data",
+ })?,
+ payment_method_type: request.payment_method_type,
+ payment_method_subtype: request.payment_method_subtype,
+ };
+
+ let combined_pm_data: Vec<_> = split_payment_method_data
+ .into_iter()
+ .chain(std::iter::once(payment_method_data))
+ .collect();
+
+ let (gift_card_pm_data, non_gift_card_pm_data): (Vec<_>, Vec<_>) = combined_pm_data
+ .into_iter()
+ .partition(|pm_data| pm_data.payment_method_type.is_gift_card());
+
+ // Validate at most one non-gift-card payment method
+ if non_gift_card_pm_data.len() > 1 {
+ Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "At most one non-gift card payment method is allowed".to_string(),
+ })?
+ }
+
+ // It is possible that non-gift card payment method is not present, e.g. only 2 gift cards were provided
+ let non_gift_card_pm_data = non_gift_card_pm_data.into_iter().next();
+
+ let gift_card_data_vec = gift_card_pm_data
+ .iter()
+ .map(|elem| {
+ if let PaymentMethodData::GiftCard(gift_card_data) = elem.payment_method_data.clone() {
+ Ok(gift_card_data.as_ref().clone())
+ } else {
+ Err(report!(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Only Gift Card supported for Split Payments".to_string(),
+ }))
+ }
+ })
+ .collect::<RouterResult<Vec<_>>>()?;
+
+ let balance_check_data_vec = gift_card_data_vec
+ .iter()
+ .cloned()
+ .map(api_models::payments::BalanceCheckPaymentMethodData::GiftCard)
+ .collect::<Vec<_>>();
+
+ let balances = payment_method_balance::fetch_payment_methods_balances_from_redis(
+ state,
+ payment_id,
+ &balance_check_data_vec,
+ )
+ .await?;
+
+ // TODO: Add surcharge calculation when it is added in v2
+ let total_amount = payment_intent.amount_details.calculate_net_amount();
+
+ let mut remaining_to_allocate = total_amount;
+ let pm_split_amt_tuple: Vec<(PaymentMethodData, MinorUnit)> = gift_card_data_vec
+ .iter()
+ .filter_map(|gift_card_card| {
+ if remaining_to_allocate == MinorUnit::zero() {
+ return None; // Payment already fully covered
+ }
+
+ let pm_balance_key = domain::PaymentMethodBalanceKey {
+ payment_method_type: common_enums::PaymentMethod::GiftCard,
+ payment_method_subtype: gift_card_card.get_payment_method_type(),
+ payment_method_key: domain::GiftCardData::from(gift_card_card.clone())
+ .get_payment_method_key()
+ .change_context(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Unable to get unique key for payment method".to_string(),
+ })
+ .ok()?
+ .expose(),
+ };
+
+ let pm_balance = balances
+ .get(&pm_balance_key)
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Payment Method Balance not present in Redis")
+ .ok()?;
+
+ // Use minimum of available balance and remaining amount
+ let amount_to_use = pm_balance.balance.min(remaining_to_allocate);
+ remaining_to_allocate = remaining_to_allocate - amount_to_use;
+
+ Some(Ok((
+ PaymentMethodData::GiftCard(Box::new(gift_card_card.to_owned())),
+ amount_to_use,
+ )))
+ })
+ .collect::<RouterResult<Vec<_>>>()?;
+
+ // If the gift card balances are not sufficient for payment, use the non-gift card payment method
+ // for the remaining amount
+ if remaining_to_allocate > MinorUnit::zero() {
+ let non_gift_card_pm_data = non_gift_card_pm_data
+ .ok_or(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Requires additional payment method data".to_string(),
+ })?
+ .payment_method_data;
+
+ Ok(split_payments::PaymentMethodAmountSplit {
+ balance_pm_split: pm_split_amt_tuple,
+ non_balance_pm_split: Some((non_gift_card_pm_data, remaining_to_allocate)),
+ })
+ } else {
+ Ok(split_payments::PaymentMethodAmountSplit {
+ balance_pm_split: pm_split_amt_tuple,
+ non_balance_pm_split: None,
+ })
+ }
+}
+
+pub(crate) async fn split_payments_execute_core(
+ state: SessionState,
+ req_state: ReqState,
+ merchant_context: domain::MerchantContext,
+ profile: domain::Profile,
+ request: payments_api::PaymentsConfirmIntentRequest,
+ header_payload: HeaderPayload,
+ payment_id: id_type::GlobalPaymentId,
+) -> RouterResponse<payments_api::PaymentsResponse> {
+ let db = &*state.store;
+ let key_manager_state = &(&state).into();
+
+ let payment_intent = db
+ .find_payment_intent_by_id(
+ key_manager_state,
+ &payment_id,
+ merchant_context.get_merchant_key_store(),
+ merchant_context.get_merchant_account().storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ if !payment_intent.supports_split_payments() {
+ Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Split Payments not enabled in Payment Intent".to_string(),
+ })?
+ }
+
+ let cell_id = state.conf.cell_information.id.clone();
+
+ let attempts_group_id = id_type::GlobalAttemptGroupId::generate(&cell_id);
+
+ // Change the active_attempt_id_type of PaymentIntent to `GroupID`. This indicates that the customer
+ // has attempted a split payment for this intent
+ let payment_intent_update =
+ hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::AttemptGroupUpdate {
+ updated_by: merchant_context
+ .get_merchant_account()
+ .storage_scheme
+ .to_string(),
+ active_attempt_id_type: enums::ActiveAttemptIDType::GroupID,
+ active_attempts_group_id: attempts_group_id.clone(),
+ };
+
+ let payment_intent = db
+ .update_payment_intent(
+ key_manager_state,
+ payment_intent,
+ payment_intent_update,
+ merchant_context.get_merchant_key_store(),
+ merchant_context.get_merchant_account().storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to update payment intent")?;
+
+ let pm_amount_split =
+ get_payment_method_amount_split(&state, &payment_id, &request, &payment_intent).await?;
+
+ let (
+ primary_pm_response,
+ connector_http_status_code,
+ external_latency,
+ connector_response_data,
+ ) = {
+ // If a non-balance Payment Method is present, we will execute that first, otherwise we will execute
+ // a balance Payment Method
+ let (payment_method_data, amount) = pm_amount_split
+ .non_balance_pm_split
+ .clone()
+ .or_else(|| pm_amount_split.balance_pm_split.first().cloned())
+ .get_required_value("payment method amount split")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("At least one payment method is required")?;
+
+ let operation = PaymentIntentConfirm;
+
+ let get_tracker_response: operations::GetTrackerResponse<
+ PaymentConfirmData<api::Authorize>,
+ > = operation
+ .to_get_tracker()?
+ .get_trackers_for_split_payments(
+ &state,
+ &payment_id,
+ &request,
+ &merchant_context,
+ &profile,
+ &header_payload,
+ (payment_method_data, amount),
+ &attempts_group_id,
+ )
+ .await?;
+
+ let (
+ payment_data,
+ _req,
+ _customer,
+ connector_http_status_code,
+ external_latency,
+ connector_response_data,
+ ) = Box::pin(payments_operation_core(
+ &state,
+ req_state.clone(),
+ merchant_context.clone(),
+ &profile,
+ operation,
+ request.clone(),
+ get_tracker_response,
+ CallConnectorAction::Trigger,
+ header_payload.clone(),
+ ))
+ .await?;
+
+ // payments_operation_core marks the intent as succeeded when the attempt is succesful
+ // However, for split case, we can't mark the intent as succesful until all the attempts
+ // have succeeded, so reverting the state of Payment Intent
+ if payment_data.payment_intent.is_succeeded() {
+ let payment_intent_update =
+ hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::SplitPaymentStatusUpdate {
+ status: common_enums::IntentStatus::RequiresPaymentMethod,
+ updated_by: merchant_context
+ .get_merchant_account()
+ .storage_scheme
+ .to_string(),
+ };
+
+ let updated_payment_intent = db
+ .update_payment_intent(
+ key_manager_state,
+ payment_data.payment_intent.clone(),
+ payment_intent_update,
+ merchant_context.get_merchant_key_store(),
+ merchant_context.get_merchant_account().storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to update payment intent")?;
+ }
+
+ (
+ payment_data,
+ connector_http_status_code,
+ external_latency,
+ connector_response_data,
+ )
+ };
+
+ let mut split_pm_response_data = SplitPaymentResponseData {
+ primary_payment_response_data: primary_pm_response,
+ secondary_payment_response_data: vec![],
+ };
+
+ // We have executed the primary payment method, now get a vector of the secondary payment methods
+ // If we had a non-balance payment method, it was executed first, so the remaining ones are the balance PMs
+ // otherwise the first balance payment method was executed, so remove it from the remaining PMs
+ let remaining_pm_amount_split = if pm_amount_split.non_balance_pm_split.is_some() {
+ pm_amount_split.balance_pm_split
+ } else {
+ pm_amount_split
+ .balance_pm_split
+ .iter()
+ .skip(1)
+ .cloned()
+ .collect()
+ };
+
+ for (payment_method_data, amount) in remaining_pm_amount_split {
+ let operation = PaymentIntentConfirm;
+
+ let get_tracker_response: operations::GetTrackerResponse<
+ PaymentConfirmData<api::Authorize>,
+ > = operation
+ .to_get_tracker()?
+ .get_trackers_for_split_payments(
+ &state,
+ &payment_id,
+ &request,
+ &merchant_context,
+ &profile,
+ &header_payload,
+ (payment_method_data.to_owned(), amount.to_owned()),
+ &attempts_group_id,
+ )
+ .await?;
+
+ let (
+ payment_data,
+ _req,
+ _customer,
+ _connector_http_status_code,
+ _external_latency,
+ _connector_response_data,
+ ) = Box::pin(payments_operation_core(
+ &state,
+ req_state.clone(),
+ merchant_context.clone(),
+ &profile,
+ operation,
+ request.clone(),
+ get_tracker_response,
+ CallConnectorAction::Trigger,
+ header_payload.clone(),
+ ))
+ .await?;
+
+ // payments_operation_core marks the intent as succeeded when the attempt is succesful
+ // However, for split case, we can't mark the intent as succesful until all the attempts
+ // have succeeded, so reverting the state of Payment Intent
+ if payment_data.payment_intent.is_succeeded() {
+ let payment_intent_update =
+ hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::SplitPaymentStatusUpdate {
+ status: common_enums::IntentStatus::RequiresPaymentMethod,
+ updated_by: merchant_context
+ .get_merchant_account()
+ .storage_scheme
+ .to_string(),
+ };
+
+ let _updated_payment_intent = db
+ .update_payment_intent(
+ key_manager_state,
+ payment_data.payment_intent.clone(),
+ payment_intent_update,
+ merchant_context.get_merchant_key_store(),
+ merchant_context.get_merchant_account().storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to update payment intent")?;
+ } else {
+ split_pm_response_data
+ .secondary_payment_response_data
+ .push(payment_data);
+
+ // Exit the loop if a payment failed
+ break;
+ }
+
+ split_pm_response_data
+ .secondary_payment_response_data
+ .push(payment_data);
+ }
+
+ let payment_intent_update =
+ hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::SplitPaymentStatusUpdate {
+ status: split_pm_response_data.get_intent_status(),
+ updated_by: merchant_context
+ .get_merchant_account()
+ .storage_scheme
+ .to_string(),
+ };
+
+ let _updated_payment_intent = db
+ .update_payment_intent(
+ key_manager_state,
+ payment_intent,
+ payment_intent_update,
+ merchant_context.get_merchant_key_store(),
+ merchant_context.get_merchant_account().storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to update payment intent")?;
+
+ split_pm_response_data.generate_response(
+ &state,
+ connector_http_status_code,
+ external_latency,
+ header_payload.x_hs_latency,
+ &merchant_context,
+ &profile,
+ Some(connector_response_data),
+ )
+}
+
+/// Construct the domain model from the ConfirmIntentRequest and PaymentIntent
+#[cfg(feature = "v2")]
+pub async fn create_domain_model_for_split_payment(
+ payment_intent: &PaymentIntent,
+ cell_id: id_type::CellId,
+ storage_scheme: enums::MerchantStorageScheme,
+ request: &api_models::payments::PaymentsConfirmIntentRequest,
+ encrypted_data: hyperswitch_domain_models::payments::payment_attempt::DecryptedPaymentAttempt,
+ split_amount: MinorUnit,
+ attempts_group_id: &id_type::GlobalAttemptGroupId,
+) -> common_utils::errors::CustomResult<domain::PaymentAttempt, errors::ApiErrorResponse> {
+ let id = id_type::GlobalAttemptId::generate(&cell_id);
+ let intent_amount_details = payment_intent.amount_details.clone();
+
+ let attempt_amount_details =
+ intent_amount_details.create_split_attempt_amount_details(request, split_amount);
+
+ let now = common_utils::date_time::now();
+
+ let payment_method_billing_address = encrypted_data
+ .payment_method_billing_address
+ .as_ref()
+ .map(|data| {
+ data.clone()
+ .deserialize_inner_value(|value| value.parse_value("Address"))
+ })
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to decode billing address")?;
+
+ let connector_token = Some(diesel_models::ConnectorTokenDetails {
+ connector_mandate_id: None,
+ connector_token_request_reference_id: Some(common_utils::generate_id_with_len(
+ hyperswitch_domain_models::consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH,
+ )),
+ });
+
+ let authentication_type = payment_intent.authentication_type.unwrap_or_default();
+
+ Ok(domain::PaymentAttempt {
+ payment_id: payment_intent.id.clone(),
+ merchant_id: payment_intent.merchant_id.clone(),
+ attempts_group_id: Some(attempts_group_id.to_owned()),
+ amount_details: attempt_amount_details,
+ status: common_enums::AttemptStatus::Started,
+ // This will be decided by the routing algorithm and updated in update trackers
+ // right before calling the connector
+ connector: None,
+ authentication_type,
+ created_at: now,
+ modified_at: now,
+ last_synced: None,
+ cancellation_reason: None,
+ browser_info: request.browser_info.clone(),
+ payment_token: request.payment_token.clone(),
+ connector_metadata: None,
+ payment_experience: None,
+ payment_method_data: None,
+ routing_result: None,
+ preprocessing_step_id: None,
+ multiple_capture_count: None,
+ connector_response_reference_id: None,
+ updated_by: storage_scheme.to_string(),
+ redirection_data: None,
+ encoded_data: None,
+ merchant_connector_id: None,
+ external_three_ds_authentication_attempted: None,
+ authentication_connector: None,
+ authentication_id: None,
+ fingerprint_id: None,
+ charges: None,
+ client_source: None,
+ client_version: None,
+ customer_acceptance: request
+ .customer_acceptance
+ .clone()
+ .map(masking::Secret::new),
+ profile_id: payment_intent.profile_id.clone(),
+ organization_id: payment_intent.organization_id.clone(),
+ payment_method_type: request.payment_method_type,
+ payment_method_id: request.payment_method_id.clone(),
+ connector_payment_id: None,
+ payment_method_subtype: request.payment_method_subtype,
+ authentication_applied: None,
+ external_reference_id: None,
+ payment_method_billing_address,
+ error: None,
+ connector_token_details: connector_token,
+ id,
+ card_discovery: None,
+ feature_metadata: None,
+ processor_merchant_id: payment_intent.merchant_id.clone(),
+ created_by: None,
+ connector_request_reference_id: None,
+ network_transaction_id: None,
+ authorized_amount: None,
+ })
+}
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index 641b3de015..b7410a04ad 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -3172,28 +3172,18 @@ pub async fn payment_confirm_intent(
let payment_id = req.global_payment_id;
let request = req.payload;
- let operation = payments::operations::PaymentIntentConfirm;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
- Box::pin(payments::payments_core::<
- api_types::Authorize,
- api_models::payments::PaymentsResponse,
- _,
- _,
- _,
- PaymentConfirmData<api_types::Authorize>,
- >(
+ Box::pin(payments::payments_execute_wrapper(
state,
req_state,
merchant_context,
auth.profile,
- operation,
request,
- payment_id,
- payments::CallConnectorAction::Trigger,
header_payload.clone(),
+ payment_id,
))
.await
},
diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rs
index 6f5257827a..172cc7bb1b 100644
--- a/crates/router/src/services/kafka/payment_attempt.rs
+++ b/crates/router/src/services/kafka/payment_attempt.rs
@@ -153,7 +153,7 @@ pub struct KafkaPaymentAttempt<'a> {
pub payment_id: &'a id_type::GlobalPaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub attempt_id: &'a id_type::GlobalAttemptId,
- pub attempts_group_id: Option<&'a String>,
+ pub attempts_group_id: Option<&'a id_type::GlobalAttemptGroupId>,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
pub connector: Option<&'a String>,
diff --git a/crates/router/src/services/kafka/payment_attempt_event.rs b/crates/router/src/services/kafka/payment_attempt_event.rs
index ed0c6177c4..c002ee9ce2 100644
--- a/crates/router/src/services/kafka/payment_attempt_event.rs
+++ b/crates/router/src/services/kafka/payment_attempt_event.rs
@@ -155,7 +155,7 @@ pub struct KafkaPaymentAttemptEvent<'a> {
pub payment_id: &'a id_type::GlobalPaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub attempt_id: &'a id_type::GlobalAttemptId,
- pub attempts_group_id: Option<&'a String>,
+ pub attempts_group_id: Option<&'a id_type::GlobalAttemptGroupId>,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
pub connector: Option<&'a String>,
diff --git a/crates/router/src/services/kafka/payment_intent.rs b/crates/router/src/services/kafka/payment_intent.rs
index 9af64625c4..726bc5470a 100644
--- a/crates/router/src/services/kafka/payment_intent.rs
+++ b/crates/router/src/services/kafka/payment_intent.rs
@@ -132,7 +132,7 @@ pub struct KafkaPaymentIntent<'a> {
pub off_session: bool,
pub active_attempt_id: Option<&'a id_type::GlobalAttemptId>,
pub active_attempt_id_type: common_enums::ActiveAttemptIDType,
- pub active_attempts_group_id: Option<&'a String>,
+ pub active_attempts_group_id: Option<&'a id_type::GlobalAttemptGroupId>,
pub attempt_count: i16,
pub profile_id: &'a id_type::ProfileId,
pub customer_email: Option<HashedString<pii::EmailStrategy>>,
diff --git a/crates/router/src/services/kafka/payment_intent_event.rs b/crates/router/src/services/kafka/payment_intent_event.rs
index ef1989a116..0e550504d5 100644
--- a/crates/router/src/services/kafka/payment_intent_event.rs
+++ b/crates/router/src/services/kafka/payment_intent_event.rs
@@ -87,7 +87,7 @@ pub struct KafkaPaymentIntentEvent<'a> {
pub off_session: bool,
pub active_attempt_id: Option<&'a id_type::GlobalAttemptId>,
pub active_attempt_id_type: common_enums::ActiveAttemptIDType,
- pub active_attempts_group_id: Option<&'a String>,
+ pub active_attempts_group_id: Option<&'a id_type::GlobalAttemptGroupId>,
pub attempt_count: i16,
pub profile_id: &'a id_type::ProfileId,
pub customer_email: Option<HashedString<pii::EmailStrategy>>,