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(router): Make Gift Card Balance Check API Generic (v2) (#9856)

Anurag Thakur2e38b2ce5c3c
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index 3493669d5e..08c05a2c85 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -2593,14 +2593,14 @@
]
}
},
- "/v2/payments/{id}/check-gift-card-balance": {
- "get": {
+ "/v2/payments/{id}/payment-methods/check-balance": {
+ "post": {
"tags": [
"Payments"
],
- "summary": "Payments - Gift Card Balance Check",
- "description": "Check the balance of the provided gift card. This endpoint also returns whether the gift card balance is enough to cover the entire amount or another payment method is needed",
- "operationId": "Retrieve Gift Card Balance",
+ "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",
@@ -2626,7 +2626,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/PaymentsGiftCardBalanceCheckRequest"
+ "$ref": "#/components/schemas/PaymentMethodBalanceCheckRequest"
}
}
},
@@ -2634,11 +2634,11 @@
},
"responses": {
"200": {
- "description": "Get the Gift Card Balance",
+ "description": "Get the Payment Method Balance",
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/GiftCardBalanceCheckResponse"
+ "$ref": "#/components/schemas/PaymentMethodBalanceCheckResponse"
}
}
}
@@ -5532,6 +5532,21 @@
}
}
},
+ "BalanceCheckPaymentMethodData": {
+ "oneOf": [
+ {
+ "type": "object",
+ "required": [
+ "gift_card"
+ ],
+ "properties": {
+ "gift_card": {
+ "$ref": "#/components/schemas/GiftCardData"
+ }
+ }
+ }
+ ]
+ },
"BancontactBankRedirectAdditionalData": {
"type": "object",
"properties": {
@@ -12401,35 +12416,6 @@
}
]
},
- "GiftCardBalanceCheckResponse": {
- "type": "object",
- "required": [
- "payment_id",
- "balance",
- "currency",
- "needs_additional_pm_data",
- "remaining_amount"
- ],
- "properties": {
- "payment_id": {
- "type": "string",
- "description": "Global Payment Id for the payment"
- },
- "balance": {
- "$ref": "#/components/schemas/MinorUnit"
- },
- "currency": {
- "$ref": "#/components/schemas/Currency"
- },
- "needs_additional_pm_data": {
- "type": "boolean",
- "description": "Whether the gift card balance is enough for the transaction (Used for split payments case)"
- },
- "remaining_amount": {
- "$ref": "#/components/schemas/MinorUnit"
- }
- }
- },
"GiftCardData": {
"oneOf": [
{
@@ -17790,6 +17776,39 @@
"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": [
{
@@ -19880,19 +19899,6 @@
}
}
},
- "PaymentsGiftCardBalanceCheckRequest": {
- "type": "object",
- "description": "Request for Gift Card balance check",
- "required": [
- "gift_card_data"
- ],
- "properties": {
- "gift_card_data": {
- "$ref": "#/components/schemas/GiftCardData"
- }
- },
- "additionalProperties": false
- },
"PaymentsIncrementalAuthorizationRequest": {
"type": "object",
"required": [
diff --git a/api-reference/v2/payments/payments--gift-card-balance-check.mdx b/api-reference/v2/payments/payments--gift-card-balance-check.mdx
index 680d08ada4..936fad7bfa 100644
--- a/api-reference/v2/payments/payments--gift-card-balance-check.mdx
+++ b/api-reference/v2/payments/payments--gift-card-balance-check.mdx
@@ -1,3 +1,3 @@
---
-openapi: get /v2/payments/{id}/check-gift-card-balance
+openapi: post /v2/payments/{id}/payment-methods/check-balance
---
\ No newline at end of file
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs
index 5619ba4969..5368842d2f 100644
--- a/crates/api_models/src/events/payment.rs
+++ b/crates/api_models/src/events/payment.rs
@@ -209,7 +209,7 @@ impl ApiEventMetric for PaymentsCreateIntentRequest {
}
#[cfg(feature = "v2")]
-impl ApiEventMetric for payments::GiftCardBalanceCheckResponse {
+impl ApiEventMetric for payments::PaymentMethodBalanceCheckResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 081a5439e2..dc2e48a314 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -679,19 +679,15 @@ pub struct PaymentsIntentResponse {
#[cfg(feature = "v2")]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
-pub struct GiftCardBalanceCheckResponse {
+pub struct PaymentMethodBalanceCheckResponse {
/// Global Payment Id for the payment
#[schema(value_type = String)]
pub payment_id: id_type::GlobalPaymentId,
- /// The balance of the gift card
+ /// The balance of the payment method
pub balance: MinorUnit,
- /// The currency of the Gift Card
+ /// The currency of the payment method
#[schema(value_type = Currency)]
pub currency: common_enums::Currency,
- /// Whether the gift card balance is enough for the transaction (Used for split payments case)
- pub needs_additional_pm_data: bool,
- /// Transaction amount left after subtracting gift card balance (Used for split payments)
- pub remaining_amount: MinorUnit,
}
#[cfg(feature = "v2")]
@@ -3171,6 +3167,13 @@ pub enum GiftCardData {
PaySafeCard {},
BhnCardNetwork(BHNGiftCardDetails),
}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum BalanceCheckPaymentMethodData {
+ GiftCard(GiftCardData),
+}
+
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct BHNGiftCardDetails {
@@ -5984,12 +5987,14 @@ pub struct PaymentsConfirmIntentRequest {
// Serialize is implemented because, this will be serialized in the api events.
// Usually request types should not have serialize implemented.
//
-/// Request for Gift Card balance check
+/// Request for Payment method balance check
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(deny_unknown_fields)]
-pub struct PaymentsGiftCardBalanceCheckRequest {
- pub gift_card_data: GiftCardData,
+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")]
diff --git a/crates/hyperswitch_connectors/src/connectors/adyen.rs b/crates/hyperswitch_connectors/src/connectors/adyen.rs
index b50fbfa6a5..ce2c6768da 100644
--- a/crates/hyperswitch_connectors/src/connectors/adyen.rs
+++ b/crates/hyperswitch_connectors/src/connectors/adyen.rs
@@ -1254,12 +1254,38 @@ impl
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- RouterData::try_from(ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ let currency = data
+ .request
+ .currency
+ .get_required_value("currency")
+ .change_context(errors::ConnectorError::MissingRequiredField {
+ field_name: "currency",
+ })?;
+
+ if response.balance.currency != currency {
+ Ok(RouterData {
+ response: Err(ErrorResponse {
+ code: NO_ERROR_CODE.to_string(),
+ message: NO_ERROR_MESSAGE.to_string(),
+ reason: Some(constants::MISMATCHED_CURRENCY.to_string()),
+ status_code: res.status_code,
+ attempt_status: Some(enums::AttemptStatus::Failure),
+ connector_transaction_id: Some(response.psp_reference),
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ }),
+ ..data.clone()
+ })
+ } else {
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
}
fn get_error_response(
diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs
index 6cc3757a6a..450d7cc417 100644
--- a/crates/hyperswitch_connectors/src/constants.rs
+++ b/crates/hyperswitch_connectors/src/constants.rs
@@ -49,6 +49,8 @@ pub const REFUND_VOIDED: &str = "Refund request has been voided.";
pub const LOW_BALANCE_ERROR_MESSAGE: &str = "Insufficient balance in the payment method";
+pub const MISMATCHED_CURRENCY: &str = "Payment Method currency does not match the payment currency";
+
pub const DUIT_NOW_BRAND_COLOR: &str = "#ED2E67";
pub const DUIT_NOW_BRAND_TEXT: &str = "MALAYSIA NATIONAL QR";
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index 79caf8b0d4..f1963d3cb6 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -706,6 +706,30 @@ pub enum GiftCardData {
BhnCardNetwork(BHNGiftCardDetails),
}
+impl GiftCardData {
+ /// Returns a key that uniquely identifies the gift card. Used in
+ /// Payment Method Balance Check Flow for storing the balance
+ /// data in Redis.
+ ///
+ pub fn get_payment_method_key(
+ &self,
+ ) -> Result<Secret<String>, error_stack::Report<common_utils::errors::ValidationError>> {
+ match self {
+ Self::Givex(givex) => Ok(givex.number.clone()),
+ Self::PaySafeCard {} =>
+ // Generate a validation error here as we don't support balance check flow for it
+ {
+ Err(error_stack::Report::new(
+ common_utils::errors::ValidationError::InvalidValue {
+ message: "PaySafeCard doesn't support balance check flow".to_string(),
+ },
+ ))
+ }
+ Self::BhnCardNetwork(bhn) => Ok(bhn.account_number.clone()),
+ }
+ }
+}
+
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct GiftCardDetails {
diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs
index e9ce905769..9c37fe084b 100644
--- a/crates/hyperswitch_domain_models/src/payment_methods.rs
+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs
@@ -1,3 +1,6 @@
+#[cfg(feature = "v2")]
+use std::collections::HashMap;
+
#[cfg(feature = "v2")]
use api_models::payment_methods::PaymentMethodsData;
use api_models::{customers, payment_methods, payments};
@@ -1177,6 +1180,69 @@ impl From<PaymentMethodVaultSourceDetails>
}
}
+/// This struct stores information to generate the key to identify
+/// a unique payment method balance entry in the HashMap stored in Redis
+#[cfg(feature = "v2")]
+#[derive(Eq, Hash, PartialEq, Clone, Debug)]
+pub struct PaymentMethodBalanceKey {
+ pub payment_method_type: common_enums::PaymentMethod,
+ pub payment_method_subtype: common_enums::PaymentMethodType,
+ pub payment_method_key: String,
+}
+
+#[cfg(feature = "v2")]
+impl PaymentMethodBalanceKey {
+ pub fn get_redis_key(&self) -> String {
+ format!(
+ "{}_{}_{}",
+ self.payment_method_type, self.payment_method_subtype, self.payment_method_key
+ )
+ }
+}
+
+/// This struct stores the balance and currency information for a specific
+/// payment method to be stored in the HashMap in Redis
+#[cfg(feature = "v2")]
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct PaymentMethodBalance {
+ pub balance: common_utils::types::MinorUnit,
+ pub currency: common_enums::Currency,
+}
+
+#[cfg(feature = "v2")]
+pub struct PaymentMethodBalanceData<'a> {
+ pub pm_balance_data: HashMap<PaymentMethodBalanceKey, PaymentMethodBalance>,
+ pub payment_intent_id: &'a id_type::GlobalPaymentId,
+}
+
+#[cfg(feature = "v2")]
+impl<'a> PaymentMethodBalanceData<'a> {
+ pub fn new(payment_intent_id: &'a id_type::GlobalPaymentId) -> Self {
+ Self {
+ pm_balance_data: HashMap::new(),
+ payment_intent_id,
+ }
+ }
+
+ pub fn get_pm_balance_redis_key(&self) -> String {
+ format!("pm_balance_{}", self.payment_intent_id.get_string_repr())
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.pm_balance_data.is_empty()
+ }
+
+ pub fn get_individual_pm_balance_key_value_pairs(&self) -> Vec<(String, PaymentMethodBalance)> {
+ self.pm_balance_data
+ .iter()
+ .map(|(pm_balance_key, pm_balance_value)| {
+ let key = pm_balance_key.get_redis_key();
+ (key, pm_balance_value.to_owned())
+ })
+ .collect()
+ }
+}
+
#[cfg(feature = "v1")]
#[cfg(test)]
mod tests {
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 6aa19875c0..e5f44d5d33 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -557,8 +557,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::GiftCardBalanceCheckResponse,
- api_models::payments::PaymentsGiftCardBalanceCheckRequest,
+ api_models::payments::PaymentMethodBalanceCheckResponse,
+ api_models::payments::PaymentMethodBalanceCheckRequest,
api_models::enums::PaymentConnectorTransmission,
api_models::enums::TriggeredBy,
api_models::payments::PaymentAttemptResponse,
@@ -633,6 +633,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::ephemeral_key::ClientSecretResponse,
api_models::payments::CustomerDetails,
api_models::payments::GiftCardData,
+ api_models::payments::BalanceCheckPaymentMethodData,
api_models::payments::GiftCardDetails,
api_models::payments::BHNGiftCardDetails,
api_models::payments::MobilePaymentData,
diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs
index c585432085..2fd535cd6a 100644
--- a/crates/openapi/src/routes/payments.rs
+++ b/crates/openapi/src/routes/payments.rs
@@ -1307,13 +1307,13 @@ pub fn list_payment_methods() {}
)]
pub fn payments_list() {}
-/// Payments - Gift Card Balance Check
+/// Payments - Payment Method Balance Check
///
-/// Check the balance of the provided gift card. This endpoint also returns whether the gift card balance is enough to cover the entire amount or another payment method is needed
+/// Check the balance of the provided payment method. Also validates whether the PM currency matches the payment currency
#[cfg(feature = "v2")]
#[utoipa::path(
- get,
- path = "/v2/payments/{id}/check-gift-card-balance",
+ post,
+ path = "/v2/payments/{id}/payment-methods/check-balance",
params(
("id" = String, Path, description = "The global payment id"),
(
@@ -1323,13 +1323,13 @@ pub fn payments_list() {}
),
),
request_body(
- content = PaymentsGiftCardBalanceCheckRequest,
+ content = PaymentMethodBalanceCheckRequest,
),
responses(
- (status = 200, description = "Get the Gift Card Balance", body = GiftCardBalanceCheckResponse),
+ (status = 200, description = "Get the Payment Method Balance", body = PaymentMethodBalanceCheckResponse),
),
tag = "Payments",
- operation_id = "Retrieve Gift Card Balance",
+ operation_id = "Retrieve Payment Method Balance",
security(("publishable_key" = []))
)]
pub fn payment_check_gift_card_balance() {}
diff --git a/crates/router/src/core/gift_card.rs b/crates/router/src/core/gift_card.rs
index d1c89eafdb..76d1d8788f 100644
--- a/crates/router/src/core/gift_card.rs
+++ b/crates/router/src/core/gift_card.rs
@@ -1,45 +1,45 @@
use std::marker::PhantomData;
-#[cfg(feature = "v2")]
-use api_models::payments::{GiftCardBalanceCheckResponse, PaymentsGiftCardBalanceCheckRequest};
+use api_models::payments::{
+ GetPaymentMethodType, PaymentMethodBalanceCheckRequest, PaymentMethodBalanceCheckResponse,
+};
use common_enums::CallConnectorAction;
-#[cfg(feature = "v2")]
-use common_utils::id_type;
-use common_utils::types::MinorUnit;
+use common_utils::{ext_traits::Encode, id_type, types::MinorUnit};
use error_stack::ResultExt;
-#[cfg(feature = "v2")]
-use hyperswitch_domain_models::payments::HeaderPayload;
use hyperswitch_domain_models::{
+ payments::HeaderPayload,
router_data_v2::{flow_common_types::GiftCardBalanceCheckFlowData, RouterDataV2},
router_flow_types::GiftCardBalanceCheck,
router_request_types::GiftCardBalanceCheckRequestData,
router_response_types::GiftCardBalanceCheckResponseData,
};
use hyperswitch_interfaces::connector_integration_interface::RouterDataConversion;
+use masking::ExposeInterface;
+use router_env::{instrument, tracing};
-use crate::db::errors::StorageErrorExt;
-#[cfg(feature = "v2")]
use crate::{
+ consts,
core::{
errors::{self, RouterResponse},
payments::helpers,
},
+ db::errors::StorageErrorExt,
routes::{app::ReqState, SessionState},
services,
+ services::logger,
types::{api, domain},
};
-#[cfg(feature = "v2")]
#[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: PaymentsGiftCardBalanceCheckRequest,
+ req: PaymentMethodBalanceCheckRequest,
_header_payload: HeaderPayload,
payment_id: id_type::GlobalPaymentId,
-) -> RouterResponse<GiftCardBalanceCheckResponse> {
+) -> RouterResponse<PaymentMethodBalanceCheckResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
@@ -107,6 +107,9 @@ 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;
+
let router_data: RouterDataV2<
GiftCardBalanceCheck,
GiftCardBalanceCheckFlowData,
@@ -119,7 +122,7 @@ pub async fn payments_check_gift_card_balance_core(
connector_auth_type,
request: GiftCardBalanceCheckRequestData {
payment_method_data: domain::PaymentMethodData::GiftCard(Box::new(
- req.gift_card_data.into(),
+ gift_card_data.clone().into(),
)),
currency: Some(payment_intent.amount_details.currency),
minor_amount: Some(payment_intent.amount_details.order_amount),
@@ -159,21 +162,81 @@ pub async fn payments_check_gift_card_balance_core(
let balance = gift_card_balance.balance;
let currency = gift_card_balance.currency;
- let remaining_amount =
- if (payment_intent.amount_details.order_amount - balance).is_greater_than(0) {
- payment_intent.amount_details.order_amount - balance
- } else {
- MinorUnit::zero()
- };
- let needs_additional_pm_data = remaining_amount.is_greater_than(0);
-
- let resp = GiftCardBalanceCheckResponse {
+
+ let 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 balance_data = domain::PaymentMethodBalanceData {
+ payment_intent_id: &payment_intent.id,
+ pm_balance_data: vec![(
+ domain::PaymentMethodBalanceKey {
+ payment_method_type: common_enums::PaymentMethod::GiftCard,
+ payment_method_subtype: gift_card_data.get_payment_method_type(),
+ payment_method_key,
+ },
+ domain::PaymentMethodBalance { balance, currency },
+ )]
+ .into_iter()
+ .collect(),
+ };
+
+ 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,
- needs_additional_pm_data,
- remaining_amount,
};
Ok(services::ApplicationResponse::Json(resp))
}
+
+#[instrument(skip_all)]
+pub async fn persist_individual_pm_balance_details_in_redis<'a>(
+ state: &SessionState,
+ business_profile: &domain::Profile,
+ pm_balance_data: &domain::PaymentMethodBalanceData<'_>,
+) -> errors::RouterResult<()> {
+ if !pm_balance_data.is_empty() {
+ let redis_conn = state
+ .store
+ .get_redis_conn()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get redis connection")?;
+ let redis_key = pm_balance_data.get_pm_balance_redis_key();
+
+ let value_list = pm_balance_data
+ .get_individual_pm_balance_key_value_pairs()
+ .into_iter()
+ .map(|(key, value)| {
+ value
+ .encode_to_string_of_json()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to encode to string of json")
+ .map(|encoded_value| (key, encoded_value))
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+
+ let intent_fulfillment_time = business_profile
+ .get_order_fulfillment_time()
+ .unwrap_or(consts::DEFAULT_FULFILLMENT_TIME);
+
+ redis_conn
+ .set_hash_fields(
+ &redis_key.as_str().into(),
+ value_list,
+ Some(intent_fulfillment_time),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to write to redis")?;
+ logger::debug!("Surcharge results stored in redis with key = {}", redis_key);
+ }
+ Ok(())
+}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index bf6b0b31a8..223b385ddd 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -788,8 +788,14 @@ impl Payments {
.route(web::get().to(payments::payments_start_redirection)),
)
.service(
- web::resource("/payment-methods")
- .route(web::get().to(payments::list_payment_methods)),
+ 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("/finish-redirection/{publishable_key}/{profile_id}")
@@ -798,10 +804,6 @@ impl Payments {
.service(
web::resource("/capture").route(web::post().to(payments::payments_capture)),
)
- .service(
- web::resource("/check-gift-card-balance")
- .route(web::post().to(payments::payment_check_gift_card_balance)),
- )
.service(web::resource("/cancel").route(web::post().to(payments::payments_cancel))),
);
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index bf91f87da1..c6ca2f6a02 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -163,7 +163,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::PaymentsConfirmIntent
| Flow::PaymentsCreateIntent
| Flow::PaymentsGetIntent
- | Flow::GiftCardBalanceCheck
+ | Flow::PaymentMethodBalanceCheck
| Flow::PaymentsPostSessionTokens
| Flow::PaymentsUpdateMetadata
| Flow::PaymentsUpdateIntent
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index b0de7c4e9c..21043d93b3 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -3196,14 +3196,14 @@ pub async fn payment_confirm_intent(
}
#[cfg(feature = "v2")]
-#[instrument(skip_all, fields(flow = ?Flow::GiftCardBalanceCheck, payment_id))]
+#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodBalanceCheck, payment_id))]
pub async fn payment_check_gift_card_balance(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
- json_payload: web::Json<api_models::payments::PaymentsGiftCardBalanceCheckRequest>,
+ json_payload: web::Json<api_models::payments::PaymentMethodBalanceCheckRequest>,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
- let flow = Flow::GiftCardBalanceCheck;
+ let flow = Flow::PaymentMethodBalanceCheck;
let global_payment_id = path.into_inner();
tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 90d24ca349..2a6ff58237 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -680,8 +680,8 @@ pub enum Flow {
RecoveryDataBackfill,
/// Revenue recovery Redis operations flow
RevenueRecoveryRedis,
- /// Gift card balance check flow
- GiftCardBalanceCheck,
+ /// Payment Method balance check flow
+ PaymentMethodBalanceCheck,
/// Payments Submit Eligibility flow
PaymentsSubmitEligibility,
}