Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(router): add open router integration for debit routing (#7907)
Shankar Singh C140d15bcbd0e
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.jsonindex 76b65a1433..b475142a57 100644--- a/api-reference-v2/openapi_spec.json+++ b/api-reference-v2/openapi_spec.json@@ -7334,7 +7334,11 @@"UnionPay","Interac","RuPay",- "Maestro"+ "Maestro",+ "Star",+ "Pulse",+ "Accel",+ "Nyce"]},"CardNetworkTokenizeRequest": {diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.jsonindex db90936370..c71ee457f5 100644--- a/api-reference/openapi_spec.json+++ b/api-reference/openapi_spec.json@@ -9284,7 +9284,11 @@"UnionPay","Interac","RuPay",- "Maestro"+ "Maestro",+ "Star",+ "Pulse",+ "Accel",+ "Nyce"]},"CardNetworkTokenizeRequest": {diff --git a/config/config.example.toml b/config/config.example.tomlindex 4cfe6a61e3..9f34eea38f 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -441,6 +441,12 @@ braintree = { long_lived_token = false, payment_method = "card" }gocardless = { long_lived_token = true, payment_method = "bank_debit" }billwerk = { long_lived_token = false, payment_method = "card" }+[debit_routing_config] # Debit Routing configs+supported_currencies = "USD" # Supported currencies for debit routing+supported_connectors = "adyen" # Supported connectors for debit routing++[debit_routing_config.connector_supported_debit_networks] # Debit Routing config that contains the supported debit networks for each connector+adyen = "Star,Pulse,Accel,Nyce" # Debit networks supported by adyen connector[temp_locker_enable_config]stripe = { payment_method = "bank_transfer" }diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.tomlindex 7907423091..1a15867e7d 100644--- a/config/deployments/integration_test.toml+++ b/config/deployments/integration_test.toml@@ -590,6 +590,13 @@ eps = { country = "AT", currency = "EUR" }ideal = { country = "NL", currency = "EUR" }przelewy24 = { country = "PL", currency = "PLN,EUR" }+[debit_routing_config]+supported_currencies = "USD"+supported_connectors = "adyen"++[debit_routing_config.connector_supported_debit_networks]+adyen = "Star,Pulse,Accel,Nyce"+[pm_filters.rapyd]apple_pay = { country = "AL,AS,AD,AR,AM,AU,AT,AZ,BH,BE,BM,BA,BR,BG,CA,KH,KY,CL,CO,CR,HR,CY,CZ,DK,DO,EC,SV,EE,FO,FI,FR,GE,DE,GI,GR,GL,GU,GT,GG,HN,HK,HU,IS,IE,IM,IL,IT,JP,KZ,KG,KW,LV,LI,LT,LU,MO,MY,MT,MX,MD,MC,ME,MA,NL,NZ,NI,MK,MP,NO,PA,PY,PR,PE,PL,PT,QA,RO,SM,RS,SG,SK,SI,ZA,ES,SE,CH,TW,TJ,TH,UA,AE,GB,US,UY,VI,VN", currency = "EUR,GBP,ISK,USD" }google_pay = { country = "AM,AT,AU,AZ,BA,BE,BG,BY,CA,CH,CL,CN,CO,CR,CY,CZ,DE,DK,DO,EC,EE,EG,ES,FI,FR,GB,GE,GL,GR,GT,HK,HN,HR,HU,IE,IL,IM,IS,IT,JE,JP,JO,KZ,KW,LA,LI,LT,LU,LV,MA,MC,MD,ME,MO,MN,MT,MX,MY,NC,NL,NO,NZ,OM,PA,PE,PL,PR,PT,QA,RO,RS,SA,SE,SG,SI,SK,SM,SV,TH,TW,UA,US,UY,VA,VN,ZA", currency = "EUR,GBP,ISK,USD" }diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.tomlindex 43f764f4e0..da9ad3daa4 100644--- a/config/deployments/sandbox.toml+++ b/config/deployments/sandbox.toml@@ -172,6 +172,13 @@ base_url = "https://app.hyperswitch.io"force_two_factor_auth = falseforce_cookies = false+[debit_routing_config]+supported_currencies = "USD"+supported_connectors = "adyen"++[debit_routing_config.connector_supported_debit_networks]+adyen = "Star,Pulse,Accel,Nyce"+[frm]enabled = truediff --git a/config/development.toml b/config/development.tomlindex ccf5649951..aeee9151c3 100644--- a/config/development.toml+++ b/config/development.toml@@ -1045,6 +1045,13 @@ payout_analytics_topic = "hyperswitch-payout-events"consolidated_events_topic = "hyperswitch-consolidated-events"authentication_analytics_topic = "hyperswitch-authentication-events"+[debit_routing_config]+supported_currencies = "USD"+supported_connectors = "adyen"++[debit_routing_config.connector_supported_debit_networks]+adyen = "Star,Pulse,Accel,Nyce"+[analytics]source = "sqlx"forex_enabled = falsediff --git a/config/docker_compose.toml b/config/docker_compose.tomlindex 9ac4bb7f35..a82ba8c4a0 100644--- a/config/docker_compose.toml+++ b/config/docker_compose.toml@@ -594,6 +594,12 @@ eps = { country = "DE",currency = "EUR" }apple_pay = { country = "DE",currency = "EUR" }paypal = { country = "DE",currency = "EUR" }+[debit_routing_config]+supported_currencies = "USD"+supported_connectors = "adyen"++[debit_routing_config.connector_supported_debit_networks]+adyen = "Star,Pulse,Accel,Nyce"[pm_filters.nuvei]credit = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" }diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rsindex 1d5bfd5846..87e874f7fa 100644--- a/crates/api_models/src/lib.rs+++ b/crates/api_models/src/lib.rs@@ -23,7 +23,6 @@ pub mod gsm;pub mod health_check;pub mod locker_migration;pub mod mandates;-#[cfg(feature = "dynamic_routing")]pub mod open_router;pub mod organization;pub mod payment_methods;diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rsindex 07af605892..f80623efc6 100644--- a/crates/api_models/src/open_router.rs+++ b/crates/api_models/src/open_router.rs@@ -1,6 +1,6 @@use std::{collections::HashMap, fmt::Debug};-use common_utils::{id_type, types::MinorUnit};+use common_utils::{errors, id_type, types::MinorUnit};pub use euclid::{dssa::types::EuclidAnalysable,frontend::{@@ -10,7 +10,10 @@ pub use euclid::{};use serde::{Deserialize, Serialize};-use crate::enums::{Currency, PaymentMethod};+use crate::{+ enums::{Currency, PaymentMethod},+ payment_methods,+};#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]@@ -27,6 +30,7 @@ pub struct OpenRouterDecideGatewayRequest {pub enum RankingAlgorithm {SrBasedRouting,PlBasedRouting,+ NtwBasedRouting,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -38,7 +42,7 @@ pub struct PaymentInfo {// customerId: Option<ETCu::CustomerId>,// preferredGateway: Option<ETG::Gateway>,pub payment_type: String,- // metadata: Option<String>,+ pub metadata: Option<String>,// internalMetadata: Option<String>,// isEmi: Option<bool>,// emiBank: Option<String>,@@ -48,7 +52,7 @@ pub struct PaymentInfo {// paymentSource: Option<String>,// authType: Option<ETCa::txn_card_info::AuthType>,// cardIssuerBankName: Option<String>,- // cardIsin: Option<String>,+ pub card_isin: Option<String>,// cardType: Option<ETCa::card_type::CardType>,// cardSwitchProvider: Option<Secret<String>>,}@@ -56,6 +60,63 @@ pub struct PaymentInfo {#[derive(Debug, Serialize, Deserialize, PartialEq)]pub struct DecidedGateway {pub gateway_priority_map: Option<HashMap<String, f64>>,+ pub debit_routing_output: Option<DebitRoutingOutput>,+}++#[derive(Debug, Serialize, Deserialize, PartialEq)]+pub struct DebitRoutingOutput {+ pub co_badged_card_networks: Vec<common_enums::CardNetwork>,+ pub issuer_country: common_enums::CountryAlpha2,+ pub is_regulated: bool,+ pub regulated_name: Option<common_enums::RegulatedName>,+ pub card_type: common_enums::CardType,+}++impl From<&DebitRoutingOutput> for payment_methods::CoBadgedCardData {+ fn from(output: &DebitRoutingOutput) -> Self {+ Self {+ co_badged_card_networks: output.co_badged_card_networks.clone(),+ issuer_country_code: output.issuer_country,+ is_regulated: output.is_regulated,+ regulated_name: output.regulated_name.clone(),+ }+ }+}++impl TryFrom<(payment_methods::CoBadgedCardData, String)> for DebitRoutingRequestData {+ type Error = error_stack::Report<errors::ParsingError>;++ fn try_from(+ (output, card_type): (payment_methods::CoBadgedCardData, String),+ ) -> Result<Self, Self::Error> {+ let parsed_card_type = card_type.parse::<common_enums::CardType>().map_err(|_| {+ error_stack::Report::new(errors::ParsingError::EnumParseFailure("CardType"))+ })?;++ Ok(Self {+ co_badged_card_networks: output.co_badged_card_networks,+ issuer_country: output.issuer_country_code,+ is_regulated: output.is_regulated,+ regulated_name: output.regulated_name,+ card_type: parsed_card_type,+ })+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct CoBadgedCardRequest {+ pub merchant_category_code: common_enums::MerchantCategoryCode,+ pub acquirer_country: common_enums::CountryAlpha2,+ pub co_badged_card_data: Option<DebitRoutingRequestData>,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+pub struct DebitRoutingRequestData {+ pub co_badged_card_networks: Vec<common_enums::CardNetwork>,+ pub issuer_country: common_enums::CountryAlpha2,+ pub is_regulated: bool,+ pub regulated_name: Option<common_enums::RegulatedName>,+ pub card_type: common_enums::CardType,}#[derive(Debug, Serialize, Deserialize)]diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex df4074dc00..6e9a174c9f 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -985,6 +985,15 @@ pub struct CardDetailsPaymentMethod {pub card_type: Option<String>,#[serde(default = "saved_in_locker_default")]pub saved_to_locker: bool,+ pub co_badged_card_data: Option<CoBadgedCardData>,+}++#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]+pub struct CoBadgedCardData {+ pub co_badged_card_networks: Vec<api_enums::CardNetwork>,+ pub issuer_country_code: common_enums::CountryAlpha2,+ pub is_regulated: bool,+ pub regulated_name: Option<common_enums::RegulatedName>,}#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]@@ -1313,6 +1322,7 @@ impl From<CardDetail> for CardDetailsPaymentMethod {card_network: item.card_network,card_type: item.card_type.map(|card| card.to_string()),saved_to_locker: true,+ co_badged_card_data: None,}}}@@ -1321,8 +1331,10 @@ impl From<CardDetail> for CardDetailsPaymentMethod {any(feature = "v1", feature = "v2"),not(feature = "payment_methods_v2")))]-impl From<CardDetailFromLocker> for CardDetailsPaymentMethod {- fn from(item: CardDetailFromLocker) -> Self {+impl From<(CardDetailFromLocker, Option<&CoBadgedCardData>)> for CardDetailsPaymentMethod {+ fn from(+ (item, co_badged_card_data): (CardDetailFromLocker, Option<&CoBadgedCardData>),+ ) -> Self {Self {issuer_country: item.issuer_country,last4_digits: item.last4_digits,@@ -1335,6 +1347,7 @@ impl From<CardDetailFromLocker> for CardDetailsPaymentMethod {card_network: item.card_network,card_type: item.card_type,saved_to_locker: item.saved_to_locker,+ co_badged_card_data: co_badged_card_data.cloned(),}}}@@ -1354,6 +1367,7 @@ impl From<CardDetailFromLocker> for CardDetailsPaymentMethod {card_network: item.card_network,card_type: item.card_type,saved_to_locker: item.saved_to_locker,+ co_badged_card_data: None,}}}diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 880062cef2..226471dcc7 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -2310,6 +2310,130 @@ pub enum CardNetwork {RuPay,#[serde(alias = "MAESTRO")]Maestro,+ #[serde(alias = "STAR")]+ Star,+ #[serde(alias = "PULSE")]+ Pulse,+ #[serde(alias = "ACCEL")]+ Accel,+ #[serde(alias = "NYCE")]+ Nyce,+}++#[derive(+ Clone,+ Debug,+ Eq,+ Hash,+ PartialEq,+ serde::Deserialize,+ serde::Serialize,+ strum::Display,+ strum::EnumIter,+ strum::EnumString,+ utoipa::ToSchema,+)]+#[router_derive::diesel_enum(storage_type = "db_enum")]+#[serde(rename_all = "snake_case")]+pub enum RegulatedName {+ #[serde(rename = "GOVERNMENT NON-EXEMPT INTERCHANGE FEE (WITH FRAUD)")]+ #[strum(serialize = "GOVERNMENT NON-EXEMPT INTERCHANGE FEE (WITH FRAUD)")]+ NonExemptWithFraud,++ #[serde(untagged)]+ #[strum(default)]+ Unknown(String),+}++#[derive(+ Clone,+ Debug,+ Eq,+ Hash,+ PartialEq,+ serde::Deserialize,+ serde::Serialize,+ strum::Display,+ strum::EnumIter,+ strum::EnumString,+ utoipa::ToSchema,+ Copy,+)]+#[router_derive::diesel_enum(storage_type = "db_enum")]+#[serde(rename_all = "snake_case")]+#[strum(serialize_all = "lowercase")]+pub enum PanOrToken {+ Pan,+ Token,+}++#[derive(+ Clone,+ Debug,+ Eq,+ Hash,+ PartialEq,+ serde::Deserialize,+ serde::Serialize,+ strum::Display,+ strum::EnumIter,+ strum::EnumString,+ utoipa::ToSchema,+ Copy,+)]+#[router_derive::diesel_enum(storage_type = "db_enum")]+#[strum(serialize_all = "UPPERCASE")]+#[serde(rename_all = "snake_case")]+pub enum CardType {+ Credit,+ Debit,+}++#[derive(Debug, Clone, Serialize, Deserialize, strum::EnumString, strum::Display)]+#[serde(rename_all = "snake_case")]+pub enum MerchantCategoryCode {+ #[serde(rename = "merchant_category_code_0001")]+ Mcc0001,+}++impl CardNetwork {+ pub fn is_global_network(&self) -> bool {+ match self {+ Self::Interac+ | Self::Star+ | Self::Pulse+ | Self::Accel+ | Self::Nyce+ | Self::CartesBancaires => false,++ Self::Visa+ | Self::Mastercard+ | Self::AmericanExpress+ | Self::JCB+ | Self::DinersClub+ | Self::Discover+ | Self::UnionPay+ | Self::RuPay+ | Self::Maestro => true,+ }+ }++ pub fn is_us_local_network(&self) -> bool {+ match self {+ Self::Star | Self::Pulse | Self::Accel | Self::Nyce => true,+ Self::Interac+ | Self::CartesBancaires+ | Self::Visa+ | Self::Mastercard+ | Self::AmericanExpress+ | Self::JCB+ | Self::DinersClub+ | Self::Discover+ | Self::UnionPay+ | Self::RuPay+ | Self::Maestro => false,+ }+ }}/// Stage of the disputediff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rsindex 55dcc4e5bd..40b37b6b3c 100644--- a/crates/common_utils/src/types.rs+++ b/crates/common_utils/src/types.rs@@ -402,6 +402,11 @@ impl MinorUnit {Self(value)}+ /// checks if the amount is greater than the given value+ pub fn is_greater_than(&self, value: i64) -> bool {+ self.get_amount_as_i64() > value+ }+/// Convert the amount to its major denomination based on Currency and return String/// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies./// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.tomlindex a4403923fd..b46733d17c 100644--- a/crates/connector_configs/toml/development.toml+++ b/crates/connector_configs/toml/development.toml@@ -83,6 +83,14 @@ merchant_secret="Source verification key"payment_method_type = "Mastercard"[[adyen.debit]]payment_method_type = "Visa"+[[adyen.debit]]+ payment_method_type = "Nyce"+[[adyen.debit]]+ payment_method_type = "Pulse"+[[adyen.debit]]+ payment_method_type = "Star"+[[adyen.debit]]+ payment_method_type = "Accel"[[adyen.debit]]payment_method_type = "Interac"[[adyen.debit]]diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.tomlindex d9dea35440..331c92c39b 100644--- a/crates/connector_configs/toml/sandbox.toml+++ b/crates/connector_configs/toml/sandbox.toml@@ -83,6 +83,14 @@ merchant_secret="Source verification key"payment_method_type = "Mastercard"[[adyen.debit]]payment_method_type = "Visa"+[[adyen.debit]]+ payment_method_type = "Nyce"+[[adyen.debit]]+ payment_method_type = "Pulse"+[[adyen.debit]]+ payment_method_type = "Star"+[[adyen.debit]]+ payment_method_type = "Accel"[[adyen.debit]]payment_method_type = "Interac"[[adyen.debit]]diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rsindex c899c62561..26ba1cbe52 100644--- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs@@ -1257,6 +1257,7 @@ pub enum CardBrand {Visa,MC,Amex,+ Accel,Argencard,Bcmc,Bijcard,@@ -1281,13 +1282,16 @@ pub enum CardBrand {Mir,Naranja,Oasis,+ Pulse,Rupay,Shopping,+ Star,Solo,Troy,Uatp,Visaalphabankbonus,Visadankort,+ Nyce,Warehouse,}@@ -2091,6 +2095,10 @@ fn get_adyen_card_network(card_network: common_enums::CardNetwork) -> Option<Carcommon_enums::CardNetwork::UnionPay => Some(CardBrand::Cup),common_enums::CardNetwork::RuPay => Some(CardBrand::Rupay),common_enums::CardNetwork::Maestro => Some(CardBrand::Maestro),+ common_enums::CardNetwork::Star => Some(CardBrand::Star),+ common_enums::CardNetwork::Accel => Some(CardBrand::Accel),+ common_enums::CardNetwork::Pulse => Some(CardBrand::Pulse),+ common_enums::CardNetwork::Nyce => Some(CardBrand::Nyce),common_enums::CardNetwork::Interac => None,}}diff --git a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rsindex 3a627fdfdf..7aed189fbd 100644--- a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs@@ -556,7 +556,12 @@ fn get_boa_card_type(card_network: common_enums::CardNetwork) -> Option<&'staticcommon_enums::CardNetwork::UnionPay => Some("062"),//"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024"common_enums::CardNetwork::Maestro => Some("042"),- common_enums::CardNetwork::Interac | common_enums::CardNetwork::RuPay => None,+ common_enums::CardNetwork::Interac+ | common_enums::CardNetwork::RuPay+ | common_enums::CardNetwork::Star+ | common_enums::CardNetwork::Accel+ | common_enums::CardNetwork::Pulse+ | common_enums::CardNetwork::Nyce => None,}}diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rsindex 85125d1ddc..25eedcd5e6 100644--- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs@@ -4305,7 +4305,12 @@ fn get_cybersource_card_type(card_network: common_enums::CardNetwork) -> Option<common_enums::CardNetwork::UnionPay => Some("062"),//"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024"common_enums::CardNetwork::Maestro => Some("042"),- common_enums::CardNetwork::Interac | common_enums::CardNetwork::RuPay => None,+ common_enums::CardNetwork::Interac+ | common_enums::CardNetwork::RuPay+ | common_enums::CardNetwork::Star+ | common_enums::CardNetwork::Accel+ | common_enums::CardNetwork::Pulse+ | common_enums::CardNetwork::Nyce => None,}}diff --git a/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rsindex 0cfccd280f..a967eefbd7 100644--- a/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs@@ -204,7 +204,11 @@ impl TryFrom<&HipayRouterData<&PaymentsAuthorizeRouterData>> for HipayPaymentsReSome(CardNetwork::Interac) => "interac".to_string(),Some(CardNetwork::RuPay) => "rupay".to_string(),Some(CardNetwork::Maestro) => "maestro".to_string(),- None => "".to_string(),+ Some(CardNetwork::Star)+ | Some(CardNetwork::Accel)+ | Some(CardNetwork::Pulse)+ | Some(CardNetwork::Nyce)+ | None => "".to_string(),},},amount: item.amount.clone(),diff --git a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rsindex da6ec76936..73d9007706 100644--- a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs@@ -1398,7 +1398,11 @@ fn get_stripe_card_network(card_network: common_enums::CardNetwork) -> Option<St| common_enums::CardNetwork::UnionPay| common_enums::CardNetwork::Interac| common_enums::CardNetwork::RuPay- | common_enums::CardNetwork::Maestro => None,+ | common_enums::CardNetwork::Maestro+ | common_enums::CardNetwork::Star+ | common_enums::CardNetwork::Accel+ | common_enums::CardNetwork::Pulse+ | common_enums::CardNetwork::Nyce => None,}}diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rsindex 9f62dbbe98..4ddb32b4d6 100644--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs@@ -77,6 +77,14 @@ impl PaymentMethodData {pub fn is_network_token_payment_method_data(&self) -> bool {matches!(self, Self::NetworkToken(_))}++ pub fn get_co_badged_card_data(&self) -> Option<&payment_methods::CoBadgedCardData> {+ if let Self::Card(card) = self {+ card.co_badged_card_data.as_ref()+ } else {+ None+ }+ }}#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]@@ -92,6 +100,7 @@ pub struct Card {pub bank_code: Option<String>,pub nick_name: Option<Secret<String>>,pub card_holder_name: Option<Secret<String>>,+ pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>,}#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]@@ -120,6 +129,7 @@ pub struct CardDetail {pub bank_code: Option<String>,pub nick_name: Option<Secret<String>>,pub card_holder_name: Option<Secret<String>>,+ pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>,}impl CardDetailsForNetworkTransactionId {@@ -162,6 +172,7 @@ impl From<&Card> for CardDetail {bank_code: item.bank_code.to_owned(),nick_name: item.nick_name.to_owned(),card_holder_name: item.card_holder_name.to_owned(),+ co_badged_card_data: item.co_badged_card_data.to_owned(),}}}@@ -723,6 +734,7 @@ impl TryFrom<payment_methods::PaymentMethodCreateData> for PaymentMethodData {bank_code: None,nick_name,card_holder_name,+ co_badged_card_data: None,})),}}@@ -732,7 +744,7 @@ impl From<api_models::payments::PaymentMethodData> for PaymentMethodData {fn from(api_model_payment_method_data: api_models::payments::PaymentMethodData) -> Self {match api_model_payment_method_data {api_models::payments::PaymentMethodData::Card(card_data) => {- Self::Card(Card::from(card_data))+ Self::Card(Card::from((card_data, None)))}api_models::payments::PaymentMethodData::CardRedirect(card_redirect) => {Self::CardRedirect(From::from(card_redirect))@@ -782,8 +794,18 @@ impl From<api_models::payments::PaymentMethodData> for PaymentMethodData {}}-impl From<api_models::payments::Card> for Card {- fn from(value: api_models::payments::Card) -> Self {+impl+ From<(+ api_models::payments::Card,+ Option<payment_methods::CoBadgedCardData>,+ )> for Card+{+ fn from(+ (value, co_badged_card_data_optional): (+ api_models::payments::Card,+ Option<payment_methods::CoBadgedCardData>,+ ),+ ) -> Self {let api_models::payments::Card {card_number,card_exp_month,@@ -810,6 +832,7 @@ impl From<api_models::payments::Card> for Card {bank_code,nick_name,card_holder_name,+ co_badged_card_data: co_badged_card_data_optional,}}}@@ -1875,6 +1898,16 @@ pub enum PaymentMethodsData {NetworkToken(NetworkTokenDetailsPaymentMethod),}+impl PaymentMethodsData {+ pub fn get_co_badged_card_data(&self) -> Option<payment_methods::CoBadgedCardData> {+ if let Self::Card(card) = self {+ card.co_badged_card_data.clone()+ } else {+ None+ }+ }+}+#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]pub struct NetworkTokenDetailsPaymentMethod {pub last4_digits: Option<String>,@@ -1909,6 +1942,7 @@ pub struct CardDetailsPaymentMethod {pub card_type: Option<String>,#[serde(default = "saved_in_locker_default")]pub saved_to_locker: bool,+ pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>,}#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]@@ -1926,6 +1960,7 @@ impl From<payment_methods::CardDetail> for CardDetailsPaymentMethod {card_network: item.card_network,card_type: item.card_type.map(|card| card.to_string()),saved_to_locker: true,+ co_badged_card_data: None,}}}diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rsindex 955d01c94d..de7d964144 100644--- a/crates/hyperswitch_domain_models/src/payment_methods.rs+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs@@ -12,7 +12,11 @@ use common_utils::{};use diesel_models::{enums as storage_enums, PaymentMethodUpdate};use error_stack::ResultExt;+#[cfg(feature = "v1")]+use masking::ExposeInterface;use masking::{PeekInterface, Secret};+#[cfg(feature = "v1")]+use router_env::logger;#[cfg(feature = "v2")]use rustc_hash::FxHashMap;#[cfg(feature = "v2")]@@ -20,13 +24,11 @@ use serde_json::Value;use time::PrimitiveDateTime;#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]-use crate::{- address::Address, payment_method_data as domain_payment_method_data,- type_encryption::OptionalEncryptableJsonType,-};+use crate::{address::Address, type_encryption::OptionalEncryptableJsonType};use crate::{mandates::{self, CommonMandateReference},merchant_key_store::MerchantKeyStore,+ payment_method_data as domain_payment_method_data,type_encryption::{crypto_operation, AsyncLift, CryptoOperation},};@@ -131,6 +133,25 @@ impl PaymentMethod {&self.payment_method_id}+ #[cfg(feature = "v1")]+ pub fn get_payment_methods_data(+ &self,+ ) -> Option<domain_payment_method_data::PaymentMethodsData> {+ self.payment_method_data+ .clone()+ .map(|value| value.into_inner().expose())+ .and_then(|value| {+ serde_json::from_value::<domain_payment_method_data::PaymentMethodsData>(value)+ .map_err(|error| {+ logger::warn!(+ ?error,+ "Failed to parse payment method data in payment method info"+ );+ })+ .ok()+ })+ }+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]pub fn get_id(&self) -> &id_type::GlobalPaymentMethodId {&self.iddiff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rsindex 93e4f8e040..1b5d3392aa 100644--- a/crates/kgraph_utils/src/transformers.rs+++ b/crates/kgraph_utils/src/transformers.rs@@ -325,6 +325,10 @@ impl IntoDirValue for api_enums::CardNetwork {Self::Interac => Ok(dirval!(CardNetwork = Interac)),Self::RuPay => Ok(dirval!(CardNetwork = RuPay)),Self::Maestro => Ok(dirval!(CardNetwork = Maestro)),+ Self::Star => Ok(dirval!(CardNetwork = Star)),+ Self::Accel => Ok(dirval!(CardNetwork = Accel)),+ Self::Pulse => Ok(dirval!(CardNetwork = Pulse)),+ Self::Nyce => Ok(dirval!(CardNetwork = Nyce)),}}}diff --git a/crates/payment_methods/src/core/migration/payment_methods.rs b/crates/payment_methods/src/core/migration/payment_methods.rsindex 3dc8f3a5e5..a957d2375b 100644--- a/crates/payment_methods/src/core/migration/payment_methods.rs+++ b/crates/payment_methods/src/core/migration/payment_methods.rs@@ -540,8 +540,9 @@ pub async fn skip_locker_call_and_migrate_payment_method(.await.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;- let payment_method_card_details =- pm_api::PaymentMethodsData::Card(pm_api::CardDetailsPaymentMethod::from(card.clone()));+ let payment_method_card_details = pm_api::PaymentMethodsData::Card(+ pm_api::CardDetailsPaymentMethod::from((card.clone(), None)),+ );let payment_method_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = Some(create_encrypted_data(diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rsindex 12cc03eb92..49800dd3c8 100644--- a/crates/router/src/configs/secrets_transformers.rs+++ b/crates/router/src/configs/secrets_transformers.rs@@ -536,6 +536,7 @@ pub(crate) async fn fetch_raw_secrets(platform: conf.platform,authentication_providers: conf.authentication_providers,open_router: conf.open_router,+ debit_routing_config: conf.debit_routing_config,clone_connector_allowlist: conf.clone_connector_allowlist,}}diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex c0f2d680d3..34270971ef 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -115,6 +115,7 @@ pub struct Settings<S: SecretState> {#[cfg(feature = "payouts")]pub payouts: Payouts,pub payout_method_filters: ConnectorFilters,+ pub debit_routing_config: DebitRoutingConfig,pub applepay_decrypt_keys: SecretStateContainer<ApplePayDecryptConfig, S>,pub paze_decrypt_keys: Option<SecretStateContainer<PazeDecryptConfig, S>>,pub google_pay_decrypt_keys: Option<GooglePayDecryptConfig>,@@ -156,6 +157,16 @@ pub struct Settings<S: SecretState> {pub clone_connector_allowlist: Option<CloneConnectorAllowlistConfig>,}+#[derive(Debug, Deserialize, Clone, Default)]+pub struct DebitRoutingConfig {+ #[serde(deserialize_with = "deserialize_hashmap")]+ pub connector_supported_debit_networks: HashMap<enums::Connector, HashSet<enums::CardNetwork>>,+ #[serde(deserialize_with = "deserialize_hashset")]+ pub supported_currencies: HashSet<enums::Currency>,+ #[serde(deserialize_with = "deserialize_hashset")]+ pub supported_connectors: HashSet<enums::Connector>,+}+#[derive(Debug, Deserialize, Clone, Default)]pub struct OpenRouter {pub enabled: bool,diff --git a/crates/router/src/core.rs b/crates/router/src/core.rsindex e96aa339e9..db2122b242 100644--- a/crates/router/src/core.rs+++ b/crates/router/src/core.rs@@ -45,6 +45,8 @@ pub mod refunds;#[cfg(feature = "v2")]pub mod refunds_v2;+#[cfg(feature = "v1")]+pub mod debit_routing;pub mod routing;pub mod surcharge_decision_config;#[cfg(feature = "olap")]diff --git a/crates/router/src/core/authentication/utils.rs b/crates/router/src/core/authentication/utils.rsindex 71cc4bd840..0e7315c5d4 100644--- a/crates/router/src/core/authentication/utils.rs+++ b/crates/router/src/core/authentication/utils.rs@@ -24,28 +24,30 @@ pub fn get_connector_data_if_separate_authn_supported(connector_call_type: &api::ConnectorCallType,) -> Option<api::ConnectorData> {match connector_call_type {- api::ConnectorCallType::PreDetermined(connector_data) => {- if connector_data+ api::ConnectorCallType::PreDetermined(connector_routing_data) => {+ if connector_routing_data+ .connector_data.connector_name.is_separate_authentication_supported(){- Some(connector_data.clone())+ Some(connector_routing_data.connector_data.clone())} else {None}}- api::ConnectorCallType::Retryable(connectors) => {- connectors.first().and_then(|connector_data| {- if connector_data+ api::ConnectorCallType::Retryable(connector_routing_data) => connector_routing_data+ .first()+ .and_then(|connector_routing_data| {+ if connector_routing_data+ .connector_data.connector_name.is_separate_authentication_supported(){- Some(connector_data.clone())+ Some(connector_routing_data.connector_data.clone())} else {None}- })- }+ }),api::ConnectorCallType::SessionMultiple(_) => None,}}diff --git a/crates/router/src/core/debit_routing.rs b/crates/router/src/core/debit_routing.rsnew file mode 100644index 0000000000..5824946c3e--- /dev/null+++ b/crates/router/src/core/debit_routing.rs@@ -0,0 +1,460 @@+use std::{collections::HashSet, fmt::Debug};++use api_models::{enums as api_enums, open_router};+use common_enums::enums;+use common_utils::id_type;+use error_stack::ResultExt;+use masking::Secret;++use super::{+ payments::{OperationSessionGetters, OperationSessionSetters},+ routing::TransactionData,+};+use crate::{+ core::{+ errors,+ payments::{operations::BoxedOperation, routing},+ },+ logger,+ routes::SessionState,+ settings,+ types::{+ api::{self, ConnectorCallType},+ domain,+ },+};++pub struct DebitRoutingResult {+ pub debit_routing_connector_call_type: ConnectorCallType,+ pub debit_routing_output: open_router::DebitRoutingOutput,+}++pub async fn perform_debit_routing<F, Req, D>(+ operation: &BoxedOperation<'_, F, Req, D>,+ state: &SessionState,+ business_profile: &domain::Profile,+ payment_data: &mut D,+ connector: Option<ConnectorCallType>,+) -> (+ Option<ConnectorCallType>,+ Option<open_router::DebitRoutingOutput>,+)+where+ F: Send + Clone,+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,+{+ let mut debit_routing_output = None;++ if should_execute_debit_routing(state, business_profile, operation, payment_data).await {+ let debit_routing_config = state.conf.debit_routing_config.clone();+ let debit_routing_supported_connectors = debit_routing_config.supported_connectors.clone();++ if let Some((call_connector_type, acquirer_country)) = connector+ .clone()+ .zip(business_profile.merchant_business_country)+ {+ debit_routing_output = match call_connector_type {+ ConnectorCallType::PreDetermined(connector_data) => {+ logger::info!("Performing debit routing for PreDetermined connector");+ handle_pre_determined_connector(+ state,+ &debit_routing_config,+ debit_routing_supported_connectors,+ &connector_data,+ payment_data,+ acquirer_country,+ )+ .await+ }+ ConnectorCallType::Retryable(connector_data) => {+ logger::info!("Performing debit routing for Retryable connector");+ handle_retryable_connector(+ state,+ &debit_routing_config,+ debit_routing_supported_connectors,+ connector_data,+ payment_data,+ acquirer_country,+ )+ .await+ }+ ConnectorCallType::SessionMultiple(_) => {+ logger::info!(+ "SessionMultiple connector type is not supported for debit routing"+ );+ None+ }+ #[cfg(feature = "v2")]+ ConnectorCallType::Skip => {+ logger::info!("Skip connector type is not supported for debit routing");+ None+ }+ };+ }+ }++ if let Some(debit_routing_output) = debit_routing_output {+ (+ Some(debit_routing_output.debit_routing_connector_call_type),+ Some(debit_routing_output.debit_routing_output),+ )+ } else {+ // If debit_routing_output is None, return the static routing output (connector)+ logger::info!("Debit routing is not performed, returning static routing output");+ (connector, None)+ }+}++async fn should_execute_debit_routing<F, Req, D>(+ state: &SessionState,+ business_profile: &domain::Profile,+ operation: &BoxedOperation<'_, F, Req, D>,+ payment_data: &D,+) -> bool+where+ F: Send + Clone,+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,+{+ if business_profile.is_debit_routing_enabled+ && state.conf.open_router.enabled+ && business_profile.merchant_business_country.is_some()+ {+ logger::info!("Debit routing is enabled for the profile");++ let debit_routing_config = &state.conf.debit_routing_config;++ if should_perform_debit_routing_for_the_flow(operation, payment_data, debit_routing_config)+ {+ let is_debit_routable_connector_present = check_for_debit_routing_connector_in_profile(+ state,+ business_profile.get_id(),+ payment_data,+ )+ .await;++ if is_debit_routable_connector_present {+ logger::debug!("Debit routable connector is configured for the profile");+ return true;+ }+ }+ }+ false+}++pub fn should_perform_debit_routing_for_the_flow<Op: Debug, F: Clone, D>(+ operation: &Op,+ payment_data: &D,+ debit_routing_config: &settings::DebitRoutingConfig,+) -> bool+where+ D: OperationSessionGetters<F> + Send + Sync + Clone,+{+ match format!("{operation:?}").as_str() {+ "PaymentConfirm" => {+ logger::info!("Checking if debit routing is required");+ let payment_intent = payment_data.get_payment_intent();+ let payment_attempt = payment_data.get_payment_attempt();++ request_validation(payment_intent, payment_attempt, debit_routing_config)+ }+ _ => false,+ }+}++pub fn request_validation(+ payment_intent: &hyperswitch_domain_models::payments::PaymentIntent,+ payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,+ debit_routing_config: &settings::DebitRoutingConfig,+) -> bool {+ logger::debug!("Validating request for debit routing");+ let is_currency_supported = payment_intent.currency.map(|currency| {+ debit_routing_config+ .supported_currencies+ .contains(¤cy)+ });++ payment_intent.setup_future_usage != Some(enums::FutureUsage::OffSession)+ && payment_intent.amount.is_greater_than(0)+ && is_currency_supported == Some(true)+ && payment_attempt.authentication_type != Some(enums::AuthenticationType::ThreeDs)+ && payment_attempt.payment_method == Some(enums::PaymentMethod::Card)+ && payment_attempt.payment_method_type == Some(enums::PaymentMethodType::Debit)+}++pub async fn check_for_debit_routing_connector_in_profile<+ F: Clone,+ D: OperationSessionGetters<F>,+>(+ state: &SessionState,+ business_profile_id: &id_type::ProfileId,+ payment_data: &D,+) -> bool {+ logger::debug!("Checking for debit routing connector in profile");+ let debit_routing_supported_connectors =+ state.conf.debit_routing_config.supported_connectors.clone();++ let transaction_data = super::routing::PaymentsDslInput::new(+ payment_data.get_setup_mandate(),+ payment_data.get_payment_attempt(),+ payment_data.get_payment_intent(),+ payment_data.get_payment_method_data(),+ payment_data.get_address(),+ payment_data.get_recurring_details(),+ payment_data.get_currency(),+ );++ let fallback_config_optional = super::routing::helpers::get_merchant_default_config(+ &*state.clone().store,+ business_profile_id.get_string_repr(),+ &enums::TransactionType::from(&TransactionData::Payment(transaction_data)),+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .map_err(|error| {+ logger::warn!(?error, "Failed to fetch default connector for a profile");+ })+ .ok();++ let is_debit_routable_connector_present = fallback_config_optional+ .map(|fallback_config| {+ fallback_config.iter().any(|fallback_config_connector| {+ debit_routing_supported_connectors.contains(&api_enums::Connector::from(+ fallback_config_connector.connector,+ ))+ })+ })+ .unwrap_or(false);++ is_debit_routable_connector_present+}++async fn handle_pre_determined_connector<F, D>(+ state: &SessionState,+ debit_routing_config: &settings::DebitRoutingConfig,+ debit_routing_supported_connectors: HashSet<api_enums::Connector>,+ connector_data: &api::ConnectorRoutingData,+ payment_data: &mut D,+ acquirer_country: enums::CountryAlpha2,+) -> Option<DebitRoutingResult>+where+ F: Send + Clone,+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,+{+ if debit_routing_supported_connectors.contains(&connector_data.connector_data.connector_name) {+ logger::debug!("Chosen connector is supported for debit routing");++ let debit_routing_output =+ get_debit_routing_output::<F, D>(state, payment_data, acquirer_country).await?;++ logger::debug!(+ "Sorted co-badged networks: {:?}",+ debit_routing_output.co_badged_card_networks+ );++ let valid_connectors = build_connector_routing_data(+ connector_data,+ debit_routing_config,+ &debit_routing_output.co_badged_card_networks,+ );++ if !valid_connectors.is_empty() {+ return Some(DebitRoutingResult {+ debit_routing_connector_call_type: ConnectorCallType::Retryable(valid_connectors),+ debit_routing_output,+ });+ }+ }++ None+}++pub async fn get_debit_routing_output<+ F: Clone,+ D: OperationSessionGetters<F> + OperationSessionSetters<F>,+>(+ state: &SessionState,+ payment_data: &mut D,+ acquirer_country: enums::CountryAlpha2,+) -> Option<open_router::DebitRoutingOutput> {+ logger::debug!("Fetching sorted card networks");+ let payment_attempt = payment_data.get_payment_attempt();++ let (saved_co_badged_card_data, saved_card_type, card_isin) =+ extract_saved_card_info(payment_data);++ match (+ saved_co_badged_card_data+ .clone()+ .zip(saved_card_type.clone()),+ card_isin.clone(),+ ) {+ (None, None) => {+ logger::debug!("Neither co-badged data nor ISIN found; skipping routing");+ None+ }+ _ => {+ let co_badged_card_data = saved_co_badged_card_data+ .zip(saved_card_type)+ .and_then(|(co_badged, card_type)| {+ open_router::DebitRoutingRequestData::try_from((co_badged, card_type))+ .map(Some)+ .map_err(|error| {+ logger::warn!("Failed to convert co-badged card data: {:?}", error);+ })+ .ok()+ })+ .flatten();++ if co_badged_card_data.is_none() && card_isin.is_none() {+ logger::debug!("Neither co-badged data nor ISIN found; skipping routing");+ return None;+ }++ let co_badged_card_request = open_router::CoBadgedCardRequest {+ merchant_category_code: enums::MerchantCategoryCode::Mcc0001,+ acquirer_country,+ co_badged_card_data,+ };++ routing::perform_open_routing_for_debit_routing(+ state,+ payment_attempt,+ co_badged_card_request,+ card_isin,+ )+ .await+ .map_err(|error| {+ logger::warn!(?error, "Debit routing call to open router failed");+ })+ .ok()+ }+ }+}++fn extract_saved_card_info<F, D>(+ payment_data: &D,+) -> (+ Option<api_models::payment_methods::CoBadgedCardData>,+ Option<String>,+ Option<Secret<String>>,+)+where+ D: OperationSessionGetters<F>,+{+ let payment_method_data_optional = payment_data.get_payment_method_data();+ match payment_data+ .get_payment_method_info()+ .and_then(|info| info.get_payment_methods_data())+ {+ Some(hyperswitch_domain_models::payment_method_data::PaymentMethodsData::Card(card)) => {+ match (&card.co_badged_card_data, &card.card_isin) {+ (Some(co_badged), _) => {+ logger::debug!("Co-badged card data found in saved payment method");+ (Some(co_badged.clone()), card.card_type, None)+ }+ (None, Some(card_isin)) => {+ logger::debug!("No co-badged data; using saved card ISIN");+ (None, None, Some(Secret::new(card_isin.clone())))+ }+ _ => (None, None, None),+ }+ }+ _ => match payment_method_data_optional {+ Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::Card(card)) => {+ logger::debug!("Using card data from payment request");+ (+ None,+ None,+ Some(Secret::new(card.card_number.get_card_isin())),+ )+ }+ _ => (None, None, None),+ },+ }+}++fn check_connector_support_for_network(+ debit_routing_config: &settings::DebitRoutingConfig,+ connector_name: api_enums::Connector,+ network: &enums::CardNetwork,+) -> Option<enums::CardNetwork> {+ debit_routing_config+ .connector_supported_debit_networks+ .get(&connector_name)+ .and_then(|supported_networks| {+ (supported_networks.contains(network) || network.is_global_network())+ .then(|| network.clone())+ })+}++fn build_connector_routing_data(+ connector_data: &api::ConnectorRoutingData,+ debit_routing_config: &settings::DebitRoutingConfig,+ fee_sorted_debit_networks: &[enums::CardNetwork],+) -> Vec<api::ConnectorRoutingData> {+ fee_sorted_debit_networks+ .iter()+ .filter_map(|network| {+ check_connector_support_for_network(+ debit_routing_config,+ connector_data.connector_data.connector_name,+ network,+ )+ .map(|valid_network| api::ConnectorRoutingData {+ connector_data: connector_data.connector_data.clone(),+ network: Some(valid_network),+ })+ })+ .collect()+}++async fn handle_retryable_connector<F, D>(+ state: &SessionState,+ debit_routing_config: &settings::DebitRoutingConfig,+ debit_routing_supported_connectors: HashSet<api_enums::Connector>,+ connector_data_list: Vec<api::ConnectorRoutingData>,+ payment_data: &mut D,+ acquirer_country: enums::CountryAlpha2,+) -> Option<DebitRoutingResult>+where+ F: Send + Clone,+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,+{+ let is_any_debit_routing_connector_supported =+ connector_data_list.iter().any(|connector_data| {+ debit_routing_supported_connectors+ .contains(&connector_data.connector_data.connector_name)+ });++ if is_any_debit_routing_connector_supported {+ let debit_routing_output =+ get_debit_routing_output::<F, D>(state, payment_data, acquirer_country).await?;++ logger::debug!(+ "Sorted co-badged networks: {:?}",+ debit_routing_output.co_badged_card_networks+ );++ let supported_connectors: Vec<_> = connector_data_list+ .iter()+ .flat_map(|connector_data| {+ build_connector_routing_data(+ connector_data,+ debit_routing_config,+ &debit_routing_output.co_badged_card_networks,+ )+ })+ .collect();++ if !supported_connectors.is_empty() {+ return Some(DebitRoutingResult {+ debit_routing_connector_call_type: ConnectorCallType::Retryable(+ supported_connectors,+ ),+ debit_routing_output,+ });+ }+ }++ None+}diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex 221390e573..0b4590b2be 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -780,6 +780,11 @@ pub(crate) async fn get_payment_method_create_request(Some(pm_data) => match payment_method {Some(payment_method) => match pm_data {domain::PaymentMethodData::Card(card) => {+ let card_network = get_card_network_with_us_local_debit_network_override(+ card.card_network.clone(),+ card.co_badged_card_data.as_ref(),+ );+let card_detail = payment_methods::CardDetail {card_number: card.card_number.clone(),card_exp_month: card.card_exp_month.clone(),@@ -787,7 +792,7 @@ pub(crate) async fn get_payment_method_create_request(card_holder_name: billing_name,nick_name: card.nick_name.clone(),card_issuing_country: card.card_issuing_country.clone(),- card_network: card.card_network.clone(),+ card_network: card_network.clone(),card_issuer: card.card_issuer.clone(),card_type: card.card_type.clone(),};@@ -803,8 +808,8 @@ pub(crate) async fn get_payment_method_create_request(card: Some(card_detail),metadata: None,customer_id: customer_id.clone(),- card_network: card- .card_network+ card_network: card_network+ .clone().as_ref().map(|card_network| card_network.to_string()),client_secret: None,@@ -852,6 +857,32 @@ pub(crate) async fn get_payment_method_create_request(}}+/// Determines the appropriate card network to to be stored.+///+/// If the provided card network is a US local network, this function attempts to+/// override it with the first global network from the co-badged card data, if available.+/// Otherwise, it returns the original card network as-is.+///+fn get_card_network_with_us_local_debit_network_override(+ card_network: Option<common_enums::CardNetwork>,+ co_badged_card_data: Option<&payment_methods::CoBadgedCardData>,+) -> Option<common_enums::CardNetwork> {+ if let Some(true) = card_network+ .as_ref()+ .map(|network| network.is_us_local_network())+ {+ services::logger::debug!("Card network is a US local network, checking for global network in co-badged card data");+ co_badged_card_data.and_then(|data| {+ data.co_badged_card_networks+ .iter()+ .find(|network| network.is_global_network())+ .cloned()+ })+ } else {+ card_network+ }+}+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]#[instrument(skip_all)]pub async fn create_payment_method(diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex a11562c7c2..6c2c2cb073 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -424,7 +424,7 @@ impl PaymentMethodsController for PmCards<'_> {logger::debug!("Network token added to locker");let (token_pm_resp, _duplication_check) = resp;let pm_token_details = token_pm_resp.card.as_ref().map(|card| {- PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))+ PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None)))});let pm_network_token_data_encrypted = pm_token_details.async_map(|pm_card| {@@ -502,10 +502,9 @@ impl PaymentMethodsController for PmCards<'_> {network_token_locker_id: Option<String>,network_token_payment_method_data: crypto::OptionalEncryptableValue,) -> errors::RouterResult<domain::PaymentMethod> {- let pm_card_details = resp- .card- .clone()- .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())));+ let pm_card_details = resp.card.clone().map(|card| {+ PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None)))+ });let key_manager_state = self.state.into();let pm_data_encrypted: crypto::OptionalEncryptableValue = pm_card_details.clone()@@ -1278,7 +1277,10 @@ impl PaymentMethodsController for PmCards<'_> {});let updated_pmd = updated_card.as_ref().map(|card| {- PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))+ PaymentMethodsData::Card(CardDetailsPaymentMethod::from((+ card.clone(),+ None,+ )))});let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> =updated_pmd@@ -1593,6 +1595,7 @@ pub async fn add_payment_method_data(card_issuer: card_info.as_ref().and_then(|ci| ci.card_issuer.clone()),card_type: card_info.as_ref().and_then(|ci| ci.card_type.clone()),saved_to_locker: true,+ co_badged_card_data: None,};let pm_data_encrypted: Encryptable<Secret<serde_json::Value>> =create_encrypted_data(@@ -1836,9 +1839,9 @@ pub async fn update_customer_payment_method(saved_to_locker: true,});- let updated_pmd = updated_card- .as_ref()- .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())));+ let updated_pmd = updated_card.as_ref().map(|card| {+ PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None)))+ });let key_manager_state = (&state).into();let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd.async_map(|updated_pmd| {diff --git a/crates/router/src/core/payment_methods/tokenize.rs b/crates/router/src/core/payment_methods/tokenize.rsindex cc27e813b5..98eca478c9 100644--- a/crates/router/src/core/payment_methods/tokenize.rs+++ b/crates/router/src/core/payment_methods/tokenize.rs@@ -272,6 +272,7 @@ wherecard_network: card_details.card_network.clone(),card_type: card_details.card_type.clone(),saved_to_locker,+ co_badged_card_data: card_details.co_badged_card_data.clone(),});create_encrypted_data(&self.state.into(), self.key_store, pm_data).await@@ -297,6 +298,7 @@ wherecard_network: card_details.card_network.clone(),card_type: card_details.card_type.clone(),saved_to_locker,+ co_badged_card_data: None,});create_encrypted_data(&self.state.into(), self.key_store, token_data).awaitdiff --git a/crates/router/src/core/payment_methods/tokenize/card_executor.rs b/crates/router/src/core/payment_methods/tokenize/card_executor.rsindex b714bdb9a6..2537a244a5 100644--- a/crates/router/src/core/payment_methods/tokenize/card_executor.rs+++ b/crates/router/src/core/payment_methods/tokenize/card_executor.rs@@ -132,6 +132,7 @@ impl<'a> NetworkTokenizationBuilder<'a, CardRequestValidated> {.map_or(card_req.card_issuing_country.clone(), |card_info| {card_info.card_issuing_country.clone()}),+ co_badged_card_data: None,};NetworkTokenizationBuilder {state: std::marker::PhantomData,diff --git a/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs b/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rsindex 2249434b10..a55896b36c 100644--- a/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs+++ b/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs@@ -151,6 +151,7 @@ impl<'a> NetworkTokenizationBuilder<'a, PmValidated> {card_issuing_country: optional_card_info.as_ref().and_then(|card_info| card_info.card_issuing_country.clone()),+ co_badged_card_data: None,};NetworkTokenizationBuilder {state: std::marker::PhantomData,diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rsindex 2231f7d89f..af60d07a46 100644--- a/crates/router/src/core/payment_methods/vault.rs+++ b/crates/router/src/core/payment_methods/vault.rs@@ -121,6 +121,7 @@ impl Vaultable for domain::Card {card_type: None,nick_name: value1.nickname.map(masking::Secret::new),card_holder_name: value1.card_holder_name,+ co_badged_card_data: None,};let supp_data = SupplementaryVaultData {diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex d166bc41a2..cb68ece203 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -88,9 +88,11 @@ use self::{use super::{errors::StorageErrorExt, payment_methods::surcharge_decision_configs, routing::TransactionData,};+#[cfg(feature = "v1")]+use crate::core::debit_routing;#[cfg(feature = "frm")]use crate::core::fraud_check as frm_core;-#[cfg(all(feature = "v1", feature = "dynamic_routing"))]+#[cfg(feature = "v1")]use crate::core::routing::helpers as routing_helpers;#[cfg(all(feature = "v1", feature = "dynamic_routing"))]use crate::types::api::convert_connector_data_to_routable_connectors;@@ -197,7 +199,7 @@ wherestate,req_state.clone(),&merchant_context,- connector_data.clone(),+ connector_data.connector_data.clone(),&operation,&mut payment_data,&customer,@@ -353,6 +355,15 @@ where).await?;+ let (connector, debit_routing_output) = debit_routing::perform_debit_routing(+ &operation,+ state,+ &business_profile,+ &mut payment_data,+ connector,+ )+ .await;+let should_add_task_to_process_tracker = should_add_task_to_process_tracker(&payment_data);let locale = header_payload.locale.clone();@@ -487,7 +498,7 @@ wherelet schedule_time = if should_add_task_to_process_tracker {payment_sync::get_sync_process_schedule_time(&*state.store,- connector.connector.id(),+ connector.connector_data.connector.id(),merchant_context.get_merchant_account().get_id(),0,)@@ -501,7 +512,7 @@ wherestate,req_state.clone(),merchant_context,- connector.clone(),+ connector.connector_data.clone(),&operation,&mut payment_data,&customer,@@ -516,6 +527,7 @@ where&business_profile,false,false,+ None,).await?;@@ -579,7 +591,7 @@ wheremerchant_context,&customer,&mca,- connector,+ &connector.connector_data,&mut payment_data,op_ref,Some(header_payload.clone()),@@ -599,7 +611,12 @@ wherelet mut connectors = connectors.clone().into_iter();- let connector_data = get_connector_data(&mut connectors)?;+ let (connector_data, routing_decision) =+ get_connector_data_with_routing_decision(+ &mut connectors,+ &business_profile,+ debit_routing_output,+ )?;let schedule_time = if should_add_task_to_process_tracker {payment_sync::get_sync_process_schedule_time(@@ -633,6 +650,7 @@ where&business_profile,false,false,+ routing_decision,).await?;@@ -1018,9 +1036,10 @@ whereadd_connector_http_status_code_metrics(connector_http_status_code);#[cfg(all(feature = "dynamic_routing", feature = "v1"))]- let routable_connectors = convert_connector_data_to_routable_connectors(&[connector.clone()])- .map_err(|e| logger::error!(routable_connector_error=?e))- .unwrap_or_default();+ let routable_connectors =+ convert_connector_data_to_routable_connectors(&[connector.clone().into()])+ .map_err(|e| logger::error!(routable_connector_error=?e))+ .unwrap_or_default();let mut payment_data = operation.to_post_update_tracker()?@@ -1126,7 +1145,7 @@ wherestate,req_state.clone(),&merchant_context,- connector_data.clone(),+ connector_data.connector_data.clone(),&operation,&mut payment_data,call_connector_action.clone(),@@ -1404,14 +1423,50 @@ where#[inline]pub fn get_connector_data(- connectors: &mut IntoIter<api::ConnectorData>,-) -> RouterResult<api::ConnectorData> {+ connectors: &mut IntoIter<api::ConnectorRoutingData>,+) -> RouterResult<api::ConnectorRoutingData> {connectors.next().ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("Connector not found in connectors iterator")}+#[cfg(feature = "v1")]+pub fn get_connector_with_networks(+ connectors: &mut IntoIter<api::ConnectorRoutingData>,+) -> Option<(api::ConnectorData, enums::CardNetwork)> {+ connectors.find_map(|connector| {+ connector+ .network+ .map(|network| (connector.connector_data, network))+ })+}++#[cfg(feature = "v1")]+fn get_connector_data_with_routing_decision(+ connectors: &mut IntoIter<api::ConnectorRoutingData>,+ business_profile: &domain::Profile,+ debit_routing_output_optional: Option<api_models::open_router::DebitRoutingOutput>,+) -> RouterResult<(+ api::ConnectorData,+ Option<routing_helpers::RoutingDecisionData>,+)> {+ if business_profile.is_debit_routing_enabled && debit_routing_output_optional.is_some() {+ if let Some((data, card_network)) = get_connector_with_networks(connectors) {+ let debit_routing_output =+ debit_routing_output_optional.get_required_value("debit routing output")?;+ let routing_decision =+ routing_helpers::RoutingDecisionData::get_debit_routing_decision_data(+ card_network,+ debit_routing_output,+ );+ return Ok((data, Some(routing_decision)));+ }+ }++ Ok((get_connector_data(connectors)?.connector_data, None))+}+#[cfg(feature = "v2")]#[instrument(skip_all)]pub async fn call_surcharge_decision_management_for_session_flow(@@ -3013,6 +3068,7 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>(business_profile: &domain::Profile,is_retry_payment: bool,should_retry_with_pan: bool,+ routing_decision: Option<routing_helpers::RoutingDecisionData>,) -> RouterResult<(RouterData<F, RouterDReq, router_types::PaymentsResponseData>,helpers::MerchantConnectorAccountType,@@ -3075,6 +3131,10 @@ where.await?;*payment_data = pd;+ // This is used to apply any kind of routing decision to the required data,+ // before the call to `connector` is made.+ routing_decision.map(|decision| decision.apply_routing_decision(payment_data));+// Validating the blocklist guard and generate the fingerprintblocklist_guard(state, merchant_context, operation, payment_data).await?;@@ -6434,7 +6494,7 @@ where.attach_printable("Invalid connector name received in 'routed_through'")?;routing_data.routed_through = Some(connector_name.clone());- return Ok(ConnectorCallType::PreDetermined(connector_data));+ return Ok(ConnectorCallType::PreDetermined(connector_data.into()));}if let Some(mandate_connector_details) = payment_data.get_mandate_connector().as_ref() {@@ -6453,7 +6513,7 @@ where.merchant_connector_id.clone_from(&mandate_connector_details.merchant_connector_id);- return Ok(ConnectorCallType::PreDetermined(connector_data));+ return Ok(ConnectorCallType::PreDetermined(connector_data.into()));}if let Some((pre_routing_results, storage_pm_type)) =@@ -6497,7 +6557,8 @@ whereconnector_choice.merchant_connector_id.clone(),).change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Invalid connector name received")?;+ .attach_printable("Invalid connector name received")?+ .into();pre_routing_connector_data_list.push(connector_data);}@@ -6664,7 +6725,7 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clonestate: &SessionState,payment_data: &mut D,routing_data: &mut storage::RoutingData,- connectors: Vec<api::ConnectorData>,+ connectors: Vec<api::ConnectorRoutingData>,mandate_type: Option<api::MandateTransactionType>,is_connector_agnostic_mit_enabled: Option<bool>,is_network_tokenization_enabled: bool,@@ -6751,12 +6812,16 @@ where"no eligible connector found for token-based MIT payment",)?;- routing_data.routed_through =- Some(chosen_connector_data.connector_name.to_string());+ routing_data.routed_through = Some(+ chosen_connector_data+ .connector_data+ .connector_name+ .to_string(),+ );routing_data.merchant_connector_id- .clone_from(&chosen_connector_data.merchant_connector_id);+ .clone_from(&chosen_connector_data.connector_data.merchant_connector_id);payment_data.set_mandate_id(payments_api::MandateIds {mandate_id: None,@@ -6788,16 +6853,20 @@ whereSome(api::MandateTransactionType::RecurringMandateTransaction),) => {if let Some(connector) = connectors.first() {+ let connector = &connector.connector_data;routing_data.routed_through = Some(connector.connector_name.clone().to_string());routing_data.merchant_connector_id.clone_from(&connector.merchant_connector_id);- Ok(ConnectorCallType::PreDetermined(api::ConnectorData {- connector: connector.connector.clone(),- connector_name: connector.connector_name,- get_token: connector.get_token.clone(),- merchant_connector_id: connector.merchant_connector_id.clone(),- }))+ Ok(ConnectorCallType::PreDetermined(+ api::ConnectorData {+ connector: connector.connector.clone(),+ connector_name: connector.connector_name,+ get_token: connector.get_token.clone(),+ merchant_connector_id: connector.merchant_connector_id.clone(),+ }+ .into(),+ ))} else {logger::error!("no eligible connector found for the ppt_mandate payment");Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration.into())@@ -6813,9 +6882,10 @@ where.attach_printable("no eligible connector found for payment")?.clone();- routing_data.routed_through = Some(first_choice.connector_name.to_string());+ routing_data.routed_through =+ Some(first_choice.connector_data.connector_name.to_string());- routing_data.merchant_connector_id = first_choice.merchant_connector_id;+ routing_data.merchant_connector_id = first_choice.connector_data.merchant_connector_id;Ok(ConnectorCallType::Retryable(connectors))}@@ -6847,7 +6917,7 @@ pub async fn decide_connector_for_normal_or_recurring_payment<F: Clone, D>(state: &SessionState,payment_data: &mut D,routing_data: &mut storage::RoutingData,- connectors: Vec<api::ConnectorData>,+ connectors: Vec<api::ConnectorRoutingData>,is_connector_agnostic_mit_enabled: Option<bool>,payment_method_info: &domain::PaymentMethod,) -> RouterResult<ConnectorCallType>@@ -6863,7 +6933,8 @@ wherelet mut connector_choice = None;- for connector_data in connectors {+ for connector_info in connectors {+ let connector_data = connector_info.connector_data;let merchant_connector_id = connector_data.merchant_connector_id.as_ref()@@ -6897,11 +6968,12 @@ where)?;let mandate_reference_id = Some(payments_api::MandateReferenceId::ConnectorMandateId(api_models::payments::ConnectorMandateReferenceId::new(- Some(mandate_reference_record.connector_mandate_id.clone()), // connector_mandate_id- Some(payment_method_info.get_id().clone()), // payment_method_id- None, // update_history- mandate_reference_record.mandate_metadata.clone(), // mandate_metadata- mandate_reference_record.connector_mandate_request_reference_id.clone(), // connector_mandate_request_reference_id+ Some(mandate_reference_record.connector_mandate_id.clone()),+ Some(payment_method_info.get_id().clone()),+ // update_history+ None,+ mandate_reference_record.mandate_metadata.clone(),+ mandate_reference_record.connector_mandate_request_reference_id.clone(),)));payment_data.set_recurring_mandate_payment_data(@@ -6959,16 +7031,18 @@ wheremandate_reference_id,});- Ok(ConnectorCallType::PreDetermined(chosen_connector_data))+ Ok(ConnectorCallType::PreDetermined(+ chosen_connector_data.into(),+ ))}pub fn filter_ntid_supported_connectors(- connectors: Vec<api::ConnectorData>,+ connectors: Vec<api::ConnectorRoutingData>,ntid_supported_connectors: &HashSet<enums::Connector>,-) -> Vec<api::ConnectorData> {+) -> Vec<api::ConnectorRoutingData> {connectors.into_iter()- .filter(|data| ntid_supported_connectors.contains(&data.connector_name))+ .filter(|data| ntid_supported_connectors.contains(&data.connector_data.connector_name)).collect()}@@ -6991,12 +7065,14 @@ pub enum ActionType {}pub fn filter_network_tokenization_supported_connectors(- connectors: Vec<api::ConnectorData>,+ connectors: Vec<api::ConnectorRoutingData>,network_tokenization_supported_connectors: &HashSet<enums::Connector>,-) -> Vec<api::ConnectorData> {+) -> Vec<api::ConnectorRoutingData> {connectors.into_iter()- .filter(|data| network_tokenization_supported_connectors.contains(&data.connector_name))+ .filter(|data| {+ network_tokenization_supported_connectors.contains(&data.connector_data.connector_name)+ }).collect()}@@ -7006,7 +7082,7 @@ pub async fn decide_action_type(is_connector_agnostic_mit_enabled: Option<bool>,is_network_tokenization_enabled: bool,payment_method_info: &domain::PaymentMethod,- filtered_nt_supported_connectors: Vec<api::ConnectorData>, //network tokenization supported connectors+ filtered_nt_supported_connectors: Vec<api::ConnectorRoutingData>, //network tokenization supported connectors) -> Option<ActionType> {match (is_network_token_with_network_transaction_id_flow(@@ -7351,6 +7427,7 @@ whereapi::GetToken::Connector,conn.merchant_connector_id,)+ .map(|connector_data| connector_data.into())}).collect::<CustomResult<Vec<_>, _>>().change_context(errors::ApiErrorResponse::InternalServerError)@@ -7440,6 +7517,7 @@ pub async fn route_connector_v1_for_payouts(api::GetToken::Connector,conn.merchant_connector_id,)+ .map(|connector_data| connector_data.into())}).collect::<CustomResult<Vec<_>, _>>().change_context(errors::ApiErrorResponse::InternalServerError)@@ -7970,7 +8048,6 @@ pub trait PaymentMethodChecker<F> {fn should_update_in_post_update_tracker(&self) -> bool;fn should_update_in_update_tracker(&self) -> bool;}-#[cfg(feature = "v1")]impl<F: Clone> PaymentMethodChecker<F> for PaymentData<F> {fn should_update_in_post_update_tracker(&self) -> bool {@@ -8066,6 +8143,11 @@ pub trait OperationSessionSetters<F> {&mut self,merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,);+ fn set_card_network(&mut self, card_network: enums::CardNetwork);+ fn set_co_badged_card_data(+ &mut self,+ debit_routing_ouput: &api_models::open_router::DebitRoutingOutput,+ );#[cfg(feature = "v1")]fn set_capture_method_in_attempt(&mut self, capture_method: enums::CaptureMethod);fn set_frm_message(&mut self, frm_message: FraudCheck);@@ -8298,6 +8380,31 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentData<F> {self.payment_attempt.merchant_connector_id = merchant_connector_id;}+ fn set_card_network(&mut self, card_network: enums::CardNetwork) {+ if let Some(domain::PaymentMethodData::Card(card)) = &mut self.payment_method_data {+ logger::debug!("set card network {:?}", card_network.clone());+ card.card_network = Some(card_network);+ };+ }++ fn set_co_badged_card_data(+ &mut self,+ debit_routing_ouput: &api_models::open_router::DebitRoutingOutput,+ ) {+ let co_badged_card_data =+ api_models::payment_methods::CoBadgedCardData::from(debit_routing_ouput);+ let card_type = debit_routing_ouput+ .card_type+ .clone()+ .to_string()+ .to_uppercase();+ if let Some(domain::PaymentMethodData::Card(card)) = &mut self.payment_method_data {+ card.co_badged_card_data = Some(co_badged_card_data);+ card.card_type = Some(card_type);+ logger::debug!("set co-badged card data in payment method data");+ };+ }+#[cfg(feature = "v1")]fn set_capture_method_in_attempt(&mut self, capture_method: enums::CaptureMethod) {self.payment_attempt.capture_method = Some(capture_method);@@ -8523,6 +8630,17 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> {todo!()}+ fn set_card_network(&mut self, card_network: enums::CardNetwork) {+ todo!()+ }++ fn set_co_badged_card_data(+ &mut self,+ debit_routing_ouput: &api_models::open_router::DebitRoutingOutput,+ ) {+ todo!()+ }+fn set_email_if_not_present(&mut self, _email: pii::Email) {todo!()}@@ -8763,6 +8881,17 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentConfirmData<F> {todo!()}+ fn set_card_network(&mut self, card_network: enums::CardNetwork) {+ todo!()+ }++ fn set_co_badged_card_data(+ &mut self,+ debit_routing_ouput: &api_models::open_router::DebitRoutingOutput,+ ) {+ todo!()+ }+fn set_surcharge_details(&mut self, _surcharge_details: Option<types::SurchargeDetails>) {todo!()}@@ -8975,6 +9104,17 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentStatusData<F> {todo!()}+ fn set_card_network(&mut self, card_network: enums::CardNetwork) {+ todo!()+ }++ fn set_co_badged_card_data(+ &mut self,+ debit_routing_ouput: &api_models::open_router::DebitRoutingOutput,+ ) {+ todo!()+ }+fn set_pm_token(&mut self, _token: String) {todo!()}@@ -9197,6 +9337,17 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentCaptureData<F> {todo!()}+ fn set_card_network(&mut self, card_network: enums::CardNetwork) {+ todo!()+ }++ fn set_co_badged_card_data(+ &mut self,+ debit_routing_ouput: &api_models::open_router::DebitRoutingOutput,+ ) {+ todo!()+ }+fn set_email_if_not_present(&mut self, _email: pii::Email) {todo!()}diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 59b25d9b86..0cada8c368 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -2120,6 +2120,11 @@ pub async fn retrieve_payment_method_data_with_permanent_token(.network_token_requestor_reference_id.clone(),);++ let co_badged_card_data = payment_method_info+ .get_payment_methods_data()+ .and_then(|payment_methods_data| payment_methods_data.get_co_badged_card_data());+match vault_fetch_action {VaultFetchAction::FetchCardDetailsFromLocker => {let card = vault_data@@ -2132,6 +2137,7 @@ pub async fn retrieve_payment_method_data_with_permanent_token(&payment_intent.merchant_id,locker_id,card_token_data,+ co_badged_card_data,).await})@@ -2182,6 +2188,7 @@ pub async fn retrieve_payment_method_data_with_permanent_token(&payment_intent.merchant_id,locker_id,card_token_data,+ co_badged_card_data,).await})@@ -2246,6 +2253,7 @@ pub async fn retrieve_card_with_permanent_token_for_external_authentication(&payment_intent.merchant_id,locker_id,card_token_data,+ None,).await.change_context(errors::ApiErrorResponse::InternalServerError)@@ -2263,7 +2271,9 @@ pub async fn fetch_card_details_from_locker(merchant_id: &id_type::MerchantId,locker_id: &str,card_token_data: Option<&domain::CardToken>,+ co_badged_card_data: Option<api_models::payment_methods::CoBadgedCardData>,) -> RouterResult<domain::Card> {+ logger::debug!("Fetching card details from locker");let card = cards::get_card_from_locker(state, customer_id, merchant_id, locker_id).await.change_context(errors::ApiErrorResponse::InternalServerError)@@ -2308,7 +2318,7 @@ pub async fn fetch_card_details_from_locker(card_issuing_country: None,bank_code: None,};- Ok(api_card.into())+ Ok(domain::Card::from((api_card, co_badged_card_data)))}#[cfg(all(@@ -4584,15 +4594,32 @@ pub async fn get_additional_payment_data(_ => None,};- let card_network = match card_data+ // Added an additional check for card_data.co_badged_card_data.is_some()+ // because is_cobadged_card() only returns true if the card number matches a specific regex.+ // However, this regex does not cover all possible co-badged networks.+ // The co_badged_card_data field is populated based on a co-badged BIN lookup+ // and helps identify co-badged cards that may not match the regex alone.+ // Determine the card network based on cobadge detection and co-badged BIN data+ let is_cobadged_based_on_regex = card_data.card_number.is_cobadged_card().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Card cobadge check failed due to an invalid card network regex",- )? {- true => card_data.card_network.clone(),- false => None,+ )?;++ let card_network = match (+ is_cobadged_based_on_regex,+ card_data.co_badged_card_data.is_some(),+ ) {+ (false, false) => {+ logger::debug!("Card network is not cobadged");+ None+ }+ _ => {+ logger::debug!("Card network is cobadged");+ card_data.card_network.clone()+ }};let last4 = Some(card_data.card_number.get_last4());@@ -5170,10 +5197,10 @@ pub async fn get_apple_pay_retryable_connectors<F, D>(state: &SessionState,merchant_context: &domain::MerchantContext,payment_data: &D,- pre_routing_connector_data_list: &[api::ConnectorData],+ pre_routing_connector_data_list: &[api::ConnectorRoutingData],merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>,business_profile: domain::Profile,-) -> CustomResult<Option<Vec<api::ConnectorData>>, errors::ApiErrorResponse>+) -> CustomResult<Option<Vec<api::ConnectorRoutingData>>, errors::ApiErrorResponse>whereF: Send + Clone,D: payments::OperationSessionGetters<F> + Send,@@ -5190,7 +5217,10 @@ wherepayment_data.get_creds_identifier(),merchant_context.get_merchant_key_store(),profile_id,- &pre_decided_connector_data_first.connector_name.to_string(),+ &pre_decided_connector_data_first+ .connector_data+ .connector_name+ .to_string(),merchant_connector_id,).await?;@@ -5225,19 +5255,22 @@ wheremerchant_connector_account.metadata.clone(),Some(&merchant_connector_account.connector_name),)? {- let connector_data = api::ConnectorData::get_connector_by_name(- &state.conf.connectors,- &merchant_connector_account.connector_name.to_string(),- api::GetToken::Connector,- Some(merchant_connector_account.get_id()),- )- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Invalid connector name received")?;+ let routing_data: api::ConnectorRoutingData =+ api::ConnectorData::get_connector_by_name(+ &state.conf.connectors,+ &merchant_connector_account.connector_name.to_string(),+ api::GetToken::Connector,+ Some(merchant_connector_account.get_id()),+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Invalid connector name received")?+ .into();if !connector_data_list.iter().any(|connector_details| {- connector_details.merchant_connector_id == connector_data.merchant_connector_id+ connector_details.connector_data.merchant_connector_id+ == routing_data.connector_data.merchant_connector_id}) {- connector_data_list.push(connector_data)+ connector_data_list.push(routing_data)}}}@@ -5260,7 +5293,7 @@ wherelet mut routing_connector_data_list = Vec::new();pre_routing_connector_data_list.iter().for_each(|pre_val| {- routing_connector_data_list.push(pre_val.merchant_connector_id.clone())+ routing_connector_data_list.push(pre_val.connector_data.merchant_connector_id.clone())});fallback_connetors_list.iter().for_each(|fallback_val| {@@ -5281,7 +5314,7 @@ where.iter().for_each(|merchant_connector_id| {let connector_data = connector_data_list.iter().find(|connector_data| {- *merchant_connector_id == connector_data.merchant_connector_id+ *merchant_connector_id == connector_data.connector_data.merchant_connector_id});if let Some(connector_data_details) = connector_data {ordered_connector_data_list.push(connector_data_details.clone());diff --git a/crates/router/src/core/payments/operations/payment_capture_v2.rs b/crates/router/src/core/payments/operations/payment_capture_v2.rsindex ecdf436597..9fe4e805f9 100644--- a/crates/router/src/core/payments/operations/payment_capture_v2.rs+++ b/crates/router/src/core/payments/operations/payment_capture_v2.rs@@ -288,7 +288,7 @@ impl<F: Clone + Send> Domain<F, PaymentsCaptureRequest, PaymentCaptureData<F>> f.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Invalid connector name received")?;- Ok(ConnectorCallType::PreDetermined(connector_data))+ Ok(ConnectorCallType::PreDetermined(connector_data.into()))}}diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rsindex 37cb3875b9..2074b28fd0 100644--- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs+++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs@@ -365,7 +365,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsConfirmIntentRequest, PaymentConfSome(merchant_connector_id),)?;- Ok(ConnectorCallType::PreDetermined(connector_data))+ Ok(ConnectorCallType::PreDetermined(connector_data.into()))}}diff --git a/crates/router/src/core/payments/operations/payment_get.rs b/crates/router/src/core/payments/operations/payment_get.rsindex 14c4b15052..05536c5629 100644--- a/crates/router/src/core/payments/operations/payment_get.rs+++ b/crates/router/src/core/payments/operations/payment_get.rs@@ -293,7 +293,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsRetrieveRequest, PaymentStatusDat.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Invalid connector name received")?;- Ok(ConnectorCallType::PreDetermined(connector_data))+ Ok(ConnectorCallType::PreDetermined(connector_data.into()))}None | Some(_) => Ok(ConnectorCallType::Skip),}diff --git a/crates/router/src/core/payments/operations/proxy_payments_intent.rs b/crates/router/src/core/payments/operations/proxy_payments_intent.rsindex 5d6717b8ca..1d7fb108b3 100644--- a/crates/router/src/core/payments/operations/proxy_payments_intent.rs+++ b/crates/router/src/core/payments/operations/proxy_payments_intent.rs@@ -318,7 +318,7 @@ impl<F: Clone + Send + Sync> Domain<F, ProxyPaymentsRequest, PaymentConfirmData<merchant_connector_id,)?;- Ok(ConnectorCallType::PreDetermined(connector_data))+ Ok(ConnectorCallType::PreDetermined(connector_data.into()))} else {Err(error_stack::Report::new(errors::ApiErrorResponse::InternalServerError,diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rsindex 5fde726a21..bfe2c99855 100644--- a/crates/router/src/core/payments/retry.rs+++ b/crates/router/src/core/payments/retry.rs@@ -34,7 +34,7 @@ pub async fn do_gsm_actions<F, ApiRequest, FData, D>(state: &app::SessionState,req_state: ReqState,payment_data: &mut D,- mut connectors: IntoIter<api::ConnectorData>,+ mut connector_routing_data: IntoIter<api::ConnectorRoutingData>,original_connector_data: &api::ConnectorData,mut router_data: types::RouterData<F, FData, types::PaymentsResponseData>,merchant_context: &domain::MerchantContext,@@ -137,7 +137,7 @@ wherebreak;}- if connectors.len() == 0 {+ if connector_routing_data.len() == 0 {logger::info!("connectors exhausted for auto_retry payment");metrics::AUTO_RETRY_EXHAUSTED_COUNT.add(1, &[]);break;@@ -159,7 +159,7 @@ where// If should_retry_with_pan is true, it indicates that we are retrying with PAN using the same connector.original_connector_data.clone()} else {- super::get_connector_data(&mut connectors)?+ super::get_connector_data(&mut connector_routing_data)?.connector_data};router_data = do_retry(@@ -372,6 +372,7 @@ wherebusiness_profile,true,should_retry_with_pan,+ None,).await?;diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rsindex 9280415412..b485cd9d98 100644--- a/crates/router/src/core/payments/routing.rs+++ b/crates/router/src/core/payments/routing.rs@@ -1,27 +1,24 @@mod transformers;pub mod utils;-#[cfg(all(feature = "v1", feature = "dynamic_routing"))]use std::collections::hash_map;#[cfg(all(feature = "v1", feature = "dynamic_routing"))]use std::hash::{Hash, Hasher};use std::{collections::HashMap, str::FromStr, sync::Arc};+#[cfg(feature = "v1")]+use api_models::open_router::{self as or_types, DecidedGateway, OpenRouterDecideGatewayRequest};+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]+use api_models::routing as api_routing;use api_models::{admin as admin_api,enums::{self as api_enums, CountryAlpha2},routing::ConnectorSelection,};#[cfg(all(feature = "v1", feature = "dynamic_routing"))]-use api_models::{- open_router::{self as or_types, DecidedGateway, OpenRouterDecideGatewayRequest},- routing as api_routing,-};+use common_utils::ext_traits::AsyncExt;#[cfg(all(feature = "v1", feature = "dynamic_routing"))]-use common_utils::{- ext_traits::{AsyncExt, BytesExt},- request,-};+use common_utils::{ext_traits::BytesExt, request};use diesel_models::enums as storage_enums;use error_stack::ResultExt;use euclid::{@@ -43,7 +40,7 @@ use kgraph_utils::{transformers::{IntoContext, IntoDirValue},types::CountryCurrencyFilter,};-use masking::PeekInterface;+use masking::{PeekInterface, Secret};use rand::distributions::{self, Distribution};#[cfg(all(feature = "v1", feature = "dynamic_routing"))]use rand::SeedableRng;@@ -57,11 +54,13 @@ use utils::perform_decision_euclid_routing;use crate::core::admin;#[cfg(feature = "payouts")]use crate::core::payouts;+#[cfg(feature = "v1")]+use crate::core::routing::transformers::OpenRouterDecideGatewayRequestExt;#[cfg(all(feature = "v1", feature = "dynamic_routing"))]-use crate::{core::routing::transformers::OpenRouterDecideGatewayRequestExt, headers, services};+use crate::headers;use crate::{- core::{errors, errors as oss_errors, routing},- logger,+ core::{errors, errors as oss_errors, payments::routing::utils::EuclidApiHandler, routing},+ logger, services,types::{api::{self, routing as routing_types},domain, storage as oss_storage,@@ -1580,6 +1579,64 @@ pub async fn perform_dynamic_routing_with_open_router(Ok(connectors)}+#[cfg(feature = "v1")]+pub async fn perform_open_routing_for_debit_routing(+ state: &SessionState,+ payment_attempt: &oss_storage::PaymentAttempt,+ co_badged_card_request: or_types::CoBadgedCardRequest,+ card_isin: Option<Secret<String>>,+) -> RoutingResult<or_types::DebitRoutingOutput> {+ logger::debug!(+ "performing debit routing with open_router for profile {}",+ payment_attempt.profile_id.get_string_repr()+ );++ let metadata = Some(+ serde_json::to_string(&co_badged_card_request)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to encode Vaulting data to string")+ .change_context(errors::RoutingError::MetadataParsingError)?,+ );++ let open_router_req_body = OpenRouterDecideGatewayRequest::construct_debit_request(+ payment_attempt,+ metadata,+ card_isin,+ Some(or_types::RankingAlgorithm::NtwBasedRouting),+ );++ let response: RoutingResult<DecidedGateway> = utils::EuclidApiClient::send_euclid_request(+ state,+ services::Method::Post,+ "decide-gateway",+ Some(open_router_req_body),+ None,+ )+ .await;++ let output = match response {+ Ok(decided_gateway) => {+ let debit_routing_output = decided_gateway+ .debit_routing_output+ .get_required_value("debit_routing_output")+ .change_context(errors::RoutingError::OpenRouterError(+ "Failed to parse the response from open_router".into(),+ ))+ .attach_printable("debit_routing_output is missing in the open routing response")?;++ Ok(debit_routing_output)+ }+ Err(error_response) => {+ logger::error!("open_router_error_response: {:?}", error_response);+ Err(errors::RoutingError::OpenRouterError(+ "Failed to perform debit routing in open router".into(),+ ))+ }+ }?;++ Ok(output)+}+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]pub async fn perform_dynamic_routing_with_intelligent_router(state: &SessionState,diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rsindex 2500852363..ae68ea5377 100644--- a/crates/router/src/core/payments/tokenization.rs+++ b/crates/router/src/core/payments/tokenization.rs@@ -204,6 +204,11 @@ wherepayment_method_billing_address,).await?;+ let payment_methods_data =+ &save_payment_method_data.request.get_payment_method_data();++ let co_badged_card_data = payment_methods_data.get_co_badged_card_data();+let customer_id = customer_id.to_owned().get_required_value("customer_id")?;let merchant_id = merchant_context.get_merchant_account().get_id();let is_network_tokenization_enabled =@@ -272,7 +277,7 @@ wheresave_payment_method_data.request.get_payment_method_data(),) {(Some(card), _) => Some(PaymentMethodsData::Card(- CardDetailsPaymentMethod::from(card.clone()),+ CardDetailsPaymentMethod::from((card.clone(), co_badged_card_data)),)),(_,@@ -303,7 +308,10 @@ where> = match network_token_resp {Some(token_resp) => {let pm_token_details = token_resp.card.as_ref().map(|card| {- PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))+ PaymentMethodsData::Card(CardDetailsPaymentMethod::from((+ card.clone(),+ None,+ )))});pm_token_details@@ -645,9 +653,10 @@ where});let updated_pmd = updated_card.as_ref().map(|card| {- PaymentMethodsData::Card(CardDetailsPaymentMethod::from(+ PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(),- ))+ co_badged_card_data,+ )))});let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>,diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rsindex 55b25a0ed3..87888ab425 100644--- a/crates/router/src/core/payouts.rs+++ b/crates/router/src/core/payouts.rs@@ -82,8 +82,8 @@ pub struct PayoutData {// ********************************************** CORE FLOWS **********************************************pub fn get_next_connector(- connectors: &mut IntoIter<api::ConnectorData>,-) -> RouterResult<api::ConnectorData> {+ connectors: &mut IntoIter<api::ConnectorRoutingData>,+) -> RouterResult<api::ConnectorRoutingData> {connectors.next().ok_or(errors::ApiErrorResponse::InternalServerError)@@ -170,11 +170,11 @@ pub async fn make_connector_decision(payout_data: &mut PayoutData,) -> RouterResult<()> {match connector_call_type {- api::ConnectorCallType::PreDetermined(connector_data) => {+ api::ConnectorCallType::PreDetermined(routing_data) => {Box::pin(call_connector_payout(state,merchant_context,- &connector_data,+ &routing_data.connector_data,payout_data,)).await?;@@ -191,7 +191,7 @@ pub async fn make_connector_decision(if config_bool && payout_data.should_call_gsm() {Box::pin(retry::do_gsm_single_connector_actions(state,- connector_data,+ routing_data.connector_data,payout_data,merchant_context,))@@ -201,10 +201,10 @@ pub async fn make_connector_decision(Ok(())}- api::ConnectorCallType::Retryable(connectors) => {- let mut connectors = connectors.into_iter();+ api::ConnectorCallType::Retryable(routing_data) => {+ let mut routing_data = routing_data.into_iter();- let connector_data = get_next_connector(&mut connectors)?;+ let connector_data = get_next_connector(&mut routing_data)?.connector_data;Box::pin(call_connector_payout(state,@@ -226,7 +226,7 @@ pub async fn make_connector_decision(if config_multiple_connector_bool && payout_data.should_call_gsm() {Box::pin(retry::do_gsm_multiple_connector_actions(state,- connectors,+ routing_data,connector_data.clone(),payout_data,merchant_context,@@ -1799,10 +1799,15 @@ pub async fn complete_payout_retrieve(payout_data: &mut PayoutData,) -> RouterResult<()> {match connector_call_type {- api::ConnectorCallType::PreDetermined(connector_data) => {- create_payout_retrieve(state, merchant_context, &connector_data, payout_data)- .await- .attach_printable("Payout retrieval failed for given Payout request")?;+ api::ConnectorCallType::PreDetermined(routing_data) => {+ create_payout_retrieve(+ state,+ merchant_context,+ &routing_data.connector_data,+ payout_data,+ )+ .await+ .attach_printable("Payout retrieval failed for given Payout request")?;}api::ConnectorCallType::Retryable(_) | api::ConnectorCallType::SessionMultiple(_) => {Err(errors::ApiErrorResponse::InternalServerError)diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rsindex 010331090d..b157fb0e55 100644--- a/crates/router/src/core/payouts/helpers.rs+++ b/crates/router/src/core/payouts/helpers.rs@@ -495,6 +495,7 @@ pub async fn save_payout_data_to_locker(card_network: card_info.card_network,card_type: card_info.card_type,saved_to_locker: true,+ co_badged_card_data: None,},)})@@ -515,6 +516,7 @@ pub async fn save_payout_data_to_locker(card_network: None,card_type: None,saved_to_locker: true,+ co_badged_card_data: None,},)});@@ -847,7 +849,7 @@ pub async fn decide_payout_connector(.attach_printable("Invalid connector name received in 'routed_through'")?;routing_data.routed_through = Some(connector_name.clone());- return Ok(api::ConnectorCallType::PreDetermined(connector_data));+ return Ok(api::ConnectorCallType::PreDetermined(connector_data.into()));}// Validate and get the business_profile from payout_attempt@@ -897,6 +899,7 @@ pub async fn decide_payout_connector(api::GetToken::Connector,payout_attempt.merchant_connector_id.clone(),)+ .map(|connector_data| connector_data.into())}).collect::<CustomResult<Vec<_>, _>>().change_context(errors::ApiErrorResponse::InternalServerError)@@ -947,6 +950,7 @@ pub async fn decide_payout_connector(api::GetToken::Connector,payout_attempt.merchant_connector_id.clone(),)+ .map(|connector_data| connector_data.into())}).collect::<CustomResult<Vec<_>, _>>().change_context(errors::ApiErrorResponse::InternalServerError)diff --git a/crates/router/src/core/payouts/retry.rs b/crates/router/src/core/payouts/retry.rsindex 3e0697bea1..3b5e93eaf1 100644--- a/crates/router/src/core/payouts/retry.rs+++ b/crates/router/src/core/payouts/retry.rs@@ -23,7 +23,7 @@ use crate::{#[allow(clippy::too_many_arguments)]pub async fn do_gsm_multiple_connector_actions(state: &app::SessionState,- mut connectors: IntoIter<api::ConnectorData>,+ mut connectors_routing_data: IntoIter<api::ConnectorRoutingData>,original_connector_data: api::ConnectorData,payout_data: &mut PayoutData,merchant_context: &domain::MerchantContext,@@ -53,13 +53,13 @@ pub async fn do_gsm_multiple_connector_actions(break;}- if connectors.len() == 0 {+ if connectors_routing_data.len() == 0 {logger::info!("connectors exhausted for auto_retry payout");metrics::AUTO_PAYOUT_RETRY_EXHAUSTED_COUNT.add(1, &[]);break;}- connector = super::get_next_connector(&mut connectors)?;+ connector = super::get_next_connector(&mut connectors_routing_data)?.connector_data;Box::pin(do_retry(&state.clone(),diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rsindex 39b601ed29..c65a8c6b9e 100644--- a/crates/router/src/core/routing/helpers.rs+++ b/crates/router/src/core/routing/helpers.rs@@ -8,7 +8,7 @@ use std::str::FromStr;#[cfg(all(feature = "dynamic_routing", feature = "v1"))]use std::sync::Arc;-#[cfg(all(feature = "v1", feature = "dynamic_routing"))]+#[cfg(feature = "v1")]use api_models::open_router;use api_models::routing as routing_types;#[cfg(all(feature = "dynamic_routing", feature = "v1"))]@@ -303,6 +303,56 @@ pub struct RoutingAlgorithmHelpers<'h> {pub routing_algorithm: &'h routing_types::RoutingAlgorithm,}+#[cfg(feature = "v1")]+pub enum RoutingDecisionData {+ DebitRouting(DebitRoutingDecisionData),+}+#[cfg(feature = "v1")]+pub struct DebitRoutingDecisionData {+ pub card_network: common_enums::enums::CardNetwork,+ pub debit_routing_result: open_router::DebitRoutingOutput,+}+#[cfg(feature = "v1")]+impl RoutingDecisionData {+ pub fn apply_routing_decision<F, D>(&self, payment_data: &mut D)+ where+ F: Send + Clone,+ D: crate::core::payments::OperationSessionGetters<F>+ + crate::core::payments::OperationSessionSetters<F>+ + Send+ + Sync+ + Clone,+ {+ match self {+ Self::DebitRouting(data) => data.apply_debit_routing_decision(payment_data),+ }+ }++ pub fn get_debit_routing_decision_data(+ network: common_enums::enums::CardNetwork,+ debit_routing_result: open_router::DebitRoutingOutput,+ ) -> Self {+ Self::DebitRouting(DebitRoutingDecisionData {+ card_network: network,+ debit_routing_result,+ })+ }+}+#[cfg(feature = "v1")]+impl DebitRoutingDecisionData {+ pub fn apply_debit_routing_decision<F, D>(&self, payment_data: &mut D)+ where+ F: Send + Clone,+ D: crate::core::payments::OperationSessionGetters<F>+ + crate::core::payments::OperationSessionSetters<F>+ + Send+ + Sync+ + Clone,+ {+ payment_data.set_card_network(self.card_network.clone());+ payment_data.set_co_badged_card_data(&self.debit_routing_result);+ }+}#[derive(Clone, Debug)]pub struct ConnectNameAndMCAIdForProfile<'a>(pub FxHashSet<(diff --git a/crates/router/src/core/routing/transformers.rs b/crates/router/src/core/routing/transformers.rsindex e9088ded2e..ebf521c460 100644--- a/crates/router/src/core/routing/transformers.rs+++ b/crates/router/src/core/routing/transformers.rs@@ -2,7 +2,7 @@ use api_models::routing::{MerchantRoutingAlgorithm, RoutingAlgorithm as Algorithm, RoutingAlgorithmKind,RoutingDictionaryRecord,};-#[cfg(all(feature = "v1", feature = "dynamic_routing"))]+#[cfg(feature = "v1")]use api_models::{open_router::{OpenRouterDecideGatewayRequest, PaymentInfo, RankingAlgorithm},routing::RoutableConnectorChoice,@@ -12,8 +12,9 @@ use diesel_models::{enums as storage_enums,routing_algorithm::{RoutingAlgorithm, RoutingProfileMetadata},};-#[cfg(all(feature = "v1", feature = "dynamic_routing"))]+#[cfg(feature = "v1")]use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt;+use masking::{PeekInterface, Secret};use crate::{core::{errors, routing},@@ -108,7 +109,7 @@ impl From<&routing::TransactionData<'_>> for storage_enums::TransactionType {}}-#[cfg(all(feature = "v1", feature = "dynamic_routing"))]+#[cfg(feature = "v1")]pub trait OpenRouterDecideGatewayRequestExt {fn construct_sr_request(attempt: &PaymentAttempt,@@ -118,9 +119,18 @@ pub trait OpenRouterDecideGatewayRequestExt {) -> SelfwhereSelf: Sized;++ fn construct_debit_request(+ attempt: &PaymentAttempt,+ metadata: Option<String>,+ card_isin: Option<Secret<String>>,+ ranking_algorithm: Option<RankingAlgorithm>,+ ) -> Self+ where+ Self: Sized;}-#[cfg(all(feature = "v1", feature = "dynamic_routing"))]+#[cfg(feature = "v1")]impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest {fn construct_sr_request(attempt: &PaymentAttempt,@@ -134,9 +144,10 @@ impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest {amount: attempt.net_amount.get_order_amount(),currency: attempt.currency.unwrap_or(storage_enums::Currency::USD),payment_type: "ORDER_PAYMENT".to_string(),- // payment_method_type: attempt.payment_method_type.clone().unwrap(),payment_method_type: "UPI".into(), // TODO: once open-router makes this field string, we can send from attemptpayment_method: attempt.payment_method.unwrap_or_default(),+ metadata: None,+ card_isin: None,},merchant_id: attempt.profile_id.clone(),eligible_gateway_list: Some(@@ -149,4 +160,29 @@ impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest {elimination_enabled: Some(is_elimination_enabled),}}++ fn construct_debit_request(+ attempt: &PaymentAttempt,+ metadata: Option<String>,+ card_isin: Option<Secret<String>>,+ ranking_algorithm: Option<RankingAlgorithm>,+ ) -> Self {+ Self {+ payment_info: PaymentInfo {+ payment_id: attempt.payment_id.clone(),+ amount: attempt.net_amount.get_order_amount(),+ currency: attempt.currency.unwrap_or(storage_enums::Currency::USD),+ payment_type: "ORDER_PAYMENT".to_string(),+ card_isin: card_isin.map(|value| value.peek().clone()),+ metadata,+ payment_method_type: "UPI".into(), // TODO: once open-router makes this field string, we can send from attempt+ payment_method: attempt.payment_method.unwrap_or_default(),+ },+ merchant_id: attempt.profile_id.clone(),+ // eligible gateway list is not used in debit routing+ eligible_gateway_list: None,+ ranking_algorithm,+ elimination_enabled: None,+ }+ }}diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rsindex 9291bdb3bf..5009b99371 100644--- a/crates/router/src/types/api.rs+++ b/crates/router/src/types/api.rs@@ -92,8 +92,8 @@ use crate::{};#[derive(Clone)]pub enum ConnectorCallType {- PreDetermined(ConnectorData),- Retryable(Vec<ConnectorData>),+ PreDetermined(ConnectorRoutingData),+ Retryable(Vec<ConnectorRoutingData>),SessionMultiple(SessionConnectorDatas),#[cfg(feature = "v2")]Skip,@@ -122,6 +122,15 @@ pub struct ConnectorData {pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,}+impl From<ConnectorData> for ConnectorRoutingData {+ fn from(connector_data: ConnectorData) -> Self {+ Self {+ connector_data,+ network: None,+ }+ }+}+#[derive(Clone, Debug)]pub struct SessionConnectorData {pub payment_method_sub_type: api_enums::PaymentMethodType,@@ -186,11 +195,15 @@ common_utils::create_list_wrapper!();pub fn convert_connector_data_to_routable_connectors(- connectors: &[ConnectorData],+ connectors: &[ConnectorRoutingData],) -> CustomResult<Vec<RoutableConnectorChoice>, common_utils::errors::ValidationError> {connectors.iter()- .map(|connector_data| RoutableConnectorChoice::foreign_try_from(connector_data.clone()))+ .map(|connectors_routing_data| {+ RoutableConnectorChoice::foreign_try_from(+ connectors_routing_data.connector_data.clone(),+ )+ }).collect()}diff --git a/crates/router/src/types/api/fraud_check.rs b/crates/router/src/types/api/fraud_check.rsindex 44dc351466..b0ed7ed35d 100644--- a/crates/router/src/types/api/fraud_check.rs+++ b/crates/router/src/types/api/fraud_check.rs@@ -24,11 +24,17 @@ pub struct FraudCheckConnectorData {pub connector_name: enums::FrmConnectors,}pub enum ConnectorCallType {- PreDetermined(ConnectorData),- Retryable(Vec<ConnectorData>),+ PreDetermined(ConnectorRoutingData),+ Retryable(Vec<ConnectorRoutingData>),SessionMultiple(SessionConnectorDatas),}+#[derive(Clone)]+pub struct ConnectorRoutingData {+ pub connector_data: ConnectorData,+ pub network: Option<common_enums::CardNetwork>,+}+impl FraudCheckConnectorData {pub fn get_connector_by_name(name: &str) -> CustomResult<Self, errors::ApiErrorResponse> {let connector_name = enums::FrmConnectors::from_str(name)diff --git a/crates/router/src/utils/verify_connector.rs b/crates/router/src/utils/verify_connector.rsindex b13ba70e6f..0f5d9e6b31 100644--- a/crates/router/src/utils/verify_connector.rs+++ b/crates/router/src/utils/verify_connector.rs@@ -24,6 +24,7 @@ pub fn generate_card_from_details(card_issuing_country: None,bank_code: None,card_holder_name: None,+ co_badged_card_data: None,})}diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rsindex 8b3372d7de..3497a048a8 100644--- a/crates/router/tests/connectors/aci.rs+++ b/crates/router/tests/connectors/aci.rs@@ -52,6 +52,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData {bank_code: None,nick_name: Some(Secret::new("nick_name".into())),card_holder_name: Some(Secret::new("card holder name".into())),+ co_badged_card_data: None,}),confirm: true,statement_descriptor_suffix: None,@@ -302,6 +303,7 @@ async fn payments_create_failure() {bank_code: None,nick_name: Some(Secret::new("nick_name".into())),card_holder_name: Some(Secret::new("card holder name".into())),+ co_badged_card_data: None,});let response = services::api::execute_connector_processing_step(diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rsindex c7ad3b69a3..d7017d3d44 100644--- a/crates/router/tests/connectors/adyen.rs+++ b/crates/router/tests/connectors/adyen.rs@@ -154,6 +154,7 @@ impl AdyenTest {bank_code: None,nick_name: Some(Secret::new("nick_name".into())),card_holder_name: Some(Secret::new("card holder name".into())),+ co_badged_card_data: None,}),confirm: true,statement_descriptor_suffix: None,diff --git a/crates/router/tests/connectors/airwallex.rs b/crates/router/tests/connectors/airwallex.rsindex 0e538818d5..bf5a06f157 100644--- a/crates/router/tests/connectors/airwallex.rs+++ b/crates/router/tests/connectors/airwallex.rs@@ -83,6 +83,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {bank_code: None,nick_name: Some(Secret::new("nick_name".into())),card_holder_name: Some(Secret::new("card holder name".into())),+ co_badged_card_data: None,}),capture_method: Some(diesel_models::enums::CaptureMethod::Manual),router_return_url: Some("https://google.com".to_string()),diff --git a/crates/router/tests/connectors/fiserv.rs b/crates/router/tests/connectors/fiserv.rsindex 78235278ed..77ab822314 100644--- a/crates/router/tests/connectors/fiserv.rs+++ b/crates/router/tests/connectors/fiserv.rs@@ -54,6 +54,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {bank_code: None,nick_name: Some(Secret::new("nick_name".into())),card_holder_name: Some(Secret::new("card holder name".into())),+ co_badged_card_data: None,}),capture_method: Some(diesel_models::enums::CaptureMethod::Manual),..utils::PaymentAuthorizeType::default().0diff --git a/crates/router/tests/connectors/rapyd.rs b/crates/router/tests/connectors/rapyd.rsindex ee6ac303e8..e173f4753d 100644--- a/crates/router/tests/connectors/rapyd.rs+++ b/crates/router/tests/connectors/rapyd.rs@@ -54,6 +54,7 @@ async fn should_only_authorize_payment() {bank_code: None,nick_name: Some(Secret::new("nick_name".into())),card_holder_name: Some(Secret::new("card holder name".into())),+ co_badged_card_data: None,}),capture_method: Some(diesel_models::enums::CaptureMethod::Manual),..utils::PaymentAuthorizeType::default().0@@ -82,6 +83,7 @@ async fn should_authorize_and_capture_payment() {bank_code: None,nick_name: Some(Secret::new("nick_name".into())),card_holder_name: Some(Secret::new("card holder name".into())),+ co_badged_card_data: None,}),..utils::PaymentAuthorizeType::default().0}),diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rsindex ede3aeb17d..d6925ae166 100644--- a/crates/router/tests/connectors/utils.rs+++ b/crates/router/tests/connectors/utils.rs@@ -941,6 +941,7 @@ impl Default for CCardType {bank_code: None,nick_name: Some(Secret::new("nick_name".into())),card_holder_name: Some(Secret::new("card holder name".into())),+ co_badged_card_data: None,})}}diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rsindex 793a1cc15f..22fd198bd0 100644--- a/crates/router/tests/connectors/worldline.rs+++ b/crates/router/tests/connectors/worldline.rs@@ -84,6 +84,7 @@ impl WorldlineTest {bank_code: None,nick_name: Some(Secret::new("nick_name".into())),card_holder_name: Some(Secret::new("card holder name".into())),+ co_badged_card_data: None,}),confirm: true,statement_descriptor_suffix: None,diff --git a/cypress-tests/cypress/e2e/configs/Payment/Noon.js b/cypress-tests/cypress/e2e/configs/Payment/Noon.jsindex 7bf529af37..2ae1d2a224 100644--- a/cypress-tests/cypress/e2e/configs/Payment/Noon.js+++ b/cypress-tests/cypress/e2e/configs/Payment/Noon.js@@ -191,7 +191,7 @@ export const connectorDetails = {},},No3DSAutoCapture: {- Configs:{+ Configs: {TRIGGER_SKIP: true,},Request: {@@ -234,7 +234,7 @@ export const connectorDetails = {body: {status: "partially_captured",amount: 9000,- amount_received:6500,+ amount_received: 6500,amount_capturable: 0,},},@@ -260,7 +260,7 @@ export const connectorDetails = {},},manualPaymentRefund: {- Configs:{+ Configs: {TRIGGER_SKIP: true,},Request: {@@ -274,7 +274,7 @@ export const connectorDetails = {},},manualPaymentPartialRefund: {- Configs:{+ Configs: {TRIGGER_SKIP: true,},Request: {@@ -401,7 +401,7 @@ export const connectorDetails = {},},MandateMultiUseNo3DSManualCapture: {- Configs:{+ Configs: {TRIGGER_SKIP: true,},Request: {diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.jsindex 8a517dfc52..da76d4090d 100644--- a/cypress-tests/cypress/support/commands.js+++ b/cypress-tests/cypress/support/commands.js@@ -1640,7 +1640,10 @@ Cypress.Commands.add(expect(resData.body[key], [key]).to.deep.equal(response.body[key]);- if (setupFutureUsage === "off_session" && response.body.status==="succeeded") {+ if (+ setupFutureUsage === "off_session" &&+ response.body.status === "succeeded"+ ) {expect(response.body.connector_mandate_id,"connector_mandate_id"@@ -1671,7 +1674,10 @@ Cypress.Commands.add(expect(resData.body[key], [key]).to.deep.equal(response.body[key]);- if (setupFutureUsage === "off_session" && response.body.status === "succeeded") {+ if (+ setupFutureUsage === "off_session" &&+ response.body.status === "succeeded"+ ) {expect(response.body.connector_mandate_id,"connector_mandate_id"@@ -2630,7 +2636,10 @@ Cypress.Commands.add(expect(resData.body[key], [key]).to.deep.equal(response.body[key]);- if (setupFutureUsage === "off_session" && response.body.status === "succeeded") {+ if (+ setupFutureUsage === "off_session" &&+ response.body.status === "succeeded"+ ) {expect(response.body.connector_mandate_id,"connector_mandate_id"@@ -2663,7 +2672,10 @@ Cypress.Commands.add(expect(resData.body[key], [key]).to.deep.equal(response.body[key]);- if (setupFutureUsage === "off_session" && response.body.status === "succeeded") {+ if (+ setupFutureUsage === "off_session" &&+ response.body.status === "succeeded"+ ) {expect(response.body.connector_mandate_id,"connector_mandate_id"@@ -2892,10 +2904,10 @@ Cypress.Commands.add(allowedActiveStatuses);- expect(- response.body.payment_method_status,+ expect(+ response.body.payment_method_status,"payment_method_status for active status"- ).to.equal("active");+ ).to.equal("active");if (connector_agnostic_mit) {expect(diff --git a/loadtest/config/development.toml b/loadtest/config/development.tomlindex f4f1eeb2fa..d682b5c3f8 100644--- a/loadtest/config/development.toml+++ b/loadtest/config/development.toml@@ -590,6 +590,12 @@ bank_redirect.trustly.connector_list = "adyen,aci"bank_redirect.open_banking_uk.connector_list = "adyen"bank_redirect.eps.connector_list = "globalpay,nexinets,aci"+[debit_routing_config]+supported_currencies = "USD"+supported_connectors = "adyen"++[debit_routing_config.connector_supported_debit_networks]+adyen = "Star,Pulse,Accel,Nyce"[cors]max_age = 30