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
fix(connector): preserve InterPayments surcharge errors (#14996)
nithin-juspaye6ee1c177273
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex a845327707..61ebb1e517 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -2259,7 +2259,7 @@"Payments"],"summary": "Payments - Submit Eligibility Data",- "description": "Runs eligibility checks (blocklist, card testing guard) and calculates an external surcharge\nin a single call. Intended to be called by the SDK before the final confirm step.\n\n- If eligibility is denied the response will contain `sdk_next_action: deny` and no surcharge details.\n- If the merchant has no surcharge connector configured, `surcharge_details` will be `null`.\n- Surcharge calculation is best-effort: if the external call fails the payment still proceeds\nwith `surcharge_details: null`.",+ "description": "Runs eligibility checks (blocklist, card testing guard) and calculates an external surcharge\nin a single call. Intended to be called by the SDK before the final confirm step.\n\n- If eligibility is denied the response will contain `sdk_next_action: deny` and no surcharge details.\n- If the merchant has no surcharge connector configured, `surcharge_details` will be `null`.\n- A connector calculation error leaves the payment payable amount unchanged. Its surcharge\ndetails contain a zero surcharge and the connector message. The error code is included\nonly when the connector supplies one.\n- If no calculation is attempted, `surcharge_details` is `null`.","operationId": "Submit Eligibility data for a Payment","parameters": [{@@ -24672,6 +24672,14 @@"sale_notified": {"type": "boolean","description": "Whether /v1/ch/sale has been successfully called"+ },+ "error_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/SurchargeErrorDetails"+ }+ ],+ "nullable": true}}},@@ -35224,6 +35232,41 @@}}},+ "PaymentSurchargeDetailsResponse": {+ "type": "object",+ "description": "Surcharge applied to a payment, or a zero surcharge with connector error details.",+ "required": [+ "surcharge_amount"+ ],+ "properties": {+ "surcharge_amount": {+ "type": "integer",+ "format": "int64",+ "example": 325+ },+ "tax_amount": {+ "allOf": [+ {+ "$ref": "#/components/schemas/MinorUnit"+ }+ ],+ "nullable": true+ },+ "surcharge_percentage": {+ "type": "number",+ "format": "double",+ "nullable": true+ },+ "error_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/SurchargeErrorDetails"+ }+ ],+ "nullable": true+ }+ }+ },"PaymentType": {"type": "string","description": "The type of the payment that differentiates between normal and various types of mandate payments. Use 'setup_mandate' in case of zero auth flow.",@@ -36979,7 +37022,7 @@"surcharge_details": {"allOf": [{- "$ref": "#/components/schemas/RequestSurchargeDetails"+ "$ref": "#/components/schemas/PaymentSurchargeDetailsResponse"}],"nullable": true@@ -38879,7 +38922,7 @@"surcharge_details": {"allOf": [{- "$ref": "#/components/schemas/RequestSurchargeDetails"+ "$ref": "#/components/schemas/PaymentSurchargeDetailsResponse"}],"nullable": true@@ -48739,6 +48782,37 @@"format": "double","description": "Surcharge percentage returned by the external surcharge connector, if provided.","nullable": true+ },+ "error_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/SurchargeErrorDetails"+ }+ ],+ "nullable": true+ }+ }+ },+ "SurchargeErrorDetails": {+ "type": "object",+ "description": "Connector error details shared by surcharge responses, cached quotes, and stored attempts.",+ "properties": {+ "error_code": {+ "type": "string",+ "description": "Connector error code when the external calculation failed.",+ "example": "INVALID_NICN",+ "nullable": true+ },+ "error_message": {+ "type": "string",+ "description": "Connector error message when the external calculation failed.",+ "example": "Card BIN is invalid",+ "nullable": true+ },+ "error_reason": {+ "type": "string",+ "description": "Connector reason for a failed calculation.",+ "nullable": true}}},diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex a5e7e1bf5c..af96d8f621 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -16011,6 +16011,14 @@"sale_notified": {"type": "boolean","description": "Whether /v1/ch/sale has been successfully called"+ },+ "error_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/SurchargeErrorDetails"+ }+ ],+ "nullable": true}}},@@ -25836,6 +25844,41 @@}}},+ "PaymentSurchargeDetailsResponse": {+ "type": "object",+ "description": "Surcharge applied to a payment, or a zero surcharge with connector error details.",+ "required": [+ "surcharge_amount"+ ],+ "properties": {+ "surcharge_amount": {+ "type": "integer",+ "format": "int64",+ "example": 325+ },+ "tax_amount": {+ "allOf": [+ {+ "$ref": "#/components/schemas/MinorUnit"+ }+ ],+ "nullable": true+ },+ "surcharge_percentage": {+ "type": "number",+ "format": "double",+ "nullable": true+ },+ "error_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/SurchargeErrorDetails"+ }+ ],+ "nullable": true+ }+ }+ },"PaymentType": {"type": "string","description": "The type of the payment that differentiates between normal and various types of mandate payments. Use 'setup_mandate' in case of zero auth flow.",@@ -34994,6 +35037,37 @@"format": "double","description": "Surcharge percentage returned by the external surcharge connector, if provided.","nullable": true+ },+ "error_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/SurchargeErrorDetails"+ }+ ],+ "nullable": true+ }+ }+ },+ "SurchargeErrorDetails": {+ "type": "object",+ "description": "Connector error details shared by surcharge responses, cached quotes, and stored attempts.",+ "properties": {+ "error_code": {+ "type": "string",+ "description": "Connector error code when the external calculation failed.",+ "example": "INVALID_NICN",+ "nullable": true+ },+ "error_message": {+ "type": "string",+ "description": "Connector error message when the external calculation failed.",+ "example": "Card BIN is invalid",+ "nullable": true+ },+ "error_reason": {+ "type": "string",+ "description": "Connector reason for a failed calculation.",+ "nullable": true}}},diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex ca5eb60e76..c0f0fc8e65 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -6,6 +6,7 @@ use std::{};use cards::CardNumber;+pub use common_types::payments::SurchargeErrorDetails;use common_types::payments::{ApplePayPredecryptData, BillingFrequency, GPayPredecryptData, InstallmentInterestRate,};@@ -2638,6 +2639,26 @@ pub struct SurchargeDetailsResponse {pub display_total_surcharge_amount: f64,/// Surcharge percentage returned by the external surcharge connector, if provided.pub surcharge_percentage: Option<f64>,+ /// Connector error details when the external calculation failed; null on success.+ pub error_details: Option<SurchargeErrorDetails>,+}++impl SurchargeDetailsResponse {+ pub fn connector_error(code: Option<String>, message: String, reason: Option<String>) -> Self {+ Self {+ surcharge: SurchargeResponse::Fixed(MinorUnit::zero()),+ tax_on_surcharge: None,+ display_surcharge_amount: 0.0,+ display_tax_on_surcharge_amount: 0.0,+ display_total_surcharge_amount: 0.0,+ surcharge_percentage: None,+ error_details: Some(SurchargeErrorDetails {+ error_code: code,+ error_message: Some(message),+ error_reason: reason,+ }),+ }+ }}#[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)]diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex e559764331..a946bc9081 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -2035,6 +2035,77 @@ pub struct RequestSurchargeDetails {pub surcharge_percentage: Option<f64>,}+/// Surcharge applied to a payment, or a zero surcharge with connector error details.+#[derive(Debug, Clone, PartialEq, Serialize, ToSchema, SmithyModel)]+#[smithy(namespace = "com.hyperswitch.smithy.types")]+pub struct PaymentSurchargeDetailsResponse {+ #[schema(value_type = i64, example = 325)]+ #[smithy(value_type = "i64")]+ pub surcharge_amount: MinorUnit,+ #[smithy(value_type = "Option<i64>")]+ pub tax_amount: Option<MinorUnit>,+ #[smithy(value_type = "Option<f64>")]+ pub surcharge_percentage: Option<f64>,+ /// Connector error details when the external calculation failed; null on success.+ #[schema(value_type = Option<SurchargeErrorDetails>)]+ #[smithy(value_type = "Option<SurchargeErrorDetails>")]+ pub error_details: Option<payment_methods::SurchargeErrorDetails>,+}++impl PaymentSurchargeDetailsResponse {+ pub fn from_calculated_amounts(+ surcharge_amount: MinorUnit,+ tax_amount: Option<MinorUnit>,+ surcharge_percentage: Option<f64>,+ ) -> Self {+ Self {+ surcharge_amount,+ tax_amount,+ surcharge_percentage,+ error_details: None,+ }+ }++ pub fn from_connector_error(+ code: Option<String>,+ message: Option<String>,+ reason: Option<String>,+ ) -> Self {+ Self {+ surcharge_amount: MinorUnit::zero(),+ tax_amount: None,+ surcharge_percentage: None,+ error_details: Some(payment_methods::SurchargeErrorDetails {+ error_code: code,+ error_message: message,+ error_reason: reason,+ }),+ }+ }++ pub fn from_surcharge_details(+ amount: Option<MinorUnit>,+ tax_amount: Option<MinorUnit>,+ external: Option<&common_types::payments::ExternalSurchargeDetails>,+ ) -> Option<Self> {+ match external {+ Some(details) if details.has_error() => Some(Self {+ surcharge_amount: MinorUnit::zero(),+ tax_amount: None,+ surcharge_percentage: None,+ error_details: details.error_details.clone(),+ }),+ _ => amount.map(|value| {+ Self::from_calculated_amounts(+ value,+ tax_amount,+ external.and_then(|details| details.surcharge_percentage_as_f64()),+ )+ }),+ }+ }+}+// for v2 use the type from common_utils::types#[cfg(feature = "v1")]/// Browser information to be used for 3DS 2.0@@ -7917,8 +7988,8 @@ pub struct PaymentsResponse {pub profile_id: Option<id_type::ProfileId>,/// Details of surcharge applied on this payment- #[smithy(value_type = "Option<RequestSurchargeDetails>")]- pub surcharge_details: Option<RequestSurchargeDetails>,+ #[smithy(value_type = "Option<PaymentSurchargeDetailsResponse>")]+ pub surcharge_details: Option<PaymentSurchargeDetailsResponse>,/// Applied Offer Engine offer details for this payment, if an offer was applied.#[schema(value_type = Option<AppliedOffer>)]@@ -9652,7 +9723,7 @@ pub struct PlatformPaymentListItem {pub sender_payment_instrument_id: Option<String>,/// Surcharge and tax-on-surcharge applied on the active attempt.- pub surcharge_details: Option<RequestSurchargeDetails>,+ pub surcharge_details: Option<PaymentSurchargeDetailsResponse>,/// Installment options available/selected for this payment.pub installment_options: Option<Vec<common_types::payments::InstallmentOption>>,diff --git a/crates/common_types/src/consts.rs b/crates/common_types/src/consts.rsindex 027cd94d70..6c206e79ce 100644--- a/crates/common_types/src/consts.rs+++ b/crates/common_types/src/consts.rs@@ -1,5 +1,8 @@//! Constants that are used in the domain level.+/// Placeholder when the surcharge connector does not return a transaction ID.+pub const NO_SURCHARGE_ID_FOUND: &str = "NO_SURCHARGE_ID_FOUND";+/// Base value for converting percentage to decimal (e.g., 12% → 0.12)pub const PERCENTAGE_BASE: f64 = 100.0;diff --git a/crates/common_types/src/payments.rs b/crates/common_types/src/payments.rsindex 2321b94030..17cba37d8f 100644--- a/crates/common_types/src/payments.rs+++ b/crates/common_types/src/payments.rs@@ -1617,6 +1617,22 @@ pub enum TokenSource {ApplePay,}+/// Connector error details shared by surcharge responses, cached quotes, and stored attempts.+#[derive(+ Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize, ToSchema, smithy::SmithyModel,+)]+#[smithy(namespace = "com.hyperswitch.smithy.types")]+pub struct SurchargeErrorDetails {+ /// Connector error code when the external calculation failed.+ #[schema(example = "INVALID_NICN")]+ pub error_code: Option<String>,+ /// Connector error message when the external calculation failed.+ #[schema(example = "Card BIN is invalid")]+ pub error_message: Option<String>,+ /// Connector reason for a failed calculation.+ pub error_reason: Option<String>,+}+/// External surcharge details from InterPayments (stored as JSONB)#[derive(Clone, Debug, serde::Deserialize, Eq, ToSchema, PartialEq, serde::Serialize)]#[cfg_attr(feature = "diesel", derive(diesel::AsExpression))]@@ -1632,9 +1648,31 @@ pub struct ExternalSurchargeDetails {pub surcharge_percentage: Option<Decimal>,/// Whether /v1/ch/sale has been successfully calledpub sale_notified: bool,+ /// Connector error details when the calculation failed; null on success.+ #[serde(default)]+ pub error_details: Option<SurchargeErrorDetails>,}impl ExternalSurchargeDetails {+ /// Whether any connector error details are present.+ pub fn has_error(&self) -> bool {+ self.error_details.is_some()+ }++ /// Connector ID only when a successful calculation can be notified or reused.+ pub fn usable_connector_id(&self) -> Option<&str> {+ match self {+ details+ if !details.has_error()+ && !details.external_surcharge_id.is_empty()+ && details.external_surcharge_id != crate::consts::NO_SURCHARGE_ID_FOUND =>+ {+ Some(details.external_surcharge_id.as_str())+ }+ _ => None,+ }+ }+/// Convert an `f64` surcharge percentage (as produced by the surcharge connector) into the/// `Decimal` representation stored on the attempt. Returns `None` for `None`/non-finite input.pub fn decimal_percentage_from_f64(value: Option<f64>) -> Option<Decimal> {diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rsindex 8b9b7b47dc..1c1ebf8c2d 100644--- a/crates/diesel_models/src/payment_attempt.rs+++ b/crates/diesel_models/src/payment_attempt.rs@@ -674,7 +674,7 @@ pub enum PaymentAttemptUpdate {network_transaction_link_id: Option<String>,is_stored_credential: Option<bool>,request_extended_authorization: Option<RequestExtendedAuthorizationBool>,- external_surcharge_details: Option<common_types::payments::ExternalSurchargeDetails>,+ external_surcharge_details: Option<Box<common_types::payments::ExternalSurchargeDetails>>,applied_offer_details: Option<common_types::payments::AppliedOfferDetails>,applied_overrides: Option<common_types::payments::AppliedOverrides>,active_frm_id: Option<String>,@@ -2818,7 +2818,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {installment_data,encrypted_payment_method_data: None,error_details: None,- external_surcharge_details,+ external_surcharge_details: external_surcharge_details.map(|details| *details),applied_offer_details,applied_overrides,payment_account_reference: None,diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rsindex e7657c1d70..e789752eb7 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs@@ -2569,7 +2569,7 @@ impl PaymentAttemptUpdate {network_transaction_link_id,is_stored_credential,request_extended_authorization,- external_surcharge_details,+ external_surcharge_details: external_surcharge_details.map(Box::new),applied_offer_details,applied_overrides,active_frm_id,diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rsindex 20a35c0a83..c02fd6c13d 100644--- a/crates/hyperswitch_domain_models/src/router_request_types.rs+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs@@ -1338,7 +1338,7 @@ impl}}-/// Surcharge calculated during /eligibility and cached for /confirm to consume.+/// Surcharge result from /eligibility, including connector errors, cached for /confirm./// The payment_method / payment_method_type carried here are the ones the surcharge/// was calculated against; /confirm must match them before applying.#[derive(Clone, Debug, Serialize, Deserialize)]@@ -1349,6 +1349,7 @@ pub struct ExternalSurchargeDetails {pub payment_method_type: Option<common_enums::PaymentMethodType>,pub external_surcharge_id: String,pub surcharge_percentage: Option<f64>,+ pub error_details: Option<common_types::payments::SurchargeErrorDetails>,}impl ExternalSurchargeDetails {diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex ac3752cf9c..45a4612b01 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -820,6 +820,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payments::BacsBankTransferInstructions,api_models::payments::RedirectResponse,api_models::payments::RequestSurchargeDetails,+ api_models::payments::PaymentSurchargeDetailsResponse,api_models::payments::PaymentAttemptResponse,api_models::payments::CaptureResponse,api_models::payments::PaymentsIncrementalAuthorizationRequest,@@ -860,6 +861,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payment_methods::DefaultPaymentMethod,api_models::payment_methods::MaskedBankDetails,api_models::payment_methods::SurchargeDetailsResponse,+ api_models::payment_methods::SurchargeErrorDetails,api_models::payment_methods::SurchargeResponse,api_models::payment_methods::SurchargePercentage,api_models::enums::SurchargeStrategy,diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rsindex 341f9e2c6a..5808a5512a 100644--- a/crates/openapi/src/openapi_v2.rs+++ b/crates/openapi/src/openapi_v2.rs@@ -697,6 +697,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payments::BacsBankTransferInstructions,api_models::payments::RedirectResponse,api_models::payments::RequestSurchargeDetails,+ api_models::payments::PaymentSurchargeDetailsResponse,api_models::payments::PaymentRevenueRecoveryMetadata,api_models::payments::BillingConnectorPaymentDetails,api_models::payments::ApplyPaymentMethodDataRequest,@@ -749,6 +750,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payment_methods::RequiredFieldInfo,api_models::payment_methods::MaskedBankDetails,api_models::payment_methods::SurchargeDetailsResponse,+ api_models::payment_methods::SurchargeErrorDetails,api_models::payment_methods::SurchargeResponse,api_models::payment_methods::SurchargePercentage,api_models::payment_methods::PaymentMethodCollectLinkRequest,diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rsindex a761987612..f4836a12fe 100644--- a/crates/openapi/src/routes/payments.rs+++ b/crates/openapi/src/routes/payments.rs@@ -1327,8 +1327,10 @@ pub fn payments_submit_eligibility_check() {}////// - If eligibility is denied the response will contain `sdk_next_action: deny` and no surcharge details./// - If the merchant has no surcharge connector configured, `surcharge_details` will be `null`.-/// - Surcharge calculation is best-effort: if the external call fails the payment still proceeds-/// with `surcharge_details: null`.+/// - A connector calculation error leaves the payment payable amount unchanged. Its surcharge+/// details contain a zero surcharge and the connector message. The error code is included+/// only when the connector supplies one.+/// - If no calculation is attempted, `surcharge_details` is `null`.#[utoipa::path(post,path = "/payments/{payment_id}/eligibility",diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rsindex e8a671992e..a29cd16d33 100644--- a/crates/router/src/core/payment_link.rs+++ b/crates/router/src/core/payment_link.rs@@ -365,8 +365,10 @@ pub async fn initiate_secure_payment_link_flow(payment_id: common_utils::id_type::PaymentId,request_headers: &header::HeaderMap,) -> RouterResponse<services::PaymentLinkFormData> {- let (payment_link, payment_link_details, payment_link_config) =- form_payment_link_data(&state, processor, merchant_id, payment_id).await?;+ let (payment_link, payment_link_details, payment_link_config) = Box::pin(+ form_payment_link_data(&state, processor, merchant_id, payment_id),+ )+ .await?;validator::validate_secure_payment_link_render_request(request_headers,@@ -472,8 +474,13 @@ pub async fn initiate_payment_link_flow(merchant_id: common_utils::id_type::MerchantId,payment_id: common_utils::id_type::PaymentId,) -> RouterResponse<services::PaymentLinkFormData> {- let (_, payment_details, payment_link_config) =- form_payment_link_data(&state, processor, merchant_id, payment_id).await?;+ let (_, payment_details, payment_link_config) = Box::pin(form_payment_link_data(+ &state,+ processor,+ merchant_id,+ payment_id,+ ))+ .await?;let css_script = get_payment_link_css_script(&payment_link_config)?;let js_script = get_js_script(&payment_details)?;diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 6ec763d108..1bbf54fba6 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -58,6 +58,8 @@ use euclid::backend::inputs as dsl_inputs;use events::EventInfo;use futures::future::join_all;use helpers::{decrypt_paze_token, ApplePayData};+#[cfg(feature = "v1")]+use hyperswitch_domain_models::payments::SurchargeMode;#[cfg(feature = "v2")]use hyperswitch_domain_models::payments::{PaymentAttemptListData, PaymentCancelData, PaymentCaptureData, PaymentConfirmData,@@ -2498,28 +2500,55 @@ wheretodo!()}-// True when the profile uses external surcharge and the attempt hasn't been populated yet-// (retry safety). Gates preload_external_surcharge_for_routing so both CIT and MIT share-// one entry check.#[cfg(feature = "v1")]-fn is_external_surcharge_pending<F, D>(business_profile: &domain::Profile, payment_data: &D) -> bool-where- F: Send + Clone,- D: OperationSessionGetters<F>,-{- payment_data- .get_payment_intent()- .get_surcharge_mode(business_profile)- == Some(domain_payments::SurchargeMode::External)- && payment_data- .get_payment_attempt()- .external_surcharge_details- .is_none()+#[derive(Clone, Copy, Debug)]+enum ExternalSurchargeAction {+ Skip,+ LoadEligibilityResult,+ CalculateInline,}-// Populates payment_attempt.external_surcharge_details before choose_connector so the routing-// DSL can condition on `surcharge_amount`. CIT reads from Redis (cached by /eligibility);-// MIT computes inline via UCS.+#[cfg(feature = "v1")]+impl ExternalSurchargeAction {+ fn from_payment_data<F, D>(business_profile: &domain::Profile, payment_data: &D) -> Self+ where+ F: Send + Clone,+ D: OperationSessionGetters<F>,+ {+ let payment_intent = payment_data.get_payment_intent();+ let is_mit = payment_intent.off_session == Some(true);+ match (payment_intent.get_surcharge_mode(business_profile), is_mit) {+ // CIT always refreshes from eligibility, including when the attempt has details.+ (Some(SurchargeMode::External), false) => Self::LoadEligibilityResult,+ (Some(SurchargeMode::External), true) => {+ if payment_data+ .get_payment_attempt()+ .external_surcharge_details+ .as_ref()+ .and_then(common_types::payments::ExternalSurchargeDetails::usable_connector_id)+ .is_some()+ {+ Self::Skip+ } else {+ Self::CalculateInline+ }+ }+ // Failed eligibility disables the fee but its cached error must still be loaded.+ (None, false)+ if business_profile+ .surcharge_connector_details+ .as_ref()+ .and_then(|details| details.surcharge_connector_id.as_ref())+ .is_some() =>+ {+ Self::LoadEligibilityResult+ }+ _ => Self::Skip,+ }+ }+}++/// Prepare the amount and calculation details before the routing DSL reads the attempt.#[cfg(feature = "v1")]#[instrument(skip_all)]pub async fn populate_external_surcharge_details<F, D>(@@ -2532,44 +2561,72 @@ whereF: Send + Clone,D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync,{- if is_external_surcharge_pending(business_profile, payment_data) {- let is_mit = payment_data.get_payment_intent().off_session == Some(true);-- let external_surcharge_details = if is_mit {+ let action = ExternalSurchargeAction::from_payment_data(business_profile, payment_data);+ let details = match action {+ ExternalSurchargeAction::Skip => return Ok(()),+ ExternalSurchargeAction::LoadEligibilityResult => {+ load_eligibility_surcharge(state, payment_data).await+ }+ ExternalSurchargeAction::CalculateInline => {compute_mit_external_surcharge(state, processor, business_profile, payment_data).await- } else {- resolve_external_surcharge(state, payment_data)- .await- .map(|cached| common_types::payments::ExternalSurchargeDetails {- external_surcharge_id: cached.external_surcharge_id,- external_surcharge_amount: cached.surcharge_amount,- surcharge_percentage:- common_types::payments::ExternalSurchargeDetails::decimal_percentage_from_f64(- cached.surcharge_percentage,- ),- sale_notified: false,- })- };-- if let Some(external_surcharge_details) = external_surcharge_details {- let mut attempt = payment_data.get_payment_attempt().clone();- attempt.net_amount.set_external_surcharge_amount(Some(- external_surcharge_details.external_surcharge_amount,- ));- attempt.external_surcharge_details = Some(external_surcharge_details);- payment_data.set_payment_attempt(attempt);- } else {- logger::debug!(- is_mit,- "external surcharge not populated at pre-routing preload; routing DSL will see 0"- );}+ };++ if details.is_none() {+ logger::debug!(+ ?action,+ "external surcharge not populated at pre-routing preload; routing DSL will see 0"+ );}+ apply_external_surcharge_result(payment_data, details);Ok(())}-// Populates internal surcharge on the payment attempt. External surcharge (both CIT and MIT)-// is owned by preload_external_surcharge_for_routing, which runs before choose_connector.+#[cfg(feature = "v1")]+fn apply_external_surcharge_result<F, D>(+ payment_data: &mut D,+ details: Option<common_types::payments::ExternalSurchargeDetails>,+) where+ F: Send + Clone,+ D: OperationSessionGetters<F> + OperationSessionSetters<F>,+{+ let mut attempt = payment_data.get_payment_attempt().clone();+ attempt+ .net_amount+ .set_external_surcharge_amount(details.as_ref().and_then(|details| {+ details+ .usable_connector_id()+ .map(|_| details.external_surcharge_amount)+ }));+ attempt.external_surcharge_details = match details {+ Some(details) => Some(details),+ // Expired or mismatched quotes must not leave a stale fee on the attempt.+ // Preserve any existing error so the response can still explain the failure.+ None => attempt+ .external_surcharge_details+ .filter(common_types::payments::ExternalSurchargeDetails::has_error),+ };+ payment_data.set_payment_attempt(attempt);+}++#[cfg(feature = "v1")]+fn cached_surcharge_to_attempt_details(+ cached: hyperswitch_domain_models::router_request_types::ExternalSurchargeDetails,+) -> common_types::payments::ExternalSurchargeDetails {+ common_types::payments::ExternalSurchargeDetails {+ external_surcharge_id: cached.external_surcharge_id,+ external_surcharge_amount: cached.surcharge_amount,+ surcharge_percentage:+ common_types::payments::ExternalSurchargeDetails::decimal_percentage_from_f64(+ cached.surcharge_percentage,+ ),+ sale_notified: false,+ error_details: cached.error_details,+ }+}++// Populates internal surcharge on the payment attempt. External surcharge is prepared+// by populate_external_surcharge_details before choose_connector.#[cfg(feature = "v1")]#[instrument(skip_all)]pub async fn populate_surcharge_details<F, D>(@@ -2584,7 +2641,7 @@ whereif payment_data.get_payment_intent().get_surcharge_mode(business_profile)- != Some(domain_payments::SurchargeMode::Internal)+ != Some(SurchargeMode::Internal){return Ok(());}@@ -2655,10 +2712,10 @@ where// CIT external surcharge: read whatever /eligibility cached in Redis, if any.#[cfg(feature = "v1")]-async fn resolve_external_surcharge<F, D>(+async fn load_eligibility_surcharge<F, D>(state: &SessionState,payment_data: &D,-) -> Option<hyperswitch_domain_models::router_request_types::ExternalSurchargeDetails>+) -> Option<common_types::payments::ExternalSurchargeDetails>whereF: Send + Clone,D: OperationSessionGetters<F>,@@ -2670,8 +2727,13 @@ whereexternal.matches_payment_method(payment_attempt.payment_method,payment_attempt.payment_method_type,- )+ ) && (payment_data+ .get_payment_intent()+ .external_surcharge_applicable+ .unwrap_or(false)+ || external.error_details.is_some())})+ .map(cached_surcharge_to_attempt_details)}#[cfg(feature = "v1")]@@ -6797,10 +6859,10 @@ where).await?;- // Internal surcharge only; external surcharge is populated by preload_external_surcharge_for_routing.+ // Internal surcharge only; external surcharge is prepared before connector selection.populate_surcharge_details(state, business_profile, payment_data).await?;- let (pd, tokenization_action) = get_connector_tokenization_action_when_confirm_true(+ let (pd, tokenization_action) = Box::pin(get_connector_tokenization_action_when_confirm_true(state,operation,payment_data,@@ -6809,7 +6871,7 @@ wherebusiness_profile,should_retry_with_pan,feature_config,- )+ )).await?;*payment_data = pd;@@ -15188,8 +15250,9 @@ async fn previous_connector_surcharge_id(Ok(attempt) => attempt.external_surcharge_details.as_ref()- .filter(|surcharge_details| !surcharge_details.sale_notified)- .map(|surcharge_details| surcharge_details.external_surcharge_id.clone()),+ .filter(|details| !details.sale_notified)+ .and_then(|details| details.usable_connector_id())+ .map(ToString::to_string),Err(err) => {logger::warn!(error=?err, "Failed to fetch payment_attempt before surcharge calc; proceeding without previous_id");None@@ -15198,16 +15261,11 @@ async fn previous_connector_surcharge_id(}#[cfg(all(feature = "oltp", feature = "v1"))]-#[allow(clippy::too_many_arguments)]async fn store_external_surcharge_in_redis(state: &SessionState,payment_id: &id_type::PaymentId,merchant_id: &id_type::MerchantId,- surcharge_amount: MinorUnit,- payment_method: common_enums::PaymentMethod,- payment_method_type: Option<common_enums::PaymentMethodType>,- external_surcharge_id: String,- surcharge_percentage: Option<f64>,+ surcharge_details: &hyperswitch_domain_models::router_request_types::ExternalSurchargeDetails,) -> RouterResult<()> {let redis_conn = state.store@@ -15215,19 +15273,10 @@ async fn store_external_surcharge_in_redis(.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to get redis connection for surcharge")?;let redis_key = payment_id.get_external_surcharge_redis_key(merchant_id);- let surcharge_to_store =- hyperswitch_domain_models::router_request_types::ExternalSurchargeDetails {- surcharge_amount,- tax_amount: None,- payment_method,- payment_method_type,- external_surcharge_id,- surcharge_percentage,- };redis_conn.serialize_and_set_key_with_expiry(&redis_key.as_str().into(),- &surcharge_to_store,+ surcharge_details,consts::EXTERNAL_SURCHARGE_TTL,).await@@ -15256,6 +15305,7 @@ fn build_surcharge_response(display_tax_on_surcharge_amount: 0.0,display_total_surcharge_amount: surcharge_f64,surcharge_percentage,+ error_details: None,}}@@ -15284,7 +15334,7 @@ async fn calculate_external_surcharge(}None => None,};- let surcharge_details = match (surcharge_mca, inputs.card_iin.clone(), inputs.currency) {+ let calculation_result = match (surcharge_mca, inputs.card_iin.clone(), inputs.currency) {(Some(surcharge_mca), Some(card_iin), Some(currency)) => {match run_external_surcharge_ucs(state,@@ -15298,64 +15348,94 @@ async fn calculate_external_surcharge().await?{- Some(resp) => {- let surcharge_amount = resp.surcharge_amount;+ Some(Ok(resp)) => {let surcharge_percentage = resp.surcharge_fee_percent.as_ref().map(|percent| percent.get_percentage());- let external_surcharge_id = resp.connector_surcharge_id.clone();- let merchant_id = processor.get_processor_merchant_id();- let storage_scheme = processor.get_storage_scheme();- let key_store = processor.get_key_store().clone();- // Both writes must succeed: without Redis the cached surcharge can't be- // applied on /confirm, and without the flag /confirm wouldn't even try.- store_external_surcharge_in_redis(- state,- payment_id,- &merchant_id,- surcharge_amount,- inputs.payment_method,- inputs.payment_method_type,- external_surcharge_id,- surcharge_percentage,- )- .await- .attach_printable("eligibility: failed to write surcharge to Redis")?;- state- .store- .update_payment_intent(- payment_intent,- storage::PaymentIntentUpdate::ExternalSurchargeApplicableUpdate {- external_surcharge_applicable: true,- updated_by: storage_scheme.inner().to_string(),- },- &key_store,- storage_scheme,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(- "eligibility: failed to set external_surcharge_applicable on payment_intent",- )?;- Some(build_surcharge_response(- surcharge_amount,+ let response = build_surcharge_response(+ resp.surcharge_amount,currency,surcharge_percentage,- ))+ );+ let cached_result =+ hyperswitch_domain_models::router_request_types::ExternalSurchargeDetails {+ surcharge_amount: resp.surcharge_amount,+ tax_amount: None,+ payment_method: inputs.payment_method,+ payment_method_type: inputs.payment_method_type,+ external_surcharge_id: resp.connector_surcharge_id,+ surcharge_percentage,+ // A successful calculation has no connector error details.+ error_details: None,+ };+ Some((cached_result, response, true))+ }+ Some(Err(error)) => {+ let code = (error.code != hyperswitch_interfaces::consts::NO_ERROR_CODE)+ .then(|| error.code.clone());+ let cached_result =+ hyperswitch_domain_models::router_request_types::ExternalSurchargeDetails {+ surcharge_amount: MinorUnit::zero(),+ tax_amount: None,+ payment_method: inputs.payment_method,+ payment_method_type: inputs.payment_method_type,+ external_surcharge_id: error.connector_transaction_id.unwrap_or_else(+ || common_types::consts::NO_SURCHARGE_ID_FOUND.to_string(),+ ),+ surcharge_percentage: None,+ error_details: Some(common_types::payments::SurchargeErrorDetails {+ error_code: code.clone(),+ error_message: Some(error.message.clone()),+ error_reason: error.reason.clone(),+ }),+ };+ let response =+ api_models::payment_methods::SurchargeDetailsResponse::connector_error(+ code,+ error.message,+ error.reason,+ );+ Some((cached_result, response, false))}None => None,}}_ => None,};- Ok(surcharge_details)+ match calculation_result {+ Some((cached_result, response, external_surcharge_applicable)) => {+ let merchant_id = processor.get_processor_merchant_id();+ let storage_scheme = processor.get_storage_scheme();+ // Overwrite any previous success or error before updating the flag.+ // Confirmation consumes this result and persists it on the attempt.+ store_external_surcharge_in_redis(state, payment_id, &merchant_id, &cached_result)+ .await+ .attach_printable("eligibility: failed to write surcharge result to Redis")?;+ state+ .store+ .update_payment_intent(+ payment_intent,+ storage::PaymentIntentUpdate::ExternalSurchargeApplicableUpdate {+ external_surcharge_applicable,+ updated_by: storage_scheme.inner().to_string(),+ },+ processor.get_key_store(),+ storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("eligibility: failed to update external_surcharge_applicable")?;+ Ok(Some(response))+ }+ None => Ok(None),+ }}// Fire the UCS `surcharge_calculate` gRPC for `payment_id` using the given-// surcharge MCA and return the connector's surcharge amount + id. Best-effort:-// any UCS error is swallowed and returned as `Ok(None)` so the caller can-// proceed without a surcharge.+// surcharge MCA and return the connector's surcharge amount + id or error details.+// Failures remain non-blocking, but must reach the caller's surcharge error handling+// so eligibility exposes them and replaces any previous cached quote with the error.#[cfg(all(feature = "oltp", feature = "v1"))]#[allow(clippy::too_many_arguments)]async fn run_external_surcharge_ucs(@@ -15368,7 +15448,12 @@ async fn run_external_surcharge_ucs(currency: storage_enums::Currency,inputs: &SurchargeCalculationInputs,) -> RouterResult<- Option<hyperswitch_domain_models::router_response_types::SurchargeCalculationResponseData>,+ Option<+ Result<+ hyperswitch_domain_models::router_response_types::SurchargeCalculationResponseData,+ hyperswitch_domain_models::router_data::ErrorResponse,+ >,+ >,> {let merchant_id = processor.get_processor_merchant_id();let storage_scheme = processor.get_storage_scheme();@@ -15418,13 +15503,13 @@ async fn run_external_surcharge_ucs(error=?err,"External surcharge calculation failed; proceeding without surcharge");- Ok(None)+ Ok(Some(Err(err.current_context().clone().into())))}}}// MIT /confirm has no prior /eligibility call, so compute surcharge inline.-// Best-effort: any failure returns None and confirm proceeds with the original amount.+// Best-effort: calculation failures retain error details and confirm proceeds with the original amount.#[cfg(feature = "v1")]async fn calculate_mit_external_surcharge(state: &SessionState,@@ -15545,16 +15630,28 @@ async fn calculate_mit_external_surcharge(.await;match ucs_response {- Ok(Some(resp)) => Some(common_types::payments::ExternalSurchargeDetails {+ Ok(Some(Ok(resp))) => Some(common_types::payments::ExternalSurchargeDetails {external_surcharge_id: resp.connector_surcharge_id,external_surcharge_amount: resp.surcharge_amount,- surcharge_percentage:- common_types::payments::ExternalSurchargeDetails::decimal_percentage_from_f64(- resp.surcharge_fee_percent- .as_ref()- .map(|percent| percent.get_percentage()),- ),+ surcharge_percentage: common_types::payments::ExternalSurchargeDetails::decimal_percentage_from_f64(+ resp.surcharge_fee_percent+ .as_ref()+ .map(|percent| percent.get_percentage()),+ ),sale_notified: false,+ error_details: None,+ }),+ Ok(Some(Err(error))) => Some(common_types::payments::ExternalSurchargeDetails {+ external_surcharge_id: error.connector_transaction_id.unwrap_or_else(|| common_types::consts::NO_SURCHARGE_ID_FOUND.to_string()),+ external_surcharge_amount: MinorUnit::zero(),+ surcharge_percentage: None,+ sale_notified: false,+ error_details: Some(common_types::payments::SurchargeErrorDetails {+ error_code: (error.code != hyperswitch_interfaces::consts::NO_ERROR_CODE)+ .then_some(error.code),+ error_message: Some(error.message),+ error_reason: error.reason,+ }),}),Ok(None) => None,Err(err) => {diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rsindex 19c63bb7d6..9c995e87c0 100644--- a/crates/router/src/core/payments/routing.rs+++ b/crates/router/src/core/payments/routing.rs@@ -674,6 +674,7 @@ pub fn make_dsl_input(.payment_attempt.external_surcharge_details.as_ref()+ .filter(|details| details.usable_connector_id().is_some()).map(|details| details.external_surcharge_amount),};diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rsindex afcdda7ac1..8b0383c8c4 100644--- a/crates/router/src/core/payments/transformers.rs+++ b/crates/router/src/core/payments/transformers.rs@@ -8,7 +8,6 @@ use api_models::payments as api_payments;use api_models::payments::RevenueRecoveryGetIntentResponse;use api_models::payments::{Address, CustomerDetails, CustomerDetailsResponse, FrmMessage, NetworkDetails,- RequestSurchargeDetails,};use common_enums::{Currency, MerchantAccountType, RequestIncrementalAuthorization};#[cfg(feature = "v1")]@@ -3971,17 +3970,11 @@ where.attach_printable("Failed to parse the AdditionalPaymentData from payment_attempt.payment_method_data")?;let surcharge_details =- payment_attempt- .net_amount- .get_surcharge_amount()- .map(|surcharge_amount| RequestSurchargeDetails {- surcharge_amount,- tax_amount: payment_attempt.net_amount.get_tax_on_surcharge(),- surcharge_percentage: payment_attempt- .external_surcharge_details- .as_ref()- .and_then(|details| details.surcharge_percentage_as_f64()),- });+ api_models::payments::PaymentSurchargeDetailsResponse::from_surcharge_details(+ payment_attempt.net_amount.get_surcharge_amount(),+ payment_attempt.net_amount.get_tax_on_surcharge(),+ payment_attempt.external_surcharge_details.as_ref(),+ );let merchant_decision = payment_intent.merchant_decision.to_owned();let frm_message = payment_data.get_frm_message().map(FrmMessage::foreign_from);@@ -4805,16 +4798,12 @@ impl ForeignFrom<(DieselPaymentIntent, DieselPaymentAttempt)> for api::PlatformPpartner_merchant_identifier_details: pi.partner_merchant_identifier_details,installment_data: pa.installment_data,sender_payment_instrument_id: pa.sender_payment_instrument_id,- surcharge_details: pa.surcharge_amount.map(|surcharge_amount| {- RequestSurchargeDetails {- surcharge_amount,- tax_amount: pa.tax_amount,- surcharge_percentage: pa- .external_surcharge_details- .as_ref()- .and_then(|details| details.surcharge_percentage_as_f64()),- }- }),+ surcharge_details:+ api_models::payments::PaymentSurchargeDetailsResponse::from_surcharge_details(+ pa.surcharge_amount,+ pa.tax_amount,+ pa.external_surcharge_details.as_ref(),+ ),installment_options: pi.installment_options.map(|options| options.0),}}@@ -5008,16 +4997,11 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Payfeature_metadata: None,reference_id: None,payment_link: None,- surcharge_details: pa.net_amount.get_surcharge_amount().map(|surcharge_amount| {- RequestSurchargeDetails {- surcharge_amount,- tax_amount: pa.net_amount.get_tax_on_surcharge(),- surcharge_percentage: pa- .external_surcharge_details- .as_ref()- .and_then(|details| details.surcharge_percentage_as_f64()),- }- }),+ surcharge_details: api_models::payments::PaymentSurchargeDetailsResponse::from_surcharge_details(+ pa.net_amount.get_surcharge_amount(),+ pa.net_amount.get_tax_on_surcharge(),+ pa.external_surcharge_details.as_ref(),+ ),merchant_decision: None,incremental_authorization_allowed: None,authorization_count: None,diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rsindex a45668c614..c3eb5365c0 100644--- a/crates/router/src/core/payments/types.rs+++ b/crates/router/src/core/payments/types.rs@@ -226,6 +226,7 @@ impl ForeignTryFrom<(&SurchargeDetails, &PaymentAttempt)> for SurchargeDetailsRedisplay_tax_on_surcharge_amount,display_total_surcharge_amount,surcharge_percentage: None,+ error_details: None,})}}diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex ff71c17f35..e55a21177b 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -4816,8 +4816,12 @@ pub async fn call_unified_connector_service_for_surcharge_calculate(payment_id: &id_type::PaymentId,profile_id: &id_type::ProfileId,connector_name: String,-) -> RouterResult<hyperswitch_domain_models::router_response_types::SurchargeCalculationResponseData>-{+) -> RouterResult<+ Result<+ hyperswitch_domain_models::router_response_types::SurchargeCalculationResponseData,+ ErrorResponse,+ >,+> {let ucs_client = get_ucs_client(state)?;let connector_auth_metadata = build_unified_connector_service_auth_metadata(@@ -4878,26 +4882,33 @@ pub async fn call_unified_connector_service_for_surcharge_calculate(let response = ucs_client.surcharge_calculate(surcharge_request, connector_auth_metadata, grpc_headers)- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("UCS surcharge_calculate gRPC call failed")?;+ .await;+ match response {+ Ok(response) => {+ let surcharge_response = Result::<+ hyperswitch_domain_models::router_response_types::SurchargeCalculationResponseData,+ ErrorResponse,+ >::foreign_try_from(response.into_inner())+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse UCS surcharge calculate response")?;- let surcharge_response = Result::<- hyperswitch_domain_models::router_response_types::SurchargeCalculationResponseData,- ErrorResponse,- >::foreign_try_from(response.into_inner())- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to parse UCS surcharge calculate response")?;-- surcharge_response.map_err(|error| {- error_stack::report!(errors::ApiErrorResponse::ExternalConnectorError {- code: error.code,- message: error.message,- connector: connector_name,- status_code: error.status_code,- reason: error.reason,- })- })+ Ok(surcharge_response)+ }+ Err(error) => {+ let error_response = match error.current_context() {+ UnifiedConnectorServiceError::ConnectorError(inner) => inner.as_ref().into(),+ error => {+ let api_error: errors::ApiErrorResponse = error.switch();+ let status_code = api_error.status_code().as_u16();+ ErrorResponse {+ status_code,+ ..api_error.into()+ }+ }+ };+ Ok(Err(error_response))+ }+ }}#[cfg(feature = "v1")]diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rsindex d6a09b2c6c..d5a9aa9456 100644--- a/crates/router/src/core/unified_connector_service/transformers.rs+++ b/crates/router/src/core/unified_connector_service/transformers.rs@@ -10966,38 +10966,45 @@ impl transformers::ForeignTryFrom<payments_grpc::SurchargeServiceCalculateRespon) -> Result<Self, Self::Error> {let status_code = convert_connector_service_status_code(grpc_response.status_code)?;- if let Some(error_info) = grpc_response.error.as_ref() {- return Ok(Err(build_ucs_connector_error_response(+ match grpc_response.error.as_ref() {+ Some(error_info) => Ok(Err(build_ucs_connector_error_response(error_info,status_code,- grpc_response.connector_surcharge_id.clone(),- )));+ grpc_response.connector_surcharge_id.clone().or_else(|| {+ error_info+ .connector_details+ .as_ref()+ .and_then(|details| details.connector_transaction_id.clone())+ }),+ ))),+ None => {+ let surcharge_amount = grpc_response+ .surcharge_amount+ .map(|money| MinorUnit::new(money.minor_amount))+ .unwrap_or_else(MinorUnit::zero);++ let external_surcharge_transaction_id = grpc_response+ .connector_surcharge_id+ .unwrap_or_else(|| common_types::consts::NO_SURCHARGE_ID_FOUND.to_string());++ let surcharge_fee_percent = grpc_response+ .surcharge_percentage+ .map(|percent| {+ types::Percentage::<2>::from_string(percent.to_string())+ .change_context(UnifiedConnectorServiceError::ParsingFailed)+ .attach_printable("Failed to parse surcharge percentage")+ })+ .transpose()?;++ Ok(Ok(SurchargeCalculationResponseData {+ surcharge_amount,+ connector_surcharge_id: external_surcharge_transaction_id,+ surcharge_fee_percent,+ error_code: None,+ error_message: None,+ }))+ }}-- let surcharge_amount = grpc_response- .surcharge_amount- .map(|money| MinorUnit::new(money.minor_amount))- .unwrap_or_else(MinorUnit::zero);-- let external_surcharge_transaction_id =- grpc_response.connector_surcharge_id.unwrap_or_default();-- let surcharge_fee_percent = grpc_response- .surcharge_percentage- .map(|percent| {- types::Percentage::<2>::from_string(percent.to_string())- .change_context(UnifiedConnectorServiceError::ParsingFailed)- .attach_printable("Failed to parse surcharge percentage")- })- .transpose()?;-- Ok(Ok(SurchargeCalculationResponseData {- surcharge_amount,- connector_surcharge_id: external_surcharge_transaction_id,- surcharge_fee_percent,- error_code: None,- error_message: None,- }))}}diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rsindex ce244c2736..97a35b5c6a 100644--- a/crates/router/src/core/webhooks/outgoing.rs+++ b/crates/router/src/core/webhooks/outgoing.rs@@ -829,8 +829,8 @@ async fn update_payment_attempt_from_webhook_response(}};let existing_details = match payment_attempt.external_surcharge_details.clone() {- Some(details) => details,- None => {+ Some(details) if details.usable_connector_id().is_some() => details,+ Some(_) | None => {logger::debug!(attempt_id = %attempt_id,"No external_surcharge_details found; nothing to update"@@ -843,6 +843,7 @@ async fn update_payment_attempt_from_webhook_response(external_surcharge_amount: existing_details.external_surcharge_amount,surcharge_percentage: existing_details.surcharge_percentage,sale_notified: true,+ error_details: existing_details.error_details,};let update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ExternalSurchargeUpdate {external_surcharge_details: updated_details,diff --git a/crates/router/src/core/webhooks/types.rs b/crates/router/src/core/webhooks/types.rsindex 34c8fde03a..83a5672c33 100644--- a/crates/router/src/core/webhooks/types.rs+++ b/crates/router/src/core/webhooks/types.rs@@ -261,10 +261,11 @@ impl WebhookPayload {Ok(payment_attempt.external_surcharge_details.as_ref()- .map(|external_surcharge_details| {+ .filter(|details| details.usable_connector_id().is_some())+ .map(|details| {let feature_specific_data = SurchargeDetails {- surcharge_amount: external_surcharge_details.external_surcharge_amount,- external_surcharge_id: external_surcharge_details.external_surcharge_id.clone(),+ surcharge_amount: details.external_surcharge_amount,+ external_surcharge_id: details.external_surcharge_id.clone(),payment_id: payment_attempt.payment_id.clone(),attempt_id: payment_attempt.attempt_id.clone(),};diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rsindex 10363209bd..29eb649c94 100644--- a/crates/storage_impl/src/redis/cache.rs+++ b/crates/storage_impl/src/redis/cache.rs@@ -946,15 +946,18 @@ where// in-memory hit answers during a redis outage rather than erroring, and concurrent// misses for one key cost a single redis round trip between them.cache- .get_or_populate_in_memory(cache_key, async {- let redis = store- .get_redis_conn()- .change_context(StorageError::RedisError(- RedisError::RedisConnectionError.into(),- ))- .attach_printable("Failed to get redis connection")?;- get_or_populate_redis(&redis, key, redis_ttl, fun).await- })+ .get_or_populate_in_memory(+ cache_key,+ Box::pin(async {+ let redis = store+ .get_redis_conn()+ .change_context(StorageError::RedisError(+ RedisError::RedisConnectionError.into(),+ ))+ .attach_printable("Failed to get redis connection")?;+ Box::pin(get_or_populate_redis(&redis, key, redis_ttl, fun)).await+ }),+ ).await}