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(core): add support for surcharge in eligibility and introduced eligibility_check endpoint (#12401)
Swangi Kumari3b8ae139ca5a
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex 58dcd7f3b9..27bf67e593 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -1664,18 +1664,76 @@]}},+ "/payments/{payment_id}/eligibility_check": {+ "post": {+ "tags": [+ "Payments"+ ],+ "summary": "Payments - Submit Eligibility Check Data",+ "operationId": "Submit Eligibility Check data for a Payment",+ "parameters": [+ {+ "name": "payment_id",+ "in": "path",+ "description": "The identifier for payment",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PaymentsEligibilityCheckRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Eligibility Check submit is successful",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PaymentsEligibilityCheckResponse"+ }+ }+ }+ },+ "400": {+ "description": "Bad Request",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GenericErrorResponseOpenApi"+ }+ }+ }+ }+ },+ "security": [+ {+ "publishable_key": []+ }+ ]+ }+ },"/payments/{payment_id}/eligibility": {"post": {"tags": ["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`.","operationId": "Submit Eligibility data for a Payment","parameters": [{"name": "payment_id","in": "path",- "description": "The identifier for payment",+ "description": "The identifier for the payment","required": true,"schema": {"type": "string"@@ -1694,7 +1752,7 @@},"responses": {"200": {- "description": "Eligibility submit is successful",+ "description": "Eligibility and surcharge checks successful","content": {"application/json": {"schema": {@@ -1712,6 +1770,16 @@}}}+ },+ "404": {+ "description": "Payment not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GenericErrorResponseOpenApi"+ }+ }+ }}},"security": [@@ -30893,6 +30961,14 @@"type": "string","description": "Identification for the profile acquirer to be used for this payment.","nullable": true+ },+ "external_surcharge_strategy": {+ "allOf": [+ {+ "$ref": "#/components/schemas/SurchargeStrategy"+ }+ ],+ "nullable": true}}},@@ -31444,6 +31520,14 @@"type": "string","description": "Identification for the profile acquirer to be used for this payment.","nullable": true+ },+ "external_surcharge_strategy": {+ "allOf": [+ {+ "$ref": "#/components/schemas/SurchargeStrategy"+ }+ ],+ "nullable": true}}},@@ -32270,7 +32354,7 @@}}},- "PaymentsEligibilityRequest": {+ "PaymentsEligibilityCheckRequest": {"type": "object","required": ["client_secret",@@ -32317,8 +32401,73 @@}}},+ "PaymentsEligibilityCheckResponse": {+ "type": "object",+ "required": [+ "payment_id",+ "sdk_next_action"+ ],+ "properties": {+ "payment_id": {+ "type": "string",+ "description": "The identifier for the payment"+ },+ "sdk_next_action": {+ "$ref": "#/components/schemas/SdkNextAction"+ }+ }+ },+ "PaymentsEligibilityRequest": {+ "type": "object",+ "description": "Request body for the eligibility endpoint.\nCombines eligibility checks with external surcharge calculation in a single call.",+ "required": [+ "client_secret",+ "payment_method_type",+ "payment_token"+ ],+ "properties": {+ "client_secret": {+ "type": "string",+ "description": "Token used for client side verification",+ "example": "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo"+ },+ "payment_method_type": {+ "$ref": "#/components/schemas/PaymentMethod"+ },+ "payment_method_subtype": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PaymentMethodType"+ }+ ],+ "nullable": true+ },+ "payment_method_data": {+ "allOf": [+ {+ "$ref": "#/components/schemas/EligibilityPaymentMethodDataRequest"+ }+ ],+ "nullable": true+ },+ "browser_info": {+ "allOf": [+ {+ "$ref": "#/components/schemas/BrowserInformation"+ }+ ],+ "nullable": true+ },+ "payment_token": {+ "type": "string",+ "description": "The payment token to look up the saved payment method",+ "example": "token_abc123xyz"+ }+ }+ },"PaymentsEligibilityResponse": {"type": "object",+ "description": "Response body for the eligibility endpoint.","required": ["payment_id","sdk_next_action"@@ -32330,6 +32479,14 @@},"sdk_next_action": {"$ref": "#/components/schemas/SdkNextAction"+ },+ "surcharge_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/SurchargeDetailsResponse"+ }+ ],+ "nullable": true}}},@@ -33120,6 +33277,14 @@"type": "string","description": "Identification for the profile acquirer to be used for this payment.","nullable": true+ },+ "external_surcharge_strategy": {+ "allOf": [+ {+ "$ref": "#/components/schemas/SurchargeStrategy"+ }+ ],+ "nullable": true}},"additionalProperties": false@@ -34623,6 +34788,14 @@"type": "string","description": "Identification for the profile acquirer to be used for this payment.","nullable": true+ },+ "external_surcharge_strategy": {+ "allOf": [+ {+ "$ref": "#/components/schemas/SurchargeStrategy"+ }+ ],+ "nullable": true}}},@@ -40972,6 +41145,11 @@"properties": {"next_action": {"$ref": "#/components/schemas/NextActionCall"+ },+ "should_block_confirm": {+ "type": "boolean",+ "description": "Whether the SDK should block the confirm call for user.",+ "nullable": true}}},@@ -42288,6 +42466,14 @@"propertyName": "type"}},+ "SurchargeStrategy": {+ "type": "string",+ "description": "Strategy for applying external surcharge",+ "enum": [+ "apply",+ "waive"+ ]+ },"SwishQrData": {"type": "object"},diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex 848c9a3141..ed09f6b50a 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -30229,6 +30229,11 @@"properties": {"next_action": {"$ref": "#/components/schemas/NextActionCall"+ },+ "should_block_confirm": {+ "type": "boolean",+ "description": "Whether the SDK should block the confirm call for user.",+ "nullable": true}}},diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rsindex b17e6d1a0f..a325b93eae 100644--- a/crates/api_models/src/events/payment.rs+++ b/crates/api_models/src/events/payment.rs@@ -190,6 +190,24 @@ impl ApiEventMetric for payments::PaymentsRequest {}}+#[cfg(feature = "v1")]+impl ApiEventMetric for payments::PaymentsEligibilityCheckRequest {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::Payment {+ payment_id: self.payment_id.clone(),+ })+ }+}++#[cfg(feature = "v1")]+impl ApiEventMetric for payments::PaymentsEligibilityCheckResponse {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::Payment {+ payment_id: self.payment_id.clone(),+ })+ }+}+#[cfg(feature = "v1")]impl ApiEventMetric for payments::PaymentsEligibilityRequest {fn get_api_event_type(&self) -> Option<ApiEventsType> {diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex 932359ca12..95bd3a3cfc 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -1596,6 +1596,10 @@ pub struct PaymentsRequest {/// Identification for the profile acquirer to be used for this payment.#[schema(value_type = Option<String>)]pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>,++ /// The strategy to use when applying surcharge for this payment.+ #[schema(value_type = Option<SurchargeStrategy>)]+ pub external_surcharge_strategy: Option<common_enums::SurchargeStrategy>,}#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema, SmithyModel)]@@ -10533,6 +10537,8 @@ pub struct SdkNextAction {/// The type of next action#[smithy(value_type = "NextActionCall")]pub next_action: NextActionCall,+ /// Whether the SDK should block the confirm call for user.+ pub should_block_confirm: Option<bool>,}#[derive(@@ -12542,7 +12548,7 @@ pub struct ClickToPaySessionResponse {#[cfg(feature = "v1")]#[derive(Debug, serde::Deserialize, Clone, ToSchema)]-pub struct PaymentsEligibilityRequest {+pub struct PaymentsEligibilityCheckRequest {/// The identifier for the payment/// Added in the payload for ApiEventMetrics, populated from the path param#[serde(skip)]@@ -12569,7 +12575,7 @@ pub struct PaymentsEligibilityRequest {}#[cfg(feature = "v1")]-impl PaymentsEligibilityRequest {+impl PaymentsEligibilityCheckRequest {/// Validates that either payment_token or payment_method_data is providedpub fn validate_payment_method_input(&self,@@ -12777,6 +12783,61 @@ pub struct EligibilityPaymentMethodDataRequest {pub billing: Option<Address>,}+#[derive(Debug, serde::Serialize, Clone, ToSchema)]+pub struct PaymentsEligibilityCheckResponse {+ /// The identifier for the payment+ #[schema(value_type = String)]+ pub payment_id: id_type::PaymentId,+ /// Next action to be performed by the SDK+ pub sdk_next_action: SdkNextAction,+}++/// Request body for the eligibility endpoint.+/// Combines eligibility checks with external surcharge calculation in a single call.+#[cfg(feature = "v1")]+#[derive(Debug, Clone, serde::Deserialize, ToSchema)]+pub struct PaymentsEligibilityRequest {+ /// The identifier for the payment+ /// Added in the payload for ApiEventMetrics, populated from the path param+ #[serde(skip)]+ pub payment_id: id_type::PaymentId,+ /// Token used for client side verification+ #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")]+ pub client_secret: Option<Secret<String>>,+ /// The payment method to be used for the payment+ #[schema(value_type = PaymentMethod, example = "card")]+ pub payment_method_type: api_enums::PaymentMethod,+ /// The payment method type to be used for the payment+ #[schema(value_type = Option<PaymentMethodType>)]+ pub payment_method_subtype: Option<api_enums::PaymentMethodType>,+ /// The payment instrument data for eligibility check and surcharge BIN lookup+ #[serde(with = "eligibility_payment_method_data_serde", default)]+ pub payment_method_data: Option<EligibilityPaymentMethodDataRequest>,+ /// The browser information for the payment+ #[schema(value_type = Option<BrowserInformation>)]+ pub browser_info: Option<BrowserInformation>,+ /// The payment token to look up the saved payment method+ #[schema(value_type = String, example = "token_abc123xyz")]+ pub payment_token: Option<Secret<String>>,+}++#[cfg(feature = "v1")]+impl From<PaymentsEligibilityRequest> for PaymentsEligibilityCheckRequest {+ fn from(req: PaymentsEligibilityRequest) -> Self {+ Self {+ payment_id: req.payment_id,+ client_secret: req.client_secret,+ payment_method_type: req.payment_method_type,+ payment_method_subtype: req.payment_method_subtype,+ payment_method_data: req.payment_method_data,+ browser_info: req.browser_info,+ payment_token: req.payment_token,+ }+ }+}++/// Response body for the eligibility endpoint.+#[cfg(feature = "v1")]#[derive(Debug, serde::Serialize, Clone, ToSchema)]pub struct PaymentsEligibilityResponse {/// The identifier for the payment@@ -12784,6 +12845,10 @@ pub struct PaymentsEligibilityResponse {pub payment_id: id_type::PaymentId,/// Next action to be performed by the SDKpub sdk_next_action: SdkNextAction,+ /// Surcharge details if an external surcharge was calculated. None if eligibility was denied+ /// or no surcharge connector is configured for this merchant.+ #[schema(value_type = Option<SurchargeDetailsResponse>)]+ pub surcharge_details: Option<payment_methods::SurchargeDetailsResponse>,}#[cfg(feature = "v1")]diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 580c7dc2f3..857f5e7869 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -791,6 +791,32 @@ pub enum ConnectorType {VaultProcessor,}+/// Strategy for applying external surcharge+#[derive(+ Clone,+ Copy,+ Debug,+ Default,+ Eq,+ Hash,+ PartialEq,+ serde::Serialize,+ serde::Deserialize,+ strum::Display,+ strum::EnumString,+ ToSchema,+)]+#[router_derive::diesel_enum(storage_type = "text")]+#[serde(rename_all = "snake_case")]+#[strum(serialize_all = "snake_case")]+pub enum SurchargeStrategy {+ /// Apply the calculated surcharge to the payment (default)+ #[default]+ Apply,+ /// Do not apply the surcharge; return the amount only+ Waive,+}+#[derive(Debug, Eq, PartialEq)]pub enum PaymentAction {PSync,diff --git a/crates/common_utils/src/id_type/payment.rs b/crates/common_utils/src/id_type/payment.rsindex 33cd41102c..759ab4f925 100644--- a/crates/common_utils/src/id_type/payment.rs+++ b/crates/common_utils/src/id_type/payment.rs@@ -54,6 +54,15 @@ impl PaymentId {format!("external_authentication_{}", self.get_string_repr())}+ /// Get the Redis key used to store external surcharge details during eligibility+ pub fn get_external_surcharge_redis_key(&self, merchant_id: &super::MerchantId) -> String {+ format!(+ "{}_{}_external_surcharge_details",+ merchant_id.get_string_repr(),+ self.get_string_repr()+ )+ }+/// Generate a test payment id with prefix test_pub fn generate_test_payment_id_for_sample_data() -> Self {let id = generate_id_with_default_len("test");diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rsindex 5a0e1e5f76..3ee7ebade6 100644--- a/crates/diesel_models/src/payment_attempt.rs+++ b/crates/diesel_models/src/payment_attempt.rs@@ -1252,6 +1252,7 @@ pub struct PaymentAttemptUpdateInternal {pub authorized_amount: Option<MinorUnit>,pub error_details: Option<Option<ErrorDetails>>,pub sender_payment_instrument_id: Option<String>,+ pub external_surcharge_details: Option<common_types::payments::ExternalSurchargeDetails>,}#[cfg(feature = "v1")]@@ -1462,6 +1463,7 @@ impl PaymentAttemptUpdate {error_details,installment_data,sender_payment_instrument_id,+ external_surcharge_details,} = PaymentAttemptUpdateInternal::from(self).populate_derived_fields(&source);PaymentAttempt {amount: amount.unwrap_or(source.amount),@@ -1549,6 +1551,8 @@ impl PaymentAttemptUpdate {error_details: error_details.unwrap_or(source.error_details),sender_payment_instrument_id: sender_payment_instrument_id.or(source.sender_payment_instrument_id),+ external_surcharge_details: external_surcharge_details+ .or(source.external_surcharge_details),..source}}@@ -2918,6 +2922,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {installment_data: None,encrypted_payment_method_data: None,error_details: None,+ external_surcharge_details: None,},PaymentAttemptUpdate::AuthenticationTypeUpdate {authentication_type,@@ -2995,6 +3000,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {encrypted_payment_method_data: None,error_details: None,sender_payment_instrument_id: None,+ external_surcharge_details: None,},PaymentAttemptUpdate::ConfirmUpdate {amount,@@ -3111,6 +3117,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {installment_data,encrypted_payment_method_data: None,error_details: None,+ external_surcharge_details: None,},PaymentAttemptUpdate::VoidUpdate {status,@@ -3189,6 +3196,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {error_details: None,installment_data: None,sender_payment_instrument_id: None,+ external_surcharge_details: None,},PaymentAttemptUpdate::RejectUpdate {status,@@ -3268,6 +3276,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {error_details: None,installment_data: None,sender_payment_instrument_id: None,+ external_surcharge_details: None,},PaymentAttemptUpdate::BlocklistUpdate {status,@@ -3347,6 +3356,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {error_details: None,installment_data: None,sender_payment_instrument_id: None,+ external_surcharge_details: None,},PaymentAttemptUpdate::ConnectorMandateDetailUpdate {connector_mandate_detail,@@ -3425,6 +3435,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {error_details: None,installment_data: None,sender_payment_instrument_id: None,+ external_surcharge_details: None,},PaymentAttemptUpdate::PaymentMethodDetailsUpdate {payment_method_id,@@ -3502,6 +3513,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {error_details: None,installment_data: None,sender_payment_instrument_id: None,+ external_surcharge_details: None,},PaymentAttemptUpdate::ResponseUpdate {status,@@ -3617,6 +3629,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {error_details,installment_data: None,sender_payment_instrument_id,+ external_surcharge_details: None,}}PaymentAttemptUpdate::ErrorUpdate {@@ -3718,6 +3731,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {encrypted_payment_method_data,error_details,sender_payment_instrument_id: None,+ external_surcharge_details: None,}}PaymentAttemptUpdate::StatusUpdate { status, updated_by } => Self {@@ -3793,6 +3807,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {encrypted_payment_method_data: None,error_details: None,sender_payment_instrument_id: None,+ external_surcharge_details: None,},PaymentAttemptUpdate::UpdateTrackers {payment_token,@@ -3878,6 +3893,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {installment_data: None,encrypted_payment_method_data: None,error_details: None,+ external_surcharge_details: None,},PaymentAttemptUpdate::UnresolvedResponseUpdate {status,@@ -3970,6 +3986,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {encrypted_payment_method_data: None,error_details,sender_payment_instrument_id: None,+ external_surcharge_details: None,}}PaymentAttemptUpdate::PreprocessingUpdate {@@ -4059,6 +4076,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {encrypted_payment_method_data: None,error_details: None,sender_payment_instrument_id: None,+ external_surcharge_details: None,}}PaymentAttemptUpdate::CaptureUpdate {@@ -4138,6 +4156,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {encrypted_payment_method_data: None,error_details: None,sender_payment_instrument_id: None,+ external_surcharge_details: None,},PaymentAttemptUpdate::AmountToCaptureUpdate {status,@@ -4216,6 +4235,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {encrypted_payment_method_data: None,error_details: None,sender_payment_instrument_id: None,+ external_surcharge_details: None,},PaymentAttemptUpdate::ConnectorResponse {authentication_data,@@ -4303,6 +4323,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {encrypted_payment_method_data: None,error_details: None,sender_payment_instrument_id: None,+ external_surcharge_details: None,}}PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate {@@ -4381,6 +4402,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {encrypted_payment_method_data: None,error_details: None,sender_payment_instrument_id: None,+ external_surcharge_details: None,},PaymentAttemptUpdate::AuthenticationUpdate {status,@@ -4461,6 +4483,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {encrypted_payment_method_data: None,error_details: None,sender_payment_instrument_id: None,+ external_surcharge_details: None,},PaymentAttemptUpdate::ManualUpdate {status,@@ -4551,6 +4574,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {encrypted_payment_method_data: None,error_details: None,sender_payment_instrument_id: None,+ external_surcharge_details: None,}}PaymentAttemptUpdate::PostSessionTokensUpdate {@@ -4629,6 +4653,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {encrypted_payment_method_data: None,error_details: None,sender_payment_instrument_id: None,+ external_surcharge_details: None,},PaymentAttemptUpdate::RecurrenceUpdate {status,@@ -4710,6 +4735,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {installment_data: None,encrypted_payment_method_data: None,sender_payment_instrument_id: None,+ external_surcharge_details: None,},}}diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rsindex 4f60004bc2..77a8a7fcda 100644--- a/crates/diesel_models/src/payment_intent.rs+++ b/crates/diesel_models/src/payment_intent.rs@@ -89,6 +89,8 @@ pub struct PaymentIntent {pub state_metadata: Option<PaymentIntentStateMetadata>,pub installment_options: Option<common_types::payments::InstallmentOptions>,pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,+ pub external_surcharge_strategy: Option<common_enums::SurchargeStrategy>,+ pub external_surcharge_applicable: Option<bool>,pub merchant_reference_id: Option<common_utils::id_type::PaymentReferenceId>,pub billing_address: Option<Encryption>,pub shipping_address: Option<Encryption>,@@ -201,6 +203,8 @@ pub struct PaymentIntent {pub state_metadata: Option<PaymentIntentStateMetadata>,pub installment_options: Option<common_types::payments::InstallmentOptions>,pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,+ pub external_surcharge_strategy: Option<common_enums::SurchargeStrategy>,+ pub external_surcharge_applicable: Option<bool>,}#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression, PartialEq)]@@ -419,6 +423,8 @@ pub struct PaymentIntentNew {pub state_metadata: Option<PaymentIntentStateMetadata>,pub installment_options: Option<common_types::payments::InstallmentOptions>,pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,+ pub external_surcharge_strategy: Option<common_enums::SurchargeStrategy>,+ pub external_surcharge_applicable: Option<bool>,}#[cfg(feature = "v1")]@@ -511,6 +517,8 @@ pub struct PaymentIntentNew {pub state_metadata: Option<PaymentIntentStateMetadata>,pub installment_options: Option<common_types::payments::InstallmentOptions>,pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,+ pub external_surcharge_strategy: Option<common_enums::SurchargeStrategy>,+ pub external_surcharge_applicable: Option<bool>,}#[cfg(feature = "v2")]@@ -598,6 +606,10 @@ pub enum PaymentIntentUpdate {surcharge_applicable: Option<bool>,updated_by: String,},+ ExternalSurchargeApplicableUpdate {+ external_surcharge_applicable: Option<bool>,+ updated_by: String,+ },IncrementalAuthorizationAmountUpdate {amount: MinorUnit,},@@ -650,6 +662,8 @@ pub struct PaymentIntentUpdateFields {pub is_iframe_redirection_enabled: Option<bool>,pub payment_channel: Option<Option<common_enums::PaymentChannel>>,pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,+ pub external_surcharge_strategy: Option<common_enums::SurchargeStrategy>,+ pub external_surcharge_applicable: Option<bool>,}#[cfg(feature = "v1")]@@ -696,6 +710,8 @@ pub struct PaymentIntentUpdateFields {pub shipping_cost: Option<MinorUnit>,pub installment_options: Option<common_types::payments::InstallmentOptions>,pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,+ pub external_surcharge_strategy: Option<common_enums::SurchargeStrategy>,+ pub external_surcharge_applicable: Option<bool>,}// TODO: uncomment fields as necessary@@ -745,6 +761,8 @@ pub struct PaymentIntentUpdateInternal {pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>,pub state_metadata: Option<PaymentIntentStateMetadata>,pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,+ pub external_surcharge_strategy: Option<common_enums::SurchargeStrategy>,+ pub external_surcharge_applicable: Option<bool>,}#[cfg(feature = "v2")]@@ -793,6 +811,8 @@ impl PaymentIntentUpdateInternal {enable_partial_authorization,state_metadata,profile_acquirer_id,+ external_surcharge_strategy,+ external_surcharge_applicable,} = self;PaymentIntent {@@ -840,6 +860,10 @@ impl PaymentIntentUpdateInternal {request_external_three_ds_authentication: request_external_three_ds_authentication.or(source.request_external_three_ds_authentication),profile_acquirer_id: profile_acquirer_id.or(source.profile_acquirer_id),+ external_surcharge_strategy: external_surcharge_strategy+ .or(source.external_surcharge_strategy),+ external_surcharge_applicable: external_surcharge_applicable+ .or(source.external_surcharge_applicable),updated_by,force_3ds_challenge: force_3ds_challenge.or(source.force_3ds_challenge),is_iframe_redirection_enabled: is_iframe_redirection_enabled@@ -943,6 +967,8 @@ pub struct PaymentIntentUpdateInternal {pub state_metadata: Option<PaymentIntentStateMetadata>,pub installment_options: Option<common_types::payments::InstallmentOptions>,pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,+ pub external_surcharge_strategy: Option<common_enums::SurchargeStrategy>,+ pub external_surcharge_applicable: Option<bool>,}#[cfg(feature = "v1")]@@ -1001,6 +1027,8 @@ impl PaymentIntentUpdate {state_metadata: _,installment_options: _,profile_acquirer_id,+ external_surcharge_strategy,+ external_surcharge_applicable,..} = self.into();PaymentIntent {@@ -1065,6 +1093,10 @@ impl PaymentIntentUpdate {enable_overcapture: enable_overcapture.or(source.enable_overcapture),shipping_cost: shipping_cost.or(source.shipping_cost),profile_acquirer_id: profile_acquirer_id.or(source.profile_acquirer_id),+ external_surcharge_strategy: external_surcharge_strategy+ .or(source.external_surcharge_strategy),+ external_surcharge_applicable: external_surcharge_applicable+ .or(source.external_surcharge_applicable),..source}}@@ -1131,6 +1163,8 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {enable_overcapture: None,shipping_cost: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,},PaymentIntentUpdate::StateMetadataUpdate {state_metadata,@@ -1188,6 +1222,8 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {shipping_cost: None,profile_acquirer_id: None,installment_options: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,},PaymentIntentUpdate::Update(value) => Self {amount: Some(value.amount),@@ -1243,6 +1279,8 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {state_metadata: None,installment_options: value.installment_options,profile_acquirer_id: value.profile_acquirer_id,+ external_surcharge_strategy: value.external_surcharge_strategy,+ external_surcharge_applicable: value.external_surcharge_applicable,},PaymentIntentUpdate::PaymentCreateUpdate {return_url,@@ -1305,6 +1343,8 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {enable_overcapture: None,shipping_cost: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,},PaymentIntentUpdate::PGStatusUpdate {status,@@ -1364,6 +1404,8 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {enable_overcapture: None,shipping_cost: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,},PaymentIntentUpdate::MerchantStatusUpdate {status,@@ -1423,6 +1465,8 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {enable_overcapture: None,shipping_cost: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,},PaymentIntentUpdate::ResponseUpdate {// amount,@@ -1490,6 +1534,8 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {enable_overcapture: None,shipping_cost: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,},PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate {active_attempt_id,@@ -1548,6 +1594,8 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {enable_overcapture: None,shipping_cost: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,},PaymentIntentUpdate::StatusAndAttemptUpdate {status,@@ -1607,6 +1655,8 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {enable_overcapture: None,shipping_cost: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,},PaymentIntentUpdate::ApproveUpdate {status,@@ -1665,6 +1715,8 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {enable_overcapture: None,shipping_cost: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,},PaymentIntentUpdate::RejectUpdate {status,@@ -1723,6 +1775,8 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {enable_overcapture: None,shipping_cost: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,},PaymentIntentUpdate::SurchargeApplicableUpdate {surcharge_applicable,@@ -1780,6 +1834,67 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {enable_overcapture: None,shipping_cost: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,+ },+ PaymentIntentUpdate::ExternalSurchargeApplicableUpdate {+ external_surcharge_applicable,+ updated_by,+ } => Self {+ external_surcharge_applicable,+ updated_by,+ amount: None,+ currency: None,+ status: None,+ amount_captured: None,+ customer_id: None,+ return_url: None,+ setup_future_usage: None,+ off_session: None,+ metadata: None,+ billing_address_id: None,+ shipping_address_id: None,+ modified_at: common_utils::date_time::now(),+ active_attempt_id: None,+ business_country: None,+ business_label: None,+ description: None,+ statement_descriptor_name: None,+ statement_descriptor_suffix: None,+ order_details: None,+ attempt_count: None,+ merchant_decision: None,+ payment_confirm_source: None,+ surcharge_applicable: None,+ incremental_authorization_allowed: None,+ authorization_count: None,+ session_expiry: None,+ fingerprint_id: None,+ request_external_three_ds_authentication: None,+ frm_metadata: None,+ customer_details: None,+ billing_details: None,+ merchant_order_reference_id: None,+ shipping_details: None,+ is_payment_processor_token_flow: None,+ tax_details: None,+ force_3ds_challenge: None,+ is_iframe_redirection_enabled: None,+ extended_return_url: None,+ payment_channel: None,+ feature_metadata: None,+ state_metadata: None,+ installment_options: None,+ tax_status: None,+ discount_amount: None,+ order_date: None,+ shipping_amount_tax: None,+ duty_amount: None,+ enable_partial_authorization: None,+ enable_overcapture: None,+ shipping_cost: None,+ profile_acquirer_id: None,+ external_surcharge_strategy: None,},PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate { amount } => Self {amount: Some(amount),@@ -1834,6 +1949,8 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {enable_overcapture: None,shipping_cost: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,},PaymentIntentUpdate::AuthorizationCountUpdate {authorization_count,@@ -1890,6 +2007,8 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {enable_overcapture: None,shipping_cost: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,},PaymentIntentUpdate::CompleteAuthorizeUpdate {shipping_address_id,@@ -1946,6 +2065,8 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {enable_overcapture: None,shipping_cost: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,},PaymentIntentUpdate::ManualUpdate { status, updated_by } => Self {status,@@ -2000,6 +2121,8 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {enable_overcapture: None,shipping_cost: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,},PaymentIntentUpdate::SessionResponseUpdate {tax_details,@@ -2059,6 +2182,8 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {enable_overcapture: None,shipping_cost: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,},PaymentIntentUpdate::RecurrenceUpdate { status, updated_by } => Self {status: Some(status),@@ -2113,6 +2238,8 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {enable_overcapture: None,shipping_cost: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,},}}diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rsindex bab95c54b0..e9e34c635d 100644--- a/crates/diesel_models/src/schema.rs+++ b/crates/diesel_models/src/schema.rs@@ -1329,6 +1329,9 @@ diesel::table! {installment_options -> Nullable<Jsonb>,#[max_length = 64]profile_acquirer_id -> Nullable<Varchar>,+ #[max_length = 64]+ external_surcharge_strategy -> Nullable<Varchar>,+ external_surcharge_applicable -> Nullable<Bool>,}}diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rsindex 5ce322ae29..5042d49dc4 100644--- a/crates/diesel_models/src/schema_v2.rs+++ b/crates/diesel_models/src/schema_v2.rs@@ -1264,6 +1264,9 @@ diesel::table! {#[max_length = 64]profile_acquirer_id -> Nullable<Varchar>,#[max_length = 64]+ external_surcharge_strategy -> Nullable<Varchar>,+ external_surcharge_applicable -> Nullable<Bool>,+ #[max_length = 64]merchant_reference_id -> Nullable<Varchar>,billing_address -> Nullable<Bytea>,shipping_address -> Nullable<Bytea>,diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rsindex 6ef8509e31..58942bf93f 100644--- a/crates/external_services/src/grpc_client/unified_connector_service.rs+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs@@ -46,6 +46,8 @@ pub struct UnifiedConnectorServiceClient {payments_grpc::payment_method_authentication_service_client::PaymentMethodAuthenticationServiceClient<tonic::transport::Channel>,/// The Payout Service Clientpub payout_service_client: payments_grpc::payout_service_client::PayoutServiceClient<tonic::transport::Channel>,+ /// The Surcharge Service Client+ pub surcharge_service_client: payments_grpc::surcharge_service_client::SurchargeServiceClient<tonic::transport::Channel>,}/// Contains the Unified Connector Service Client config@@ -292,6 +294,15 @@ impl UnifiedConnectorServiceClient {timeout);+ let surcharge_service_client = build_grpc_client!(+ payments_grpc::surcharge_service_client::SurchargeServiceClient<+ tonic::transport::Channel,+ >,+ "surcharge_service_client",+ uri,+ timeout+ );+logger::info!("Successfully connected to Unified Connector Service");Some(Self {@@ -305,6 +316,7 @@ impl UnifiedConnectorServiceClient {merchant_authentication_service_client,payment_method_authentication_service_client,payout_service_client,+ surcharge_service_client,})}None => {@@ -1298,6 +1310,40 @@ impl UnifiedConnectorServiceClient {)})}++ /// Performs surcharge calculation via the Surcharge Service+ pub async fn surcharge_calculate(+ &self,+ surcharge_calculate_request: payments_grpc::SurchargeServiceCalculateRequest,+ connector_auth_metadata: ConnectorAuthMetadata,+ grpc_headers: GrpcHeadersUcs,+ ) -> UnifiedConnectorServiceResult<+ tonic::Response<payments_grpc::SurchargeServiceCalculateResponse>,+ > {+ let mut request = tonic::Request::new(surcharge_calculate_request);++ let connector_name = connector_auth_metadata.connector_name.clone();+ let metadata = build_unified_connector_service_grpc_headers_for_surcharge(+ connector_auth_metadata,+ grpc_headers,+ )?;++ *request.metadata_mut() = metadata;++ self.surcharge_service_client+ .clone()+ .calculate(request)+ .await+ .change_context(UnifiedConnectorServiceError::SurchargeCalculateFailure)+ .inspect_err(|error| {+ logger::error!(+ grpc_error=?error,+ method="surcharge_calculate",+ connector_name=?connector_name,+ "UCS surcharge_calculate gRPC call failed"+ )+ })+ }}/// Build the gRPC Headers for Unified Connector Service Request@@ -1478,3 +1524,34 @@ fn build_grpc_headers_internal(Ok(metadata)}++/// Build gRPC headers for UCS surcharge requests.+/// Same as [`build_unified_connector_service_grpc_headers`] but uses+/// `x-surcharge-connector` instead of `x-connector` for the connector name,+/// since surcharge uses a distinct connector type.+pub fn build_unified_connector_service_grpc_headers_for_surcharge(+ meta: ConnectorAuthMetadata,+ grpc_headers: GrpcHeadersUcs,+) -> Result<MetadataMap, UnifiedConnectorServiceError> {+ let mut metadata = build_unified_connector_service_grpc_headers(meta.clone(), grpc_headers)?;++ metadata.remove(consts::UCS_HEADER_CONNECTOR);++ // Add the surcharge-specific connector header+ let connector_name = meta.connector_name.clone();+ let surcharge_connector_value =+ connector_name+ .parse::<MetadataValue<_>>()+ .map_err(|error| {+ logger::error!(?error);+ UnifiedConnectorServiceError::HeaderInjectionFailed(+ consts::UCS_HEADER_SURCHARGE_CONNECTOR.to_string(),+ )+ })?;+ metadata.append(+ consts::UCS_HEADER_SURCHARGE_CONNECTOR,+ surcharge_connector_value,+ );++ Ok(metadata)+}diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rsindex 4ed5a941ab..7d6f655601 100644--- a/crates/external_services/src/lib.rs+++ b/crates/external_services/src/lib.rs@@ -73,6 +73,9 @@ pub mod consts {/// Header key used to specify the payout connector name in UCS requests.pub(crate) const UCS_HEADER_PAYOUT_CONNECTOR: &str = "x-payout-connector";+ /// Header key used to specify the surcharge connector name in UCS requests.+ pub(crate) const UCS_HEADER_SURCHARGE_CONNECTOR: &str = "x-surcharge-connector";+/// Header key used to indicate the authentication type being used.pub(crate) const UCS_HEADER_AUTH_TYPE: &str = "x-auth";diff --git a/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rsindex 7cab45be3e..c21abcbafd 100644--- a/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs@@ -586,6 +586,7 @@ implsdk_next_action: {SdkNextAction {next_action: NextActionCall::Confirm,+ should_block_confirm: None,}},connector_reference_id: None,diff --git a/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs b/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rsindex 22c600a994..3b0425b62d 100644--- a/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs@@ -1894,6 +1894,7 @@ impldelayed_session_token: false,sdk_next_action: api_models::payments::SdkNextAction {next_action: api_models::payments::NextActionCall::Confirm,+ should_block_confirm: None,},connector_reference_id: None,connector_sdk_public_key: None,@@ -1963,6 +1964,7 @@ implconnector: data.connector.clone(),sdk_next_action: payment_types::SdkNextAction {next_action: payment_types::NextActionCall::Confirm,+ should_block_confirm: None,},},),@@ -1984,6 +1986,7 @@ implsession_token: paypal_sdk_data.data.client_id,sdk_next_action: api_models::payments::SdkNextAction {next_action: api_models::payments::NextActionCall::Confirm,+ should_block_confirm: None,},client_token: Some(res.data.create_client_token.client_token.clone().expose(),diff --git a/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payme/transformers.rsindex 46945f5d32..9e7237f443 100644--- a/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs@@ -679,7 +679,8 @@ impl<F>delayed_session_token: true,sdk_next_action: api_models::payments::SdkNextAction {next_action: api_models::payments::NextActionCall::Sync,- },+ should_block_confirm: None,+},connector_reference_id: Some(item.response.payme_sale_id.to_owned()),connector_sdk_public_key: Some(payme_auth_type.payme_public_key.expose(),@@ -807,7 +808,8 @@ impl<F>delayed_session_token: true,sdk_next_action: api_models::payments::SdkNextAction {next_action: api_models::payments::NextActionCall::Sync,- },+ should_block_confirm: None,+},connector_reference_id: Some(item.response.payme_sale_id.to_owned()),connector_sdk_public_key: Some(payme_auth_type.payme_public_key.expose(),diff --git a/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rsindex 730adb4150..066f4a0379 100644--- a/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs@@ -1564,6 +1564,7 @@ implsession_token: credentials.get_client_id().clone().expose(),sdk_next_action: SdkNextAction {next_action: NextActionCall::PostSessionTokens,+ should_block_confirm: None,},client_token: None,data_user_id_token: response.id_token.clone().map(|id| id.expose()),diff --git a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rsindex ca75f33dc1..0d9d2d15d0 100644--- a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs@@ -1504,6 +1504,7 @@ pub(crate) fn get_apple_pay_session<F, T>(sdk_next_action: {api_models::payments::SdkNextAction {next_action: api_models::payments::NextActionCall::Sync,+ should_block_confirm: None,}},connector_reference_id: None,@@ -1537,6 +1538,7 @@ pub(crate) fn get_google_pay_session<F, T>(sdk_next_action: {api_models::payments::SdkNextAction {next_action: api_models::payments::NextActionCall::Sync,+ should_block_confirm: None,}},merchant_info: google_pay_init_result.merchant_info.into(),diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rsindex 25e8fb9a5e..8d2a4f3c1e 100644--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs@@ -361,6 +361,13 @@ impl EligibilityPaymentMethodData {pub fn is_eligible_for_profile_config_blocklist(&self) -> bool {matches!(self, Self::Card(_))}++ pub fn get_card_iin(&self) -> Option<String> {+ match self {+ Self::Card(card) => Some(card.card_number.get_card_isin()),+ _ => None,+ }+ }}#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)]diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rsindex ec1599a407..016997273a 100644--- a/crates/hyperswitch_domain_models/src/payments.rs+++ b/crates/hyperswitch_domain_models/src/payments.rs@@ -154,6 +154,14 @@ pub struct PaymentIntent {pub state_metadata: Option<common_types::payments::PaymentIntentStateMetadata>,pub installment_options: Option<Vec<common_types::payments::InstallmentOption>>,pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>,+ pub external_surcharge_strategy: Option<common_enums::SurchargeStrategy>,+ pub external_surcharge_applicable: Option<bool>,+}++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum SurchargeMode {+ Internal,+ External,}impl PaymentIntent {@@ -167,6 +175,17 @@ impl PaymentIntent {&self.id}+ #[cfg(feature = "v1")]+ pub fn get_surcharge_mode(&self) -> Option<SurchargeMode> {+ if self.surcharge_applicable.unwrap_or(false) {+ Some(SurchargeMode::Internal)+ } else if self.external_surcharge_applicable.unwrap_or(false) {+ Some(SurchargeMode::External)+ } else {+ None+ }+ }+#[cfg(feature = "v2")]/// This is the url to which the customer will be redirected to, to complete the redirection flowpub fn create_start_redirection_url(@@ -901,6 +920,9 @@ pub struct PaymentIntent {pub is_payment_id_from_merchant: Option<bool>,/// Denotes whether merchant requested for partial authorization to be enabled for this payment.pub enable_partial_authorization: primitive_wrappers::EnablePartialAuthorizationBool,+ /// Denotes the surcharge strategy for this payment.+ pub external_surcharge_strategy: Option<common_enums::SurchargeStrategy>,+ pub external_surcharge_applicable: Option<bool>,}#[cfg(feature = "v2")]@@ -1109,6 +1131,8 @@ impl PaymentIntent {.enable_partial_authorization.unwrap_or(false.into()),profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,})}diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rsindex c71e4e0546..4226c1c60e 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs@@ -222,6 +222,8 @@ pub struct PaymentIntentUpdateFields {pub active_attempt_id_type: Option<common_enums::ActiveAttemptIDType>,pub active_attempts_group_id: Option<id_type::GlobalAttemptGroupId>,pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>,+ pub external_surcharge_strategy: Option<common_enums::SurchargeStrategy>,+ pub external_surcharge_applicable: Option<bool>,}#[cfg(feature = "v1")]@@ -269,6 +271,8 @@ pub struct PaymentIntentUpdateFields {pub shipping_cost: Option<MinorUnit>,pub installment_options: Option<Vec<common_types::payments::InstallmentOption>>,pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>,+ pub external_surcharge_strategy: Option<common_enums::SurchargeStrategy>,+ pub external_surcharge_applicable: Option<bool>,}#[cfg(feature = "v1")]@@ -334,6 +338,10 @@ pub enum PaymentIntentUpdate {surcharge_applicable: bool,updated_by: String,},+ ExternalSurchargeApplicableUpdate {+ external_surcharge_applicable: bool,+ updated_by: String,+ },IncrementalAuthorizationAmountUpdate {amount: MinorUnit,},@@ -494,6 +502,8 @@ pub struct PaymentIntentUpdateInternal {pub state_metadata: Option<common_types::payments::PaymentIntentStateMetadata>,pub installment_options: Option<Vec<common_types::payments::InstallmentOption>>,pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>,+ pub external_surcharge_strategy: Option<common_enums::SurchargeStrategy>,+ pub external_surcharge_applicable: Option<bool>,}// This conversion is used in the `update_payment_intent` function@@ -549,6 +559,8 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalenable_partial_authorization: None,state_metadata: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,}),PaymentIntentUpdate::ConfirmIntentPostUpdate {@@ -599,6 +611,8 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalenable_partial_authorization: None,state_metadata: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,}),PaymentIntentUpdate::SyncUpdate {status,@@ -647,6 +661,8 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalenable_partial_authorization: None,state_metadata: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,}),PaymentIntentUpdate::CaptureUpdate {status,@@ -695,6 +711,8 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalenable_partial_authorization: None,state_metadata: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,}),PaymentIntentUpdate::SessionIntentUpdate {prerouting_algorithm,@@ -746,6 +764,8 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalenable_partial_authorization: None,state_metadata: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,}),PaymentIntentUpdate::UpdateIntent(boxed_intent) => {let PaymentIntentUpdateFields {@@ -787,6 +807,8 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalactive_attempt_id_type,active_attempts_group_id,profile_acquirer_id,+ external_surcharge_strategy,+ external_surcharge_applicable,} = *boxed_intent;Ok(Self {status: None,@@ -837,6 +859,8 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalenable_partial_authorization,state_metadata: None,profile_acquirer_id,+ external_surcharge_strategy,+ external_surcharge_applicable,})}PaymentIntentUpdate::RecordUpdate {@@ -888,6 +912,8 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalenable_partial_authorization: None,state_metadata: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,}),PaymentIntentUpdate::VoidUpdate { status, updated_by } => Ok(Self {status: Some(status),@@ -933,6 +959,8 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalenable_partial_authorization: None,state_metadata: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,}),PaymentIntentUpdate::AttemptGroupUpdate {updated_by,@@ -981,6 +1009,8 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalenable_partial_authorization: None,state_metadata: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,}),PaymentIntentUpdate::SplitPaymentStatusUpdate { status, updated_by } => Ok(Self {status: Some(status),@@ -1025,6 +1055,8 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalenable_partial_authorization: None,state_metadata: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,}),}}@@ -1080,6 +1112,8 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {shipping_amount_tax: value.shipping_amount_tax,duty_amount: value.duty_amount,installment_options: value.installment_options,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,..Default::default()},PaymentIntentUpdate::PaymentCreateUpdate {@@ -1200,6 +1234,14 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {updated_by,..Default::default()},+ PaymentIntentUpdate::ExternalSurchargeApplicableUpdate {+ external_surcharge_applicable,+ updated_by,+ } => Self {+ external_surcharge_applicable: Some(external_surcharge_applicable),+ updated_by,+ ..Default::default()+ },PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate { amount } => Self {amount: Some(amount),..Default::default()@@ -1289,6 +1331,8 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {shipping_cost: None,installment_options: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,},PaymentIntentUpdate::RecurrenceUpdate { status, updated_by } => Self {status: Some(status),@@ -1342,6 +1386,8 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {shipping_cost: None,installment_options: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,},}}@@ -1449,6 +1495,8 @@ impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate {.installment_options.map(common_types::payments::InstallmentOptions),profile_acquirer_id: value.profile_acquirer_id,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,}))}PaymentIntentUpdate::PaymentCreateUpdate {@@ -1535,6 +1583,13 @@ impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate {surcharge_applicable: Some(surcharge_applicable),updated_by,},+ PaymentIntentUpdate::ExternalSurchargeApplicableUpdate {+ external_surcharge_applicable,+ updated_by,+ } => Self::ExternalSurchargeApplicableUpdate {+ external_surcharge_applicable: Some(external_surcharge_applicable),+ updated_by,+ },PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate { amount } => {Self::IncrementalAuthorizationAmountUpdate { amount }}@@ -1625,6 +1680,8 @@ impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateIntstate_metadata,installment_options,profile_acquirer_id,+ external_surcharge_strategy,+ external_surcharge_applicable,} = value;Self {amount,@@ -1680,6 +1737,8 @@ impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateIntinstallment_options: installment_options.map(common_types::payments::InstallmentOptions),profile_acquirer_id,+ external_surcharge_strategy,+ external_surcharge_applicable,}}}@@ -2065,6 +2124,8 @@ impl behaviour::Conversion for PaymentIntent {is_payment_id_from_merchant,enable_partial_authorization,profile_acquirer_id,+ external_surcharge_strategy,+ external_surcharge_applicable,} = self;Ok(DieselPaymentIntent {skip_external_tax_calculation: Some(amount_details.get_external_tax_action_as_bool()),@@ -2177,6 +2238,8 @@ impl behaviour::Conversion for PaymentIntent {state_metadata: None,installment_options: None,profile_acquirer_id,+ external_surcharge_strategy,+ external_surcharge_applicable,})}async fn convert_back(@@ -2331,6 +2394,8 @@ impl behaviour::Conversion for PaymentIntent {.enable_partial_authorization.unwrap_or(false.into()),profile_acquirer_id: storage_model.profile_acquirer_id,+ external_surcharge_strategy: storage_model.external_surcharge_strategy,+ external_surcharge_applicable: storage_model.external_surcharge_applicable,})}.await@@ -2443,6 +2508,8 @@ impl behaviour::Conversion for PaymentIntent {state_metadata: None,installment_options: None,profile_acquirer_id: self.profile_acquirer_id,+ external_surcharge_strategy: self.external_surcharge_strategy,+ external_surcharge_applicable: self.external_surcharge_applicable,})}}@@ -2535,6 +2602,8 @@ impl behaviour::Conversion for PaymentIntent {.installment_options.map(common_types::payments::InstallmentOptions),profile_acquirer_id: self.profile_acquirer_id,+ external_surcharge_strategy: self.external_surcharge_strategy,+ external_surcharge_applicable: self.external_surcharge_applicable,})}@@ -2652,6 +2721,8 @@ impl behaviour::Conversion for PaymentIntent {state_metadata: storage_model.state_metadata,installment_options: storage_model.installment_options.map(|o| o.0),profile_acquirer_id: storage_model.profile_acquirer_id,+ external_surcharge_strategy: storage_model.external_surcharge_strategy,+ external_surcharge_applicable: storage_model.external_surcharge_applicable,})}.await@@ -2742,6 +2813,8 @@ impl behaviour::Conversion for PaymentIntent {.installment_options.map(common_types::payments::InstallmentOptions),profile_acquirer_id: self.profile_acquirer_id,+ external_surcharge_strategy: self.external_surcharge_strategy,+ external_surcharge_applicable: self.external_surcharge_applicable,})}}diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rsindex 46be0ab553..e24e1c6ab6 100644--- a/crates/hyperswitch_domain_models/src/router_request_types.rs+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs@@ -1338,6 +1338,54 @@ impl}}+/// Surcharge calculated during /eligibility and cached for /confirm to consume.+/// 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)]+pub struct ExternalSurchargeDetails {+ pub surcharge_amount: MinorUnit,+ pub tax_amount: Option<MinorUnit>,+ pub payment_method: common_enums::PaymentMethod,+ pub payment_method_type: Option<common_enums::PaymentMethodType>,+}++impl ExternalSurchargeDetails {+ pub fn matches_payment_method(+ &self,+ payment_method: Option<common_enums::PaymentMethod>,+ payment_method_type: Option<common_enums::PaymentMethodType>,+ ) -> bool {+ payment_method == Some(self.payment_method)+ && (self.payment_method_type.is_none()+ || self.payment_method_type == payment_method_type)+ }+}++#[cfg(feature = "v1")]+impl+ From<(+ &ExternalSurchargeDetails,+ &payments::payment_attempt::PaymentAttempt,+ )> for SurchargeDetails+{+ fn from(+ (external_surcharge_details, payment_attempt): (+ &ExternalSurchargeDetails,+ &payments::payment_attempt::PaymentAttempt,+ ),+ ) -> Self {+ let surcharge_amount = external_surcharge_details.surcharge_amount;+ let tax_on_surcharge_amount = external_surcharge_details.tax_amount.unwrap_or_default();+ Self {+ original_amount: payment_attempt.net_amount.get_order_amount(),+ surcharge: common_utils::types::Surcharge::Fixed(surcharge_amount),+ tax_on_surcharge: None,+ surcharge_amount,+ tax_on_surcharge_amount,+ }+ }+}+#[derive(Debug, Clone, Serialize, Deserialize)]pub struct UcsAuthenticationData {pub eci: Option<String>,@@ -1763,17 +1811,8 @@ pub struct PaymentsSurchargeCalculationData {pub previous_connector_surcharge_id: Option<String>,/// Country in ISO alpha-2 format (optional, defaults to USA)pub country: Option<common_enums::CountryAlpha2>,- /// wave strategy for surcharge application (optional, defaults to Apply)- pub surcharge_strategy: Option<SurchargeStrategy>,-}--#[derive(Debug, Default, Clone)]-pub enum SurchargeStrategy {- /// Apply the calculated surcharge to the payment- #[default]- Apply,- /// Do not apply the surcharge, just return the calculated amount- Waive,+ /// Strategy for surcharge application (optional, defaults to Apply)+ pub external_surcharge_strategy: Option<common_enums::SurchargeStrategy>,}#[derive(Debug, Clone)]diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rsindex b23b122e23..8ffa0a7b78 100644--- a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs@@ -218,6 +218,10 @@ pub enum UnifiedConnectorServiceError {/// Failed to perform Payout Enroll Disburse Account from gRPC Server#[error("Failed to perform Payout Enroll Disburse Account from gRPC Server")]PayoutEnrollDisburseAccountFailure,++ /// Failed to perform Surcharge Calculate from gRPC Server+ #[error("Failed to perform Surcharge Calculate from gRPC Server")]+ SurchargeCalculateFailure,}/// Inner data for [`UnifiedConnectorServiceError::ConnectorError`].@@ -1118,6 +1122,7 @@ impl ErrorSwitch<ConnectorError> for UnifiedConnectorServiceError {| Self::PayoutVoidFailure| Self::PayoutStageFailure| Self::PayoutCreateRecipientFailure+ | Self::SurchargeCalculateFailure| Self::PayoutEnrollDisburseAccountFailure => ConnectorError::ResponseHandlingFailed,}}diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex 8072ec1e3c..abc83eb0d2 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -89,6 +89,7 @@ Never share your secret api keys. Keep them guarded and secure.routes::payments::payments_complete_authorize,routes::payments::payments_post_session_tokens,routes::payments::payments_update_metadata,+ routes::payments::payments_submit_eligibility_check,routes::payments::payments_submit_eligibility,// Routes for relay@@ -614,8 +615,8 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payments::EligibilityCard,api_models::payments::EligibilityPaymentMethodData,api_models::payments::EligibilityPaymentMethodDataRequest,- api_models::payments::PaymentsEligibilityRequest,- api_models::payments::PaymentsEligibilityResponse,+ api_models::payments::PaymentsEligibilityCheckRequest,+ api_models::payments::PaymentsEligibilityCheckResponse,api_models::payments::PaymentsCreateResponseOpenApi,api_models::errors::types::GenericErrorResponseOpenApi,api_models::payments::PaymentRetrieveBody,@@ -775,6 +776,9 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payment_methods::SurchargeDetailsResponse,api_models::payment_methods::SurchargeResponse,api_models::payment_methods::SurchargePercentage,+ api_models::enums::SurchargeStrategy,+ api_models::payments::PaymentsEligibilityRequest,+ api_models::payments::PaymentsEligibilityResponse,api_models::payment_methods::PaymentMethodCollectLinkRequest,api_models::payment_methods::PaymentMethodCollectLinkResponse,api_models::payment_methods::CardType,diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rsindex 91d695a544..1c92e7f554 100644--- a/crates/openapi/src/routes/payments.rs+++ b/crates/openapi/src/routes/payments.rs@@ -1032,19 +1032,46 @@ pub fn payments_post_session_tokens() {})]pub fn payments_update_metadata() {}-/// Payments - Submit Eligibility Data+/// Payments - Submit Eligibility Check Data#[utoipa::path(post,- path = "/payments/{payment_id}/eligibility",+ path = "/payments/{payment_id}/eligibility_check",params(("payment_id" = String, Path, description = "The identifier for payment")),- request_body=PaymentsEligibilityRequest,+ request_body=PaymentsEligibilityCheckRequest,responses(- (status = 200, description = "Eligibility submit is successful", body = PaymentsEligibilityResponse),+ (status = 200, description = "Eligibility Check submit is successful", body = PaymentsEligibilityCheckResponse),(status = 400, description = "Bad Request", body = GenericErrorResponseOpenApi)),tag = "Payments",+ operation_id = "Submit Eligibility Check data for a Payment",+ security(("publishable_key" = []))+)]+pub fn payments_submit_eligibility_check() {}++/// Payments - Submit Eligibility Data+///+/// Runs eligibility checks (blocklist, card testing guard) and calculates an external surcharge+/// in a single call. Intended to be called by the SDK before the final confirm step.+///+/// - 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`.+#[utoipa::path(+ post,+ path = "/payments/{payment_id}/eligibility",+ params(+ ("payment_id" = String, Path, description = "The identifier for the payment")+ ),+ request_body = PaymentsEligibilityRequest,+ responses(+ (status = 200, description = "Eligibility and surcharge checks successful", body = PaymentsEligibilityResponse),+ (status = 400, description = "Bad Request", body = GenericErrorResponseOpenApi),+ (status = 404, description = "Payment not found", body = GenericErrorResponseOpenApi)+ ),+ tag = "Payments",operation_id = "Submit Eligibility data for a Payment",security(("publishable_key" = [])))]diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex bbb359188d..b04fa7072e 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -127,6 +127,9 @@ pub const POLL_ID_TTL: i64 = 900;// 15 minutes = 900 secondspub const AUTHENTICATION_ELIGIBILITY_CHECK_DATA_TTL: i64 = 900;+// TTL for external surcharge details stored in Redis (15 minutes)+pub const EXTERNAL_SURCHARGE_TTL: i64 = 900;+// Prefix key for storing authentication eligibility check data in redispub const AUTHENTICATION_ELIGIBILITY_CHECK_DATA_KEY: &str = "AUTH_ELIGIBILITY_CHECK_DATA_";diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex 7d3e222143..ae89f5947b 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -4158,10 +4158,17 @@ pub async fn build_merchant_enabled_pms_context(};// ---- sdk_next_action ----+ let has_surcharge_processor = business_profile+ .surcharge_connector_details+ .as_ref()+ .and_then(|details| details.surcharge_connector_id.as_ref())+ .is_some();+let sdk_next_action = payment_method_utils::get_sdk_next_action_for_payment_method_list(state,&dimensions,payment_intent.and_then(|pi| pi.customer_id.as_ref()),+ has_surcharge_processor,).await;diff --git a/crates/router/src/core/payment_methods/utils.rs b/crates/router/src/core/payment_methods/utils.rsindex 452149314e..3a07e8180b 100644--- a/crates/router/src/core/payment_methods/utils.rs+++ b/crates/router/src/core/payment_methods/utils.rs@@ -871,21 +871,26 @@ pub async fn get_sdk_next_action_for_payment_method_list(state: &SessionState,dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,customer_id: Option<&common_utils::id_type::CustomerId>,+ has_surcharge_processor: bool,) -> api_models::payments::SdkNextAction {- let should_perform_eligibility_check = dimensions+ let should_perform_eligibility = dimensions.get_should_perform_eligibility(state.store.as_ref(),state.superposition_service.as_ref(),customer_id,).await;- let next_action_call = if should_perform_eligibility_check {- api_models::payments::NextActionCall::EligibilityCheck++ if should_perform_eligibility {+ api_models::payments::SdkNextAction {+ next_action: api_models::payments::NextActionCall::EligibilityCheck,+ should_block_confirm: Some(has_surcharge_processor),+ }} else {- api_models::payments::NextActionCall::Confirm- };- api_models::payments::SdkNextAction {- next_action: next_action_call,+ api_models::payments::SdkNextAction {+ next_action: api_models::payments::NextActionCall::Confirm,+ should_block_confirm: Some(false),+ }}}diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 8e417bdfd7..dec0ab3d44 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -101,6 +101,8 @@ use self::{gateway::context as gateway_context,operations::{BoxedOperation, Operation, PaymentResponse},};+#[cfg(all(feature = "oltp", feature = "v1"))]+use super::unified_connector_service::call_unified_connector_service_for_surcharge_calculate;use super::{errors::StorageErrorExt,payment_methods::surcharge_decision_configs,@@ -2257,74 +2259,126 @@ async fn populate_surcharge_details<F>(whereF: Send + Clone,{- if payment_data- .payment_intent- .surcharge_applicable- .unwrap_or(false)- {- logger::debug!("payment_intent.surcharge_applicable = true");- if let Some(surcharge_details) = payment_data.payment_attempt.get_surcharge_details() {- // if retry payment, surcharge would have been populated from the previous attempt. Use the same surcharge+ let surcharge_mode = payment_data.payment_intent.get_surcharge_mode();++ if surcharge_mode == Some(domain_payments::SurchargeMode::Internal) {+ if let Some(attempt_surcharge) = payment_data.payment_attempt.get_surcharge_details() {let surcharge_details =- types::SurchargeDetails::from((&surcharge_details, &payment_data.payment_attempt));+ types::SurchargeDetails::from((&attempt_surcharge, &payment_data.payment_attempt));payment_data.surcharge_details = Some(surcharge_details);return Ok(());}- let raw_card_key = payment_data- .payment_method_data- .as_ref()- .and_then(helpers::get_key_params_for_surcharge_details)- .map(|(payment_method, payment_method_type, card_network)| {- types::SurchargeKey::PaymentMethodData(- payment_method,- payment_method_type,- card_network,- )- });- let saved_card_key = payment_data.token.clone().map(types::SurchargeKey::Token);+ }- let surcharge_key = raw_card_key- .or(saved_card_key)- .get_required_value("payment_method_data or payment_token")?;- logger::debug!(surcharge_key_confirm =? surcharge_key);+ let surcharge_details = match surcharge_mode {+ Some(domain_payments::SurchargeMode::Internal) => {+ resolve_internal_surcharge_from_dss(state, payment_data).await?+ }+ Some(domain_payments::SurchargeMode::External) => {+ load_external_surcharge_from_redis(state, &payment_data.payment_attempt)+ .await+ .filter(|external| {+ external.matches_payment_method(+ payment_data.payment_attempt.payment_method,+ payment_data.payment_attempt.payment_method_type,+ )+ })+ .map(|external| {+ types::SurchargeDetails::from((&external, &payment_data.payment_attempt))+ })+ }+ None => None,+ };- let calculated_surcharge_details =- match types::SurchargeMetadata::get_individual_surcharge_detail_from_redis(- state,- surcharge_key,- &payment_data.payment_attempt.attempt_id,+ payment_data+ .payment_attempt+ .net_amount+ .set_surcharge_details(surcharge_details.clone());+ payment_data.surcharge_details = surcharge_details;+ Ok(())+}++#[cfg(feature = "v1")]+async fn resolve_internal_surcharge_from_dss<F>(+ state: &SessionState,+ payment_data: &PaymentData<F>,+) -> RouterResult<Option<types::SurchargeDetails>>+where+ F: Send + Clone,+{+ logger::debug!("payment_intent.surcharge_applicable = true");+ let raw_card_key = payment_data+ .payment_method_data+ .as_ref()+ .and_then(helpers::get_key_params_for_surcharge_details)+ .map(|(payment_method, payment_method_type, card_network)| {+ types::SurchargeKey::PaymentMethodData(+ payment_method,+ payment_method_type,+ card_network,)- .await- {- Ok(surcharge_details) => Some(surcharge_details),- Err(err) if err.current_context() == &RedisError::NotFound => None,- Err(err) => {- Err(err).change_context(errors::ApiErrorResponse::InternalServerError)?- }- };+ });+ let saved_card_key = payment_data.token.clone().map(types::SurchargeKey::Token);- payment_data.surcharge_details = calculated_surcharge_details.clone();+ let surcharge_key = raw_card_key+ .or(saved_card_key)+ .get_required_value("payment_method_data or payment_token")?;+ logger::debug!(surcharge_key_confirm =? surcharge_key);- //Update payment_attempt net_amount with surcharge details- payment_data- .payment_attempt- .net_amount- .set_surcharge_details(calculated_surcharge_details);- } else {- let surcharge_details =- payment_data- .payment_attempt- .get_surcharge_details()- .map(|surcharge_details| {- logger::debug!("surcharge sent in payments create request");- types::SurchargeDetails::from((- &surcharge_details,- &payment_data.payment_attempt,- ))- });- payment_data.surcharge_details = surcharge_details;+ match types::SurchargeMetadata::get_individual_surcharge_detail_from_redis(+ state,+ surcharge_key,+ &payment_data.payment_attempt.attempt_id,+ )+ .await+ {+ Ok(surcharge_details) => Ok(Some(surcharge_details)),+ Err(err) if err.current_context() == &RedisError::NotFound => Ok(None),+ Err(err) => Err(err).change_context(errors::ApiErrorResponse::InternalServerError),+ }+}++#[cfg(feature = "v1")]+async fn load_external_surcharge_from_redis(+ state: &SessionState,+ payment_attempt: &storage::PaymentAttempt,+) -> Option<hyperswitch_domain_models::router_request_types::ExternalSurchargeDetails> {+ let redis_key = payment_attempt+ .payment_id+ .get_external_surcharge_redis_key(&payment_attempt.merchant_id);+ let redis_conn = match state.store.get_redis_conn() {+ Ok(conn) => conn,+ Err(err) => {+ logger::warn!(error=?err, "Could not get redis conn to fetch external surcharge");+ return None;+ }+ };+ match redis_conn+ .get_and_deserialize_key::<hyperswitch_domain_models::router_request_types::ExternalSurchargeDetails>(+ &redis_key.as_str().into(),+ "ExternalSurchargeDetails",+ )+ .await+ {+ Ok(surcharge) => {+ logger::info!(+ payment_id = %payment_attempt.payment_id.get_string_repr(),+ "Loaded external surcharge from Redis for confirm"+ );+ Some(surcharge)+ }+ Err(err) => {+ if matches!(err.current_context(), RedisError::NotFound) {+ logger::info!(+ payment_id = %payment_attempt.payment_id.get_string_repr(),+ "confirm: no external surcharge found in Redis; proceeding without surcharge"+ );+ } else {+ logger::warn!(error=?err, "Failed to fetch external surcharge from Redis");+ }+ None+ }}- Ok(())}/// Calculates the total installment interest to be added to the order amount.@@ -9292,7 +9346,7 @@ impl PaymentEligibilityData {pub async fn from_request(state: &SessionState,platform: &domain::Platform,- payments_eligibility_request: &api_models::payments::PaymentsEligibilityRequest,+ payments_eligibility_request: &api_models::payments::PaymentsEligibilityCheckRequest,) -> CustomResult<Self, errors::ApiErrorResponse> {payments_eligibility_request.validate_payment_method_input()@@ -12923,6 +12977,7 @@ impl From<CheckResult> for Option<api_models::payments::SdkNextAction> {CheckResult::Allow => None,CheckResult::Deny { message } => Some(api_models::payments::SdkNextAction {next_action: api_models::payments::NextActionCall::Deny { message },+ should_block_confirm: None,}),}}@@ -13104,15 +13159,34 @@ impl EligibilityHandler {false => None,})}++ // Run all eligibility checks in sequence, short-circuiting on the first deny.+ // Returns Confirm if no check denies.+ async fn run_all_eligiblity_checks(+ &self,+ ) -> CustomResult<api_models::payments::SdkNextAction, errors::ApiErrorResponse> {+ let sdk_next_action = self+ .run_check(BlockListCheck)+ .await+ .transpose()+ .async_or_else(|| async { self.run_check(CardTestingCheck).await.transpose() })+ .await+ .transpose()?+ .unwrap_or(api_models::payments::SdkNextAction {+ next_action: api_models::payments::NextActionCall::Confirm,+ should_block_confirm: None,+ });+ Ok(sdk_next_action)+ }}#[cfg(all(feature = "oltp", feature = "v1"))]-pub async fn payments_submit_eligibility(+pub async fn payments_submit_eligibility_check(state: SessionState,platform: domain::Platform,- req: api_models::payments::PaymentsEligibilityRequest,+ req: api_models::payments::PaymentsEligibilityCheckRequest,payment_id: id_type::PaymentId,-) -> RouterResponse<api_models::payments::PaymentsEligibilityResponse> {+) -> RouterResponse<api_models::payments::PaymentsEligibilityCheckResponse> {let payment_eligibility_data = Box::pin(PaymentEligibilityData::from_request(&state, &platform, &req,))@@ -13132,26 +13206,337 @@ pub async fn payments_submit_eligibility(})?;let eligibility_handler =EligibilityHandler::new(state, platform, payment_eligibility_data, business_profile);- // Run the checks in sequence, short-circuiting on the first that returns a next action- let sdk_next_action = eligibility_handler- .run_check(BlockListCheck)+ let sdk_next_action = eligibility_handler.run_all_eligiblity_checks().await?;+ Ok(services::ApplicationResponse::Json(+ api_models::payments::PaymentsEligibilityCheckResponse {+ payment_id,+ sdk_next_action,+ },+ ))+}++#[cfg(all(feature = "oltp", feature = "v1"))]+struct SurchargeCalculationInputs {+ amount: MinorUnit,+ currency: Option<storage_enums::Currency>,+ external_surcharge_strategy: Option<common_enums::SurchargeStrategy>,+ active_attempt_id: String,+ card_iin: Option<String>,+ billing_address: Option<hyperswitch_domain_models::address::Address>,+ payment_method: common_enums::PaymentMethod,+ payment_method_type: Option<common_enums::PaymentMethodType>,+}++#[cfg(all(feature = "oltp", feature = "v1"))]+impl SurchargeCalculationInputs {+ fn from_eligibility_data(+ data: &PaymentEligibilityData,+ req: &api_models::payments::PaymentsEligibilityCheckRequest,+ ) -> Self {+ let pi_billing_address: Option<hyperswitch_domain_models::address::Address> =+ data.payment_intent.billing_details.as_ref().and_then(|b| {+ match b+ .clone()+ .deserialize_inner_value(|value| value.parse_value("Address"))+ {+ Ok(enc) => Some(enc.into_inner()),+ Err(err) => {+ logger::warn!(+ error=?err,+ "eligibility: failed to deserialize payment_intent billing_details; proceeding without PI billing fallback"+ );+ None+ }+ }+ });+ let req_billing_address: Option<hyperswitch_domain_models::address::Address> = req+ .payment_method_data+ .as_ref()+ .and_then(|pmd| pmd.billing.clone())+ .map(Into::into);+ let billing_address = match req_billing_address {+ Some(req_billing) => Some(req_billing.unify_address(pi_billing_address.as_ref())),+ None => pi_billing_address,+ };+ let card_iin = data+ .payment_method_data+ .as_ref()+ .and_then(domain::EligibilityPaymentMethodData::get_card_iin);+ Self {+ amount: data.payment_intent.amount,+ currency: data.payment_intent.currency,+ external_surcharge_strategy: data.payment_intent.external_surcharge_strategy,+ active_attempt_id: data.payment_intent.active_attempt.get_id().clone(),+ card_iin,+ billing_address,+ payment_method: req.payment_method_type,+ payment_method_type: req.payment_method_subtype,+ }+ }+}++#[cfg(all(feature = "oltp", feature = "v1"))]+async fn previous_connector_surcharge_id(+ state: &SessionState,+ payment_id: &id_type::PaymentId,+ merchant_id: &id_type::MerchantId,+ attempt_id: &str,+ storage_scheme: storage_enums::MerchantStorageScheme,+ key_store: &domain::MerchantKeyStore,+) -> Option<String> {+ match state+ .store+ .find_payment_attempt_by_payment_id_processor_merchant_id_attempt_id(+ payment_id,+ merchant_id,+ attempt_id,+ storage_scheme,+ key_store,+ ).await- .transpose()- .async_or_else(|| async {- eligibility_handler- .run_check(CardTestingCheck)+ {+ Ok(attempt) => attempt+ .external_surcharge_details+ .as_ref()+ .filter(|surcharge_details| !surcharge_details.sale_notified)+ .map(|surcharge_details| surcharge_details.external_surcharge_id.clone()),+ Err(err) => {+ logger::warn!(error=?err, "Failed to fetch payment_attempt before surcharge calc; proceeding without previous_id");+ None+ }+ }+}++#[cfg(all(feature = "oltp", feature = "v1"))]+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>,+) -> RouterResult<()> {+ let redis_conn = state+ .store+ .get_redis_conn()+ .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,+ };+ redis_conn+ .serialize_and_set_key_with_expiry(+ &redis_key.as_str().into(),+ &surcharge_to_store,+ consts::EXTERNAL_SURCHARGE_TTL,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to store external surcharge in redis")?;+ logger::info!(+ redis_key = %redis_key,+ "eligibility: stored surcharge in Redis"+ );+ Ok(())+}++#[cfg(all(feature = "oltp", feature = "v1"))]+fn build_surcharge_response(+ surcharge_amount: MinorUnit,+ currency: storage_enums::Currency,+) -> api_models::payment_methods::SurchargeDetailsResponse {+ let surcharge_f64 = currency+ .to_currency_base_unit_asf64(surcharge_amount.get_amount_as_i64())+ .unwrap_or_default();+ api_models::payment_methods::SurchargeDetailsResponse {+ surcharge: api_models::payment_methods::SurchargeResponse::Fixed(surcharge_amount),+ tax_on_surcharge: None,+ display_surcharge_amount: surcharge_f64,+ display_tax_on_surcharge_amount: 0.0,+ display_total_surcharge_amount: surcharge_f64,+ }+}++#[cfg(all(feature = "oltp", feature = "v1"))]+async fn calculate_external_surcharge(+ state: &SessionState,+ platform: &domain::Platform,+ payment_id: &id_type::PaymentId,+ profile_id: &id_type::ProfileId,+ surcharge_connector_id: Option<id_type::MerchantConnectorAccountId>,+ payment_intent: storage::PaymentIntent,+ inputs: SurchargeCalculationInputs,+) -> RouterResult<Option<api_models::payment_methods::SurchargeDetailsResponse>> {+ let surcharge_details = match (surcharge_connector_id, inputs.card_iin, inputs.currency) {+ (Some(surcharge_connector_id), Some(card_iin), Some(currency)) => {+ let processor = platform.get_processor();+ let merchant_id = processor.get_account().get_id().clone();+ let storage_scheme = processor.get_account().storage_scheme;+ let key_store = processor.get_key_store().clone();++ let surcharge_mca = state+ .store+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(+ &merchant_id,+ &surcharge_connector_id,+ &key_store,+ ).await- .transpose()- })+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to fetch SurchargeProcessor MCA by id")?;++ let previous_connector_surcharge_id = previous_connector_surcharge_id(+ state,+ payment_id,+ &merchant_id,+ &inputs.active_attempt_id,+ storage_scheme,+ &key_store,+ )+ .await;++ let billing_details = inputs+ .billing_address+ .as_ref()+ .and_then(|addr| addr.address.as_ref());+ let surcharge_data =+ hyperswitch_domain_models::router_request_types::PaymentsSurchargeCalculationData {+ amount: inputs.amount,+ currency,+ postal_code: billing_details.and_then(|det| det.zip.clone()),+ card_iin,+ previous_connector_surcharge_id,+ country: billing_details.and_then(|det| det.country),+ external_surcharge_strategy: inputs.external_surcharge_strategy,+ };+ let connector_name = surcharge_mca.connector_name.clone();+ let mca_type = helpers::MerchantConnectorAccountType::DbVal(Box::new(surcharge_mca));++ match call_unified_connector_service_for_surcharge_calculate(+ state,+ processor,+ mca_type,+ surcharge_data,+ payment_id,+ profile_id,+ connector_name,+ )+ .await+ {+ Ok(resp) => {+ let surcharge_amount = resp.surcharge_amount;+ // 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,+ )+ .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.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, currency))+ }+ Err(err) => {+ logger::warn!(error=?err, "Surcharge calculation failed; proceeding without surcharge");+ None+ }+ }+ }+ _ => None,+ };+ Ok(surcharge_details)+}++#[cfg(all(feature = "oltp", feature = "v1"))]+pub async fn payments_submit_eligibility(+ state: SessionState,+ platform: domain::Platform,+ req: api_models::payments::PaymentsEligibilityRequest,+ payment_id: id_type::PaymentId,+) -> RouterResponse<api_models::payments::PaymentsEligibilityResponse> {+ let eligibility_req: api_models::payments::PaymentsEligibilityCheckRequest = req.into();+ let payment_eligibility_data = Box::pin(PaymentEligibilityData::from_request(+ &state,+ &platform,+ &eligibility_req,+ ))+ .await?;+ let profile_id = payment_eligibility_data+ .payment_intent+ .profile_id+ .clone()+ .ok_or(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("'profile_id' not set in payment intent")?;+ let business_profile = state+ .store+ .find_business_profile_by_profile_id(platform.get_processor().get_key_store(), &profile_id).await- .transpose()?- .unwrap_or(api_models::payments::SdkNextAction {- next_action: api_models::payments::NextActionCall::Confirm,- });+ .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {+ id: profile_id.get_string_repr().to_owned(),+ })?;++ // Capture surcharge inputs and clone state/platform before the handler takes ownership.+ let surcharge_inputs = SurchargeCalculationInputs::from_eligibility_data(+ &payment_eligibility_data,+ &eligibility_req,+ );+ let surcharge_connector_id = business_profile+ .surcharge_connector_details+ .as_ref()+ .and_then(|details| details.surcharge_connector_id.clone());+ let payment_intent_for_surcharge = payment_eligibility_data.payment_intent.clone();+ let state_for_surcharge = state.clone();+ let platform_for_surcharge = platform.clone();++ let eligibility_handler =+ EligibilityHandler::new(state, platform, payment_eligibility_data, business_profile);+ let sdk_next_action = eligibility_handler.run_all_eligiblity_checks().await?;++ let surcharge_details = match sdk_next_action.next_action {+ api_models::payments::NextActionCall::Deny { .. } => None,+ _ => {+ calculate_external_surcharge(+ &state_for_surcharge,+ &platform_for_surcharge,+ &payment_id,+ &profile_id,+ surcharge_connector_id,+ payment_intent_for_surcharge,+ surcharge_inputs,+ )+ .await?+ }+ };+Ok(services::ApplicationResponse::Json(api_models::payments::PaymentsEligibilityResponse {payment_id,sdk_next_action,+ surcharge_details,},))}diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rsindex a8f11e0627..02aa52a127 100644--- a/crates/router/src/core/payments/flows/session_flow.rs+++ b/crates/router/src/core/payments/flows/session_flow.rs@@ -949,7 +949,12 @@ fn create_apple_pay_session_response(payment_request_data: apple_pay_payment_request,connector: connector_name,delayed_session_token: delayed_response,- sdk_next_action: { payment_types::SdkNextAction { next_action } },+ sdk_next_action: {+ payment_types::SdkNextAction {+ next_action,+ should_block_confirm: None,+ }+ },connector_reference_id: None,connector_sdk_public_key: None,connector_merchant_id: None,@@ -981,7 +986,12 @@ fn create_apple_pay_session_response(payment_request_data: apple_pay_payment_request,connector: connector_name,delayed_session_token: delayed_response,- sdk_next_action: { payment_types::SdkNextAction { next_action } },+ sdk_next_action: {+ payment_types::SdkNextAction {+ next_action,+ should_block_confirm: None,+ }+ },connector_reference_id: None,connector_sdk_public_key: None,connector_merchant_id: None,@@ -1033,6 +1043,7 @@ fn create_gpay_session_token(connector: connector.connector_name.to_string(),sdk_next_action: payment_types::SdkNextAction {next_action: payment_types::NextActionCall::Confirm,+ should_block_confirm: None,},},),@@ -1124,6 +1135,7 @@ fn create_gpay_session_token(connector: connector.connector_name.to_string(),sdk_next_action: payment_types::SdkNextAction {next_action: payment_types::NextActionCall::Confirm,+ should_block_confirm: None,},delayed_session_token: false,secrets: None,@@ -1225,6 +1237,7 @@ fn create_gpay_session_token(connector: connector.connector_name.to_string(),sdk_next_action: payment_types::SdkNextAction {next_action: payment_types::NextActionCall::Confirm,+ should_block_confirm: None,},delayed_session_token: false,secrets: None,@@ -1400,6 +1413,7 @@ fn create_paypal_sdk_session_token(session_token: paypal_sdk_data.data.client_id,sdk_next_action: payment_types::SdkNextAction {next_action: payment_types::NextActionCall::PostSessionTokens,+ should_block_confirm: None,},data_user_id_token: None,client_token: None,diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 39f74495c6..83e7bc9b24 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -4696,6 +4696,8 @@ mod tests {state_metadata: None,installment_options: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,};let req_cs = Some("1".to_string());assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_ok());@@ -4788,6 +4790,8 @@ mod tests {state_metadata: None,installment_options: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,};let req_cs = Some("1".to_string());assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent,).is_err())@@ -4878,6 +4882,8 @@ mod tests {state_metadata: None,installment_options: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,};let req_cs = Some("1".to_string());assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_err())diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex 66f2569baf..88e6c90ffb 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -2823,6 +2823,12 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for.payment_intent.profile_acquirer_id.clone(),+ external_surcharge_strategy: payment_data+ .payment_intent+ .external_surcharge_strategy,+ external_surcharge_applicable: payment_data+ .payment_intent+ .external_surcharge_applicable,})),&m_key_store,storage_scheme,diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rsindex cfeddc3eea..8bd78aa037 100644--- a/crates/router/src/core/payments/operations/payment_create.rs+++ b/crates/router/src/core/payments/operations/payment_create.rs@@ -1981,6 +1981,8 @@ impl PaymentCreate {state_metadata: None,installment_options: request.installment_options.clone(),profile_acquirer_id: request.profile_acquirer_id.clone(),+ external_surcharge_strategy: request.external_surcharge_strategy,+ external_surcharge_applicable: None,})}}diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rsindex 2138024810..0a9e108c02 100644--- a/crates/router/src/core/payments/operations/payment_update.rs+++ b/crates/router/src/core/payments/operations/payment_update.rs@@ -1113,6 +1113,12 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> forshipping_cost,installment_options: payment_data.payment_intent.installment_options.clone(),profile_acquirer_id: payment_data.payment_intent.profile_acquirer_id.clone(),+ external_surcharge_strategy: payment_data+ .payment_intent+ .external_surcharge_strategy,+ external_surcharge_applicable: payment_data+ .payment_intent+ .external_surcharge_applicable,})),key_store,storage_scheme,diff --git a/crates/router/src/core/payments/operations/payment_update_intent.rs b/crates/router/src/core/payments/operations/payment_update_intent.rsindex c3a5e34824..eab8dedca6 100644--- a/crates/router/src/core/payments/operations/payment_update_intent.rs+++ b/crates/router/src/core/payments/operations/payment_update_intent.rs@@ -398,6 +398,8 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentIntentData<F>, PaymentsUpdateInactive_attempts_group_id: intent.active_attempts_group_id,active_attempt_id_type: Some(intent.active_attempt_id_type),profile_acquirer_id: intent.profile_acquirer_id,+ external_surcharge_strategy: intent.external_surcharge_strategy,+ external_surcharge_applicable: intent.external_surcharge_applicable,}));let new_payment_intent = dbdiff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex 1d6a1ac9dd..147480d54f 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -3229,3 +3229,89 @@ pub async fn call_unified_connector_service_for_refund_sync(.await.map(|(router_data, _flow_response)| router_data)}++/// Execute a surcharge calculation call via UCS SurchargeService.Calculate.+///+/// This is a lightweight helper — it does not go through the full RouterData+/// machinery. It is called from `payments_submit_eligibility` after eligibility+/// checks pass.+#[cfg(all(feature = "oltp", feature = "v1"))]+#[instrument(skip_all, fields(connector_name))]+pub async fn call_unified_connector_service_for_surcharge_calculate(+ state: &SessionState,+ processor: &Processor,+ #[cfg(feature = "v1")] merchant_connector_account: MerchantConnectorAccountType,+ payments_surcharge_calculate_data: hyperswitch_domain_models::router_request_types::PaymentsSurchargeCalculationData,+ payment_id: &id_type::PaymentId,+ profile_id: &id_type::ProfileId,+ connector_name: String,+) -> RouterResult<hyperswitch_domain_models::router_response_types::SurchargeCalculationResponseData>+{+ let ucs_client = get_ucs_client(state)?;++ let connector_auth_metadata = build_unified_connector_service_auth_metadata(+ merchant_connector_account,+ processor,+ connector_name.clone(),+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to build UCS auth metadata for surcharge calculate")?;++ // Build the gRPC request directly+ let amount = payments_grpc::Money {+ minor_amount: payments_surcharge_calculate_data.amount.get_amount_as_i64(),+ currency: payments_grpc::Currency::foreign_try_from(+ payments_surcharge_calculate_data.currency,+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to convert currency for surcharge gRPC request")?+ .into(),+ };+ let surcharge_request = payments_grpc::SurchargeServiceCalculateRequest {+ merchant_surcharge_id: Some(payment_id.get_string_repr().to_owned()),+ amount: Some(amount),+ card_bin: payments_surcharge_calculate_data.card_iin.clone(),+ postal_code: payments_surcharge_calculate_data.postal_code.clone(),+ previous_connector_surcharge_id: payments_surcharge_calculate_data+ .previous_connector_surcharge_id+ .clone(),+ country: payments_surcharge_calculate_data+ .country+ .as_ref()+ .and_then(|c| payments_grpc::CountryAlpha2::from_str_name(&c.to_string()))+ .map(|c| c.into()),+ surcharge_strategy: payments_surcharge_calculate_data+ .external_surcharge_strategy+ .as_ref()+ .map(|s| payments_grpc::SurchargeStrategy::foreign_from(*s).into()),+ };++ // Build gRPC headers+ let lineage_ids = LineageIds::new(processor.get_account().get_id().clone(), profile_id.clone());+ let merchant_reference_id = id_type::PaymentReferenceId::from_str(payment_id.get_string_repr())+ .inspect_err(+ |err| logger::warn!(error=?err, "Invalid PaymentId for surcharge UCS reference id"),+ )+ .ok()+ .map(ucs_types::UcsReferenceId::Payment);++ let grpc_header_builder = state+ .get_grpc_headers_ucs(ExecutionMode::Primary)+ .lineage_ids(lineage_ids)+ .external_vault_proxy_metadata(None)+ .merchant_reference_id(merchant_reference_id)+ .resource_id(None);+ let grpc_headers = grpc_header_builder.build();++ 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")?;++ hyperswitch_domain_models::router_response_types::SurchargeCalculationResponseData::foreign_try_from(+ response.into_inner(),+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse UCS surcharge calculate response")+}diff --git a/crates/router/src/core/unified_connector_service/connector_config.rs b/crates/router/src/core/unified_connector_service/connector_config.rsindex 1a150211a1..63579b0a11 100644--- a/crates/router/src/core/unified_connector_service/connector_config.rs+++ b/crates/router/src/core/unified_connector_service/connector_config.rs@@ -544,6 +544,11 @@ pub enum ConnectorSpecificConfig {api_key: Secret<String>,merchant_id: String,},+ /// InterPayments surcharge connector configuration+ Interpayments {+ api_key: Secret<String>,+ base_url: Option<String>,+ },}impl ForeignTryFrom<(Connector, &ConnectorAuthType, Option<&serde_json::Value>)>@@ -1470,6 +1475,13 @@ impl ForeignTryFrom<(Connector, &ConnectorAuthType, Option<&serde_json::Value>)>}),_ => Err(err("Payconex requires BodyKey auth type")),},+ Connector::Interpayments => match auth {+ ConnectorAuthType::HeaderKey { api_key } => Ok(Self::Interpayments {+ api_key: api_key.clone(),+ base_url: None,+ }),+ _ => Err(err("Interpayments requires HeaderKey auth type")),+ },// --- Unsupported connectors ---_ => Err(error_stack::report!(errors::ApiErrorResponse::InternalServerError)diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rsindex ed985bc2e8..ab2fd628ea 100644--- a/crates/router/src/core/unified_connector_service/transformers.rs+++ b/crates/router/src/core/unified_connector_service/transformers.rs@@ -4813,7 +4813,10 @@ impl transformers::ForeignTryFrom<payments_grpc::SdkNextAction> for SdkNextActiopayments_grpc::SdkNextAction::PostSessionTokens => NextActionCall::PostSessionTokens,};- Ok(Self { next_action })+ Ok(Self {+ next_action,+ should_block_confirm: None,+ })}}@@ -7300,18 +7303,17 @@ impl.map(|country| country.into()),surcharge_strategy: router_data.request- .surcharge_strategy- .clone()+ .external_surcharge_strategy.map(|s| payments_grpc::SurchargeStrategy::foreign_from(s).into()),})}}-impl ForeignFrom<router_request_types::SurchargeStrategy> for payments_grpc::SurchargeStrategy {- fn foreign_from(strategy: router_request_types::SurchargeStrategy) -> Self {+impl ForeignFrom<common_enums::SurchargeStrategy> for payments_grpc::SurchargeStrategy {+ fn foreign_from(strategy: common_enums::SurchargeStrategy) -> Self {match strategy {- router_request_types::SurchargeStrategy::Apply => Self::Apply,- router_request_types::SurchargeStrategy::Waive => Self::Waive,+ common_enums::SurchargeStrategy::Apply => Self::Apply,+ common_enums::SurchargeStrategy::Waive => Self::Waive,}}}diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 5d566f16b7..032d01efd3 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -1011,13 +1011,17 @@ impl Payments {.route(web::post().to(payments::payments_reject)),).service(- web::resource("/{payment_id}/eligibility")- .route(web::post().to(payments::payments_submit_eligibility)),+ web::resource("/{payment_id}/eligibility_check")+ .route(web::post().to(payments::payments_submit_eligibility_check)),).service(web::resource("/{payment_id}/client").route(web::get().to(payment_methods::list_payment_methods_for_payments_client)),)+ .service(+ web::resource("/{payment_id}/eligibility")+ .route(web::post().to(payments::payments_submit_eligibility)),+ ).service(web::resource("/redirect/{payment_id}/{merchant_id}/{attempt_id}").route(web::get().to(payments::payments_start)),diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rsindex fa901ae856..0ca1a6d6f0 100644--- a/crates/router/src/routes/lock_utils.rs+++ b/crates/router/src/routes/lock_utils.rs@@ -188,6 +188,7 @@ impl From<Flow> for ApiIdentifier {| Flow::PaymentsRetrieveUsingMerchantReferenceId| Flow::PaymentAttemptsList| Flow::RecoveryPaymentsCreate+ | Flow::PaymentsSubmitCheckEligibility| Flow::PaymentsSubmitEligibility => Self::Payments,Flow::PayoutsCreate| Flow::PayoutsRetrievediff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rsindex 82562bf5aa..7e659dce0a 100644--- a/crates/router/src/routes/payments.rs+++ b/crates/router/src/routes/payments.rs@@ -2866,6 +2866,53 @@ pub async fn retrieve_extended_card_info(.await}+#[cfg(all(feature = "oltp", feature = "v1"))]+#[instrument(skip_all, fields(flow = ?Flow::PaymentsSubmitCheckEligibility, payment_id))]+pub async fn payments_submit_eligibility_check(+ state: web::Data<app::AppState>,+ http_req: actix_web::HttpRequest,+ json_payload: web::Json<payment_types::PaymentsEligibilityCheckRequest>,+ path: web::Path<common_utils::id_type::PaymentId>,+) -> impl Responder {+ let flow = Flow::PaymentsSubmitCheckEligibility;+ let payment_id = path.into_inner();+ let mut payload = json_payload.into_inner();+ payload.payment_id = payment_id.clone();++ let api_auth = auth::ApiKeyAuth {+ allow_connected_scope_operation: true,+ allow_platform_self_operation: false,+ };++ let (auth_type, _auth_flow) =+ match auth::check_sdk_auth_and_get_auth(http_req.headers(), &payload, api_auth) {+ Ok(auth) => auth,+ Err(err) => return api::log_and_return_error_response(report!(err)),+ };++ Box::pin(api::server_wrap(+ flow,+ state,+ &http_req,+ payment_id,+ |state, auth: auth::AuthenticationData, payment_id, _| {+ let mut payload = payload.clone();+ if let Some(client_secret) = auth.client_secret {+ payload.client_secret = Some(Secret::new(client_secret));+ }+ payments::payments_submit_eligibility_check(+ state,+ auth.platform,+ payload.clone(),+ payment_id,+ )+ },+ &*auth_type,+ api_locking::LockAction::NotApplicable,+ ))+ .await+}+#[cfg(all(feature = "oltp", feature = "v1"))]#[instrument(skip_all, fields(flow = ?Flow::PaymentsSubmitEligibility, payment_id))]pub async fn payments_submit_eligibility(diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rsindex 62bb8390cc..3e08b8bc24 100644--- a/crates/router/src/services/authentication.rs+++ b/crates/router/src/services/authentication.rs@@ -5555,6 +5555,15 @@ impl ClientSecretFetch for payments::PaymentsRequest {}}+#[cfg(feature = "v1")]+impl ClientSecretFetch for payments::PaymentsEligibilityCheckRequest {+ fn get_client_secret(&self) -> Option<&String> {+ self.client_secret+ .as_ref()+ .map(|client_secret| client_secret.peek())+ }+}+#[cfg(feature = "v1")]impl ClientSecretFetch for payments::PaymentsEligibilityRequest {fn get_client_secret(&self) -> Option<&String> {diff --git a/crates/router/src/services/kafka/payment_intent.rs b/crates/router/src/services/kafka/payment_intent.rsindex 4d9785534c..89a87dc199 100644--- a/crates/router/src/services/kafka/payment_intent.rs+++ b/crates/router/src/services/kafka/payment_intent.rs@@ -149,6 +149,7 @@ pub struct KafkaPaymentIntent<'a> {pub payment_link_id: Option<&'a String>,pub updated_by: &'a String,pub surcharge_applicable: Option<bool>,+ pub external_surcharge_applicable: Option<bool>,pub request_incremental_authorization: RequestIncrementalAuthorization,pub split_txns_enabled: common_enums::SplitTxnsEnabled,pub authorization_count: Option<i32>,@@ -247,6 +248,8 @@ impl<'a> KafkaPaymentIntent<'a> {is_payment_id_from_merchant,enable_partial_authorization,profile_acquirer_id: _,+ external_surcharge_strategy: _,+ external_surcharge_applicable: _,} = intent;Self {@@ -280,6 +283,7 @@ impl<'a> KafkaPaymentIntent<'a> {payment_link_id: payment_link_id.as_ref(),updated_by,surcharge_applicable: None,+ external_surcharge_applicable: None,request_incremental_authorization: *request_incremental_authorization,split_txns_enabled: *split_txns_enabled,authorization_count: *authorization_count,diff --git a/crates/router/src/services/kafka/payment_intent_event.rs b/crates/router/src/services/kafka/payment_intent_event.rsindex 5d9dd1fedd..cebc6ce2b6 100644--- a/crates/router/src/services/kafka/payment_intent_event.rs+++ b/crates/router/src/services/kafka/payment_intent_event.rs@@ -102,6 +102,7 @@ pub struct KafkaPaymentIntentEvent<'a> {pub payment_link_id: Option<&'a String>,pub updated_by: &'a String,pub surcharge_applicable: Option<bool>,+ pub external_surcharge_applicable: Option<bool>,pub request_incremental_authorization: RequestIncrementalAuthorization,pub split_txns_enabled: common_enums::SplitTxnsEnabled,pub authorization_count: Option<i32>,@@ -261,6 +262,8 @@ impl<'a> KafkaPaymentIntentEvent<'a> {is_payment_id_from_merchant,enable_partial_authorization,profile_acquirer_id: _,+ external_surcharge_strategy: _,+ external_surcharge_applicable: _,} = intent;Self {@@ -294,6 +297,7 @@ impl<'a> KafkaPaymentIntentEvent<'a> {payment_link_id: payment_link_id.as_ref(),updated_by,surcharge_applicable: None,+ external_surcharge_applicable: None,request_incremental_authorization: *request_incremental_authorization,split_txns_enabled: *split_txns_enabled,authorization_count: *authorization_count,diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rsindex 2e0bc3f8a3..ae9aa30fc4 100644--- a/crates/router/src/types/api/payments.rs+++ b/crates/router/src/types/api/payments.rs@@ -7,7 +7,8 @@ pub use api_models::payments::{#[cfg(feature = "v1")]pub use api_models::payments::{PaymentListFilterConstraints, PaymentListResponse, PaymentListResponseV2, PaymentRetrieveBody,- PaymentRetrieveBodyWithCredentials, PaymentsEligibilityRequest,+ PaymentRetrieveBodyWithCredentials, PaymentsEligibilityCheckRequest,+ PaymentsEligibilityRequest,};pub use api_models::{feature_matrix::{diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rsindex 759cd9d6c6..ebff601c02 100644--- a/crates/router/src/utils/user/sample_data.rs+++ b/crates/router/src/utils/user/sample_data.rs@@ -301,6 +301,8 @@ pub async fn generate_sample_data(state_metadata: None,installment_options: None,profile_acquirer_id: None,+ external_surcharge_strategy: None,+ external_surcharge_applicable: None,};let (connector_transaction_id, processor_transaction_data) =ConnectorTransactionId::form_id_and_data(attempt_id.clone());diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rsindex e1f211e701..893a40ad8d 100644--- a/crates/router_env/src/logger/types.rs+++ b/crates/router_env/src/logger/types.rs@@ -735,7 +735,9 @@ pub enum Flow {RevenueRecoveryRedis,/// Payment Method balance check flowPaymentMethodBalanceCheck,- /// Payments Submit Eligibility flow+ /// Payments Submit Eligibility Check flow+ PaymentsSubmitCheckEligibility,+ /// Payments Submit Eligibility flow (combined eligibility + external surcharge)PaymentsSubmitEligibility,/// Apply payment method data flowApplyPaymentMethodData,diff --git a/migrations/2026-05-19-000001_add_surcharge_processor_in_connector_type/down.sql b/migrations/2026-05-19-000001_add_surcharge_processor_in_connector_type/down.sqlnew file mode 100644index 0000000000..e0ac49d1ec--- /dev/null+++ b/migrations/2026-05-19-000001_add_surcharge_processor_in_connector_type/down.sql@@ -0,0 +1 @@+SELECT 1;diff --git a/migrations/2026-05-19-000001_add_surcharge_processor_in_connector_type/up.sql b/migrations/2026-05-19-000001_add_surcharge_processor_in_connector_type/up.sqlnew file mode 100644index 0000000000..fd781e3ce0--- /dev/null+++ b/migrations/2026-05-19-000001_add_surcharge_processor_in_connector_type/up.sql@@ -0,0 +1,3 @@+-- Your SQL goes here+ALTER TYPE "ConnectorType"+ADD VALUE IF NOT EXISTS 'surcharge_processor';diff --git a/migrations/2026-05-20-000002_add_surcharge_strategy_to_payment_intent/down.sql b/migrations/2026-05-20-000002_add_surcharge_strategy_to_payment_intent/down.sqlnew file mode 100644index 0000000000..0e6a9db599--- /dev/null+++ b/migrations/2026-05-20-000002_add_surcharge_strategy_to_payment_intent/down.sql@@ -0,0 +1,2 @@+-- This file should undo anything in `up.sql`+ALTER TABLE payment_intent DROP COLUMN IF EXISTS external_surcharge_strategy;diff --git a/migrations/2026-05-20-000002_add_surcharge_strategy_to_payment_intent/up.sql b/migrations/2026-05-20-000002_add_surcharge_strategy_to_payment_intent/up.sqlnew file mode 100644index 0000000000..68230f4264--- /dev/null+++ b/migrations/2026-05-20-000002_add_surcharge_strategy_to_payment_intent/up.sql@@ -0,0 +1,2 @@+-- Your SQL goes here+ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS external_surcharge_strategy VARCHAR(64);diff --git a/migrations/2026-06-09-000001_add_external_surcharge_applicable_to_payment_intent/down.sql b/migrations/2026-06-09-000001_add_external_surcharge_applicable_to_payment_intent/down.sqlnew file mode 100644index 0000000000..61ba2f6e3d--- /dev/null+++ b/migrations/2026-06-09-000001_add_external_surcharge_applicable_to_payment_intent/down.sql@@ -0,0 +1,2 @@+-- This file should undo anything in `up.sql`+ALTER TABLE payment_intent DROP COLUMN IF EXISTS external_surcharge_applicable;diff --git a/migrations/2026-06-09-000001_add_external_surcharge_applicable_to_payment_intent/up.sql b/migrations/2026-06-09-000001_add_external_surcharge_applicable_to_payment_intent/up.sqlnew file mode 100644index 0000000000..d08af5d84f--- /dev/null+++ b/migrations/2026-06-09-000001_add_external_surcharge_applicable_to_payment_intent/up.sql@@ -0,0 +1,2 @@+-- Your SQL goes here+ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS external_surcharge_applicable BOOLEAN;