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(installments): add connector-currency config for installment payment visibility (#11481)
Ayush Anand01fe77ac5c03
diff --git a/config/config.example.toml b/config/config.example.tomlindex 5e8ec07ee6..709788a439 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -614,6 +614,9 @@ card.debit = { connector_list = "cybersource" } # Update Mandate supported paymcard.credit = "adyen" # Installment supported payment method type and connector for cardcard.debit = "adyen" # Installment supported payment method type and connector for card+[installment_config]+adyen = ["BRL", "MXN", "JPY"] # Connectors and their supported currencies for installment payments+# Required fields info used while listing the payment_method_data[required_fields.pay_later] # payment_method = "pay_later"afterpay_clearpay = { fields = { stripe = [ # payment_method_type = afterpay_clearpay, connector = "stripe"diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.tomlindex 1c6155461d..869b970430 100644--- a/config/deployments/integration_test.toml+++ b/config/deployments/integration_test.toml@@ -286,6 +286,9 @@ card.debit = { connector_list = "cybersource" } # Update Mandate supcard.credit = "adyen"card.debit = "adyen"+[installment_config]+adyen = ["BRL", "MXN", "JPY"]+[network_transaction_id_supported_connectors]connector_list = "adyen,archipel,checkout,cybersource,novalnet,nuvei,stripe,worldpay,worldpayvantiv"diff --git a/config/deployments/production.toml b/config/deployments/production.tomlindex 620e59145b..c65d36a786 100644--- a/config/deployments/production.toml+++ b/config/deployments/production.toml@@ -286,6 +286,9 @@ card.debit = { connector_list = "cybersource" } # Update Mandate supcard.credit = "adyen"card.debit = "adyen"+[installment_config]+adyen = ["BRL", "MXN", "JPY"]+[network_transaction_id_supported_connectors]connector_list = "adyen,archipel,checkout,cybersource,stripe,nuvei,worldpayvantiv"diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.tomlindex 64713e40aa..cb82221bbc 100644--- a/config/deployments/sandbox.toml+++ b/config/deployments/sandbox.toml@@ -293,6 +293,9 @@ card.debit = { connector_list = "cybersource" } # Update Mandate supcard.credit = "adyen"card.debit = "adyen"+[installment_config]+adyen = ["BRL", "MXN", "JPY"]+[network_transaction_id_supported_connectors]connector_list = "adyen,archipel,checkout,cybersource,novalnet,nuvei,stripe,worldpay,worldpayvantiv"diff --git a/config/development.toml b/config/development.tomlindex fb8b96da55..7de7350185 100644--- a/config/development.toml+++ b/config/development.toml@@ -1213,6 +1213,9 @@ card.debit = { connector_list = "cybersource" }card.credit = "adyen"card.debit = "adyen"+[installment_config]+adyen = ["BRL", "MXN", "JPY"]+[network_transaction_id_supported_connectors]connector_list = "adyen,archipel,checkout,cybersource,novalnet,nuvei,stripe,worldpay,worldpayvantiv"diff --git a/config/docker_compose.toml b/config/docker_compose.tomlindex 0e014c88af..51835071e4 100644--- a/config/docker_compose.toml+++ b/config/docker_compose.toml@@ -1110,6 +1110,9 @@ card.debit = { connector_list = "cybersource" }card.credit = "adyen"card.debit = "adyen"+[installment_config]+adyen = ["BRL", "MXN", "JPY"]+[network_transaction_id_supported_connectors]connector_list = "adyen,archipel,checkout,cybersource,novalnet,stripe,worldpay,worldpayvantiv"diff --git a/crates/common_types/src/payments.rs b/crates/common_types/src/payments.rsindex 6fedf17280..1fd46ae110 100644--- a/crates/common_types/src/payments.rs+++ b/crates/common_types/src/payments.rs@@ -1249,7 +1249,7 @@ pub struct NetworkTransactionIdAndDecryptedWalletTokenDetails {}/// Billing frequency for a card installment plan-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)]+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq, Hash)]#[serde(rename_all = "snake_case")]pub enum BillingFrequency {/// Monthly billing@@ -1396,6 +1396,81 @@ pub struct InstallmentOptionData {pub interest_rate: InstallmentInterestRate,}+/// A validated list of installment entries with no duplicate counts per billing frequency.+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]+#[serde(try_from = "Vec<InstallmentOptionData>")]+pub struct InstallmentEntries(Vec<InstallmentOptionData>);++impl InstallmentEntries {+ /// Validates that no installment count appears more than once for the same billing frequency+ /// across all entries.+ /// Uses two nested `try_fold`s because the data is two-dimensional:+ /// - The **outer** `try_fold` iterates over each `InstallmentOptionData` entry, carrying a+ /// `HashMap<BillingFrequency, HashSet<count>>` as the accumulator to track all counts seen+ /// so far grouped by frequency.+ /// - The **inner** `try_fold` iterates over the `number_of_installments` vec within a single+ /// entry, attempting to insert each count into the set for its frequency. If `insert` returns+ /// `false` (count already present), it short-circuits with a validation error.+ fn validate_no_duplicate_counts_per_frequency(+ installments: &[InstallmentOptionData],+ ) -> Result<(), errors::ValidationError> {+ installments+ .iter()+ .try_fold(+ HashMap::<&BillingFrequency, HashSet<NonZeroU8>>::new(),+ |mut seen, entry| {+ entry+ .number_of_installments+ .as_slice()+ .iter()+ .try_fold(&mut seen, |seen, &count| {+ seen.entry(&entry.billing_frequency)+ .or_default()+ .insert(count)+ .then_some(seen)+ .ok_or_else(|| {+ error_stack::report!(+ errors::ValidationError::InvalidValue {+ message: format!(+ "installment count {count} appears in multiple entries with the same billing frequency."+ ),+ }+ )+ })+ })?;+ Ok(seen)+ },+ )+ .map(|_| ())+ }+}++impl TryFrom<Vec<InstallmentOptionData>> for InstallmentEntries {+ type Error = Report<errors::ValidationError>;++ fn try_from(entries: Vec<InstallmentOptionData>) -> Result<Self, errors::ValidationError> {+ Self::validate_no_duplicate_counts_per_frequency(&entries)?;+ Ok(Self(entries))+ }+}++impl std::ops::Deref for InstallmentEntries {+ type Target = Vec<InstallmentOptionData>;++ fn deref(&self) -> &Self::Target {+ &self.0+ }+}++impl IntoIterator for InstallmentEntries {+ type Item = InstallmentOptionData;+ type IntoIter = std::vec::IntoIter<InstallmentOptionData>;++ fn into_iter(self) -> Self::IntoIter {+ self.0.into_iter()+ }+}+/// Installment options grouped by payment method#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq)]pub struct InstallmentOption {@@ -1403,7 +1478,8 @@ pub struct InstallmentOption {#[schema(value_type = PaymentMethod)]pub payment_method: common_enums::PaymentMethod,/// List of available installment configurations- pub installments: Vec<InstallmentOptionData>,+ #[schema(value_type = Vec<InstallmentOptionData>)]+ pub installments: InstallmentEntries,}/// A list of installment options stored as a single JSONB column value.diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rsindex 6ac352f970..3db2a7709b 100644--- a/crates/hyperswitch_domain_models/src/payments.rs+++ b/crates/hyperswitch_domain_models/src/payments.rs@@ -448,6 +448,7 @@ impl PaymentIntent {pub fn into_payment_method_list_intent_data(self,net_amount: MinorUnit,+ show_installments: bool,) -> CustomResult<PaymentMethodListIntentData, errors::api_error_response::ApiErrorResponse>{let billing: Option<Address> = self@@ -466,28 +467,31 @@ impl PaymentIntent {.attach_printable("Failed to parse shipping address")?.map(|enc| enc.into_inner());- let installment_options = self- .installment_options- .map(|opts| {- let currency = self.currency.get_required_value("currency")?;- opts.into_iter()- .map(|opt| {- PaymentMethodListInstallmentOption::from_installment_option(- opt.clone(),- self.amount,- net_amount,- currency,- )- .change_context(- errors::api_error_response::ApiErrorResponse::InternalServerError,- )- .attach_printable_lazy(|| {- format!("Failed to transform installment option: {:?}", opt)+ let installment_options = match show_installments {+ false => None,+ true => self+ .installment_options+ .map(|opts| {+ let currency = self.currency.get_required_value("currency")?;+ opts.into_iter()+ .map(|opt| {+ PaymentMethodListInstallmentOption::from_installment_option(+ opt.clone(),+ self.amount,+ net_amount,+ currency,+ )+ .change_context(+ errors::api_error_response::ApiErrorResponse::InternalServerError,+ )+ .attach_printable_lazy(|| {+ format!("Failed to transform installment option: {:?}", opt)+ })})- })- .collect::<CustomResult<Vec<_>, _>>()- })- .transpose()?;+ .collect::<CustomResult<Vec<_>, _>>()+ })+ .transpose()?,+ };Ok(PaymentMethodListIntentData {payment_id: self.payment_id,diff --git a/crates/payment_methods/src/configs/settings.rs b/crates/payment_methods/src/configs/settings.rsindex 87b467d9fb..8deb384714 100644--- a/crates/payment_methods/src/configs/settings.rs+++ b/crates/payment_methods/src/configs/settings.rs@@ -109,6 +109,24 @@ pub struct SupportedPaymentMethodTypesForInstallments(pub struct SupportedConnectorsForInstallments(#[serde(deserialize_with = "deserialize_hashset")] pub HashSet<enums::Connector>,);++#[derive(Debug, Deserialize, Clone, Default)]+#[serde(default)]+pub struct InstallmentConfig(pub HashMap<enums::Connector, Vec<common_enums::enums::Currency>>);++impl InstallmentConfig {+ pub fn is_connector_currency_supported(+ &self,+ connector: &enums::Connector,+ currency: common_enums::enums::Currency,+ ) -> bool {+ self.0+ .get(connector)+ .map(|currencies| currencies.contains(¤cy))+ .unwrap_or(false)+ }+}+#[derive(Debug, Deserialize, Clone)]pub struct Mandates {pub supported_payment_methods: SupportedPaymentMethodsForMandate,diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rsindex e7a9dcaea7..2f9c892866 100644--- a/crates/router/src/configs/secrets_transformers.rs+++ b/crates/router/src/configs/secrets_transformers.rs@@ -571,6 +571,7 @@ pub(crate) async fn fetch_raw_secrets(mandates: conf.mandates,zero_mandates: conf.zero_mandates,installments: conf.installments,+ installment_config: conf.installment_config,network_transaction_id_supported_connectors: conf.network_transaction_id_supported_connectors,card_only_mit_supported_connectors: conf.card_only_mit_supported_connectors,diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex 5f0a73466c..42a4004ae1 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -36,9 +36,9 @@ pub use hyperswitch_interfaces::{use masking::{Maskable, Secret};pub use payment_methods::configs::settings::{BankRedirectConfig, BanksVector, ConnectorBankNames, ConnectorFields, EligiblePaymentMethods,- Installments, Mandates, PaymentMethodAuth, PaymentMethodType, RequiredFieldFinal,- RequiredFields, SupportedConnectorsForMandate, SupportedPaymentMethodTypesForMandate,- SupportedPaymentMethodsForMandate, ZeroMandates,+ InstallmentConfig, Installments, Mandates, PaymentMethodAuth, PaymentMethodType,+ RequiredFieldFinal, RequiredFields, SupportedConnectorsForMandate,+ SupportedPaymentMethodTypesForMandate, SupportedPaymentMethodsForMandate, ZeroMandates,};use payment_methods::configs::MicroServicesConfig;use rand::seq::IteratorRandom;@@ -118,6 +118,7 @@ pub struct Settings<S: SecretState> {pub mandates: Mandates,pub zero_mandates: ZeroMandates,pub installments: Installments,+ pub installment_config: InstallmentConfig,pub network_transaction_id_supported_connectors: NetworkTransactionIdSupportedConnectors,pub card_only_mit_supported_connectors: CardOnlyMitSupportedConnectors,pub list_dispute_supported_connectors: ListDiputeSupportedConnectors,diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex a065fe873f..dd0d174b8d 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -3848,6 +3848,20 @@ pub async fn list_payment_methods(.as_ref().map(|payment_intent| payment_intent.customer_id.is_none()).unwrap_or(true);+ let connector_supports_installments = currency.is_some_and(|cur| {+ filtered_mcas.iter().any(|mca| {+ mca.connector_name+ .parse::<api_enums::Connector>()+ .ok()+ .is_some_and(|connector| {+ state+ .conf+ .installment_config+ .is_connector_currency_supported(&connector, cur)+ })+ })+ });+let merchant_surcharge_configs = if let Some((payment_attempt, payment_intent)) =payment_attempt.as_ref().zip(payment_intent.clone()){@@ -3892,7 +3906,7 @@ pub async fn list_payment_methods(.as_ref().map(|pa| pa.net_amount.get_total_amount()).unwrap_or(pi.amount);- pi.into_payment_method_list_intent_data(net_amount)+ pi.into_payment_method_list_intent_data(net_amount, connector_supports_installments)}).transpose().change_context(errors::ApiErrorResponse::InternalServerError)