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): Deduplicate PML response and populate bank details (V2) (#8583)
Anurag Thakur7d54ce87f0db
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex 4820c944dc..64add77b78 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -17645,10 +17645,7 @@],"properties": {"bank_names": {- "type": "array",- "items": {- "$ref": "#/components/schemas/BankCodeResponse"- }+ "$ref": "#/components/schemas/BankNames"}}}@@ -22371,11 +22368,11 @@"$ref": "#/components/schemas/PaymentMethodType"},"payment_experience": {- "allOf": [- {- "$ref": "#/components/schemas/PaymentExperience"- }- ],+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/PaymentExperience"+ },+ "description": "The payment experience for the payment method","nullable": true},"required_fields": {diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex 4cdfe9dcfe..a70dceb962 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -16,12 +16,11 @@ use masking::PeekInterface;use serde::de;use utoipa::{schema, ToSchema};+#[cfg(feature = "v1")]+use crate::payments::BankCodeResponse;#[cfg(feature = "payouts")]use crate::payouts;-use crate::{- admin, enums as api_enums, open_router,- payments::{self, BankCodeResponse},-};+use crate::{admin, enums as api_enums, open_router, payments};#[cfg(feature = "v1")]#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]@@ -1471,7 +1470,10 @@ pub enum PaymentMethodSubtypeSpecificData {card_networks: Vec<CardNetworkTypes>,},#[schema(title = "bank")]- Bank { bank_names: Vec<BankCodeResponse> },+ Bank {+ #[schema(value_type = BankNames)]+ bank_names: Vec<common_enums::BankNames>,+ },}#[cfg(feature = "v2")]diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex 90792e9633..3697c555e7 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -7727,8 +7727,8 @@ pub struct ResponsePaymentMethodTypesForPayments {pub payment_method_subtype: common_enums::PaymentMethodType,/// The payment experience for the payment method- #[schema(value_type = Option<PaymentExperience>)]- pub payment_experience: Option<common_enums::PaymentExperience>,+ #[schema(value_type = Option<Vec<PaymentExperience>>)]+ pub payment_experience: Option<Vec<common_enums::PaymentExperience>>,/// payment method subtype specific information#[serde(flatten)]diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 1d00a45170..893473cfbc 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -1832,7 +1832,9 @@ pub enum SamsungPayCardBrand {Copy,Debug,Eq,+ Ord,Hash,+ PartialOrd,PartialEq,serde::Deserialize,serde::Serialize,@@ -2081,6 +2083,8 @@ impl masking::SerializableSecret for PaymentMethodType {}Debug,Default,Eq,+ PartialOrd,+ Ord,Hash,PartialEq,serde::Deserialize,diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rsindex d5848c7f41..ca2d5d1015 100644--- a/crates/router/src/core/payment_methods/vault.rs+++ b/crates/router/src/core/payment_methods/vault.rs@@ -1598,7 +1598,7 @@ pub async fn retrieve_and_delete_cvc_from_payment_token(.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to get redis connection")?;- let key = format!("pm_token_{payment_token}_{payment_method}_hyperswitch_cvc");+ let key = format!("pm_token_{payment_token}_{payment_method}_hyperswitch_cvc",);let data = redis_conn.get_key::<bytes::Bytes>(&key.clone().into())diff --git a/crates/router/src/core/payments/payment_methods.rs b/crates/router/src/core/payments/payment_methods.rsindex 1cf17289a2..e21b3b9610 100644--- a/crates/router/src/core/payments/payment_methods.rs+++ b/crates/router/src/core/payments/payment_methods.rs@@ -1,11 +1,15 @@//! Contains functions of payment methods that are used in payments//! one of such functions is `list_payment_methods`+use std::collections::{BTreeMap, HashSet};+use common_utils::{ext_traits::OptionExt, id_type};use error_stack::ResultExt;use super::errors;-use crate::{core::payment_methods, db::errors::StorageErrorExt, routes, types::domain};+use crate::{+ core::payment_methods, db::errors::StorageErrorExt, logger, routes, settings, types::domain,+};#[cfg(feature = "v2")]pub async fn list_payment_methods(@@ -55,10 +59,12 @@ pub async fn list_payment_methods(};let response =- hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled::from_payment_connectors_list(payment_connector_accounts)+ FlattenedPaymentMethodsEnabled(hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled::from_payment_connectors_list(payment_connector_accounts)).perform_filtering()+ .merge_and_transform().get_required_fields(RequiredFieldsInput::new()).perform_surcharge_calculation()+ .populate_pm_subtype_specific_data(&state.conf.bank_config).generate_response(customer_payment_methods);Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(@@ -75,12 +81,79 @@ impl RequiredFieldsInput {}}+struct FlattenedPaymentMethodsEnabled(+ hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled,+);++impl FlattenedPaymentMethodsEnabled {+ fn perform_filtering(self) -> FilteredPaymentMethodsEnabled {+ FilteredPaymentMethodsEnabled(self.0.payment_methods_enabled)+ }+}+/// Container for the filtered payment methodsstruct FilteredPaymentMethodsEnabled(Vec<hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector>,);impl FilteredPaymentMethodsEnabled {+ fn merge_and_transform(self) -> MergedEnabledPaymentMethodTypes {+ let values = self+ .0+ .into_iter()+ // BTreeMap used to ensure soretd response, otherwise the response is arbitrarily ordered+ .fold(BTreeMap::new(), |mut acc, item| {+ let key = (+ item.payment_method,+ item.payment_methods_enabled.payment_method_subtype,+ );+ let (experiences, connectors) = acc+ .entry(key)+ // HashSet used to ensure payment_experience does not have duplicates, due to multiple connectors for a pm_subtype+ .or_insert_with(|| (HashSet::new(), Vec::new()));++ if let Some(experience) = item.payment_methods_enabled.payment_experience {+ experiences.insert(experience);+ }+ connectors.push(item.connector);++ acc+ })+ .into_iter()+ .map(+ |(+ (payment_method_type, payment_method_subtype),+ (payment_experience, connectors),+ )| {+ MergedEnabledPaymentMethod {+ payment_method_type,+ payment_method_subtype,+ payment_experience: if payment_experience.is_empty() {+ None+ } else {+ Some(payment_experience.into_iter().collect())+ },+ connectors,+ }+ },+ )+ .collect();+ MergedEnabledPaymentMethodTypes(values)+ }+}++/// Element container to hold the filtered payment methods with payment_experience and connectors merged for a pm_subtype+struct MergedEnabledPaymentMethod {+ payment_method_subtype: common_enums::PaymentMethodType,+ payment_method_type: common_enums::PaymentMethod,+ payment_experience: Option<Vec<common_enums::PaymentExperience>>,+ connectors: Vec<api_models::enums::Connector>,+}++/// Container to hold the filtered payment methods with payment_experience and connectors merged for a pm_subtype+struct MergedEnabledPaymentMethodTypes(Vec<MergedEnabledPaymentMethod>);++impl MergedEnabledPaymentMethodTypes {fn get_required_fields(self,_input: RequiredFieldsInput,@@ -91,13 +164,10 @@ impl FilteredPaymentMethodsEnabled {.map(|payment_methods_enabled| RequiredFieldsForEnabledPaymentMethod {required_field: None,- payment_method_type: payment_methods_enabled.payment_method,- payment_method_subtype: payment_methods_enabled- .payment_methods_enabled- .payment_method_subtype,- payment_experience: payment_methods_enabled- .payment_methods_enabled- .payment_experience,+ payment_method_type: payment_methods_enabled.payment_method_type,+ payment_method_subtype: payment_methods_enabled.payment_method_subtype,+ payment_experience: payment_methods_enabled.payment_experience,+ connectors: payment_methods_enabled.connectors,},).collect();@@ -111,18 +181,44 @@ struct RequiredFieldsForEnabledPaymentMethod {required_field: Option<Vec<api_models::payment_methods::RequiredFieldInfo>>,payment_method_subtype: common_enums::PaymentMethodType,payment_method_type: common_enums::PaymentMethod,- payment_experience: Option<common_enums::PaymentExperience>,+ payment_experience: Option<Vec<common_enums::PaymentExperience>>,+ connectors: Vec<api_models::enums::Connector>,}/// Container to hold the filtered payment methods enabled with required fieldsstruct RequiredFieldsForEnabledPaymentMethodTypes(Vec<RequiredFieldsForEnabledPaymentMethod>);+impl RequiredFieldsForEnabledPaymentMethodTypes {+ fn perform_surcharge_calculation(+ self,+ ) -> RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes {+ // TODO: Perform surcharge calculation+ let details_with_surcharge = self+ .0+ .into_iter()+ .map(+ |payment_methods_enabled| RequiredFieldsAndSurchargeForEnabledPaymentMethodType {+ payment_method_type: payment_methods_enabled.payment_method_type,+ required_field: payment_methods_enabled.required_field,+ payment_method_subtype: payment_methods_enabled.payment_method_subtype,+ payment_experience: payment_methods_enabled.payment_experience,+ surcharge: None,+ connectors: payment_methods_enabled.connectors,+ },+ )+ .collect();++ RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes(details_with_surcharge)+ }+}+/// Element Container to hold the filtered payment methods enabled with required fields and surchargestruct RequiredFieldsAndSurchargeForEnabledPaymentMethodType {required_field: Option<Vec<api_models::payment_methods::RequiredFieldInfo>>,payment_method_subtype: common_enums::PaymentMethodType,payment_method_type: common_enums::PaymentMethod,- payment_experience: Option<common_enums::PaymentExperience>,+ payment_experience: Option<Vec<common_enums::PaymentExperience>>,+ connectors: Vec<api_models::enums::Connector>,surcharge: Option<api_models::payment_methods::SurchargeDetailsResponse>,}@@ -131,7 +227,105 @@ struct RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes(Vec<RequiredFieldsAndSurchargeForEnabledPaymentMethodType>,);+fn get_pm_subtype_specific_data(+ bank_config: &settings::BankRedirectConfig,+ payment_method_type: common_enums::enums::PaymentMethod,+ payment_method_subtype: common_enums::enums::PaymentMethodType,+ connectors: &[api_models::enums::Connector],+) -> Option<api_models::payment_methods::PaymentMethodSubtypeSpecificData> {+ match payment_method_type {+ // TODO: Return card_networks+ common_enums::PaymentMethod::Card | common_enums::PaymentMethod::CardRedirect => None,++ common_enums::PaymentMethod::BankRedirect+ | common_enums::PaymentMethod::BankTransfer+ | common_enums::PaymentMethod::BankDebit+ | common_enums::PaymentMethod::OpenBanking => {+ if let Some(connector_bank_names) = bank_config.0.get(&payment_method_subtype) {+ let bank_names = connectors+ .iter()+ .filter_map(|connector| {+ connector_bank_names.0.get(&connector.to_string())+ .map(|connector_hash_set| {+ connector_hash_set.banks.clone()+ })+ .or_else(|| {+ logger::debug!("Could not find any configured connectors for payment_method -> {payment_method_subtype} for connector -> {connector}");+ None+ })+ })+ .flatten()+ .collect();+ Some(+ api_models::payment_methods::PaymentMethodSubtypeSpecificData::Bank {+ bank_names,+ },+ )+ } else {+ logger::debug!("Could not find any configured banks for payment_method -> {payment_method_subtype}");+ None+ }+ }++ common_enums::PaymentMethod::PayLater+ | common_enums::PaymentMethod::Wallet+ | common_enums::PaymentMethod::Crypto+ | common_enums::PaymentMethod::Reward+ | common_enums::PaymentMethod::RealTimePayment+ | common_enums::PaymentMethod::Upi+ | common_enums::PaymentMethod::Voucher+ | common_enums::PaymentMethod::GiftCard+ | common_enums::PaymentMethod::MobilePayment => None,+ }+}+impl RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes {+ fn populate_pm_subtype_specific_data(+ self,+ bank_config: &settings::BankRedirectConfig,+ ) -> RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodTypes {+ let response_payment_methods = self+ .0+ .into_iter()+ .map(|payment_methods_enabled| {+ RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodType {+ payment_method_type: payment_methods_enabled.payment_method_type,+ payment_method_subtype: payment_methods_enabled.payment_method_subtype,+ payment_experience: payment_methods_enabled.payment_experience,+ required_field: payment_methods_enabled.required_field,+ surcharge: payment_methods_enabled.surcharge,+ pm_subtype_specific_data: get_pm_subtype_specific_data(+ bank_config,+ payment_methods_enabled.payment_method_type,+ payment_methods_enabled.payment_method_subtype,+ &payment_methods_enabled.connectors,+ ),+ }+ })+ .collect();++ RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodTypes(+ response_payment_methods,+ )+ }+}++/// Element Container to hold the filtered payment methods enabled with required fields, surcharge and subtype specific data+struct RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodType {+ required_field: Option<Vec<api_models::payment_methods::RequiredFieldInfo>>,+ payment_method_subtype: common_enums::PaymentMethodType,+ payment_method_type: common_enums::PaymentMethod,+ payment_experience: Option<Vec<common_enums::PaymentExperience>>,+ surcharge: Option<api_models::payment_methods::SurchargeDetailsResponse>,+ pm_subtype_specific_data: Option<api_models::payment_methods::PaymentMethodSubtypeSpecificData>,+}++/// Container to hold the filtered payment methods enabled with required fields, surcharge and subtype specific data+struct RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodTypes(+ Vec<RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodType>,+);++impl RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodTypes {fn generate_response(self,customer_payment_methods: Option<@@ -148,7 +342,7 @@ impl RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes {payment_experience: payment_methods_enabled.payment_experience,required_fields: payment_methods_enabled.required_field,surcharge_details: payment_methods_enabled.surcharge,- extra_information: None,+ extra_information: payment_methods_enabled.pm_subtype_specific_data,}}).collect();@@ -160,40 +354,6 @@ impl RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes {}}-impl RequiredFieldsForEnabledPaymentMethodTypes {- fn perform_surcharge_calculation(- self,- ) -> RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes {- let details_with_surcharge = self- .0- .into_iter()- .map(- |payment_methods_enabled| RequiredFieldsAndSurchargeForEnabledPaymentMethodType {- payment_method_type: payment_methods_enabled.payment_method_type,- required_field: payment_methods_enabled.required_field,- payment_method_subtype: payment_methods_enabled.payment_method_subtype,- payment_experience: payment_methods_enabled.payment_experience,- surcharge: None,- },- )- .collect();-- RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes(details_with_surcharge)- }-}--trait PerformFilteringOnPaymentMethodsEnabled {- fn perform_filtering(self) -> FilteredPaymentMethodsEnabled;-}--impl PerformFilteringOnPaymentMethodsEnabled- for hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled-{- fn perform_filtering(self) -> FilteredPaymentMethodsEnabled {- FilteredPaymentMethodsEnabled(self.payment_methods_enabled)- }-}-/// Validate if payment methods list can be performed on the current status of payment intentfn validate_payment_status_for_payment_method_list(intent_status: common_enums::IntentStatus,