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(payments): expose installment options and intent data in PML response (#11398)
Ayush Anandd7ff8307099e
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex 4361a7014c..285c8d5746 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -20982,7 +20982,7 @@"interest_rate": {"type": "number","format": "double",- "description": "Interest rate per installment as a percentage max 2 decimal places\n"+ "description": "Interest rate per installment as a percentage max 2 decimal places"}}},@@ -27152,6 +27152,197 @@"jp_bacs"]},+ "PaymentMethodListInstallmentAmountDetails": {+ "type": "object",+ "description": "Amount breakdown for a single installment plan",+ "required": [+ "amount_per_installment",+ "total_amount"+ ],+ "properties": {+ "amount_per_installment": {+ "type": "number",+ "format": "double",+ "description": "Amount charged per installment in major units"+ },+ "total_amount": {+ "type": "number",+ "format": "double",+ "description": "Total amount across all installments in major units (may differ slightly from order amount due to ceiling)"+ }+ }+ },+ "PaymentMethodListInstallmentOption": {+ "type": "object",+ "description": "Installment options for a payment method, as returned in the payment method list response",+ "required": [+ "payment_method",+ "available_plans"+ ],+ "properties": {+ "payment_method": {+ "$ref": "#/components/schemas/PaymentMethod"+ },+ "available_plans": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/PaymentMethodListInstallmentPlan"+ },+ "description": "Individual installment plans with computed amounts"+ }+ }+ },+ "PaymentMethodListInstallmentPlan": {+ "type": "object",+ "description": "A single installment plan with pre-computed amount breakdown",+ "required": [+ "number_of_installments",+ "billing_frequency",+ "interest_rate",+ "amount_details"+ ],+ "properties": {+ "number_of_installments": {+ "type": "integer",+ "format": "int32",+ "description": "Number of installments for this plan",+ "minimum": 0+ },+ "billing_frequency": {+ "$ref": "#/components/schemas/BillingFrequency"+ },+ "interest_rate": {+ "type": "number",+ "format": "double",+ "description": "Interest rate as a percentage"+ },+ "amount_details": {+ "$ref": "#/components/schemas/PaymentMethodListInstallmentAmountDetails"+ }+ }+ },+ "PaymentMethodListIntentData": {+ "type": "object",+ "description": "Intent-only payment details returned as part of the Payment Method List response",+ "required": [+ "payment_id",+ "status",+ "amount",+ "attempt_count"+ ],+ "properties": {+ "payment_id": {+ "type": "string",+ "description": "Unique identifier for the payment"+ },+ "status": {+ "$ref": "#/components/schemas/IntentStatus"+ },+ "amount": {+ "$ref": "#/components/schemas/MinorUnit"+ },+ "currency": {+ "allOf": [+ {+ "$ref": "#/components/schemas/Currency"+ }+ ],+ "nullable": true+ },+ "client_secret": {+ "type": "string",+ "description": "Client secret for client-side payment confirmation",+ "nullable": true+ },+ "description": {+ "type": "string",+ "description": "A description for the payment",+ "nullable": true+ },+ "customer_id": {+ "type": "string",+ "description": "The customer identifier",+ "nullable": true+ },+ "return_url": {+ "type": "string",+ "description": "The URL to redirect to after payment completion",+ "nullable": true+ },+ "setup_future_usage": {+ "allOf": [+ {+ "$ref": "#/components/schemas/FutureUsage"+ }+ ],+ "nullable": true+ },+ "billing": {+ "allOf": [+ {+ "$ref": "#/components/schemas/Address"+ }+ ],+ "nullable": true+ },+ "shipping": {+ "allOf": [+ {+ "$ref": "#/components/schemas/Address"+ }+ ],+ "nullable": true+ },+ "metadata": {+ "type": "object",+ "description": "Additional metadata",+ "nullable": true+ },+ "order_details": {+ "type": "array",+ "items": {+ "type": "object"+ },+ "description": "Order details for the payment",+ "nullable": true+ },+ "created": {+ "type": "string",+ "format": "date-time",+ "description": "Timestamp when the payment was created",+ "nullable": true+ },+ "expires_on": {+ "type": "string",+ "format": "date-time",+ "description": "Timestamp when the client secret expires",+ "nullable": true+ },+ "profile_id": {+ "type": "string",+ "description": "The profile identifier",+ "nullable": true+ },+ "merchant_order_reference_id": {+ "type": "string",+ "description": "Merchant-provided reference identifier",+ "nullable": true+ },+ "attempt_count": {+ "type": "integer",+ "format": "int32",+ "description": "Number of payment attempts made"+ },+ "installment_options": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/PaymentMethodListInstallmentOption"+ },+ "description": "Installment options available for this payment",+ "nullable": true+ }+ }+ },"PaymentMethodListResponse": {"type": "object","required": [@@ -27225,6 +27416,14 @@"is_guest_customer": {"type": "boolean","description": "indicates whether this is a guest customer flow"+ },+ "intent_data": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PaymentMethodListIntentData"+ }+ ],+ "nullable": true}}},diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex 45f7239d2e..c97d09bf5f 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -1,8 +1,12 @@-use std::collections::{HashMap, HashSet};#[cfg(feature = "v2")]use std::str::FromStr;+use std::{+ collections::{HashMap, HashSet},+ num::NonZeroU8,+};use cards::CardNumber;+use common_types::payments::{BillingFrequency, InstallmentInterestRate};#[cfg(feature = "v1")]use common_utils::crypto::OptionalEncryptableName;use common_utils::{@@ -10,8 +14,9 @@ use common_utils::{errors,ext_traits::OptionExt,id_type, link_utils, pii,- types::{MinorUnit, Percentage, Surcharge},+ types::{FloatMajorUnit, MinorUnit, Percentage, Surcharge},};+use error_stack::ResultExt;use masking::PeekInterface;use serde::de;use utoipa::ToSchema;@@ -2470,6 +2475,187 @@ pub struct PaymentMethodListResponse {/// indicates whether this is a guest customer flowpub is_guest_customer: bool,++ /// Payment intent details associated with this payment method list request+ pub intent_data: Option<PaymentMethodListIntentData>,+}++/// Intent-only payment details returned as part of the Payment Method List response+#[derive(Debug, serde::Serialize, ToSchema)]+pub struct PaymentMethodListIntentData {+ /// Unique identifier for the payment+ #[schema(value_type = String)]+ pub payment_id: id_type::PaymentId,++ /// The status of the payment+ #[schema(value_type = IntentStatus)]+ pub status: api_enums::IntentStatus,++ /// The payment amount+ pub amount: MinorUnit,++ /// The currency of the payment+ #[schema(example = "USD", value_type = Option<Currency>)]+ pub currency: Option<api_enums::Currency>,++ /// Client secret for client-side payment confirmation+ #[schema(value_type = Option<String>)]+ pub client_secret: Option<masking::Secret<String>>,++ /// A description for the payment+ pub description: Option<String>,++ /// The customer identifier+ #[schema(value_type = Option<String>)]+ pub customer_id: Option<id_type::CustomerId>,++ /// The URL to redirect to after payment completion+ pub return_url: Option<String>,++ /// Whether to save payment method for future use+ #[schema(value_type = Option<FutureUsage>)]+ pub setup_future_usage: Option<api_enums::FutureUsage>,++ /// The billing address for the payment+ #[schema(value_type = Option<Address>)]+ pub billing: Option<payments::Address>,++ /// The shipping address for the payment+ #[schema(value_type = Option<Address>)]+ pub shipping: Option<payments::Address>,++ /// Additional metadata+ #[schema(value_type = Option<Object>)]+ pub metadata: Option<pii::SecretSerdeValue>,++ /// Order details for the payment+ #[schema(value_type = Option<Vec<Object>>)]+ pub order_details: Option<Vec<masking::Secret<serde_json::Value>>>,++ /// Timestamp when the payment was created+ pub created: Option<time::PrimitiveDateTime>,++ /// Timestamp when the client secret expires+ pub expires_on: Option<time::PrimitiveDateTime>,++ /// The profile identifier+ #[schema(value_type = Option<String>)]+ pub profile_id: Option<id_type::ProfileId>,++ /// Merchant-provided reference identifier+ pub merchant_order_reference_id: Option<String>,++ /// Number of payment attempts made+ pub attempt_count: i16,++ /// Installment options available for this payment+ pub installment_options: Option<Vec<PaymentMethodListInstallmentOption>>,+}++/// Installment options for a payment method, as returned in the payment method list response+#[derive(Debug, serde::Serialize, ToSchema)]+pub struct PaymentMethodListInstallmentOption {+ /// The payment method these plans apply to+ #[schema(value_type = PaymentMethod)]+ pub payment_method: api_enums::PaymentMethod,+ /// Individual installment plans with computed amounts+ pub available_plans: Vec<PaymentMethodListInstallmentPlan>,+}++/// A single installment plan with pre-computed amount breakdown+#[derive(Debug, serde::Serialize, ToSchema)]+pub struct PaymentMethodListInstallmentPlan {+ /// Number of installments for this plan+ #[schema(value_type = u8)]+ pub number_of_installments: NonZeroU8,+ /// Billing frequency+ #[schema(value_type = BillingFrequency)]+ pub billing_frequency: BillingFrequency,+ /// Interest rate as a percentage+ #[schema(value_type = f64)]+ pub interest_rate: InstallmentInterestRate,+ /// Pre-computed amount breakdown+ pub amount_details: PaymentMethodListInstallmentAmountDetails,+}++/// Amount breakdown for a single installment plan+#[derive(Debug, serde::Serialize, ToSchema)]+pub struct PaymentMethodListInstallmentAmountDetails {+ /// Amount charged per installment in major units+ #[schema(value_type = f64)]+ pub amount_per_installment: FloatMajorUnit,+ /// Total amount across all installments in major units (may differ slightly from order amount due to ceiling)+ #[schema(value_type = f64)]+ pub total_amount: FloatMajorUnit,+}++impl PaymentMethodListInstallmentPlan {+ pub fn from_installment_option_data(+ data: common_types::payments::InstallmentOptionData,+ order_amount: MinorUnit,+ net_amount: MinorUnit,+ currency: api_enums::Currency,+ ) -> errors::CustomResult<Vec<Self>, errors::ParsingError> {+ data.number_of_installments+ .as_slice()+ .iter()+ .map(|&count| {+ let interest = data+ .interest_rate+ .apply_and_ceil_result(order_amount)+ .change_context(errors::ParsingError::UnknownError)+ .attach_printable("Failed to apply installment interest rate")?;+ let total_with_interest = net_amount + interest;+ let per_installment = total_with_interest / count;+ let amount_per_installment = per_installment+ .to_major_unit_as_f64(currency)+ .change_context(errors::ParsingError::UnknownError)+ .attach_printable("Failed to convert per installment amount to major unit")?;+ let total_amount = total_with_interest+ .to_major_unit_as_f64(currency)+ .change_context(errors::ParsingError::UnknownError)+ .attach_printable("Failed to convert total installment amount to major unit")?;+ Ok(Self {+ number_of_installments: count,+ billing_frequency: data.billing_frequency.clone(),+ interest_rate: data.interest_rate,+ amount_details: PaymentMethodListInstallmentAmountDetails {+ amount_per_installment,+ total_amount,+ },+ })+ })+ .collect()+ }+}++impl PaymentMethodListInstallmentOption {+ pub fn from_installment_option(+ opt: common_types::payments::InstallmentOption,+ order_amount: MinorUnit,+ net_amount: MinorUnit,+ currency: api_enums::Currency,+ ) -> errors::CustomResult<Self, errors::ParsingError> {+ let available_plans = opt+ .installments+ .into_iter()+ .map(|data| {+ PaymentMethodListInstallmentPlan::from_installment_option_data(+ data,+ order_amount,+ net_amount,+ currency,+ )+ })+ .collect::<errors::CustomResult<Vec<Vec<_>>, _>>()?+ .into_iter()+ .flatten()+ .collect();+ Ok(Self {+ payment_method: opt.payment_method,+ available_plans,+ })+ }}#[cfg(feature = "v1")]diff --git a/crates/common_types/src/payments.rs b/crates/common_types/src/payments.rsindex 840c87980d..6fedf17280 100644--- a/crates/common_types/src/payments.rs+++ b/crates/common_types/src/payments.rs@@ -1267,6 +1267,11 @@ impl InstallmentCounts {self.0.contains(&count)}+ /// Returns a slice of the installment counts.+ pub fn as_slice(&self) -> &[NonZeroU8] {+ &self.0+ }+fn validate_not_empty(counts: &[NonZeroU8]) -> Result<(), errors::ValidationError> {(!counts.is_empty()).then_some(()).ok_or_else(|| {error_stack::report!(errors::ValidationError::InvalidValue {@@ -1387,7 +1392,6 @@ pub struct InstallmentOptionData {/// Billing frequency for each installment cyclepub billing_frequency: BillingFrequency,/// Interest rate per installment as a percentage max 2 decimal places- ///#[schema(value_type = f64)]pub interest_rate: InstallmentInterestRate,}diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rsindex 3ccd2f1228..4eb1df519d 100644--- a/crates/common_utils/src/types.rs+++ b/crates/common_utils/src/types.rs@@ -13,8 +13,8 @@ use std::{borrow::Cow,fmt::Display,iter::Sum,- num::NonZeroI64,- ops::{Add, Mul, Sub},+ num::{NonZeroI64, NonZeroU8},+ ops::{Add, Div, Mul, Sub},primitive::i64,str::FromStr,};@@ -427,7 +427,7 @@ impl MinorUnit {}/// Convert the amount to its major denomination based on Currency and return f64- fn to_major_unit_as_f64(+ pub fn to_major_unit_as_f64(self,currency: enums::Currency,) -> Result<FloatMajorUnit, error_stack::Report<ParsingError>> {@@ -520,6 +520,14 @@ impl Mul<u16> for MinorUnit {}}+impl Div<NonZeroU8> for MinorUnit {+ type Output = Self;++ fn div(self, a2: NonZeroU8) -> Self::Output {+ Self(self.0 / i64::from(a2.get()))+ }+}+impl Sum for MinorUnit {fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {iter.fold(Self(0), |a, b| a + b)diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rsindex 45a476b44b..6ac352f970 100644--- a/crates/hyperswitch_domain_models/src/payments.rs+++ b/crates/hyperswitch_domain_models/src/payments.rs@@ -38,9 +38,16 @@ pub mod payment_intent;#[cfg(feature = "v2")]pub mod split_payments;+#[cfg(feature = "v1")]+use api_models::{+ payment_methods::{PaymentMethodListInstallmentOption, PaymentMethodListIntentData},+ payments::Address,+};use common_enums as storage_enums;#[cfg(feature = "v2")]use diesel_models::types::{FeatureMetadata, OrderDetailsWithAmount};+#[cfg(feature = "v1")]+use error_stack::ResultExt;use masking::ExposeInterface;use self::{payment_attempt::PaymentAttempt, payment_intent::CustomerData};@@ -52,7 +59,7 @@ use crate::{ApiModelToDieselModelConvertor,};#[cfg(feature = "v1")]-use crate::{payment_method_data, RemoteStorageObject};+use crate::{errors, ext_traits::OptionExt, payment_method_data, RemoteStorageObject};#[cfg(feature = "v1")]#[derive(Clone, Debug, PartialEq, serde::Serialize, ToEncryption)]@@ -344,7 +351,7 @@ impl PaymentIntent {#[cfg(feature = "v1")]pub fn prevent_refund_after_post_capture_void(&self,- ) -> CustomResult<(), crate::errors::api_error_response::ApiErrorResponse> {+ ) -> CustomResult<(), errors::api_error_response::ApiErrorResponse> {if self.state_metadata.as_ref()@@ -352,7 +359,7 @@ impl PaymentIntent {.unwrap_or(false){Err(error_stack::report!(- crate::errors::api_error_response::ApiErrorResponse::PreconditionFailed {+ errors::api_error_response::ApiErrorResponse::PreconditionFailed {message:"Refund void cannot be performed after a post-capture void has been issued".into()@@ -436,6 +443,74 @@ impl PaymentIntent {}).transpose()}++ #[cfg(feature = "v1")]+ pub fn into_payment_method_list_intent_data(+ self,+ net_amount: MinorUnit,+ ) -> CustomResult<PaymentMethodListIntentData, errors::api_error_response::ApiErrorResponse>+ {+ let billing: Option<Address> = self+ .billing_details+ .map(|b| b.deserialize_inner_value(|value| value.parse_value("Address")))+ .transpose()+ .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse billing address")?+ .map(|enc| enc.into_inner());++ let shipping: Option<Address> = self+ .shipping_details+ .map(|s| s.deserialize_inner_value(|value| value.parse_value("Address")))+ .transpose()+ .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)+ .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)+ })+ })+ .collect::<CustomResult<Vec<_>, _>>()+ })+ .transpose()?;++ Ok(PaymentMethodListIntentData {+ payment_id: self.payment_id,+ status: self.status,+ amount: self.amount,+ currency: self.currency,+ client_secret: self.client_secret.map(|s| s.into()),+ description: self.description,+ customer_id: self.customer_id,+ return_url: self.return_url,+ setup_future_usage: self.setup_future_usage,+ billing,+ shipping,+ metadata: self.metadata.map(Secret::new),+ order_details: self.order_details,+ created: Some(self.created_at),+ expires_on: self.session_expiry,+ profile_id: self.profile_id,+ merchant_order_reference_id: self.merchant_order_reference_id,+ attempt_count: self.attempt_count,+ installment_options,+ })+ }}#[cfg(feature = "v2")]diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex cdf5b77e36..d3b40f7647 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -362,6 +362,10 @@ Never share your secret api keys. Keep them guarded and secure.common_types::domain::AcquirerConfigMap,common_types::domain::AcquirerConfig,api_models::payment_methods::PaymentMethodListResponse,+ api_models::payment_methods::PaymentMethodListIntentData,+ api_models::payment_methods::PaymentMethodListInstallmentOption,+ api_models::payment_methods::PaymentMethodListInstallmentPlan,+ api_models::payment_methods::PaymentMethodListInstallmentAmountDetails,api_models::payment_methods::PaymentMethodDataWalletInfo,api_models::payment_methods::ResponsePaymentMethodsEnabled,api_models::payment_methods::ResponsePaymentMethodTypes,diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex ba68db0585..a065fe873f 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -3849,7 +3849,7 @@ pub async fn list_payment_methods(.map(|payment_intent| payment_intent.customer_id.is_none()).unwrap_or(true);let merchant_surcharge_configs = if let Some((payment_attempt, payment_intent)) =- payment_attempt.as_ref().zip(payment_intent)+ payment_attempt.as_ref().zip(payment_intent.clone()){Box::pin(call_surcharge_decision_management(state,@@ -3885,6 +3885,19 @@ pub async fn list_payment_methods(let is_tax_connector_enabled = business_profile.get_is_tax_connector_enabled();+ let intent_data = payment_intent+ .clone()+ .map(|pi| {+ let net_amount = payment_attempt+ .as_ref()+ .map(|pa| pa.net_amount.get_total_amount())+ .unwrap_or(pi.amount);+ pi.into_payment_method_list_intent_data(net_amount)+ })+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to build intent data for payment method list")?;+Ok(services::ApplicationResponse::Json(api::PaymentMethodListResponse {redirect_url: business_profile.return_url.clone(),@@ -3930,6 +3943,7 @@ pub async fn list_payment_methods(is_tax_calculation_enabled: is_tax_connector_enabled && !skip_external_tax_calculation,sdk_next_action,is_guest_customer,+ intent_data,},))}