Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(router): Combine payment method check-balance and apply endpoints (v2) (#10197)
Anurag Thakurd8abf356b01c
diff --git a/api-reference/docs.json b/api-reference/docs.jsonindex 30a42c7db1..4596a4fff3 100644--- a/api-reference/docs.json+++ b/api-reference/docs.json@@ -308,8 +308,7 @@"v2/payments/payments--get","v2/payments/payments--create-and-confirm-intent","v2/payments/payments--list",- "v2/payments/payments--gift-card-balance-check",- "v2/payments/payments--apply-pm-data"+ "v2/payments/payments--check-balance-and-apply-pm-data"]},{diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex bbc16782a7..3e2b4c4884 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -2593,71 +2593,13 @@]}},- "/v2/payments/{id}/payment-methods/check-balance": {+ "/v2/payments/{id}/eligibility/check-balance-and-apply-pm-data": {"post": {"tags": ["Payments"],- "summary": "Payments - Payment Method Balance Check",- "description": "Check the balance of the provided payment method. Also validates whether the PM currency matches the payment currency",- "operationId": "Retrieve Payment Method Balance",- "parameters": [- {- "name": "id",- "in": "path",- "description": "The global payment id",- "required": true,- "schema": {- "type": "string"- }- },- {- "name": "X-Profile-Id",- "in": "header",- "description": "Profile ID associated to the payment intent",- "required": true,- "schema": {- "type": "string"- },- "example": "pro_abcdefghijklmnop"- }- ],- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/PaymentMethodBalanceCheckRequest"- }- }- },- "required": true- },- "responses": {- "200": {- "description": "Get the Payment Method Balance",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/PaymentMethodBalanceCheckResponse"- }- }- }- }- },- "security": [- {- "publishable_key": []- }- ]- }- },- "/v2/payments/{id}/apply-payment-method-data": {- "post": {- "tags": [- "Payments"- ],- "summary": "Payments - Apply PM Data",- "description": "Apply the payment method data and recalculate surcharge",+ "summary": "Payments - Check Balance and Apply PM Data",+ "description": "Check the balance of the payment methods, apply the payment method data and recalculate remaining_amount and surcharge","operationId": "Apply Payment Method Data","parameters": [{@@ -2696,7 +2638,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/ApplyPaymentMethodDataResponse"+ "$ref": "#/components/schemas/CheckAndApplyPaymentMethodDataResponse"}}}@@ -5353,32 +5295,6 @@}}},- "ApplyPaymentMethodDataResponse": {- "type": "object",- "required": [- "remaining_amount",- "currency",- "requires_additional_pm_data"- ],- "properties": {- "remaining_amount": {- "$ref": "#/components/schemas/MinorUnit"- },- "currency": {- "$ref": "#/components/schemas/Currency"- },- "requires_additional_pm_data": {- "type": "boolean"- },- "surcharge_details": {- "type": "array",- "items": {- "$ref": "#/components/schemas/ApplyPaymentMethodDataSurchargeResponseItem"- },- "nullable": true- }- }- },"ApplyPaymentMethodDataSurchargeResponseItem": {"type": "object","required": [@@ -8823,6 +8739,40 @@}}},+ "CheckAndApplyPaymentMethodDataResponse": {+ "type": "object",+ "required": [+ "balances",+ "remaining_amount",+ "currency",+ "requires_additional_pm_data"+ ],+ "properties": {+ "balances": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/EligibilityBalanceCheckResponseItem"+ }+ },+ "remaining_amount": {+ "$ref": "#/components/schemas/MinorUnit"+ },+ "currency": {+ "$ref": "#/components/schemas/Currency"+ },+ "requires_additional_pm_data": {+ "type": "boolean",+ "description": "Whether the applied payment method balance is enough for the order amount or additional PM is required"+ },+ "surcharge_details": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ApplyPaymentMethodDataSurchargeResponseItem"+ },+ "nullable": true+ }+ }+ },"ClickToPaySessionResponse": {"type": "object","required": [@@ -11319,6 +11269,21 @@}]},+ "EligibilityBalanceCheckResponseItem": {+ "type": "object",+ "required": [+ "payment_method_data",+ "eligibility"+ ],+ "properties": {+ "payment_method_data": {+ "$ref": "#/components/schemas/BalanceCheckPaymentMethodData"+ },+ "eligibility": {+ "$ref": "#/components/schemas/PMBalanceCheckEligibilityResponse"+ }+ }+ },"EliminationAnalyserConfig": {"type": "object","properties": {@@ -16788,6 +16753,62 @@}}},+ "PMBalanceCheckEligibilityResponse": {+ "oneOf": [+ {+ "type": "object",+ "required": [+ "success"+ ],+ "properties": {+ "success": {+ "$ref": "#/components/schemas/PMBalanceCheckSuccessResponse"+ }+ }+ },+ {+ "type": "object",+ "required": [+ "failure"+ ],+ "properties": {+ "failure": {+ "$ref": "#/components/schemas/PMBalanceCheckFailureResponse"+ }+ }+ }+ ]+ },+ "PMBalanceCheckFailureResponse": {+ "type": "object",+ "required": [+ "error"+ ],+ "properties": {+ "error": {+ "type": "string"+ }+ }+ },+ "PMBalanceCheckSuccessResponse": {+ "type": "object",+ "required": [+ "balance",+ "applicable_amount",+ "currency"+ ],+ "properties": {+ "balance": {+ "$ref": "#/components/schemas/MinorUnit"+ },+ "applicable_amount": {+ "$ref": "#/components/schemas/MinorUnit"+ },+ "currency": {+ "$ref": "#/components/schemas/Currency"+ }+ }+ },"Passthrough": {"type": "object","required": [@@ -18003,39 +18024,6 @@"mobile_payment"]},- "PaymentMethodBalanceCheckRequest": {- "type": "object",- "description": "Request for Payment method balance check",- "required": [- "payment_method_data"- ],- "properties": {- "payment_method_data": {- "$ref": "#/components/schemas/BalanceCheckPaymentMethodData"- }- },- "additionalProperties": false- },- "PaymentMethodBalanceCheckResponse": {- "type": "object",- "required": [- "payment_id",- "balance",- "currency"- ],- "properties": {- "payment_id": {- "type": "string",- "description": "Global Payment Id for the payment"- },- "balance": {- "$ref": "#/components/schemas/MinorUnit"- },- "currency": {- "$ref": "#/components/schemas/Currency"- }- }- },"PaymentMethodCollectLinkRequest": {"allOf": [{diff --git a/api-reference/v2/payments/payments--apply-pm-data.mdx b/api-reference/v2/payments/payments--apply-pm-data.mdxdeleted file mode 100644index 1472e4333c..0000000000--- a/api-reference/v2/payments/payments--apply-pm-data.mdx+++ /dev/null@@ -1,3 +0,0 @@-----openapi: post /v2/payments/{id}/apply-payment-method-data----\ No newline at end of filediff --git a/api-reference/v2/payments/payments--check-balance-and-apply-pm-data.mdx b/api-reference/v2/payments/payments--check-balance-and-apply-pm-data.mdxnew file mode 100644index 0000000000..d897d1b55d--- /dev/null+++ b/api-reference/v2/payments/payments--check-balance-and-apply-pm-data.mdx@@ -0,0 +1,3 @@+---+openapi: post /v2/payments/{id}/eligibility/check-balance-and-apply-pm-data+---\ No newline at end of filediff --git a/api-reference/v2/payments/payments--gift-card-balance-check.mdx b/api-reference/v2/payments/payments--gift-card-balance-check.mdxdeleted file mode 100644index 936fad7bfa..0000000000--- a/api-reference/v2/payments/payments--gift-card-balance-check.mdx+++ /dev/null@@ -1,3 +0,0 @@-----openapi: post /v2/payments/{id}/payment-methods/check-balance----\ No newline at end of filediff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rsindex 0711690621..f1de76a4f6 100644--- a/crates/api_models/src/events/payment.rs+++ b/crates/api_models/src/events/payment.rs@@ -211,14 +211,7 @@ impl ApiEventMetric for PaymentsCreateIntentRequest {}#[cfg(feature = "v2")]-impl ApiEventMetric for payments::PaymentMethodBalanceCheckResponse {- fn get_api_event_type(&self) -> Option<ApiEventsType> {- None- }-}--#[cfg(feature = "v2")]-impl ApiEventMetric for payments::ApplyPaymentMethodDataResponse {+impl ApiEventMetric for payments::CheckAndApplyPaymentMethodDataResponse {fn get_api_event_type(&self) -> Option<ApiEventsType> {None}diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex 24e8d1e5ff..bac98545dd 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -703,19 +703,6 @@ pub struct PaymentsIntentResponse {pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>,}-#[cfg(feature = "v2")]-#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]-pub struct PaymentMethodBalanceCheckResponse {- /// Global Payment Id for the payment- #[schema(value_type = String)]- pub payment_id: id_type::GlobalPaymentId,- /// The balance of the payment method- pub balance: MinorUnit,- /// The currency of the payment method- #[schema(value_type = Currency)]- pub currency: common_enums::Currency,-}-#[cfg(feature = "v2")]#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]pub struct AmountDetails {@@ -3597,10 +3584,48 @@ pub struct ApplyPaymentMethodDataRequest {}#[derive(Debug, serde::Serialize, Clone, ToSchema)]-pub struct ApplyPaymentMethodDataResponse {+pub struct PMBalanceCheckSuccessResponse {+ pub balance: MinorUnit,+ pub applicable_amount: MinorUnit,+ #[schema(value_type = Currency)]+ pub currency: common_enums::Currency,+}++#[derive(Debug, serde::Serialize, Clone, ToSchema)]+pub struct PMBalanceCheckFailureResponse {+ pub error: String,+}++#[derive(Debug, serde::Serialize, Clone, ToSchema)]+#[serde(rename_all = "snake_case")]+pub enum PMBalanceCheckEligibilityResponse {+ Success(PMBalanceCheckSuccessResponse),+ Failure(PMBalanceCheckFailureResponse),+}++impl PMBalanceCheckEligibilityResponse {+ pub fn get_balance(&self) -> MinorUnit {+ match self {+ Self::Success(resp) => resp.balance,+ Self::Failure(_) => MinorUnit::zero(),+ }+ }+}++#[derive(Debug, serde::Serialize, Clone, ToSchema)]+pub struct EligibilityBalanceCheckResponseItem {+ pub payment_method_data: BalanceCheckPaymentMethodData,+ pub eligibility: PMBalanceCheckEligibilityResponse,+}++#[derive(Debug, serde::Serialize, Clone, ToSchema)]+pub struct CheckAndApplyPaymentMethodDataResponse {+ pub balances: Vec<EligibilityBalanceCheckResponseItem>,+ /// The amount left after subtracting applied payment method balance from order amountpub remaining_amount: MinorUnit,#[schema(value_type = Currency)]pub currency: common_enums::Currency,+ /// Whether the applied payment method balance is enough for the order amount or additional PM is requiredpub requires_additional_pm_data: bool,pub surcharge_details: Option<Vec<ApplyPaymentMethodDataSurchargeResponseItem>>,}@@ -7283,19 +7308,6 @@ pub struct PaymentsConfirmIntentRequest {pub webhook_url: Option<common_utils::types::Url>,}-// Serialize is implemented because, this will be serialized in the api events.-// Usually request types should not have serialize implemented.-//-/// Request for Payment method balance check-#[cfg(feature = "v2")]-#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]-#[serde(deny_unknown_fields)]-pub struct PaymentMethodBalanceCheckRequest {- /// The payment method data to be used for the balance check request. It can- /// only be a payment method that supports checking balance e.g. gift card- pub payment_method_data: BalanceCheckPaymentMethodData,-}-#[cfg(feature = "v2")]#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]#[serde(deny_unknown_fields)]diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rsindex a057a99d8f..027faaa4f5 100644--- a/crates/openapi/src/openapi_v2.rs+++ b/crates/openapi/src/openapi_v2.rs@@ -128,7 +128,6 @@ Never share your secret api keys. Keep them guarded and secure.routes::payments::payments_connector_session,routes::payments::list_payment_methods,routes::payments::payments_list,- routes::payments::payment_check_gift_card_balance,routes::payments::payments_apply_pm_data,//Routes for payment methods@@ -382,6 +381,10 @@ Never share your secret api keys. Keep them guarded and secure.common_types::domain::RetryFeatureData,api_models::payments::NullObject,api_models::payments::AddressDetails,+ api_models::payments::EligibilityBalanceCheckResponseItem,+ api_models::payments::PMBalanceCheckEligibilityResponse,+ api_models::payments::PMBalanceCheckSuccessResponse,+ api_models::payments::PMBalanceCheckFailureResponse,api_models::payments::BankDebitData,api_models::payments::AliPayQr,api_models::payments::PaymentAttemptFeatureMetadata,@@ -559,10 +562,8 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payments::RequestSurchargeDetails,api_models::payments::PaymentRevenueRecoveryMetadata,api_models::payments::BillingConnectorPaymentDetails,- api_models::payments::PaymentMethodBalanceCheckResponse,- api_models::payments::PaymentMethodBalanceCheckRequest,api_models::payments::ApplyPaymentMethodDataRequest,- api_models::payments::ApplyPaymentMethodDataResponse,+ api_models::payments::CheckAndApplyPaymentMethodDataResponse,api_models::payments::ApplyPaymentMethodDataSurchargeResponseItem,api_models::enums::PaymentConnectorTransmission,api_models::enums::TriggeredBy,diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rsindex de122d2950..6c7d9add9b 100644--- a/crates/openapi/src/routes/payments.rs+++ b/crates/openapi/src/routes/payments.rs@@ -1307,40 +1307,13 @@ pub fn list_payment_methods() {})]pub fn payments_list() {}-/// Payments - Payment Method Balance Check+/// Payments - Check Balance and Apply PM Data///-/// Check the balance of the provided payment method. Also validates whether the PM currency matches the payment currency+/// Check the balance of the payment methods, apply the payment method data and recalculate remaining_amount and surcharge#[cfg(feature = "v2")]#[utoipa::path(post,- path = "/v2/payments/{id}/payment-methods/check-balance",- params(- ("id" = String, Path, description = "The global payment id"),- (- "X-Profile-Id" = String, Header,- description = "Profile ID associated to the payment intent",- example = "pro_abcdefghijklmnop"- ),- ),- request_body(- content = PaymentMethodBalanceCheckRequest,- ),- responses(- (status = 200, description = "Get the Payment Method Balance", body = PaymentMethodBalanceCheckResponse),- ),- tag = "Payments",- operation_id = "Retrieve Payment Method Balance",- security(("publishable_key" = []))-)]-pub fn payment_check_gift_card_balance() {}--/// Payments - Apply PM Data-///-/// Apply the payment method data and recalculate surcharge-#[cfg(feature = "v2")]-#[utoipa::path(- post,- path = "/v2/payments/{id}/apply-payment-method-data",+ path = "/v2/payments/{id}/eligibility/check-balance-and-apply-pm-data",params(("id" = String, Path, description = "The global payment id"),(@@ -1353,7 +1326,7 @@ pub fn payment_check_gift_card_balance() {}content = ApplyPaymentMethodDataRequest,),responses(- (status = 200, description = "Apply the Payment Method Data", body = ApplyPaymentMethodDataResponse),+ (status = 200, description = "Apply the Payment Method Data", body = CheckAndApplyPaymentMethodDataResponse),),tag = "Payments",operation_id = "Apply Payment Method Data",diff --git a/crates/router/src/core/payment_method_balance.rs b/crates/router/src/core/payment_method_balance.rsindex ca51024346..d9246ace15 100644--- a/crates/router/src/core/payment_method_balance.rs+++ b/crates/router/src/core/payment_method_balance.rs@@ -1,8 +1,8 @@use std::{collections::HashMap, marker::PhantomData};use api_models::payments::{- ApplyPaymentMethodDataRequest, ApplyPaymentMethodDataResponse, GetPaymentMethodType,- PaymentMethodBalanceCheckRequest, PaymentMethodBalanceCheckResponse,+ ApplyPaymentMethodDataRequest, CheckAndApplyPaymentMethodDataResponse, GetPaymentMethodType,+ PMBalanceCheckFailureResponse, PMBalanceCheckSuccessResponse,};use common_enums::CallConnectorAction;use common_utils::{@@ -30,30 +30,28 @@ use crate::{},db::errors::StorageErrorExt,routes::{app::ReqState, SessionState},- services,- services::logger,+ services::{self, logger},types::{api, domain},};#[allow(clippy::too_many_arguments)]pub async fn payments_check_gift_card_balance_core(- state: SessionState,- merchant_context: domain::MerchantContext,- profile: domain::Profile,- _req_state: ReqState,- req: PaymentMethodBalanceCheckRequest,- _header_payload: HeaderPayload,- payment_id: id_type::GlobalPaymentId,-) -> RouterResponse<PaymentMethodBalanceCheckResponse> {+ state: &SessionState,+ merchant_context: &domain::MerchantContext,+ profile: &domain::Profile,+ _req_state: &ReqState,+ payment_method_data: api_models::payments::BalanceCheckPaymentMethodData,+ payment_id: &id_type::GlobalPaymentId,+) -> errors::RouterResult<(MinorUnit, common_enums::Currency)> {let db = state.store.as_ref();- let key_manager_state = &(&state).into();+ 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,+ payment_id,merchant_context.get_merchant_key_store(),storage_scheme,)@@ -82,7 +80,7 @@ pub async fn payments_check_gift_card_balance_core(let merchant_connector_account =domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(helpers::get_merchant_connector_account_v2(- &state,+ state,merchant_context.get_merchant_key_store(),Some(&gift_card_connector_id),)@@ -113,7 +111,7 @@ pub async fn payments_check_gift_card_balance_core(let resource_common_data = GiftCardBalanceCheckFlowData;let api_models::payments::BalanceCheckPaymentMethodData::GiftCard(gift_card_data) =- req.payment_method_data;+ payment_method_data;let router_data: RouterDataV2<GiftCardBalanceCheck,@@ -147,7 +145,7 @@ pub async fn payments_check_gift_card_balance_core(> = connector_data.connector.get_connector_integration();let connector_response = services::execute_connector_processing_step(- &state,+ state,connector_integration,&old_router_data,CallConnectorAction::Trigger,@@ -189,27 +187,24 @@ pub async fn payments_check_gift_card_balance_core(.collect(),};- persist_individual_pm_balance_details_in_redis(&state, &profile, &balance_data)+ persist_individual_pm_balance_details_in_redis(state, profile, &balance_data).await.attach_printable("Failed to persist gift card balance details in redis")?;- let resp = PaymentMethodBalanceCheckResponse {- payment_id: payment_intent.id.clone(),- balance,- currency,- };+ let resp = (balance, currency);- Ok(services::ApplicationResponse::Json(resp))+ Ok(resp)}#[allow(clippy::too_many_arguments)]-pub async fn payments_apply_pm_data_core(+pub async fn payments_check_and_apply_pm_data_core(state: SessionState,merchant_context: domain::MerchantContext,+ profile: domain::Profile,_req_state: ReqState,req: ApplyPaymentMethodDataRequest,payment_id: id_type::GlobalPaymentId,-) -> RouterResponse<ApplyPaymentMethodDataResponse> {+) -> RouterResponse<CheckAndApplyPaymentMethodDataResponse> {let db = state.store.as_ref();let key_manager_state = &(&state).into();let storage_scheme = merchant_context.get_merchant_account().storage_scheme;@@ -223,19 +218,114 @@ pub async fn payments_apply_pm_data_core(.await.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;- let balances =- fetch_payment_methods_balances_from_redis(&state, &payment_intent.id, &req.payment_methods)- .await- .attach_printable("Failed to retrieve payment method balances from redis")?;+ let payment_method_balances = fetch_payment_methods_balances_from_redis_fallible(+ &state,+ &payment_intent.id,+ &req.payment_methods,+ )+ .await+ .attach_printable("Failed to retrieve payment method balances from redis")?;- let total_balance: MinorUnit = balances.values().map(|value| value.balance).sum();+ let mut balance_values: Vec<api_models::payments::EligibilityBalanceCheckResponseItem> =+ futures::future::join_all(req.payment_methods.into_iter().map(|pm| async {+ let api_models::payments::BalanceCheckPaymentMethodData::GiftCard(gift_card_data) =+ pm.clone();+ let pm_balance_key = domain::PaymentMethodBalanceKey {+ payment_method_type: common_enums::PaymentMethod::GiftCard,+ payment_method_subtype: gift_card_data.get_payment_method_type(),+ payment_method_key: domain::GiftCardData::from(gift_card_data.clone())+ .get_payment_method_key()+ .change_context(errors::ApiErrorResponse::InvalidRequestData {+ message: "Unable to get unique key for payment method".to_string(),+ })?+ .expose(),+ };++ let eligibility = match payment_method_balances+ .get(&pm_balance_key)+ .and_then(|inner| inner.as_ref())+ {+ Some(balance) => {+ api_models::payments::PMBalanceCheckEligibilityResponse::Success(+ PMBalanceCheckSuccessResponse {+ balance: balance.balance,+ applicable_amount: MinorUnit::zero(), // Will be calculated after sorting+ currency: balance.currency,+ },+ )+ }+ None => {+ match payments_check_gift_card_balance_core(+ &state,+ &merchant_context,+ &profile,+ &_req_state,+ pm.clone(),+ &payment_id,+ )+ .await+ {+ Ok((balance, currency)) => {+ api_models::payments::PMBalanceCheckEligibilityResponse::Success(+ PMBalanceCheckSuccessResponse {+ balance,+ applicable_amount: MinorUnit::zero(), // Will be calculated after sorting+ currency,+ },+ )+ }+ Err(err) => {+ api_models::payments::PMBalanceCheckEligibilityResponse::Failure(+ PMBalanceCheckFailureResponse {+ error: err.to_string(),+ },+ )+ }+ }+ }+ };++ Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(+ api_models::payments::EligibilityBalanceCheckResponseItem {+ payment_method_data: pm,+ eligibility,+ },+ )+ }))+ .await+ .into_iter()+ .collect::<Result<Vec<_>, _>>()?;++ // Sort balance_values by balance in ascending order (smallest first)+ // This ensures smaller gift cards are fully utilized before larger ones+ balance_values.sort_by(|a, b| {+ a.eligibility+ .get_balance()+ .cmp(&b.eligibility.get_balance())+ });++ // Calculate applicable amounts with running total+ let mut running_total = MinorUnit::zero();+ let order_amount = payment_intent.amount_details.order_amount;+ for balance_item in balance_values.iter_mut() {+ if let api_models::payments::PMBalanceCheckEligibilityResponse::Success(balance_api) =+ &mut balance_item.eligibility+ {+ let remaining_amount = (order_amount - running_total).max(MinorUnit::zero());+ balance_api.applicable_amount = std::cmp::min(balance_api.balance, remaining_amount);+ running_total = running_total + balance_api.applicable_amount;+ }+ }++ let total_applicable_balance = running_total;// remaining_amount cannot be negative, hence using max with 0. This situation can arise when// the gift card balance exceeds the order amount- let remaining_amount =- (payment_intent.amount_details.order_amount - total_balance).max(MinorUnit::zero());+ let remaining_amount = (payment_intent.amount_details.order_amount - total_applicable_balance)+ .max(MinorUnit::zero());- let resp = ApplyPaymentMethodDataResponse {+ let resp = CheckAndApplyPaymentMethodDataResponse {+ balances: balance_values,remaining_amount,currency: payment_intent.amount_details.currency,requires_additional_pm_data: remaining_amount.is_greater_than(0),@@ -342,3 +432,56 @@ pub async fn fetch_payment_methods_balances_from_redis(}).collect::<errors::RouterResult<HashMap<_, _>>>()}++/// This function does not return an error if balance for a payment method is not found, it just sets+/// the corresponding value in the HashMap to None+pub async fn fetch_payment_methods_balances_from_redis_fallible(+ state: &SessionState,+ payment_intent_id: &id_type::GlobalPaymentId,+ payment_methods: &[api_models::payments::BalanceCheckPaymentMethodData],+) -> errors::RouterResult<+ HashMap<domain::PaymentMethodBalanceKey, Option<domain::PaymentMethodBalance>>,+> {+ let redis_conn = state+ .store+ .get_redis_conn()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to get redis connection")?;++ let balance_data = domain::PaymentMethodBalanceData::new(payment_intent_id);++ let balance_values: HashMap<String, domain::PaymentMethodBalance> = redis_conn+ .get_hash_fields::<Vec<(String, String)>>(&balance_data.get_pm_balance_redis_key().into())+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to read payment method balance data from redis")?+ .into_iter()+ .map(|(key, value)| {+ value+ .parse_struct("PaymentMethodBalance")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse PaymentMethodBalance")+ .map(|parsed| (key, parsed))+ })+ .collect::<errors::RouterResult<HashMap<_, _>>>()?;++ payment_methods+ .iter()+ .map(|pm| {+ let api_models::payments::BalanceCheckPaymentMethodData::GiftCard(gift_card_data) = pm;+ let pm_balance_key = domain::PaymentMethodBalanceKey {+ payment_method_type: common_enums::PaymentMethod::GiftCard,+ payment_method_subtype: gift_card_data.get_payment_method_type(),+ payment_method_key: domain::GiftCardData::from(gift_card_data.clone())+ .get_payment_method_key()+ .change_context(errors::ApiErrorResponse::InvalidRequestData {+ message: "Unable to get unique key for payment method".to_string(),+ })?+ .expose(),+ };+ let redis_key = pm_balance_key.get_redis_key();+ let balance_value = balance_values.get(&redis_key).cloned();+ Ok((pm_balance_key, balance_value))+ })+ .collect::<errors::RouterResult<HashMap<_, _>>>()+}diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 10892dbd67..e6270e837f 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -786,18 +786,11 @@ impl Payments {web::resource("/start-redirection").route(web::get().to(payments::payments_start_redirection)),)+ .service(web::scope("/payment-methods").service(+ web::resource("").route(web::get().to(payments::list_payment_methods)),+ )).service(- web::scope("/payment-methods")- .service(- web::resource("").route(web::get().to(payments::list_payment_methods)),- )- .service(- web::resource("/check-balance")- .route(web::post().to(payments::payment_check_gift_card_balance)),- ),- )- .service(- web::resource("/apply-payment-method-data")+ web::resource("/eligibility/check-balance-and-apply-pm-data").route(web::post().to(payments::payments_apply_pm_data)),).service(diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rsindex 44071619f6..641b3de015 100644--- a/crates/router/src/routes/payments.rs+++ b/crates/router/src/routes/payments.rs@@ -3213,14 +3213,14 @@ pub async fn payment_confirm_intent(}#[cfg(feature = "v2")]-#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodBalanceCheck, payment_id))]-pub async fn payment_check_gift_card_balance(+#[instrument(skip_all, fields(flow = ?Flow::ApplyPaymentMethodData, payment_id))]+pub async fn payments_apply_pm_data(state: web::Data<app::AppState>,req: actix_web::HttpRequest,- json_payload: web::Json<api_models::payments::PaymentMethodBalanceCheckRequest>,+ json_payload: web::Json<api_models::payments::ApplyPaymentMethodDataRequest>,path: web::Path<common_utils::id_type::GlobalPaymentId>,) -> impl Responder {- let flow = Flow::PaymentMethodBalanceCheck;+ let flow = Flow::ApplyPaymentMethodData;let global_payment_id = path.into_inner();tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());@@ -3230,13 +3230,6 @@ pub async fn payment_check_gift_card_balance(payload: json_payload.into_inner(),};- let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {- Ok(headers) => headers,- Err(err) => {- return api::log_and_return_error_response(err);- }- };-Box::pin(api::server_wrap(flow,state,@@ -3250,13 +3243,12 @@ pub async fn payment_check_gift_card_balance(domain::Context(auth.merchant_account, auth.key_store),));Box::pin(- payment_method_balance::payments_check_gift_card_balance_core(+ payment_method_balance::payments_check_and_apply_pm_data_core(state,merchant_context,auth.profile,req_state,request,- header_payload.clone(),payment_id,),)@@ -3277,60 +3269,6 @@ pub async fn payment_check_gift_card_balance(.await}-#[cfg(feature = "v2")]-#[instrument(skip_all, fields(flow = ?Flow::ApplyPaymentMethodData, payment_id))]-pub async fn payments_apply_pm_data(- state: web::Data<app::AppState>,- req: actix_web::HttpRequest,- json_payload: web::Json<api_models::payments::ApplyPaymentMethodDataRequest>,- path: web::Path<common_utils::id_type::GlobalPaymentId>,-) -> impl Responder {- let flow = Flow::ApplyPaymentMethodData;-- let global_payment_id = path.into_inner();- tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());-- let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {- global_payment_id: global_payment_id.clone(),- payload: json_payload.into_inner(),- };-- Box::pin(api::server_wrap(- flow,- state,- &req,- internal_payload,- |state, auth: auth::AuthenticationData, req, req_state| async {- let payment_id = req.global_payment_id;- let request = req.payload;-- let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(- domain::Context(auth.merchant_account, auth.key_store),- ));- Box::pin(payment_method_balance::payments_apply_pm_data_core(- state,- merchant_context,- req_state,- request,- payment_id,- ))- .await- },- auth::api_or_client_auth(- &auth::V2ApiKeyAuth {- is_connected_allowed: false,- is_platform_allowed: false,- },- &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment(- global_payment_id,- )),- req.headers(),- ),- api_locking::LockAction::NotApplicable,- ))- .await-}-#[cfg(feature = "v2")]#[instrument(skip_all, fields(flow = ?Flow::ProxyConfirmIntent, payment_id))]pub async fn proxy_confirm_intent(