Skip to content

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

refactor: introduce balance check core support (#10896)

Hrithikesh1ecacfdb1346
diff --git a/config/development.toml b/config/development.toml
index ff0966ebb8..02d6670b29 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -41,6 +41,7 @@ connection_timeout = 10
[preprocessing_flow_config]
authentication_bloated_connectors = "paypal,nmi,cybersource,barclaycard,shift4"
order_create_bloated_connectors = "trustpay,payme"
+balance_check_bloated_connectors = "adyen"
settlement_split_bloated_connectors = "xendit"
[redis]
diff --git a/crates/hyperswitch_connectors/src/connectors/adyen.rs b/crates/hyperswitch_connectors/src/connectors/adyen.rs
index 059c3de445..e2b84dcb4f 100644
--- a/crates/hyperswitch_connectors/src/connectors/adyen.rs
+++ b/crates/hyperswitch_connectors/src/connectors/adyen.rs
@@ -16,7 +16,7 @@ use common_utils::{
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
api::ApplicationResponse,
- payment_method_data::PaymentMethodData,
+ payment_method_data,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
@@ -373,7 +373,7 @@ impl ConnectorValidation for Adyen {
fn validate_mandate_payment(
&self,
pm_type: Option<PaymentMethodType>,
- pm_data: PaymentMethodData,
+ pm_data: payment_method_data::PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::Card,
@@ -3331,6 +3331,19 @@ static ADYEN_SUPPORTED_WEBHOOK_FLOWS: &[enums::EventClass] = &[
];
impl ConnectorSpecifications for Adyen {
+ fn is_balance_check_flow_required(&self, current_flow: api::CurrentFlowInfo<'_>) -> bool {
+ match current_flow {
+ api::CurrentFlowInfo::Authorize { request_data, .. } => {
+ matches!(&request_data.payment_method_data, payment_method_data::PaymentMethodData::GiftCard(giftcard_data) if giftcard_data.is_givex())
+ }
+ api::CurrentFlowInfo::SetupMandate { request_data, .. } => {
+ matches!(&request_data.payment_method_data, payment_method_data::PaymentMethodData::GiftCard(giftcard_data) if giftcard_data.is_givex())
+ }
+ api::CurrentFlowInfo::CompleteAuthorize { request_data, .. } => {
+ matches!(&request_data.payment_method_data, Some(payment_method_data::PaymentMethodData::GiftCard(giftcard_data)) if giftcard_data.is_givex())
+ }
+ }
+ }
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&ADYEN_CONNECTOR_INFO)
}
diff --git a/crates/hyperswitch_connectors/src/connectors/nmi.rs b/crates/hyperswitch_connectors/src/connectors/nmi.rs
index 5727f97821..9481114303 100644
--- a/crates/hyperswitch_connectors/src/connectors/nmi.rs
+++ b/crates/hyperswitch_connectors/src/connectors/nmi.rs
@@ -1192,7 +1192,7 @@ impl ConnectorSpecifications for Nmi {
auth_type,
} => *auth_type == enums::AuthenticationType::ThreeDs,
api::CurrentFlowInfo::CompleteAuthorize { .. } => false,
- api::CurrentFlowInfo::SetupMandate { auth_type } => {
+ api::CurrentFlowInfo::SetupMandate { auth_type, .. } => {
*auth_type == enums::AuthenticationType::ThreeDs
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei.rs b/crates/hyperswitch_connectors/src/connectors/nuvei.rs
index 9b50a9e43e..398c1a088a 100644
--- a/crates/hyperswitch_connectors/src/connectors/nuvei.rs
+++ b/crates/hyperswitch_connectors/src/connectors/nuvei.rs
@@ -1676,7 +1676,7 @@ impl ConnectorSpecifications for Nuvei {
request_data: _,
} => *auth_type == enums::AuthenticationType::ThreeDs,
api::CurrentFlowInfo::CompleteAuthorize { .. } => false,
- api::CurrentFlowInfo::SetupMandate { auth_type } => {
+ api::CurrentFlowInfo::SetupMandate { auth_type, .. } => {
*auth_type == enums::AuthenticationType::ThreeDs
}
}
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index cc31976eb9..8f5603b611 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -944,6 +944,9 @@ pub enum GiftCardData {
}
impl GiftCardData {
+ pub fn is_givex(&self) -> bool {
+ matches!(self, Self::Givex(_))
+ }
/// Returns a key that uniquely identifies the gift card. Used in
/// Payment Method Balance Check Flow for storing the balance
/// data in Redis.
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index 5599495e63..73f8ed8cc1 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -643,6 +643,44 @@ pub struct GiftCardBalanceCheckRequestData {
pub minor_amount: Option<MinorUnit>,
}
+impl TryFrom<SetupMandateRequestData> for GiftCardBalanceCheckRequestData {
+ type Error = error_stack::Report<ApiErrorResponse>;
+ fn try_from(data: SetupMandateRequestData) -> Result<Self, Self::Error> {
+ Ok(Self {
+ payment_method_data: data.payment_method_data,
+ currency: Some(data.currency),
+ minor_amount: Some(data.minor_amount),
+ })
+ }
+}
+
+impl TryFrom<CompleteAuthorizeData> for GiftCardBalanceCheckRequestData {
+ type Error = error_stack::Report<ApiErrorResponse>;
+ fn try_from(data: CompleteAuthorizeData) -> Result<Self, Self::Error> {
+ Ok(Self {
+ payment_method_data: data
+ .payment_method_data
+ .get_required_value("payment_method_data")
+ .change_context(ApiErrorResponse::MissingRequiredField {
+ field_name: "payment_method_data",
+ })?,
+ currency: Some(data.currency),
+ minor_amount: Some(data.minor_amount),
+ })
+ }
+}
+
+impl TryFrom<PaymentsAuthorizeData> for GiftCardBalanceCheckRequestData {
+ type Error = error_stack::Report<ApiErrorResponse>;
+ fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> {
+ Ok(Self {
+ payment_method_data: data.payment_method_data,
+ currency: Some(data.currency),
+ minor_amount: Some(data.minor_amount),
+ })
+ }
+}
+
impl TryFrom<PaymentsAuthorizeData> for PaymentsPreProcessingData {
type Error = error_stack::Report<ApiErrorResponse>;
diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs
index 9ec1a83bee..b74c9ae0f3 100644
--- a/crates/hyperswitch_interfaces/src/api.rs
+++ b/crates/hyperswitch_interfaces/src/api.rs
@@ -406,11 +406,12 @@ pub enum CurrentFlowInfo<'a> {
/// The payment method that is used
payment_method: Option<PaymentMethod>,
},
-
/// SetupMandate flow information
SetupMandate {
/// The authentication type being used
auth_type: &'a enums::AuthenticationType,
+ /// The payment setup mandate request data
+ request_data: &'a router_request_types::SetupMandateRequestData,
},
}
@@ -445,6 +446,10 @@ pub struct PreProcessingFlowResponse<'a> {
/// The trait that provides specifications about the connector
pub trait ConnectorSpecifications {
+ /// Check if pre-authentication flow is required
+ fn is_balance_check_flow_required(&self, _current_flow: CurrentFlowInfo<'_>) -> bool {
+ false
+ }
/// Check if pre-authentication flow is required
fn is_order_create_flow_required(&self, _current_flow: CurrentFlowInfo<'_>) -> bool {
false
diff --git a/crates/hyperswitch_interfaces/src/connector_integration_interface.rs b/crates/hyperswitch_interfaces/src/connector_integration_interface.rs
index 5a14e7c800..2ce59f2946 100644
--- a/crates/hyperswitch_interfaces/src/connector_integration_interface.rs
+++ b/crates/hyperswitch_interfaces/src/connector_integration_interface.rs
@@ -532,6 +532,12 @@ impl ConnectorValidation for ConnectorEnum {
}
impl ConnectorSpecifications for ConnectorEnum {
+ fn is_balance_check_flow_required(&self, current_flow: api::CurrentFlowInfo<'_>) -> bool {
+ match self {
+ Self::Old(connector) => connector.is_balance_check_flow_required(current_flow),
+ Self::New(connector) => connector.is_balance_check_flow_required(current_flow),
+ }
+ }
fn is_order_create_flow_required(&self, current_flow: api::CurrentFlowInfo<'_>) -> bool {
match self {
Self::Old(connector) => connector.is_order_create_flow_required(current_flow),
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 21088e7f77..c544d0dccd 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -201,6 +201,8 @@ pub struct PreProcessingFlowConfig {
#[serde(default, deserialize_with = "deserialize_hashset")]
pub order_create_bloated_connectors: HashSet<enums::Connector>,
#[serde(default, deserialize_with = "deserialize_hashset")]
+ pub balance_check_bloated_connectors: HashSet<enums::Connector>,
+ #[serde(default, deserialize_with = "deserialize_hashset")]
pub settlement_split_bloated_connectors: HashSet<enums::Connector>,
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index bfc41b7872..de7784a527 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -4109,6 +4109,20 @@ where
&call_connector_action,
);
+ // Balance check flow for payment methods like Giftcard, Voucher etc.
+ let should_continue_further = if should_continue_further {
+ let balance_check_response = router_data
+ .balance_check_flow(state, &connector, &context)
+ .await?;
+ match balance_check_response.balance_check_result {
+ Ok(balance_check_result) => router_data.payment_method_balance = balance_check_result,
+ Err(err) => router_data.response = Err(err),
+ }
+ balance_check_response.should_continue_payment
+ } else {
+ should_continue_further
+ };
+
let should_continue_further = match router_data
.create_order_at_connector(state, &connector, should_continue_further, &context)
.await?
@@ -4253,6 +4267,25 @@ where
connector.connector_name
);
(router_data, should_continue_further)
+ } else if state
+ .conf
+ .preprocessing_flow_config
+ .as_ref()
+ .is_some_and(|config| {
+ // If balance check flow is bloated up for the current connector
+ // balance check call would have already happened in the previous step.
+ config
+ .balance_check_bloated_connectors
+ .contains(&connector.connector_name)
+ })
+ {
+ // If payment method tokenization flow is enabled for the current connector
+ // Skip calling complete_preprocessing_steps_if_required function
+ logger::info!(
+ "skipping preprocessing steps for connector as balance check is enabled: {}",
+ connector.connector_name
+ );
+ (router_data, should_continue_further)
} else if state
.conf
.preprocessing_flow_config
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index 712f35f6a7..a9ff9e668b 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -99,6 +99,26 @@ pub trait Feature<F, T> {
F: Clone,
dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>;
+ /// In case of payment methods like gifcard, some connectors might support balance check API
+ /// This function can be overridden in those specific connectors to implement balance check flow
+ /// Authorize must be called only if balance is sufficient
+ async fn balance_check_flow<'a>(
+ &self,
+ _state: &SessionState,
+ _connector: &api::ConnectorData,
+ _gateway_context: &gateway_context::RouterGatewayContext,
+ ) -> RouterResult<types::BalanceCheckResult>
+ where
+ F: Clone,
+ Self: Sized,
+ dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>,
+ {
+ Ok(types::BalanceCheckResult {
+ balance_check_result: Ok(None),
+ should_continue_payment: true,
+ })
+ }
+
async fn add_access_token<'a>(
&self,
state: &SessionState,
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index 86e9beac4f..71cc9494ef 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -8,16 +8,18 @@ use common_utils::types::MinorUnit;
use common_utils::{errors, ext_traits::ValueExt, id_type, ucs_types};
use error_stack::ResultExt;
use external_services::grpc_client;
+use hyperswitch_connectors::constants as connector_consts;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payments::PaymentConfirmData;
use hyperswitch_domain_models::{
- errors::api_error_response::ApiErrorResponse, payments as domain_payments,
- router_data_v2::PaymentFlowData, router_flow_types, router_request_types,
- router_response_types,
+ errors::api_error_response::ApiErrorResponse,
+ payments as domain_payments, router_data,
+ router_data_v2::{flow_common_types, PaymentFlowData},
+ router_flow_types, router_request_types, router_response_types,
};
use hyperswitch_interfaces::{
api::{self as api_interface, gateway, ConnectorSpecifications},
- errors as interface_errors,
+ consts as interface_consts, errors as interface_errors,
unified_connector_service::transformers as ucs_transformers,
};
use masking::ExposeInterface;
@@ -266,6 +268,126 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
}
}
+ async fn balance_check_flow<'a>(
+ &self,
+ state: &SessionState,
+ connector: &api::ConnectorData,
+ _gateway_context: &gateway_context::RouterGatewayContext,
+ ) -> RouterResult<types::BalanceCheckResult> {
+ if connector.connector.is_balance_check_flow_required(
+ api_interface::CurrentFlowInfo::Authorize {
+ auth_type: &self.auth_type,
+ request_data: &self.request,
+ },
+ ) && state
+ .conf
+ .preprocessing_flow_config
+ .as_ref()
+ .is_some_and(|config| {
+ // check balance check flow is bloated up for the current connector
+ config
+ .balance_check_bloated_connectors
+ .contains(&connector.connector_name)
+ })
+ {
+ logger::info!(
+ "Balance check flow is required for connector: {}",
+ connector.connector_name
+ );
+ let balance_check_request_data =
+ router_request_types::GiftCardBalanceCheckRequestData::try_from(
+ self.request.to_owned(),
+ )?;
+ let balance_check_response_data: Result<
+ router_response_types::GiftCardBalanceCheckResponseData,
+ types::ErrorResponse,
+ > = Err(types::ErrorResponse::default());
+ let balance_check_router_data = helpers::router_data_type_conversion::<
+ _,
+ router_flow_types::GiftCardBalanceCheck,
+ _,
+ _,
+ _,
+ _,
+ >(
+ self.clone(),
+ balance_check_request_data,
+ balance_check_response_data,
+ );
+
+ let connector_integration: services::connector_integration_interface::BoxedConnectorIntegrationInterface<
+ router_flow_types::GiftCardBalanceCheck,
+ flow_common_types::GiftCardBalanceCheckFlowData,
+ router_request_types::GiftCardBalanceCheckRequestData,
+ router_response_types::GiftCardBalanceCheckResponseData,
+ > = connector.connector.get_connector_integration();
+
+ let response_router_data = services::execute_connector_processing_step(
+ state,
+ connector_integration,
+ &balance_check_router_data,
+ payments::CallConnectorAction::Trigger,
+ None,
+ None,
+ )
+ .await
+ .to_payment_failed_response()?;
+
+ let balance_check_result = match &response_router_data.response {
+ Ok(router_response_types::GiftCardBalanceCheckResponseData {
+ balance,
+ currency,
+ }) => {
+ logger::info!(
+ "Requested amount and currency: {}, {}",
+ self.request.minor_amount,
+ self.request.currency
+ );
+ logger::info!(
+ "Balance amount and currency recieved from connector : {}, {}",
+ balance,
+ currency
+ );
+ if *balance >= self.request.minor_amount {
+ Ok(Some(router_data::PaymentMethodBalance {
+ amount: *balance,
+ currency: *currency,
+ }))
+ } else {
+ // If balance is insufficient, return a connector error response
+ // At this point, connector would have returned a success response with balance details
+ Err(router_data::ErrorResponse {
+ code: interface_consts::NO_ERROR_CODE.to_string(),
+ message: interface_consts::NO_ERROR_MESSAGE.to_string(),
+ reason: Some(connector_consts::LOW_BALANCE_ERROR_MESSAGE.to_string()),
+ status_code: response_router_data
+ .connector_http_status_code
+ .unwrap_or(200),
+ attempt_status: Some(enums::AttemptStatus::Failure),
+ connector_transaction_id: None,
+ connector_response_reference_id: None,
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ })
+ }
+ }
+ Err(err) => Err(err.clone()),
+ };
+ Ok(types::BalanceCheckResult {
+ // Continue with the payment only if ok response is recieved from balance check
+ should_continue_payment: balance_check_result.is_ok(),
+ balance_check_result,
+ })
+ } else {
+ Ok(types::BalanceCheckResult {
+ balance_check_result: Ok(None),
+ should_continue_payment: true,
+ })
+ }
+ }
+
async fn add_access_token<'a>(
&self,
state: &SessionState,
diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rs
index e5fa7aa729..a0f7d50361 100644
--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs
@@ -5,13 +5,16 @@ use common_enums::connector_enums;
use common_utils::{errors, id_type, ucs_types};
use error_stack::ResultExt;
use external_services::grpc_client;
+use hyperswitch_connectors::constants as connector_consts;
use hyperswitch_domain_models::{
- router_data_v2::PaymentFlowData, router_request_types, router_response_types,
+ router_data,
+ router_data_v2::{flow_common_types, PaymentFlowData},
+ router_flow_types, router_request_types, router_response_types,
};
use hyperswitch_interfaces::{
api as api_interface,
api::{gateway, ConnectorSpecifications},
- errors as interface_errors,
+ consts as interface_consts, errors as interface_errors,
unified_connector_service::transformers as ucs_transformers,
};
use masking::{self, ExposeInterface};
@@ -164,6 +167,126 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>
}
}
+ async fn balance_check_flow<'a>(
+ &self,
+ state: &SessionState,
+ connector: &api::ConnectorData,
+ _gateway_context: &gateway_context::RouterGatewayContext,
+ ) -> RouterResult<types::BalanceCheckResult> {
+ if connector.connector.is_balance_check_flow_required(
+ api_interface::CurrentFlowInfo::CompleteAuthorize {
+ payment_method: Some(self.payment_method),
+ request_data: &self.request,
+ },
+ ) && state
+ .conf
+ .preprocessing_flow_config
+ .as_ref()
+ .is_some_and(|config| {
+ // check balance check flow is bloated up for the current connector
+ config
+ .balance_check_bloated_connectors
+ .contains(&connector.connector_name)
+ })
+ {
+ logger::info!(
+ "Balance check flow is required for connector: {}",
+ connector.connector_name
+ );
+ let balance_check_request_data =
+ router_request_types::GiftCardBalanceCheckRequestData::try_from(
+ self.request.to_owned(),
+ )?;
+ let balance_check_response_data: Result<
+ router_response_types::GiftCardBalanceCheckResponseData,
+ types::ErrorResponse,
+ > = Err(types::ErrorResponse::default());
+ let balance_check_router_data = helpers::router_data_type_conversion::<
+ _,
+ router_flow_types::GiftCardBalanceCheck,
+ _,
+ _,
+ _,
+ _,
+ >(
+ self.clone(),
+ balance_check_request_data,
+ balance_check_response_data,
+ );
+
+ let connector_integration: services::connector_integration_interface::BoxedConnectorIntegrationInterface<
+ router_flow_types::GiftCardBalanceCheck,
+ flow_common_types::GiftCardBalanceCheckFlowData,
+ router_request_types::GiftCardBalanceCheckRequestData,
+ router_response_types::GiftCardBalanceCheckResponseData,
+ > = connector.connector.get_connector_integration();
+
+ let response_router_data = services::execute_connector_processing_step(
+ state,
+ connector_integration,
+ &balance_check_router_data,
+ payments::CallConnectorAction::Trigger,
+ None,
+ None,
+ )
+ .await
+ .to_payment_failed_response()?;
+
+ let balance_check_result = match &response_router_data.response {
+ Ok(router_response_types::GiftCardBalanceCheckResponseData {
+ balance,
+ currency,
+ }) => {
+ logger::info!(
+ "Requested amount and currency: {}, {}",
+ self.request.minor_amount,
+ self.request.currency
+ );
+ logger::info!(
+ "Balance amount and currency recieved from connector : {}, {}",
+ balance,
+ currency
+ );
+ if *balance >= self.request.minor_amount {
+ Ok(Some(router_data::PaymentMethodBalance {
+ amount: *balance,
+ currency: *currency,
+ }))
+ } else {
+ // If balance is insufficient, return a connector error response
+ // At this point, connector would have returned a success response with balance details
+ Err(router_data::ErrorResponse {
+ code: interface_consts::NO_ERROR_CODE.to_string(),
+ message: interface_consts::NO_ERROR_MESSAGE.to_string(),
+ reason: Some(connector_consts::LOW_BALANCE_ERROR_MESSAGE.to_string()),
+ status_code: response_router_data
+ .connector_http_status_code
+ .unwrap_or(200),
+ attempt_status: Some(common_enums::AttemptStatus::Failure),
+ connector_transaction_id: None,
+ connector_response_reference_id: None,
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ })
+ }
+ }
+ Err(err) => Err(err.clone()),
+ };
+ Ok(types::BalanceCheckResult {
+ // Continue with the payment only if ok response is recieved from balance check
+ should_continue_payment: balance_check_result.is_ok(),
+ balance_check_result,
+ })
+ } else {
+ Ok(types::BalanceCheckResult {
+ balance_check_result: Ok(None),
+ should_continue_payment: true,
+ })
+ }
+ }
+
async fn add_access_token<'a>(
&self,
state: &SessionState,
diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
index 45d6fbed07..9d6a8d3438 100644
--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs
+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
@@ -1,8 +1,16 @@
use async_trait::async_trait;
use common_enums;
use common_types::payments as common_payments_types;
-use hyperswitch_domain_models::{payments as domain_payments, router_data_v2::PaymentFlowData};
-use hyperswitch_interfaces::api::{self as api_interface, gateway, ConnectorSpecifications};
+use hyperswitch_connectors::constants as connector_consts;
+use hyperswitch_domain_models::{
+ payments as domain_payments, router_data,
+ router_data_v2::{flow_common_types, PaymentFlowData},
+ router_flow_types, router_request_types, router_response_types,
+};
+use hyperswitch_interfaces::{
+ api::{self as api_interface, gateway, ConnectorSpecifications},
+ consts as interface_consts,
+};
use router_env::logger;
use super::{ConstructFlowSpecificData, Feature};
@@ -143,6 +151,126 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup
Ok(resp)
}
+ async fn balance_check_flow<'a>(
+ &self,
+ state: &SessionState,
+ connector: &api::ConnectorData,
+ _gateway_context: &gateway_context::RouterGatewayContext,
+ ) -> RouterResult<types::BalanceCheckResult> {
+ if connector.connector.is_balance_check_flow_required(
+ api_interface::CurrentFlowInfo::SetupMandate {
+ auth_type: &self.auth_type,
+ request_data: &self.request,
+ },
+ ) && state
+ .conf
+ .preprocessing_flow_config
+ .as_ref()
+ .is_some_and(|config| {
+ // check balance check flow is bloated up for the current connector
+ config
+ .balance_check_bloated_connectors
+ .contains(&connector.connector_name)
+ })
+ {
+ logger::info!(
+ "Balance check flow is required for connector: {}",
+ connector.connector_name
+ );
+ let balance_check_request_data =
+ router_request_types::GiftCardBalanceCheckRequestData::try_from(
+ self.request.to_owned(),
+ )?;
+ let balance_check_response_data: Result<
+ router_response_types::GiftCardBalanceCheckResponseData,
+ types::ErrorResponse,
+ > = Err(types::ErrorResponse::default());
+ let balance_check_router_data = helpers::router_data_type_conversion::<
+ _,
+ router_flow_types::GiftCardBalanceCheck,
+ _,
+ _,
+ _,
+ _,
+ >(
+ self.clone(),
+ balance_check_request_data,
+ balance_check_response_data,
+ );
+
+ let connector_integration: services::connector_integration_interface::BoxedConnectorIntegrationInterface<
+ router_flow_types::GiftCardBalanceCheck,
+ flow_common_types::GiftCardBalanceCheckFlowData,
+ router_request_types::GiftCardBalanceCheckRequestData,
+ router_response_types::GiftCardBalanceCheckResponseData,
+ > = connector.connector.get_connector_integration();
+
+ let response_router_data = services::execute_connector_processing_step(
+ state,
+ connector_integration,
+ &balance_check_router_data,
+ payments::CallConnectorAction::Trigger,
+ None,
+ None,
+ )
+ .await
+ .to_payment_failed_response()?;
+
+ let balance_check_result = match &response_router_data.response {
+ Ok(router_response_types::GiftCardBalanceCheckResponseData {
+ balance,
+ currency,
+ }) => {
+ logger::info!(
+ "Requested amount and currency: {}, {}",
+ self.request.minor_amount,
+ self.request.currency
+ );
+ logger::info!(
+ "Balance amount and currency recieved from connector : {}, {}",
+ balance,
+ currency
+ );
+ if *balance >= self.request.minor_amount {
+ Ok(Some(router_data::PaymentMethodBalance {
+ amount: *balance,
+ currency: *currency,
+ }))
+ } else {
+ // If balance is insufficient, return a connector error response
+ // At this point, connector would have returned a success response with balance details
+ Err(router_data::ErrorResponse {
+ code: interface_consts::NO_ERROR_CODE.to_string(),
+ message: interface_consts::NO_ERROR_MESSAGE.to_string(),
+ reason: Some(connector_consts::LOW_BALANCE_ERROR_MESSAGE.to_string()),
+ status_code: response_router_data
+ .connector_http_status_code
+ .unwrap_or(200),
+ attempt_status: Some(common_enums::AttemptStatus::Failure),
+ connector_transaction_id: None,
+ connector_response_reference_id: None,
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ })
+ }
+ }
+ Err(err) => Err(err.clone()),
+ };
+ Ok(types::BalanceCheckResult {
+ // Continue with the payment only if ok response is recieved from balance check
+ should_continue_payment: balance_check_result.is_ok(),
+ balance_check_result,
+ })
+ } else {
+ Ok(types::BalanceCheckResult {
+ balance_check_result: Ok(None),
+ should_continue_payment: true,
+ })
+ }
+ }
+
async fn add_access_token<'a>(
&self,
state: &SessionState,
@@ -220,6 +348,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup
if connector.connector.is_pre_authentication_flow_required(
api_interface::CurrentFlowInfo::SetupMandate {
auth_type: &self.auth_type,
+ request_data: &self.request,
},
) {
logger::info!(
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 5499313e30..e835d98b4a 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -719,6 +719,11 @@ pub struct PaymentMethodTokenResult {
pub connector_response: Option<ConnectorResponseData>,
}
+pub struct BalanceCheckResult {
+ pub balance_check_result: Result<Option<PaymentMethodBalance>, ErrorResponse>,
+ pub should_continue_payment: bool,
+}
+
#[derive(Clone)]
pub struct CreateOrderResult {
pub create_order_result: Result<String, ErrorResponse>,