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(payment_methods): add GET `/payments/{payment_id}/client` endpoint (v1) (#12271)
Shankar Singh C91f2777fa285
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex 32672e0be1..74e6c48a0f 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -29475,6 +29475,42 @@}],"nullable": true+ },+ "merchant_name": {+ "type": "string",+ "description": "The merchant's display name",+ "nullable": true+ },+ "mandate_payment": {+ "allOf": [+ {+ "$ref": "#/components/schemas/MandateData"+ }+ ],+ "nullable": true+ },+ "payment_type": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PaymentType"+ }+ ],+ "nullable": true+ },+ "request_external_three_ds_authentication": {+ "type": "boolean",+ "description": "Whether external 3DS authentication was requested",+ "nullable": true+ },+ "is_tax_calculation_enabled": {+ "type": "boolean",+ "description": "Whether tax calculation is enabled for this payment",+ "nullable": true+ },+ "is_guest_customer": {+ "type": "boolean",+ "description": "Whether the customer is a guest (not saved)",+ "nullable": true}}},diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rsindex ad9a271163..544a7e0572 100644--- a/crates/api_models/src/admin.rs+++ b/crates/api_models/src/admin.rs@@ -2144,7 +2144,7 @@ pub struct MerchantConnectorDetailsWrap {pub creds_identifier: String,/// Merchant connector details type type. Base64 Encode the credentials and send it in this type and send as a string.#[schema(value_type = Option<MerchantConnectorDetails>, example = r#"{- "connector_account_details": {+ "connector_account_details": {"auth_type": "HeaderKey","api_key":"sk_test_xxxxxexamplexxxxxx12345"},diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rsindex c2f15a6813..955e8fc84c 100644--- a/crates/api_models/src/events/payment.rs+++ b/crates/api_models/src/events/payment.rs@@ -436,6 +436,9 @@ impl ApiEventMetric for ListCountriesCurrenciesResponse {}#[cfg(feature = "v1")]impl ApiEventMetric for PaymentMethodListResponse {}+#[cfg(feature = "v1")]+impl ApiEventMetric for payment_methods::ClientPaymentMethodsListResponse {}+#[cfg(feature = "v1")]impl ApiEventMetric for payment_methods::CustomerDefaultPaymentMethodResponse {fn get_api_event_type(&self) -> Option<ApiEventsType> {diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex 92ea2a11f7..7862f5e6ed 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -2788,6 +2788,27 @@ pub struct PaymentMethodListResponse {pub intent_data: Option<PaymentMethodListIntentData>,}+/// Extra caller-supplied fields required to fully populate [`PaymentMethodListIntentData`].+///+/// Callers build this struct from their business-layer context and pass it into+/// [`PaymentIntent::into_payment_method_list_intent_data`], keeping the function pure+/// (no post-construction mutation).+#[cfg(feature = "v1")]+#[derive(Debug)]+pub struct PaymentMethodListIntentDataInput {+ /// The merchant's display name+ pub merchant_name: Option<String>,++ /// Mandate payment data derived from the payment attempt's mandate_details+ pub mandate_payment: Option<payments::MandateData>,++ /// The inferred payment type (normal / new_mandate / recurring_mandate)+ pub payment_type: Option<api_enums::PaymentType>,++ /// Capture method for the payment (e.g. "automatic", "manual")+ pub capture_method: Option<api_enums::CaptureMethod>,+}+/// Intent-only payment details returned as part of the Payment Method List response#[derive(Debug, serde::Serialize, ToSchema)]pub struct PaymentMethodListIntentData {@@ -2862,6 +2883,188 @@ pub struct PaymentMethodListIntentData {/// The capture method for the payment#[schema(value_type = Option<CaptureMethod>)]pub capture_method: Option<api_enums::CaptureMethod>,++ /// The merchant's display name+ pub merchant_name: Option<String>,++ /// Mandate payment data associated with this payment+ #[schema(value_type = Option<MandateData>)]+ pub mandate_payment: Option<payments::MandateData>,++ /// The type of payment+ #[schema(value_type = Option<PaymentType>)]+ pub payment_type: Option<api_enums::PaymentType>,++ /// Whether external 3DS authentication was requested+ pub request_external_three_ds_authentication: Option<bool>,++ /// Whether tax calculation is enabled for this payment+ pub is_tax_calculation_enabled: Option<bool>,++ /// Whether the customer is a guest (not saved)+ pub is_guest_customer: Option<bool>,+}++/// Payment experience entry in the client PM list.+/// Subtype-specific data for each payment method entry in the client list+#[cfg(feature = "v1")]+#[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)]+#[serde(untagged)]+pub enum PaymentMethodSubtypeSpecificDataForClient {+ /// Card payment method — contains card network info+ Card {+ #[schema(value_type = Vec<CardNetwork>)]+ card_networks: Vec<api_enums::CardNetwork>,+ },+ /// Bank payment method (bank_redirect) — contains supported bank names+ Bank {+ #[schema(value_type = Vec<BankNames>)]+ bank_names: Vec<common_enums::BankNames>,+ },+}++/// A single flat entry in the client payment method list — one per (payment_method_type × payment_method_subtype)+#[cfg(feature = "v1")]+#[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)]+pub struct ResponsePaymentMethodsEnabledForClient {+ /// The top-level payment method type (e.g. "card", "wallet")+ #[schema(value_type = PaymentMethod)]+ pub payment_method: api_enums::PaymentMethod,++ /// The payment method subtype (e.g. "credit", "apple_pay")+ #[schema(value_type = PaymentMethodType)]+ pub payment_method_type: api_enums::PaymentMethodType,++ /// Subtype-specific data (card_networks or bank list); absent (null) for wallets/pay_later/etc.+ #[serde(flatten, skip_serializing_if = "Option::is_none")]+ pub data: Option<PaymentMethodSubtypeSpecificDataForClient>,++ /// Payment experience options for this method (wallets, pay_later, etc.)+ pub payment_experience: Option<Vec<api_enums::PaymentExperience>>,++ /// Whether to collect shipping details from the wallet connector (null for non-wallet)+ pub collect_shipping_details_from_wallets: Option<bool>,++ /// Whether to collect billing details from the wallet connector (null for non-wallet)+ pub collect_billing_details_from_wallets: Option<bool>,+}++/// Typed subtype-specific data for a saved customer payment method, returned in the+/// `GET /payments/{payment_id}/payment-methods/client` response.+///+/// Serializes as an externally-tagged enum, producing e.g.:+/// `{ "card": { "last4_digits": "4242", ... } }`+///+/// Only variants for subtypes that actually carry extra data are included;+/// for all other subtypes the `payment_method_data` field on+/// `CustomerPaymentMethodForClient` is `None`.+/// Wallet payment method data returned in the client-facing PM list.+#[cfg(feature = "v1")]+#[derive(Debug, Clone, serde::Serialize, ToSchema)]+#[serde(rename_all = "snake_case")]+pub enum WalletPaymentMethodDataForClient {+ ApplePay(Box<PaymentMethodDataWalletInfo>),+ GooglePay(Box<PaymentMethodDataWalletInfo>),+ PayPal(Box<payments::PaypalRedirection>),+}++/// Bank debit payment method data returned in the client-facing PM list.+/// Field names use `_last4_digits` to match the modular service response.+#[cfg(feature = "v1")]+#[derive(Debug, Clone, serde::Serialize, ToSchema)]+#[serde(rename_all = "snake_case")]+pub enum BankDebitDataForClient {+ AchBankDebit {+ account_number_last4_digits: String,+ routing_number_last4_digits: String,+ #[schema(value_type = Option<String>)]+ bank_account_holder_name: Option<hyperswitch_masking::Secret<String>>,+ #[schema(value_type = String, example = "ach")]+ bank_name: Option<common_enums::BankNames>,+ #[schema(value_type = String, example = "checking")]+ bank_type: Option<common_enums::BankType>,+ #[schema(value_type = String, example = "personal")]+ bank_holder_type: Option<common_enums::BankHolderType>,+ },+}++#[cfg(feature = "v1")]+#[derive(Debug, Clone, serde::Serialize, ToSchema)]+#[serde(rename_all = "snake_case")]+pub enum CustomerPaymentMethodDataForClient {+ /// Masked card details from the card locker.+ Card(Box<CardDetailFromLocker>),+ /// Wallet details (Apple Pay, Google Pay, PayPal).+ Wallet(WalletPaymentMethodDataForClient),+ /// Bank debit details (ACH, …).+ BankDebit(BankDebitDataForClient),+}++/// A saved customer payment method as returned in the client-facing PM list.+///+/// This is a slimmed-down version of `CustomerPaymentMethod` intended for the+/// `GET /payments/{payment_id}/payment-methods/client` endpoint. Fields that are+/// Only the fields needed by the SDK are included; server-side fields+/// (e.g. `surcharge_details`, `metadata`) are omitted.+#[cfg(feature = "v1")]+#[derive(Debug, Clone, serde::Serialize, ToSchema)]+pub struct CustomerPaymentMethodForClient {+ /// Token for payment method in temporary card locker which gets refreshed often.+ /// The SDK passes this back when submitting the payment.+ #[schema(example = "7ebf443f-a050-4067-84e5-e6f6d4800aef")]+ pub payment_token: String,++ /// Top-level payment method category (card, wallet, …)+ #[schema(value_type = PaymentMethod, example = "card")]+ pub payment_method: api_enums::PaymentMethod,++ /// Specific subtype within the category (credit, debit, apple_pay, …)+ #[schema(value_type = Option<PaymentMethodType>, example = "credit")]+ pub payment_method_type: Option<api_enums::PaymentMethodType>,++ /// Whether this is the customer's default payment method+ #[schema(example = true)]+ pub default_payment_method_set: bool,++ /// Whether CVV collection is required before using this method+ #[schema(example = true)]+ pub requires_cvv: bool,++ /// When the payment method was saved+ #[schema(value_type = Option<PrimitiveDateTime>, example = "2023-01-18T11:04:09.922Z")]+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]+ pub created: Option<time::PrimitiveDateTime>,++ /// When this payment method was last used for a payment+ #[schema(value_type = Option<PrimitiveDateTime>, example = "2024-02-24T11:04:09.922Z")]+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]+ pub last_used_at: Option<time::PrimitiveDateTime>,++ /// Whether this payment method supports recurring / off-session payments+ #[schema(example = true)]+ pub recurring_enabled: Option<bool>,++ /// Subtype-specific details (e.g. masked card info for card methods)+ #[schema(value_type = Option<CustomerPaymentMethodDataForClient>)]+ pub payment_method_data: Option<CustomerPaymentMethodDataForClient>,+}++/// Response for the GET /payments/{payment_id}/payment-methods/client endpoint+#[cfg(feature = "v1")]+#[derive(Debug, serde::Serialize, ToSchema)]+pub struct ClientPaymentMethodsListResponse {+ /// Flat list of enabled payment methods — one entry per (payment_method_type × payment_method_subtype)+ pub payment_methods_enabled: Vec<ResponsePaymentMethodsEnabledForClient>,++ /// The customer's saved payment methods+ pub customer_payment_methods: Vec<CustomerPaymentMethodForClient>,++ /// The next action the SDK should take+ #[schema(value_type = SdkNextAction)]+ pub sdk_next_action: payments::SdkNextAction,++ /// Payment intent context data+ pub intent_data: PaymentMethodListIntentData,}/// Installment options for a payment method, as returned in the payment method list responsediff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rsindex 3d7b628af3..c537eb41bd 100644--- a/crates/hyperswitch_domain_models/src/business_profile.rs+++ b/crates/hyperswitch_domain_models/src/business_profile.rs@@ -26,6 +26,7 @@ use crate::{behaviour::Conversion,errors::api_error_response,merchant_key_store::MerchantKeyStore,+ payments,type_encryption::{crypto_operation, AsyncLift, CryptoOperation},};#[cfg(feature = "v1")]@@ -1599,6 +1600,14 @@ impl Profile {}}+ #[cfg(feature = "v1")]+ pub fn get_is_tax_calculation_enabled(&self, payment_intent: &payments::PaymentIntent) -> bool {+ self.get_is_tax_connector_enabled()+ && !payment_intent+ .skip_external_tax_calculation+ .unwrap_or(false)+ }+#[cfg(feature = "v1")]pub fn get_order_fulfillment_time(&self) -> Option<i64> {self.intent_fulfillment_timediff --git a/crates/hyperswitch_domain_models/src/mandates.rs b/crates/hyperswitch_domain_models/src/mandates.rsindex ce9aec6eef..9cd301267a 100644--- a/crates/hyperswitch_domain_models/src/mandates.rs+++ b/crates/hyperswitch_domain_models/src/mandates.rs@@ -147,6 +147,66 @@ impl From<ApiMandateData> for MandateData {}}+impl MandateDataType {+ /// Convert to the API `MandateData` wrapper (used in `intent_data.mandate_payment`).+ pub fn to_api_mandate_data(&self) -> ApiMandateData {+ match self {+ Self::SingleUse(single_use_mandate_data) => ApiMandateData {+ mandate_type: Some(MandateType::SingleUse(ApiMandateAmountData {+ amount: single_use_mandate_data.amount,+ currency: single_use_mandate_data.currency,+ start_date: single_use_mandate_data.start_date,+ end_date: single_use_mandate_data.end_date,+ metadata: single_use_mandate_data.metadata.clone(),+ })),+ customer_acceptance: None,+ update_mandate_id: None,+ },+ Self::MultiUse(Some(multi_use_mandate_data)) => ApiMandateData {+ mandate_type: Some(MandateType::MultiUse(Some(ApiMandateAmountData {+ amount: multi_use_mandate_data.amount,+ currency: multi_use_mandate_data.currency,+ start_date: multi_use_mandate_data.start_date,+ end_date: multi_use_mandate_data.end_date,+ metadata: multi_use_mandate_data.metadata.clone(),+ }))),+ customer_acceptance: None,+ update_mandate_id: None,+ },+ Self::MultiUse(None) => ApiMandateData {+ mandate_type: Some(MandateType::MultiUse(None)),+ customer_acceptance: None,+ update_mandate_id: None,+ },+ }+ }++ /// Convert to the bare API `MandateType` (used in top-level response `mandate_payment` field).+ pub fn to_api_mandate_type(&self) -> MandateType {+ match self {+ Self::SingleUse(single_use_mandate_data) => {+ MandateType::SingleUse(ApiMandateAmountData {+ amount: single_use_mandate_data.amount,+ currency: single_use_mandate_data.currency,+ start_date: single_use_mandate_data.start_date,+ end_date: single_use_mandate_data.end_date,+ metadata: single_use_mandate_data.metadata.clone(),+ })+ }+ Self::MultiUse(Some(multi_use_mandate_data)) => {+ MandateType::MultiUse(Some(ApiMandateAmountData {+ amount: multi_use_mandate_data.amount,+ currency: multi_use_mandate_data.currency,+ start_date: multi_use_mandate_data.start_date,+ end_date: multi_use_mandate_data.end_date,+ metadata: multi_use_mandate_data.metadata.clone(),+ }))+ }+ Self::MultiUse(None) => MandateType::MultiUse(None),+ }+ }+}+impl MandateAmountData {pub fn get_end_date(&self,diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rsindex a1ef5b1a94..9a26f17c43 100644--- a/crates/hyperswitch_domain_models/src/payments.rs+++ b/crates/hyperswitch_domain_models/src/payments.rs@@ -40,7 +40,10 @@ pub mod split_payments;#[cfg(feature = "v1")]use api_models::{- payment_methods::{PaymentMethodListInstallmentOption, PaymentMethodListIntentData},+ payment_methods::{+ PaymentMethodListInstallmentOption, PaymentMethodListIntentData,+ PaymentMethodListIntentDataInput,+ },payments::Address,};use common_enums as storage_enums;@@ -477,9 +480,14 @@ impl PaymentIntent {self,net_amount: MinorUnit,show_installments: bool,- capture_method: Option<common_enums::CaptureMethod>,+ extra: PaymentMethodListIntentDataInput,+ business_profile: &crate::business_profile::Profile,) -> CustomResult<PaymentMethodListIntentData, errors::api_error_response::ApiErrorResponse>{+ let request_ext_3ds = self.get_request_external_three_ds_authentication();+ let is_guest = self.is_guest_customer();+ let is_tax = business_profile.get_is_tax_calculation_enabled(&self);+let billing: Option<Address> = self.billing_details.map(|b| b.deserialize_inner_value(|value| value.parse_value("Address")))@@ -542,7 +550,13 @@ impl PaymentIntent {merchant_order_reference_id: self.merchant_order_reference_id,attempt_count: self.attempt_count,installment_options,- capture_method,+ merchant_name: extra.merchant_name,+ mandate_payment: extra.mandate_payment,+ payment_type: extra.payment_type,+ request_external_three_ds_authentication: Some(request_ext_3ds),+ is_tax_calculation_enabled: Some(is_tax),+ is_guest_customer: Some(is_guest),+ capture_method: extra.capture_method,})}@@ -551,6 +565,20 @@ impl PaymentIntent {self.amount == MinorUnit::zero()&& self.setup_future_usage == Some(common_enums::FutureUsage::OffSession)}++ #[cfg(feature = "v1")]+ /// Returns whether external 3DS authentication was requested, defaulting to `false`.+ pub fn get_request_external_three_ds_authentication(&self) -> bool {+ self.request_external_three_ds_authentication+ .unwrap_or(false)+ }++ #[cfg(feature = "v1")]+ /// Returns `true` when there is no saved customer on this payment (guest checkout).+ /// Default is `true` — no customer means guest.+ pub fn is_guest_customer(&self) -> bool {+ self.customer_id.is_none()+ }}#[cfg(feature = "v2")]diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rsindex 96c26c0a6e..7a63a044a2 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs@@ -1721,6 +1721,33 @@ impl PaymentAttempt {self.net_amount.get_total_amount()}+ /// Infer the payment type (Normal / NewMandate / SetupMandate / RecurringMandate)+ /// from the attempt's mandate state and whether this is a CIT transaction.+ pub fn infer_payment_type(&self, is_cit_transaction: bool) -> api_models::enums::PaymentType {+ use api_models::payments::{Amount, MandateTransactionType};+ let amount = Amount::from(self.net_amount.get_order_amount());+ let mandate_type = if self.mandate_id.is_some() {+ Some(MandateTransactionType::RecurringMandateTransaction)+ } else if is_cit_transaction {+ Some(MandateTransactionType::NewMandateTransaction)+ } else {+ None+ };+ match mandate_type {+ Some(MandateTransactionType::NewMandateTransaction) => {+ if let Amount::Value(_) = amount {+ api_models::enums::PaymentType::NewMandate+ } else {+ api_models::enums::PaymentType::SetupMandate+ }+ }+ Some(MandateTransactionType::RecurringMandateTransaction) => {+ api_models::enums::PaymentType::RecurringMandate+ }+ None => api_models::enums::PaymentType::Normal,+ }+ }+pub fn get_total_surcharge_amount(&self) -> Option<MinorUnit> {self.net_amount.get_total_surcharge_amount()}diff --git a/crates/payment_methods/src/client/list.rs b/crates/payment_methods/src/client/list.rsindex e92372cdba..aaf8952a4e 100644--- a/crates/payment_methods/src/client/list.rs+++ b/crates/payment_methods/src/client/list.rs@@ -1,14 +1,9 @@-use api_models::payment_methods::{- CustomerPaymentMethod,- CustomerPaymentMethodsListResponse as ListCustomerPaymentMethodsV1Response,- PaymentMethodListRequest,-};+use api_models::payment_methods::PaymentMethodListRequest;use common_utils::{id_type, request::Method};use hyperswitch_interfaces::micro_service::{MicroserviceClientError, MicroserviceClientErrorKind};use crate::types::{ModularListCustomerPaymentMethodsRequest, ModularListCustomerPaymentMethodsResponse,- PaymentMethodResponseData,};/// V1-facing retrieve flow type.@@ -20,6 +15,7 @@ pub struct ListCustomerPaymentMethods;pub struct ListCustomerPaymentMethodsV1Request {pub customer_id: id_type::CustomerId,pub query_params: PaymentMethodListRequest,+ pub modular_service_prefix: String,}impl TryFrom<&ListCustomerPaymentMethodsV1Request> for ModularListCustomerPaymentMethodsRequest {@@ -30,50 +26,6 @@ impl TryFrom<&ListCustomerPaymentMethodsV1Request> for ModularListCustomerPaymen}}-impl TryFrom<ModularListCustomerPaymentMethodsResponse> for ListCustomerPaymentMethodsV1Response {- type Error = MicroserviceClientError;-- fn try_from(- v2_response: ModularListCustomerPaymentMethodsResponse,- ) -> Result<Self, Self::Error> {- let customer_payment_methods = v2_response- .customer_payment_methods- .into_iter()- .map(|pm| CustomerPaymentMethod {- payment_token: pm.id.clone(),- payment_method_id: pm.id,- customer_id: pm.customer_id,- payment_method: pm.payment_method_type,- payment_method_type: Some(pm.payment_method_subtype),- payment_method_issuer: None,- payment_method_issuer_code: None,- recurring_enabled: pm.recurring_enabled,- installment_payment_enabled: None,- payment_experience: None,- card: pm.payment_method_data.and_then(|data| match data {- PaymentMethodResponseData::Card(card_detail) => Some(*card_detail),- PaymentMethodResponseData::BankDebit(_) => None,- PaymentMethodResponseData::Wallet(_) => None,- }),- metadata: None,- created: Some(pm.created),- bank_transfer: None,- bank: pm.bank,- surcharge_details: None,- requires_cvv: pm.requires_cvv,- last_used_at: Some(pm.last_used_at),- default_payment_method_set: pm.is_default,- billing: pm.billing,- })- .collect();-- Ok(Self {- customer_payment_methods,- is_guest_customer: None,- })- }-}-impl ListCustomerPaymentMethods {fn validate_request(&self,@@ -94,10 +46,13 @@ impl ListCustomerPaymentMethods {&self,request: &ListCustomerPaymentMethodsV1Request,) -> Vec<(&'static str, String)> {- vec![(- "customer_id",- request.customer_id.get_string_repr().to_string(),- )]+ vec![+ ("prefix", request.modular_service_prefix.clone()),+ (+ "customer_id",+ request.customer_id.get_string_repr().to_string(),+ ),+ ]}fn query_params(@@ -146,14 +101,23 @@ impl ListCustomerPaymentMethods {}}+pub struct ListCustomerPaymentMethodsRawResponse(pub ModularListCustomerPaymentMethodsResponse);++impl TryFrom<ModularListCustomerPaymentMethodsResponse> for ListCustomerPaymentMethodsRawResponse {+ type Error = MicroserviceClientError;+ fn try_from(value: ModularListCustomerPaymentMethodsResponse) -> Result<Self, Self::Error> {+ Ok(Self(value))+ }+}+hyperswitch_interfaces::impl_microservice_flow!(ListCustomerPaymentMethods,method = Method::Get,- path = "/v2/customers/{customer_id}/saved-payment-methods",+ path = "/{prefix}/customers/{customer_id}/saved-payment-methods",v1_request = ListCustomerPaymentMethodsV1Request,v2_request = ModularListCustomerPaymentMethodsRequest,v2_response = ModularListCustomerPaymentMethodsResponse,- v1_response = ListCustomerPaymentMethodsV1Response,+ v1_response = ListCustomerPaymentMethodsRawResponse,client = crate::client::PaymentMethodClient<'_>,path_params = ListCustomerPaymentMethods::build_path_params,query_params = ListCustomerPaymentMethods::query_params,diff --git a/crates/payment_methods/src/types.rs b/crates/payment_methods/src/types.rsindex e413247d66..150039ce7d 100644--- a/crates/payment_methods/src/types.rs+++ b/crates/payment_methods/src/types.rs@@ -13,11 +13,13 @@ pub struct ModularListCustomerPaymentMethodsRequest;#[derive(Debug, Deserialize)]// TODO: replace dummy response types with real v1/modular models.pub struct ModularListCustomerPaymentMethodsResponse {- pub customer_payment_methods: Vec<PaymentMethodResponseItem>,+ pub customer_payment_methods: Vec<PaymentMethodResponseItemV1>,}+/// V1 bridge shape — deserialized from the modular service response when called from v1 router.+/// Uses v1 ID types (String, CustomerId).#[derive(Debug, Deserialize)]-pub struct PaymentMethodResponseItem {+pub struct PaymentMethodResponseItemV1 {pub id: String,pub customer_id: id_type::CustomerId,pub payment_method_type: PaymentMethod,@@ -145,3 +147,63 @@ pub struct CardCVCTokenStorageDetails {#[serde(default, with = "common_utils::custom_serde::iso8601::option")]pub expires_at: Option<PrimitiveDateTime>,}++// ---------------------------------------------------------------------------+// From conversions → api_models client-facing types+// ---------------------------------------------------------------------------++impl From<WalletPaymentMethodData>+ for api_models::payment_methods::WalletPaymentMethodDataForClient+{+ fn from(wallet_info: WalletPaymentMethodData) -> Self {+ match wallet_info {+ WalletPaymentMethodData::ApplePay(apple_pay_info) => Self::ApplePay(apple_pay_info),+ WalletPaymentMethodData::GooglePay(google_pay_info) => Self::GooglePay(google_pay_info),+ WalletPaymentMethodData::PayPal(paypal_info) => Self::PayPal(paypal_info),+ }+ }+}++impl From<BankDebitDetailsPaymentMethod> for api_models::payment_methods::BankDebitDataForClient {+ fn from(bank_debit_info: BankDebitDetailsPaymentMethod) -> Self {+ match bank_debit_info {+ BankDebitDetailsPaymentMethod::AchBankDebit {+ account_number_last4_digits,+ routing_number_last4_digits,+ bank_account_holder_name,+ bank_name,+ bank_type,+ bank_holder_type,+ } => Self::AchBankDebit {+ account_number_last4_digits,+ routing_number_last4_digits,+ bank_account_holder_name,+ bank_name,+ bank_type,+ bank_holder_type,+ },+ }+ }+}++impl From<PaymentMethodResponseData>+ for Option<api_models::payment_methods::CustomerPaymentMethodDataForClient>+{+ fn from(payment_method_response_data: PaymentMethodResponseData) -> Self {+ match payment_method_response_data {+ PaymentMethodResponseData::Card(card_info) => Some(+ api_models::payment_methods::CustomerPaymentMethodDataForClient::Card(card_info),+ ),+ PaymentMethodResponseData::Wallet(wallet_info) => Some(+ api_models::payment_methods::CustomerPaymentMethodDataForClient::Wallet(+ wallet_info.into(),+ ),+ ),+ PaymentMethodResponseData::BankDebit(bank_debit_info) => Some(+ api_models::payment_methods::CustomerPaymentMethodDataForClient::BankDebit(+ bank_debit_info.into(),+ ),+ ),+ }+ }+}diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex cd2402a154..d58c855766 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -2,6 +2,8 @@ pub mod access_token;#[cfg(feature = "v1")]pub mod batch_retrieve;pub mod cards;+#[cfg(feature = "v1")]+pub mod client;pub mod migration;pub mod network_tokenization;pub mod surcharge_decision_configs;diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex d13cd1973f..2039978dd2 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -11,6 +11,11 @@ use ::payment_methods::{};#[cfg(feature = "v1")]use api_models::admin::PaymentMethodsEnabled;+#[cfg(feature = "v1")]+use api_models::payment_methods::{+ PaymentMethodListIntentDataInput, PaymentMethodSubtypeSpecificDataForClient,+ ResponsePaymentMethodsEnabledForClient,+};use api_models::{enums as api_enums,payment_methods::{@@ -3216,130 +3221,182 @@ pub fn get_banks(}}-fn get_val(str: String, val: &serde_json::Value) -> Option<String> {+pub fn get_val(str: String, val: &serde_json::Value) -> Option<String> {str.split('.').try_fold(val, |acc, x| acc.get(x)).and_then(|v| v.as_str()).map(|s| s.to_string())}+// ---------------------------------------------------------------------------+// Shared context returned by `build_merchant_enabled_pms_context`+// ---------------------------------------------------------------------------+#[cfg(feature = "v1")]-pub async fn list_payment_methods(- state: routes::SessionState,- platform: domain::Platform,- // Profile resolved during JWT authentication. Used as a fallback to determine- // the business profile when no client_secret is provided and payment_intent is unavailable.- auth_profile: Option<Profile>,- mut req: api::PaymentMethodListRequest,-) -> errors::RouterResponse<api::PaymentMethodListResponse> {- let db = &*state.store;- let pm_config_mapping = &state.conf.pm_filters;- let payment_intent = if let Some(cs) = &req.client_secret {- if cs.starts_with("pm_") {- validate_payment_method_and_client_secret(cs, db, &platform).await?;- None- } else {- helpers::verify_payment_intent_time_and_client_secret(- &state,- &platform,- req.client_secret.clone(),- )- .await?+pub struct MerchantEnabledPmsContext {+ pub payment_experiences_consolidated_hm: HashMap<+ api_enums::PaymentMethod,+ HashMap<api_enums::PaymentMethodType, HashMap<api_enums::PaymentExperience, Vec<String>>>,+ >,+ pub card_networks_consolidated_hm: HashMap<+ api_enums::PaymentMethod,+ HashMap<api_enums::PaymentMethodType, HashMap<api_enums::CardNetwork, Vec<String>>>,+ >,+ pub banks_consolidated_hm: HashMap<api_enums::PaymentMethodType, Vec<String>>,+ pub bank_debits_consolidated_hm: HashMap<api_enums::PaymentMethodType, Vec<String>>,+ pub bank_transfer_consolidated_hm: HashMap<api_enums::PaymentMethodType, Vec<String>>,+ pub required_fields_hm: HashMap<+ api_enums::PaymentMethod,+ HashMap<api_enums::PaymentMethodType, HashMap<String, RequiredFieldInfo>>,+ >,+ pub pmt_to_auth_connector:+ HashMap<enums::PaymentMethod, HashMap<enums::PaymentMethodType, String>>,+ pub connector_supports_installments: bool,+ pub collect_shipping_details_from_wallets: Option<bool>,+ pub collect_billing_details_from_wallets: Option<bool>,+ pub sdk_next_action: api_models::payments::SdkNextAction,+}++#[cfg(feature = "v1")]+impl MerchantEnabledPmsContext {+ /// Converts `payment_experiences_consolidated_hm` → client PM entries (wallet, pay_later, upi, …)+ pub fn payment_experience_pms_for_client(&self) -> Vec<ResponsePaymentMethodsEnabledForClient> {+ let mut out = vec![];+ for (payment_method, pmt_map) in &self.payment_experiences_consolidated_hm {+ for (payment_method_type, pe_map) in pmt_map {+ let payment_experience_types: Vec<api_enums::PaymentExperience> =+ pe_map.keys().copied().collect();++ let is_wallet = *payment_method == api_enums::PaymentMethod::Wallet+ || *payment_method == api_enums::PaymentMethod::PayLater;++ out.push(ResponsePaymentMethodsEnabledForClient {+ payment_method: *payment_method,+ payment_method_type: *payment_method_type,+ data: None,+ payment_experience: Some(payment_experience_types),+ collect_shipping_details_from_wallets: is_wallet+ .then_some(self.collect_shipping_details_from_wallets)+ .flatten(),+ collect_billing_details_from_wallets: is_wallet+ .then_some(self.collect_billing_details_from_wallets)+ .flatten(),+ });+ }}- } else {- None- };+ out+ }- let shipping_address = payment_intent- .as_ref()- .async_map(|pi| async {- helpers::get_address_by_id(- &state,- pi.shipping_address_id.clone(),- platform.get_processor().get_key_store(),- &pi.payment_id,- platform.get_processor().get_account().get_id(),- platform.get_processor().get_account().storage_scheme,- )- .await- })- .await- .transpose()?- .flatten();+ /// Converts `card_networks_consolidated_hm` → client PM entries (card, card_redirect)+ pub fn card_network_pms_for_client(&self) -> Vec<ResponsePaymentMethodsEnabledForClient> {+ let mut out = vec![];+ for (payment_method, pmt_map) in &self.card_networks_consolidated_hm {+ for (payment_method_type, card_network_hashmap) in pmt_map {+ let card_networks: Vec<api_enums::CardNetwork> =+ card_network_hashmap.keys().cloned().collect();++ out.push(ResponsePaymentMethodsEnabledForClient {+ payment_method: *payment_method,+ payment_method_type: *payment_method_type,+ data: Some(PaymentMethodSubtypeSpecificDataForClient::Card { card_networks }),+ payment_experience: None,+ collect_shipping_details_from_wallets: None,+ collect_billing_details_from_wallets: None,+ });+ }+ }+ out+ }- let billing_address = payment_intent- .as_ref()- .async_map(|pi| async {- helpers::get_address_by_id(- &state,- pi.billing_address_id.clone(),- platform.get_processor().get_key_store(),- &pi.payment_id,- platform.get_processor().get_account().get_id(),- platform.get_processor().get_account().storage_scheme,- )- .await- })- .await- .transpose()?- .flatten();+ /// Converts `banks_consolidated_hm` → client PM entries (bank_redirect)+ pub fn bank_redirect_pms_for_client(+ &self,+ state: &routes::SessionState,+ ) -> errors::RouterResult<Vec<ResponsePaymentMethodsEnabledForClient>> {+ let mut out = vec![];+ for (payment_method_type, connectors) in &self.banks_consolidated_hm {+ let bank_names = get_banks(state, *payment_method_type, connectors.clone())?;+ let bank_names_list: Vec<common_enums::BankNames> = bank_names+ .into_iter()+ .flat_map(|bank_code_response| bank_code_response.bank_name)+ .collect();++ out.push(ResponsePaymentMethodsEnabledForClient {+ payment_method: api_enums::PaymentMethod::BankRedirect,+ payment_method_type: *payment_method_type,+ data: if bank_names_list.is_empty() {+ None+ } else {+ Some(PaymentMethodSubtypeSpecificDataForClient::Bank {+ bank_names: bank_names_list,+ })+ },+ payment_experience: None,+ collect_shipping_details_from_wallets: None,+ collect_billing_details_from_wallets: None,+ });+ }+ Ok(out)+ }- let customer = payment_intent- .as_ref()- .async_and_then(|pi| async {- pi.customer_id- .as_ref()- .async_and_then(|cust| async {- db.find_customer_by_customer_id_merchant_id(- cust,- &pi.merchant_id,- platform.get_provider().get_key_store(),- platform.get_provider().get_account().storage_scheme,- )- .await- .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)- .ok()- })- .await- })- .await;+ /// Converts `bank_debits_consolidated_hm` → client PM entries (bank_debit)+ pub fn bank_debit_pms_for_client(&self) -> Vec<ResponsePaymentMethodsEnabledForClient> {+ self.bank_debits_consolidated_hm+ .keys()+ .map(+ |payment_method_type| ResponsePaymentMethodsEnabledForClient {+ payment_method: api_enums::PaymentMethod::BankDebit,+ payment_method_type: *payment_method_type,+ data: None,+ payment_experience: None,+ collect_shipping_details_from_wallets: None,+ collect_billing_details_from_wallets: None,+ },+ )+ .collect()+ }- let payment_attempt = payment_intent- .as_ref()- .async_map(|pi| async {- db.find_payment_attempt_by_payment_id_processor_merchant_id_attempt_id(- &pi.payment_id,- &pi.processor_merchant_id,- &pi.active_attempt.get_id(),- platform.get_processor().get_account().storage_scheme,- platform.get_processor().get_key_store(),+ /// Converts `bank_transfer_consolidated_hm` → client PM entries (bank_transfer)+ pub fn bank_transfer_pms_for_client(&self) -> Vec<ResponsePaymentMethodsEnabledForClient> {+ self.bank_transfer_consolidated_hm+ .keys()+ .map(+ |payment_method_type| ResponsePaymentMethodsEnabledForClient {+ payment_method: api_enums::PaymentMethod::BankTransfer,+ payment_method_type: *payment_method_type,+ data: None,+ payment_experience: None,+ collect_shipping_details_from_wallets: None,+ collect_billing_details_from_wallets: None,+ },)- .await- .change_context(errors::ApiErrorResponse::PaymentNotFound)- })- .await- .transpose()?;- let setup_future_usage = payment_intent.as_ref().and_then(|pi| pi.setup_future_usage);- let is_cit_transaction = payment_attempt- .as_ref()- .map(|pa| pa.mandate_details.is_some())- .unwrap_or(false)- || setup_future_usage- .map(|future_usage| future_usage == common_enums::FutureUsage::OffSession)- .unwrap_or(false);- let payment_type = payment_attempt.as_ref().map(|pa| {- let amount = api::Amount::from(pa.net_amount.get_order_amount());- let mandate_type = if pa.mandate_id.is_some() {- Some(api::MandateTransactionType::RecurringMandateTransaction)- } else if is_cit_transaction {- Some(api::MandateTransactionType::NewMandateTransaction)- } else {- None- };+ .collect()+ }+}- helpers::infer_payment_type(amount, mandate_type.as_ref())- });+/// Runs the two-gate PM filter pipeline (Euclid cgraph + session flow routing)+/// and builds all consolidated hashmaps needed to assemble a PM list response.+///+/// Both the legacy `list_payment_methods` and the new `list_payment_methods_client`+/// endpoint call this function and then assemble their own response types from the+/// returned `MerchantEnabledPmsContext`.+#[cfg(feature = "v1")]+#[allow(clippy::too_many_arguments)]+pub async fn build_merchant_enabled_pms_context(+ state: &routes::SessionState,+ platform: &domain::Platform,+ business_profile: &Profile,+ payment_intent: Option<&storage::PaymentIntent>,+ payment_attempt: Option<&storage::PaymentAttempt>,+ billing_address: Option<&domain::Address>,+ shipping_address: Option<&domain::Address>,+ customer: Option<&hyperswitch_domain_models::customer::Customer>,+ is_cit_transaction: bool,+) -> errors::RouterResult<MerchantEnabledPmsContext> {+ let db = &*state.store;+ let pm_config_mapping = &state.conf.pm_filters;+ // --- Load all MCAs and filter by profile + connector type ---let all_mcas = db.find_merchant_connector_account_by_merchant_id_and_disabled_list(platform.get_processor().get_account().get_id(),@@ -3349,36 +3406,13 @@ pub async fn list_payment_methods(.await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;- let (profile_id, business_profile) =- match payment_intent.as_ref().and_then(|pi| pi.profile_id.clone()) {- Some(profile_id) => {- let business_profile = db- .find_business_profile_by_profile_id(- platform.get_processor().get_key_store(),- &profile_id,- )- .await- .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {- id: profile_id.get_string_repr().to_owned(),- })?;- (profile_id, business_profile)- }- None => {- let profile =- auth_profile.ok_or(errors::ApiErrorResponse::GenericNotFoundError {- message: "Profile id not found".to_string(),- })?;- let profile_id = profile.get_id().clone();- (profile_id, profile)- }- };+ let profile_id = business_profile.get_id().clone();let dimensions = dimension_state::Dimensions::new().with_processor_merchant_id(platform.get_processor().get_processor_merchant_id()).with_provider_merchant_id(platform.get_provider().get_provider_merchant_id()).with_profile_id(profile_id.clone());- // filter out payment connectors based on profile_idlet filtered_mcas = all_mcas.clone().filter_based_on_profile_and_connector_type(&profile_id, ConnectorType::PaymentProcessor);@@ -3386,21 +3420,21 @@ pub async fn list_payment_methods(logger::debug!(mca_before_filtering=?filtered_mcas);let mut response: Vec<ResponsePaymentMethodIntermediate> = vec![];- // Key creation for storing PM_FILTER_CGRAPH- let key = {- format!(- "pm_filters_cgraph_{}_{}",- platform- .get_processor()- .get_account()- .get_id()- .get_string_repr(),- profile_id.get_string_repr()- )- };- if let Some(graph) = get_merchant_pm_filter_graph(&state, &key).await {- // Derivation of PM_FILTER_CGRAPH from MokaCache successful+ // ---- Gate 1: Euclid constraint graph ----+ let key = format!(+ "pm_filters_cgraph_{}_{}",+ platform+ .get_processor()+ .get_account()+ .get_id()+ .get_string_repr(),+ profile_id.get_string_repr()+ );++ let mut req = api::PaymentMethodListRequest::default();++ if let Some(graph) = get_merchant_pm_filter_graph(state, &key).await {for mca in &filtered_mcas {let payment_methods = match &mca.payment_methods_enabled {Some(pm) => pm,@@ -3412,16 +3446,15 @@ pub async fn list_payment_methods(payment_methods,&mut req,&mut response,- payment_intent.as_ref(),- payment_attempt.as_ref(),- billing_address.as_ref(),+ payment_intent,+ payment_attempt,+ billing_address,mca.connector_name.clone(),&state.conf,).await?;}} else {- // No PM_FILTER_CGRAPH Cache present in MokaCachelet mut builder = cgraph::ConstraintGraphBuilder::new();for mca in &filtered_mcas {let domain_id = builder.make_domain(@@ -3453,8 +3486,7 @@ pub async fn list_payment_methods(}}- // Refreshing our CGraph cache- let graph = refresh_pm_filters_cache(&state, &key, builder.build()).await;+ let graph = refresh_pm_filters_cache(state, &key, builder.build()).await;for mca in &filtered_mcas {let payment_methods = match &mca.payment_methods_enabled {@@ -3467,20 +3499,23 @@ pub async fn list_payment_methods(payment_methods,&mut req,&mut response,- payment_intent.as_ref(),- payment_attempt.as_ref(),- billing_address.as_ref(),+ payment_intent,+ payment_attempt,+ billing_address,mca.connector_name.clone(),&state.conf,).await?;}}+logger::info!("The Payment Methods available after Constraint Graph filtering are {:?}",response);+ // ---- Gate 2: Session flow routing + pm_auth Redis write + attempt write-back ----+let mut pmt_to_auth_connector: HashMap<enums::PaymentMethod,HashMap<enums::PaymentMethodType, String>,@@ -3496,7 +3531,7 @@ pub async fn list_payment_methods(.get_pre_routing_disabled_pm_pmt_key();let skip_pre_routing =- load_skip_pre_routing_config(&state, pre_routing_disabled_pm_pmt_key.to_string()).await;+ load_skip_pre_routing_config(state, pre_routing_disabled_pm_pmt_key.to_string()).await;let routing_enabled_pms = &router_consts::ROUTING_ENABLED_PAYMENT_METHODS;let routing_enabled_pm_types = &router_consts::ROUTING_ENABLED_PAYMENT_METHOD_TYPES;@@ -3511,7 +3546,7 @@ pub async fn list_payment_methods(&skip_pre_routing,) {let connector_data = helpers::get_connector_data_with_token(- &state,+ state,intermediate.connector.to_string(),None,intermediate.payment_method_type,@@ -3529,8 +3564,8 @@ pub async fn list_payment_methods(}let sfr = SessionFlowRoutingInput {- state: &state,- country: billing_address.clone().and_then(|ad| ad.country),+ state,+ country: billing_address.and_then(|ad| ad.country),key_store: platform.get_processor().get_key_store(),merchant_account: platform.get_processor().get_account(),payment_attempt,@@ -3539,7 +3574,7 @@ pub async fn list_payment_methods(};let (result, routing_approach) = routing::perform_session_flow_routing(sfr,- &business_profile,+ business_profile,&enums::TransactionType::Payment,).await@@ -3731,7 +3766,7 @@ pub async fn list_payment_methods(state.store.update_payment_attempt_with_attempt_id(- payment_attempt.clone(),+ (*payment_attempt).clone(),attempt_update,platform.get_provider().get_account().storage_scheme,platform.get_provider().get_key_store(),@@ -3740,25 +3775,27 @@ pub async fn list_payment_methods(.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;}- // Check for `use_billing_as_payment_method_billing` config under business_profile- // If this is disabled, then the billing details in required fields will be empty and have to be collected by the customer- let billing_address_for_calculating_required_fields = business_profile+ logger::info!("Payment methods after session flow routing: {:?}", response);++ // ---- Required-fields billing address config ----+ let billing_address_for_req = business_profile.use_billing_as_payment_method_billing.unwrap_or(true)- .then_some(billing_address.as_ref())+ .then_some(billing_address).flatten();- let req = api_models::payments::PaymentsRequest::foreign_try_from((- payment_attempt.as_ref(),- payment_intent.as_ref(),- shipping_address.as_ref(),- billing_address_for_calculating_required_fields,- customer.as_ref(),+ let req_for_required_fields = api_models::payments::PaymentsRequest::foreign_try_from((+ payment_attempt,+ payment_intent,+ shipping_address,+ billing_address_for_req,+ customer,))?;+ let req_val = serde_json::to_value(req_for_required_fields).ok();- let req_val = serde_json::to_value(req).ok();logger::debug!(filtered_payment_methods=?response);+ // ---- Hashmap consolidation ----let mut payment_experiences_consolidated_hm: HashMap<api_enums::PaymentMethod,HashMap<api_enums::PaymentMethodType, HashMap<api_enums::PaymentExperience, Vec<String>>>,@@ -3771,14 +3808,11 @@ pub async fn list_payment_methods(let mut banks_consolidated_hm: HashMap<api_enums::PaymentMethodType, Vec<String>> =HashMap::new();+ let mut bank_debits_consolidated_hm: HashMap<api_enums::PaymentMethodType, Vec<String>> =+ HashMap::new();+ let mut bank_transfer_consolidated_hm: HashMap<api_enums::PaymentMethodType, Vec<String>> =+ HashMap::new();- let mut bank_debits_consolidated_hm =- HashMap::<api_enums::PaymentMethodType, Vec<String>>::new();-- let mut bank_transfer_consolidated_hm =- HashMap::<api_enums::PaymentMethodType, Vec<String>>::new();-- // All the required fields will be stored here and later filtered out based on business profile configlet mut required_fields_hm = HashMap::<api_enums::PaymentMethod,HashMap<api_enums::PaymentMethodType, HashMap<String, RequiredFieldInfo>>,@@ -3807,43 +3841,42 @@ pub async fn list_payment_methods(.get(&connector_variant).map(|required_fields_final| {let mut required_fields_hs = required_fields_final.common.clone();- if is_cit_transaction {- required_fields_hs- .extend(required_fields_final.mandate.clone());- } else {- required_fields_hs- .extend(required_fields_final.non_mandate.clone());- }- required_fields_hs = should_collect_shipping_or_billing_details_from_wallet_connector(- payment_method,- element.payment_experience.as_ref(),- &business_profile,- required_fields_hs.clone(),- );-- // get the config, check the enums while adding- {- for (key, val) in &mut required_fields_hs {- let temp = req_val- .as_ref()- .and_then(|r| get_val(key.to_owned(), r));- if let Some(s) = temp {- val.value = Some(s.into())- };- }+ if is_cit_transaction {+ required_fields_hs+ .extend(required_fields_final.mandate.clone());+ } else {+ required_fields_hs+ .extend(required_fields_final.non_mandate.clone());+ }+ required_fields_hs =+ should_collect_shipping_or_billing_details_from_wallet_connector(+ payment_method,+ element.payment_experience.as_ref(),+ business_profile,+ required_fields_hs.clone(),+ );++ for (key, val) in &mut required_fields_hs {+ let temp = req_val+ .as_ref()+ .and_then(|r| get_val(key.to_owned(), r));+ if let Some(s) = temp {+ val.value = Some(s.into())+ };}let existing_req_fields_hs = required_fields_hm.get_mut(&payment_method).and_then(|inner_hm| inner_hm.get_mut(&payment_method_type));- // If payment_method_type already exist in required_fields_hm, extend the required_fields hs to existing hs.if let Some(inner_hs) = existing_req_fields_hs {inner_hs.extend(required_fields_hs);} else {- required_fields_hm.get_mut(&payment_method).map(|inner_hm| {- inner_hm.insert(payment_method_type, required_fields_hs)- });+ required_fields_hm+ .get_mut(&payment_method)+ .map(|inner_hm| {+ inner_hm.insert(payment_method_type, required_fields_hs)+ });}})})@@ -3959,8 +3992,219 @@ pub async fn list_payment_methods(}}+ // ---- connector_supports_installments ----+ let currency = payment_intent.and_then(|pi| pi.currency);+ 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)+ })+ })+ });++ // ---- wallet shipping/billing collect flags ----+ let collect_shipping_details_from_wallets = if business_profile+ .always_collect_shipping_details_from_wallet_connector+ .unwrap_or(false)+ {+ business_profile.always_collect_shipping_details_from_wallet_connector+ } else {+ business_profile.collect_shipping_details_from_wallet_connector+ };++ let collect_billing_details_from_wallets = if business_profile+ .always_collect_billing_details_from_wallet_connector+ .unwrap_or(false)+ {+ business_profile.always_collect_billing_details_from_wallet_connector+ } else {+ business_profile.collect_billing_details_from_wallet_connector+ };++ // ---- sdk_next_action ----+ let sdk_next_action = payment_method_utils::get_sdk_next_action_for_payment_method_list(+ state,+ &dimensions,+ payment_intent.and_then(|pi| pi.customer_id.as_ref()),+ )+ .await;++ Ok(MerchantEnabledPmsContext {+ payment_experiences_consolidated_hm,+ card_networks_consolidated_hm,+ banks_consolidated_hm,+ bank_debits_consolidated_hm,+ bank_transfer_consolidated_hm,+ required_fields_hm,+ pmt_to_auth_connector,+ connector_supports_installments,+ collect_shipping_details_from_wallets,+ collect_billing_details_from_wallets,+ sdk_next_action,+ })+}++#[cfg(feature = "v1")]+pub async fn list_payment_methods(+ state: routes::SessionState,+ platform: domain::Platform,+ // Profile resolved during JWT authentication. Used as a fallback to determine+ // the business profile when no client_secret is provided and payment_intent is unavailable.+ auth_profile: Option<Profile>,+ req: api::PaymentMethodListRequest,+) -> errors::RouterResponse<api::PaymentMethodListResponse> {+ let db = &*state.store;+ let payment_intent = if let Some(cs) = &req.client_secret {+ if cs.starts_with("pm_") {+ validate_payment_method_and_client_secret(cs, db, &platform).await?;+ None+ } else {+ helpers::verify_payment_intent_time_and_client_secret(+ &state,+ &platform,+ req.client_secret.clone(),+ )+ .await?+ }+ } else {+ None+ };++ let shipping_address = payment_intent+ .as_ref()+ .async_map(|pi| async {+ helpers::get_address_by_id(+ &state,+ pi.shipping_address_id.clone(),+ platform.get_processor().get_key_store(),+ &pi.payment_id,+ platform.get_processor().get_account().get_id(),+ platform.get_processor().get_account().storage_scheme,+ )+ .await+ })+ .await+ .transpose()?+ .flatten();++ let billing_address = payment_intent+ .as_ref()+ .async_map(|pi| async {+ helpers::get_address_by_id(+ &state,+ pi.billing_address_id.clone(),+ platform.get_processor().get_key_store(),+ &pi.payment_id,+ platform.get_processor().get_account().get_id(),+ platform.get_processor().get_account().storage_scheme,+ )+ .await+ })+ .await+ .transpose()?+ .flatten();++ let customer = payment_intent+ .as_ref()+ .async_and_then(|pi| async {+ pi.customer_id+ .as_ref()+ .async_and_then(|cust| async {+ db.find_customer_by_customer_id_merchant_id(+ cust,+ &pi.merchant_id,+ platform.get_provider().get_key_store(),+ platform.get_provider().get_account().storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)+ .ok()+ })+ .await+ })+ .await;++ let payment_attempt = payment_intent+ .as_ref()+ .async_map(|pi| async {+ db.find_payment_attempt_by_payment_id_processor_merchant_id_attempt_id(+ &pi.payment_id,+ &pi.processor_merchant_id,+ &pi.active_attempt.get_id(),+ platform.get_processor().get_account().storage_scheme,+ platform.get_processor().get_key_store(),+ )+ .await+ .change_context(errors::ApiErrorResponse::PaymentNotFound)+ })+ .await+ .transpose()?;+ let setup_future_usage = payment_intent.as_ref().and_then(|pi| pi.setup_future_usage);+ let is_cit_transaction = payment_attempt+ .as_ref()+ .map(|pa| pa.mandate_details.is_some())+ .unwrap_or(false)+ || setup_future_usage+ .map(|future_usage| future_usage == common_enums::FutureUsage::OffSession)+ .unwrap_or(false);+ let payment_type = payment_attempt.as_ref().map(|pa| {+ let amount = api::Amount::from(pa.net_amount.get_order_amount());+ let mandate_type = if pa.mandate_id.is_some() {+ Some(api::MandateTransactionType::RecurringMandateTransaction)+ } else if is_cit_transaction {+ Some(api::MandateTransactionType::NewMandateTransaction)+ } else {+ None+ };++ helpers::infer_payment_type(amount, mandate_type.as_ref())+ });++ let (_profile_id, business_profile) =+ match payment_intent.as_ref().and_then(|pi| pi.profile_id.clone()) {+ Some(profile_id) => {+ let business_profile = db+ .find_business_profile_by_profile_id(+ platform.get_processor().get_key_store(),+ &profile_id,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {+ id: profile_id.get_string_repr().to_owned(),+ })?;+ (profile_id, business_profile)+ }+ None => {+ let profile =+ auth_profile.ok_or(errors::ApiErrorResponse::GenericNotFoundError {+ message: "Profile id not found".to_string(),+ })?;+ let profile_id = profile.get_id().clone();+ (profile_id, profile)+ }+ };++ let pms_ctx = Box::pin(build_merchant_enabled_pms_context(+ &state,+ &platform,+ &business_profile,+ payment_intent.as_ref(),+ payment_attempt.as_ref(),+ billing_address.as_ref(),+ shipping_address.as_ref(),+ customer.as_ref(),+ is_cit_transaction,+ ))+ .await?;+let mut payment_method_responses: Vec<ResponsePaymentMethodsEnabled> = vec![];- for key in payment_experiences_consolidated_hm.iter() {+ for key in pms_ctx.payment_experiences_consolidated_hm.iter() {let mut payment_method_types = vec![];for payment_method_types_hm in key.1 {let mut payment_experience_types = vec![];@@ -3979,12 +4223,14 @@ pub async fn list_payment_methods(bank_debits: None,bank_transfers: None,// Required fields for PayLater payment method- required_fields: required_fields_hm+ required_fields: pms_ctx+ .required_fields_hm.get(key.0).and_then(|inner_hm| inner_hm.get(payment_method_types_hm.0)).cloned(),surcharge_details: None,- pm_auth_connector: pmt_to_auth_connector+ pm_auth_connector: pms_ctx+ .pmt_to_auth_connector.get(key.0).and_then(|pm_map| pm_map.get(payment_method_types_hm.0)).cloned(),@@ -3997,7 +4243,7 @@ pub async fn list_payment_methods(})}- for key in card_networks_consolidated_hm.iter() {+ for key in pms_ctx.card_networks_consolidated_hm.iter() {let mut payment_method_types = vec![];for payment_method_types_hm in key.1 {let mut card_network_types = vec![];@@ -4017,12 +4263,14 @@ pub async fn list_payment_methods(bank_debits: None,bank_transfers: None,// Required fields for Card payment method- required_fields: required_fields_hm+ required_fields: pms_ctx+ .required_fields_hm.get(key.0).and_then(|inner_hm| inner_hm.get(payment_method_types_hm.0)).cloned(),surcharge_details: None,- pm_auth_connector: pmt_to_auth_connector+ pm_auth_connector: pms_ctx+ .pmt_to_auth_connector.get(key.0).and_then(|pm_map| pm_map.get(payment_method_types_hm.0)).cloned(),@@ -4037,7 +4285,7 @@ pub async fn list_payment_methods(let mut bank_redirect_payment_method_types = vec![];- for key in banks_consolidated_hm.iter() {+ for key in pms_ctx.banks_consolidated_hm.iter() {let payment_method_type = *key.0;let connectors = key.1.clone();let bank_names = get_banks(&state, payment_method_type, connectors)?;@@ -4050,12 +4298,14 @@ pub async fn list_payment_methods(bank_debits: None,bank_transfers: None,// Required fields for BankRedirect payment method- required_fields: required_fields_hm+ required_fields: pms_ctx+ .required_fields_hm.get(&api_enums::PaymentMethod::BankRedirect).and_then(|inner_hm| inner_hm.get(key.0)).cloned(),surcharge_details: None,- pm_auth_connector: pmt_to_auth_connector+ pm_auth_connector: pms_ctx+ .pmt_to_auth_connector.get(&enums::PaymentMethod::BankRedirect).and_then(|pm_map| pm_map.get(key.0)).cloned(),@@ -4072,7 +4322,7 @@ pub async fn list_payment_methods(let mut bank_debit_payment_method_types = vec![];- for key in bank_debits_consolidated_hm.iter() {+ for key in pms_ctx.bank_debits_consolidated_hm.iter() {let payment_method_type = *key.0;let connectors = key.1.clone();bank_debit_payment_method_types.push({@@ -4086,12 +4336,14 @@ pub async fn list_payment_methods(}),bank_transfers: None,// Required fields for BankDebit payment method- required_fields: required_fields_hm+ required_fields: pms_ctx+ .required_fields_hm.get(&api_enums::PaymentMethod::BankDebit).and_then(|inner_hm| inner_hm.get(key.0)).cloned(),surcharge_details: None,- pm_auth_connector: pmt_to_auth_connector+ pm_auth_connector: pms_ctx+ .pmt_to_auth_connector.get(&enums::PaymentMethod::BankDebit).and_then(|pm_map| pm_map.get(key.0)).cloned(),@@ -4108,7 +4360,7 @@ pub async fn list_payment_methods(let mut bank_transfer_payment_method_types = vec![];- for key in bank_transfer_consolidated_hm.iter() {+ for key in pms_ctx.bank_transfer_consolidated_hm.iter() {let payment_method_type = *key.0;let connectors = key.1.clone();bank_transfer_payment_method_types.push({@@ -4122,12 +4374,14 @@ pub async fn list_payment_methods(eligible_connectors: connectors,}),// Required fields for BankTransfer payment method- required_fields: required_fields_hm+ required_fields: pms_ctx+ .required_fields_hm.get(&api_enums::PaymentMethod::BankTransfer).and_then(|inner_hm| inner_hm.get(key.0)).cloned(),surcharge_details: None,- pm_auth_connector: pmt_to_auth_connector+ pm_auth_connector: pms_ctx+ .pmt_to_auth_connector.get(&enums::PaymentMethod::BankTransfer).and_then(|pm_map| pm_map.get(key.0)).cloned(),@@ -4142,41 +4396,15 @@ pub async fn list_payment_methods(});}let currency = payment_intent.as_ref().and_then(|pi| pi.currency);- let capture_method = payment_attempt.as_ref().and_then(|pa| pa.capture_method);- let skip_external_tax_calculation = payment_intent- .as_ref()- .and_then(|intent| intent.skip_external_tax_calculation)- .unwrap_or(false);let request_external_three_ds_authentication = payment_intent.as_ref()- .and_then(|intent| intent.request_external_three_ds_authentication)+ .map(|intent| intent.get_request_external_three_ds_authentication()).unwrap_or(false);- let sdk_next_action = payment_method_utils::get_sdk_next_action_for_payment_method_list(- &state,- &dimensions,- payment_intent- .as_ref()- .and_then(|pi| pi.customer_id.as_ref()),- )- .await;let is_guest_customer = payment_intent.as_ref()- .map(|payment_intent| payment_intent.customer_id.is_none())+ .map(|intent| intent.is_guest_customer()).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())@@ -4195,37 +4423,37 @@ pub async fn list_payment_methods(api_surcharge_decision_configs::MerchantSurchargeConfigs::default()};- let collect_shipping_details_from_wallets = if business_profile- .always_collect_shipping_details_from_wallet_connector- .unwrap_or(false)- {- business_profile.always_collect_shipping_details_from_wallet_connector- } else {- business_profile.collect_shipping_details_from_wallet_connector- };-- let collect_billing_details_from_wallets = if business_profile- .always_collect_billing_details_from_wallet_connector- .unwrap_or(false)- {- business_profile.always_collect_billing_details_from_wallet_connector- } else {- business_profile.collect_billing_details_from_wallet_connector- };-- let is_tax_connector_enabled = business_profile.get_is_tax_connector_enabled();+ let is_tax_connector_enabled = payment_intent+ .as_ref()+ .map(|pi| business_profile.get_is_tax_calculation_enabled(pi))+ .unwrap_or(false);let intent_data = payment_intent.clone()- .map(|pi| {+ .map(|pi| -> errors::CustomResult<_, errors::ApiErrorResponse> {let net_amount = payment_attempt.as_ref().map(|pa| pa.net_amount.get_total_amount()).unwrap_or(pi.amount);+ let extra = PaymentMethodListIntentDataInput {+ merchant_name: platform+ .get_processor()+ .get_account()+ .merchant_name+ .as_ref()+ .map(|n| n.clone().into_inner().peek().clone()),+ mandate_payment: payment_attempt+ .as_ref()+ .and_then(|pa| pa.mandate_details.as_ref())+ .map(|d| d.to_api_mandate_data()),+ payment_type,+ capture_method: payment_attempt.as_ref().and_then(|pa| pa.capture_method),+ };pi.into_payment_method_list_intent_data(net_amount,- connector_supports_installments,- capture_method,+ pms_ctx.connector_supports_installments,+ extra,+ &business_profile,)}).transpose()@@ -4243,40 +4471,17 @@ pub async fn list_payment_methods(payment_type,payment_methods: payment_method_responses,mandate_payment: payment_attempt- .as_ref()- .and_then(|inner| inner.mandate_details.clone())- .map(|d| match d {- hyperswitch_domain_models::mandates::MandateDataType::SingleUse(i) => {- api::MandateType::SingleUse(api::MandateAmountData {- amount: i.amount,- currency: i.currency,- start_date: i.start_date,- end_date: i.end_date,- metadata: i.metadata,- })- }- hyperswitch_domain_models::mandates::MandateDataType::MultiUse(Some(i)) => {- api::MandateType::MultiUse(Some(api::MandateAmountData {- amount: i.amount,- currency: i.currency,- start_date: i.start_date,- end_date: i.end_date,- metadata: i.metadata,- }))- }- hyperswitch_domain_models::mandates::MandateDataType::MultiUse(None) => {- api::MandateType::MultiUse(None)- }- }),+ .and_then(|inner| inner.mandate_details)+ .map(|mandate_data_type| mandate_data_type.to_api_mandate_type()),show_surcharge_breakup_screen: merchant_surcharge_configs.show_surcharge_breakup_screen.unwrap_or_default(),currency,request_external_three_ds_authentication,- collect_shipping_details_from_wallets,- collect_billing_details_from_wallets,- is_tax_calculation_enabled: is_tax_connector_enabled && !skip_external_tax_calculation,- sdk_next_action,+ collect_shipping_details_from_wallets: pms_ctx.collect_shipping_details_from_wallets,+ collect_billing_details_from_wallets: pms_ctx.collect_billing_details_from_wallets,+ is_tax_calculation_enabled: is_tax_connector_enabled,+ sdk_next_action: pms_ctx.sdk_next_action,is_guest_customer,intent_data,},@@ -4284,7 +4489,7 @@ pub async fn list_payment_methods(}#[cfg(feature = "v1")]-fn should_collect_shipping_or_billing_details_from_wallet_connector(+pub fn should_collect_shipping_or_billing_details_from_wallet_connector(payment_method: api_enums::PaymentMethod,payment_experience_optional: Option<&api_enums::PaymentExperience>,business_profile: &Profile,diff --git a/crates/router/src/core/payment_methods/client.rs b/crates/router/src/core/payment_methods/client.rsnew file mode 100644index 0000000000..b7f16cc742--- /dev/null+++ b/crates/router/src/core/payment_methods/client.rs@@ -0,0 +1,565 @@+/// GET /v1/payments/{payment_id}/client+///+/// Returns a combined list of:+/// - merchant-enabled payment methods (filtered via Euclid constraint graph + session flow routing)+/// - customer saved payment methods (fetched from DB via `CustomerPaymentMethodsFetcher` trait)+///+/// Auth: `SdkAuthorizationAuth` only (Authorization: base64(publishable_key:client_secret))+use api_models::payment_methods::{+ ClientPaymentMethodsListResponse, CustomerPaymentMethod, CustomerPaymentMethodDataForClient,+ CustomerPaymentMethodForClient, PaymentMethodListIntentDataInput,+ ResponsePaymentMethodsEnabledForClient,+};+use common_utils::{consts, ext_traits::AsyncExt, generate_id, id_type};+use error_stack::ResultExt;+use router_env::{instrument, logger, tracing, Flow};++use crate::{+ core::{+ configs::dimension_state,+ errors::{self, StorageErrorExt},+ payment_methods::{+ cards, transformers::list_customer_payment_methods_from_modular_service,+ },+ payments::helpers,+ },+ pii::PeekInterface,+ routes::{self, payment_methods::ParentPaymentMethodToken},+ services,+ types::{+ domain::{self, Profile},+ storage::{self, BankDebitTokenData, PaymentTokenData},+ },+};++// ---------------------------------------------------------------------------+// Trait: CustomerPaymentMethodsFetcher+// ---------------------------------------------------------------------------++/// Abstraction over saved-PM retrieval — allows future swap to a remote PM service.+#[async_trait::async_trait]+pub trait CustomerPaymentMethodsFetcher: Send + Sync {+ async fn fetch(+ &self,+ state: &routes::SessionState,+ platform: &domain::Platform,+ payment_intent: Option<&storage::PaymentIntent>,+ customer_id: &id_type::CustomerId,+ dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,+ ) -> errors::RouterResult<Vec<CustomerPaymentMethodForClient>>;+}++/// Convert a legacy `CustomerPaymentMethod` into the slimmer client-facing type.+fn to_client_pm(pm: CustomerPaymentMethod) -> CustomerPaymentMethodForClient {+ let payment_method_data = pm+ .card+ .map(|card| CustomerPaymentMethodDataForClient::Card(Box::new(card)));++ CustomerPaymentMethodForClient {+ payment_token: pm.payment_token,+ payment_method: pm.payment_method,+ payment_method_type: pm.payment_method_type,+ default_payment_method_set: pm.default_payment_method_set,+ requires_cvv: pm.requires_cvv,+ recurring_enabled: pm.recurring_enabled,+ created: pm.created,+ last_used_at: pm.last_used_at,+ payment_method_data,+ }+}++/// DB-backed implementation — delegates to `cards::list_customer_payment_method`.+pub struct DbCustomerPaymentMethodsFetcher;++#[async_trait::async_trait]+impl CustomerPaymentMethodsFetcher for DbCustomerPaymentMethodsFetcher {+ async fn fetch(+ &self,+ state: &routes::SessionState,+ platform: &domain::Platform,+ payment_intent: Option<&storage::PaymentIntent>,+ customer_id: &id_type::CustomerId,+ dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,+ ) -> errors::RouterResult<Vec<CustomerPaymentMethodForClient>> {+ let customer_payment_methods_response = Box::pin(cards::list_customer_payment_method(+ state,+ platform.clone(),+ payment_intent.cloned(),+ customer_id,+ None, // limit+ dimensions,+ ))+ .await?;++ let response_body = match customer_payment_methods_response {+ services::ApplicationResponse::Json(response_body) => response_body,+ _ => {+ return Err(errors::ApiErrorResponse::InternalServerError.into());+ }+ };++ Ok(response_body+ .customer_payment_methods+ .into_iter()+ .map(to_client_pm)+ .collect())+ }+}++// ---------------------------------------------------------------------------+// ModularCustomerPaymentMethodsFetcher+// ---------------------------------------------------------------------------++/// Context derived from `PaymentIntentContext` needed to fetch and map modular-service PMs.+pub struct ModularCustomerPaymentMethodsFetcher {+ pub profile_id: id_type::ProfileId,+ pub intent_fulfillment_time: i64,+ pub off_session_payment_flag: bool,+ pub is_connector_agnostic_mit_enabled: bool,+}++impl ModularCustomerPaymentMethodsFetcher {+ /// Generate a short-lived Redis payment token for a modular-service PM and persist it.+ async fn store_payment_token_in_redis(+ state: &routes::SessionState,+ payment_method: common_enums::PaymentMethod,+ pm_id: String,+ intent_fulfillment_time: i64,+ ) -> errors::RouterResult<String> {+ let payment_token = generate_id(consts::ID_LENGTH, "token");++ // Build the PaymentTokenData variant that matches the payment method type,+ // mirroring the logic in `get_pm_list_context`.+ let token_data: PaymentTokenData = match payment_method {+ common_enums::PaymentMethod::Card => {+ PaymentTokenData::permanent_card(Some(pm_id.clone()), None, pm_id.clone(), None)+ }+ common_enums::PaymentMethod::Wallet => PaymentTokenData::wallet_token(pm_id.clone()),+ common_enums::PaymentMethod::BankDebit => {+ PaymentTokenData::BankDebit(BankDebitTokenData {+ payment_method_id: pm_id.clone(),+ locker_id: None,+ })+ }+ // Fallback for PM types that don't have a specific PaymentTokenData variant.+ _ => PaymentTokenData::temporary_generic(generate_id(consts::ID_LENGTH, "token")),+ };++ // Persist the token → PaymentTokenData mapping in Redis so that when the+ // customer submits the payment the token can be resolved back to the PM.+ ParentPaymentMethodToken::create_key_for_token((&payment_token, payment_method))+ .insert(intent_fulfillment_time, token_data, state)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to store payment token in Redis")?;++ Ok(payment_token)+ }+}++#[async_trait::async_trait]+impl CustomerPaymentMethodsFetcher for ModularCustomerPaymentMethodsFetcher {+ async fn fetch(+ &self,+ state: &routes::SessionState,+ platform: &domain::Platform,+ _payment_intent: Option<&storage::PaymentIntent>,+ customer_id: &id_type::CustomerId,+ dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,+ ) -> errors::RouterResult<Vec<CustomerPaymentMethodForClient>> {+ let merchant_id = platform.get_processor().get_account().get_id().clone();++ let items = list_customer_payment_methods_from_modular_service(+ state,+ &merchant_id,+ &self.profile_id,+ customer_id.clone(),+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)?;++ // Base requires_cvv from merchant/superposition config (same as legacy PM list).+ let requires_cvv_base = dimensions+ .get_requires_cvv(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ Some(customer_id),+ )+ .await;++ let mut customer_payment_methods = Vec::with_capacity(items.len());++ for pm in items {+ // Compute requires_cvv using the same logic as the legacy API+ // (using psp_tokenization_enabled in place of connector_mandate_details+ // and network_tokenization in place of network_transaction_id).+ let requires_cvv = if self.is_connector_agnostic_mit_enabled {+ requires_cvv_base+ && !(self.off_session_payment_flag+ && (pm.psp_tokenization_enabled || pm.network_tokenization.is_some()))+ } else {+ requires_cvv_base && !(self.off_session_payment_flag && pm.psp_tokenization_enabled)+ };++ // recurring_enabled is inferred from psp_tokenization_enabled.+ let recurring_enabled = Some(pm.psp_tokenization_enabled);++ let payment_token = Self::store_payment_token_in_redis(+ state,+ pm.payment_method_type,+ pm.id.clone(),+ self.intent_fulfillment_time,+ )+ .await?;++ // Build the client-facing response item.+ let payment_method_data = pm.payment_method_data.and_then(|d| d.into());++ customer_payment_methods.push(CustomerPaymentMethodForClient {+ payment_token,+ payment_method: pm.payment_method_type,+ payment_method_type: Some(pm.payment_method_subtype),+ default_payment_method_set: pm.is_default,+ requires_cvv,+ recurring_enabled,+ created: Some(pm.created),+ last_used_at: Some(pm.last_used_at),+ payment_method_data,+ });+ }++ Ok(customer_payment_methods)+ }+}++// ---------------------------------------------------------------------------+// Internal context struct+// ---------------------------------------------------------------------------++struct PaymentIntentContext {+ payment_intent: storage::PaymentIntent,+ payment_attempt: storage::PaymentAttempt,+ business_profile: Profile,+ is_cit_transaction: bool,+ billing_address: Option<domain::Address>,+ shipping_address: Option<domain::Address>,+ customer: Option<hyperswitch_domain_models::customer::Customer>,+}++async fn load_payment_intent_context(+ state: &routes::SessionState,+ platform: &domain::Platform,+ payment_id: &id_type::PaymentId,+) -> errors::RouterResult<PaymentIntentContext> {+ let db = &*state.store;++ let payment_intent = db+ .find_payment_intent_by_payment_id_processor_merchant_id(+ payment_id,+ platform.get_processor().get_account().get_id(),+ platform.get_processor().get_key_store(),+ platform.get_processor().get_account().storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;++ let payment_attempt = db+ .find_payment_attempt_by_payment_id_processor_merchant_id_attempt_id(+ &payment_intent.payment_id,+ &payment_intent.processor_merchant_id,+ &payment_intent.active_attempt.get_id(),+ platform.get_processor().get_account().storage_scheme,+ platform.get_processor().get_key_store(),+ )+ .await+ .change_context(errors::ApiErrorResponse::PaymentNotFound)?;++ let profile_id = payment_intent+ .profile_id+ .clone()+ .ok_or(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("'profile_id' not set in payment intent")?;++ let business_profile = db+ .find_business_profile_by_profile_id(platform.get_processor().get_key_store(), &profile_id)+ .await+ .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {+ id: profile_id.get_string_repr().to_owned(),+ })?;++ let shipping_address = helpers::get_address_by_id(+ state,+ payment_intent.shipping_address_id.clone(),+ platform.get_processor().get_key_store(),+ &payment_intent.payment_id,+ platform.get_processor().get_account().get_id(),+ platform.get_processor().get_account().storage_scheme,+ )+ .await?;++ let billing_address = helpers::get_address_by_id(+ state,+ payment_intent.billing_address_id.clone(),+ platform.get_processor().get_key_store(),+ &payment_intent.payment_id,+ platform.get_processor().get_account().get_id(),+ platform.get_processor().get_account().storage_scheme,+ )+ .await?;++ let customer = payment_intent+ .customer_id+ .as_ref()+ .async_and_then(|customer_id| async {+ db.find_customer_by_customer_id_merchant_id(+ customer_id,+ &payment_intent.merchant_id,+ platform.get_provider().get_key_store(),+ platform.get_provider().get_account().storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)+ .ok()+ })+ .await;++ let setup_future_usage = payment_intent.setup_future_usage;+ let is_cit_transaction = payment_attempt.mandate_details.is_some()+ || setup_future_usage+ .map(|future_usage| future_usage == common_enums::FutureUsage::OffSession)+ .unwrap_or(false);++ Ok(PaymentIntentContext {+ payment_intent,+ payment_attempt,+ business_profile,+ is_cit_transaction,+ billing_address,+ shipping_address,+ customer,+ })+}++// ---------------------------------------------------------------------------+// fetch_enabled_payment_methods — Gate 1 + Gate 2 + hashmap building+// ---------------------------------------------------------------------------++struct EnabledPmsResult {+ payment_methods_enabled: Vec<ResponsePaymentMethodsEnabledForClient>,+ sdk_next_action: api_models::payments::SdkNextAction,+ connector_supports_installments: bool,+}++async fn fetch_enabled_payment_methods(+ state: &routes::SessionState,+ platform: &domain::Platform,+ payment_intent_context: &PaymentIntentContext,+) -> errors::RouterResult<EnabledPmsResult> {+ let merchant_enabled_pms_context = Box::pin(cards::build_merchant_enabled_pms_context(+ state,+ platform,+ &payment_intent_context.business_profile,+ Some(&payment_intent_context.payment_intent),+ Some(&payment_intent_context.payment_attempt),+ payment_intent_context.billing_address.as_ref(),+ payment_intent_context.shipping_address.as_ref(),+ payment_intent_context.customer.as_ref(),+ payment_intent_context.is_cit_transaction,+ ))+ .await?;++ let mut flat_pms = merchant_enabled_pms_context.payment_experience_pms_for_client();+ flat_pms.extend(merchant_enabled_pms_context.card_network_pms_for_client());+ flat_pms.extend(merchant_enabled_pms_context.bank_redirect_pms_for_client(state)?);+ flat_pms.extend(merchant_enabled_pms_context.bank_debit_pms_for_client());+ flat_pms.extend(merchant_enabled_pms_context.bank_transfer_pms_for_client());++ Ok(EnabledPmsResult {+ payment_methods_enabled: flat_pms,+ sdk_next_action: merchant_enabled_pms_context.sdk_next_action,+ connector_supports_installments: merchant_enabled_pms_context+ .connector_supports_installments,+ })+}++// ---------------------------------------------------------------------------+// fetch_customer_payment_methods — saved PMs for the payment's customer+// ---------------------------------------------------------------------------++/// Filter `customer_payment_methods` to only those whose `(payment_method, payment_method_type)`+/// combination is present in `payment_methods_enabled`.+fn filter_customer_pms_by_enabled(+ customer_pms: Vec<CustomerPaymentMethodForClient>,+ enabled: &[ResponsePaymentMethodsEnabledForClient],+) -> Vec<CustomerPaymentMethodForClient> {+ customer_pms+ .into_iter()+ .filter(|customer_payment_method| {+ enabled.iter().any(|enabled_payment_method| {+ enabled_payment_method.payment_method == customer_payment_method.payment_method+ && match customer_payment_method.payment_method_type {+ Some(payment_method_type) => {+ enabled_payment_method.payment_method_type == payment_method_type+ }+ // Cards may have no subtype (determined by BIN lookup at payment time).+ // Allow them through if the merchant has any card subtype enabled.+ None if customer_payment_method.payment_method+ == common_enums::PaymentMethod::Card =>+ {+ true+ }+ None => false,+ }+ })+ })+ .collect()+}++async fn fetch_customer_payment_methods(+ state: &routes::SessionState,+ platform: &domain::Platform,+ payment_intent_context: &PaymentIntentContext,+) -> errors::RouterResult<Vec<CustomerPaymentMethodForClient>> {+ let customer_id = match payment_intent_context.payment_intent.customer_id.as_ref() {+ Some(customer_id) => customer_id,+ None => return Ok(vec![]),+ };++ let dimensions = dimension_state::Dimensions::new()+ .with_processor_merchant_id(platform.get_processor().get_processor_merchant_id())+ .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id());++ let feature_config = crate::core::utils::get_feature_config(state, platform, &dimensions).await;++ if feature_config.is_payment_method_modular_allowed {+ logger::info!("Fetching customer payment methods from modular service");++ let profile_id = payment_intent_context+ .payment_intent+ .profile_id+ .clone()+ .ok_or(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("'profile_id' not set in payment intent")?;++ let intent_fulfillment_time = payment_intent_context+ .business_profile+ .get_order_fulfillment_time()+ .unwrap_or(consts::DEFAULT_INTENT_FULFILLMENT_TIME);++ let off_session_payment_flag = payment_intent_context+ .payment_intent+ .setup_future_usage+ .map(|future_usage| future_usage == common_enums::FutureUsage::OffSession)+ .unwrap_or(false);++ let is_connector_agnostic_mit_enabled = payment_intent_context+ .business_profile+ .is_connector_agnostic_mit_enabled+ .unwrap_or(false);++ ModularCustomerPaymentMethodsFetcher {+ profile_id,+ intent_fulfillment_time,+ off_session_payment_flag,+ is_connector_agnostic_mit_enabled,+ }+ .fetch(+ state,+ platform,+ Some(&payment_intent_context.payment_intent),+ customer_id,+ &dimensions,+ )+ .await+ } else {+ logger::info!("Fetching customer payment methods from DB");+ DbCustomerPaymentMethodsFetcher+ .fetch(+ state,+ platform,+ Some(&payment_intent_context.payment_intent),+ customer_id,+ &dimensions,+ )+ .await+ }+}++// ---------------------------------------------------------------------------+// list_payment_methods_client — top-level orchestrator+// ---------------------------------------------------------------------------++#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsList))]+pub async fn list_payment_methods_client(+ state: routes::SessionState,+ platform: domain::Platform,+ payment_id: id_type::PaymentId,+) -> errors::RouterResponse<ClientPaymentMethodsListResponse> {+ // 1. Load payment intent + related context+ let payment_intent_context =+ load_payment_intent_context(&state, &platform, &payment_id).await?;++ // 2. Fetch enabled payment methods (Gate 1 + Gate 2 + consolidation)+ let EnabledPmsResult {+ payment_methods_enabled,+ sdk_next_action,+ connector_supports_installments,+ } = fetch_enabled_payment_methods(&state, &platform, &payment_intent_context).await?;++ // 3. Fetch saved customer payment methods+ let customer_payment_methods =+ fetch_customer_payment_methods(&state, &platform, &payment_intent_context).await?;++ // 4. Filter customer PMs to only those whose (payment_method, payment_method_type)+ // combination is present in the merchant-enabled list.+ let customer_payment_methods_filtered =+ filter_customer_pms_by_enabled(customer_payment_methods, &payment_methods_enabled);++ // 5. Build intent_data+ let net_amount = payment_intent_context+ .payment_attempt+ .net_amount+ .get_total_amount();+ let payment_type = Some(+ payment_intent_context+ .payment_attempt+ .infer_payment_type(payment_intent_context.is_cit_transaction),+ );++ let intent_data_input = PaymentMethodListIntentDataInput {+ merchant_name: platform+ .get_processor()+ .get_account()+ .merchant_name+ .as_ref()+ .map(|merchant_name| merchant_name.clone().into_inner().peek().clone()),+ mandate_payment: payment_intent_context+ .payment_attempt+ .mandate_details+ .as_ref()+ .map(|mandate_details| mandate_details.to_api_mandate_data()),+ payment_type,+ capture_method: payment_intent_context.payment_attempt.capture_method,+ };++ let intent_data = payment_intent_context+ .payment_intent+ .clone()+ .into_payment_method_list_intent_data(+ net_amount,+ connector_supports_installments,+ intent_data_input,+ &payment_intent_context.business_profile,+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to build intent_data")?;++ Ok(services::ApplicationResponse::Json(+ ClientPaymentMethodsListResponse {+ payment_methods_enabled,+ customer_payment_methods: customer_payment_methods_filtered,+ sdk_next_action,+ intent_data,+ },+ ))+}diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rsindex 2ce9d2dea3..7ed10747dd 100644--- a/crates/router/src/core/payment_methods/transformers.rs+++ b/crates/router/src/core/payment_methods/transformers.rs@@ -27,6 +27,7 @@ use josekit::jwe;use payment_methods::client::{self as pm_client,create::{CreatePaymentMethodResponse, CreatePaymentMethodV1Request},+ list::{ListCustomerPaymentMethods, ListCustomerPaymentMethodsV1Request},retrieve::{RetrievePaymentMethodResponse, RetrievePaymentMethodV1Request},UpdatePaymentMethod, UpdatePaymentMethodV1Payload, UpdatePaymentMethodV1Request,};@@ -2010,6 +2011,54 @@ pub async fn create_payment_method_in_modular_service(Ok(payment_method_with_raw_data.0)}+#[cfg(feature = "v1")]+pub async fn list_customer_payment_methods_from_modular_service(+ state: &routes::SessionState,+ merchant_id: &id_type::MerchantId,+ profile_id: &id_type::ProfileId,+ customer_id: id_type::CustomerId,+) -> CustomResult<Vec<payment_methods::types::PaymentMethodResponseItemV1>, errors::ApiErrorResponse>+{+ let internal_api_key = &state+ .conf+ .internal_merchant_id_profile_id_auth+ .internal_api_key;+ let mut parent_headers = Headers::new();+ parent_headers.insert((+ headers::X_PROFILE_ID.to_string(),+ profile_id.get_string_repr().to_string().into_masked(),+ ));+ parent_headers.insert((+ headers::X_MERCHANT_ID.to_string(),+ merchant_id.get_string_repr().to_string().into_masked(),+ ));+ parent_headers.insert((+ headers::X_INTERNAL_API_KEY.to_string(),+ internal_api_key.clone().expose().to_string().into_masked(),+ ));++ let client = pm_client::PaymentMethodClient::new(+ &state.conf.micro_services.payment_methods_base_url,+ &parent_headers,+ &state.conf.trace_header.header_name,+ );++ let request = ListCustomerPaymentMethodsV1Request {+ customer_id,+ query_params: api_models::payment_methods::PaymentMethodListRequest::default(),+ modular_service_prefix: state.conf.micro_services.payment_methods_prefix.0.clone(),+ };++ ListCustomerPaymentMethods::call(state, &client, request)+ .await+ .map(|resp| resp.0.customer_payment_methods)+ .map_err(|err| {+ logger::error!(error=?err, "modular list customer payment methods failed");+ errors::ApiErrorResponse::InternalServerError+ })+ .attach_printable("Failed to list customer payment methods from modular service")+}+#[cfg(feature = "v1")]pub async fn create_pm_modular_service_call(state: &routes::SessionState,diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 12b62ab51f..2590b06123 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -999,6 +999,10 @@ impl Payments {web::resource("/{payment_id}/eligibility").route(web::post().to(payments::payments_submit_eligibility)),)+ .service(+ web::resource("/{payment_id}/client")+ .route(web::get().to(payment_methods::list_payment_methods_for_payments_client)),+ ).service(web::resource("/redirect/{payment_id}/{merchant_id}/{attempt_id}").route(web::get().to(payments::payments_start)),diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rsindex a6a9f19372..b374e9b43f 100644--- a/crates/router/src/routes/payment_methods.rs+++ b/crates/router/src/routes/payment_methods.rs@@ -2027,3 +2027,39 @@ pub async fn payment_method_get_token_details_api()).await}++#[cfg(feature = "v1")]+/// List payment methods for a Payment (client SDK endpoint)+///+/// Returns a unified response combining merchant-enabled payment methods and+/// customer saved payment methods, filtered via Euclid constraint graph and+/// session flow routing.+#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsList))]+pub async fn list_payment_methods_for_payments_client(+ state: web::Data<AppState>,+ req: HttpRequest,+ path: web::Path<id_type::PaymentId>,+) -> HttpResponse {+ let flow = Flow::PaymentMethodsList;+ let payment_id = path.into_inner();++ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ payment_id.clone(),+ |state, auth: auth::AuthenticationData, payment_id, _| {+ payment_methods_routes::client::list_payment_methods_client(+ state,+ auth.platform,+ payment_id,+ )+ },+ &auth::SdkAuthorizationAuth {+ allow_connected_scope_operation: true,+ allow_platform_self_operation: true,+ },+ api_locking::LockAction::NotApplicable,+ ))+ .await+}