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
refactor(payment-methods): Update session tokens response with internal and external vault config (#12479)
Prasunna Soppaf4e7dcc9b313
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex e309835aa8..e4e7ddb47d 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -23070,6 +23070,19 @@},"additionalProperties": false},+ "InternalVaultSessionDetails": {+ "type": "object",+ "description": "Internal vault details for SDK authorization",+ "required": [+ "sdk_authorization"+ ],+ "properties": {+ "sdk_authorization": {+ "type": "string",+ "description": "Base64-encoded SDK authorization token for the internal vault session"+ }+ }+ },"Invoice": {"type": "object","required": [@@ -33969,7 +33982,7 @@"vault_details": {"allOf": [{- "$ref": "#/components/schemas/VaultSessionDetails"+ "$ref": "#/components/schemas/VaultDetails"}],"nullable": true@@ -43230,6 +43243,28 @@"propertyName": "type"}},+ "VaultDetails": {+ "type": "object",+ "description": "Top-level vault details returned in the session-tokens response.\nFor v1: contains both internal vault (SDK authorization) and external vault details.\nFor v2: contains only external vault details.",+ "properties": {+ "internal_vault": {+ "allOf": [+ {+ "$ref": "#/components/schemas/InternalVaultSessionDetails"+ }+ ],+ "nullable": true+ },+ "external_vault_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/VaultSessionDetails"+ }+ ],+ "nullable": true+ }+ }+ },"VaultSdk": {"type": "string","enum": [diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex 5000c4771a..6cc26b2847 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -16600,6 +16600,19 @@}}},+ "InternalVaultSessionDetails": {+ "type": "object",+ "description": "Internal vault details for SDK authorization",+ "required": [+ "sdk_authorization"+ ],+ "properties": {+ "sdk_authorization": {+ "type": "string",+ "description": "Base64-encoded SDK authorization token for the internal vault session"+ }+ }+ },"JCSVoucherData": {"type": "object","properties": {@@ -22840,6 +22853,14 @@}],"nullable": true+ },+ "external_vault_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/VaultSessionDetails"+ }+ ],+ "nullable": true}}},@@ -24795,7 +24816,7 @@"vault_details": {"allOf": [{- "$ref": "#/components/schemas/VaultSessionDetails"+ "$ref": "#/components/schemas/VaultDetails"}],"nullable": true@@ -32229,6 +32250,28 @@"propertyName": "type"}},+ "VaultDetails": {+ "type": "object",+ "description": "Top-level vault details returned in the session-tokens response.\nFor v1: contains both internal vault (SDK authorization) and external vault details.\nFor v2: contains only external vault details.",+ "properties": {+ "internal_vault": {+ "allOf": [+ {+ "$ref": "#/components/schemas/InternalVaultSessionDetails"+ }+ ],+ "nullable": true+ },+ "external_vault_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/VaultSessionDetails"+ }+ ],+ "nullable": true+ }+ }+ },"VaultSdk": {"type": "string","enum": [diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex 4eee988a4f..b95d51f856 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -4576,6 +4576,10 @@ pub struct PaymentMethodSessionResponse {/// Network token details if availablepub network_tokenization_data: Option<NetworkTokenResponse>,++ /// External vault session details if external vault is enabled for the profile+ #[schema(value_type = Option<VaultSessionDetails>)]+ pub external_vault_details: Option<payments::VaultSessionDetails>,}#[cfg(feature = "v2")]diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex be888822ea..78d9c36aaa 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -10132,6 +10132,24 @@ pub enum SessionToken {NoSessionTokenReceived,}+/// Top-level vault details returned in the session-tokens response.+/// For v1: contains both internal vault (SDK authorization) and external vault details.+/// For v2: contains only external vault details.+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]+pub struct VaultDetails {+ /// Internal vault details containing the SDK authorization token (v1 only)+ pub internal_vault: Option<InternalVaultSessionDetails>,+ /// External vault details (e.g. VGS or Hyperswitch Vault)+ pub external_vault_details: Option<VaultSessionDetails>,+}++/// Internal vault details for SDK authorization+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]+pub struct InternalVaultSessionDetails {+ /// Base64-encoded SDK authorization token for the internal vault session+ pub sdk_authorization: String,+}+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]#[serde(rename_all = "snake_case")]pub enum VaultSessionDetails {@@ -10890,8 +10908,8 @@ pub struct PaymentsSessionResponse {pub client_secret: Secret<String, pii::ClientSecret>,/// The list of session token objectpub session_token: Vec<SessionToken>,- /// External vault session details- pub vault_details: Option<VaultSessionDetails>,+ /// Vault details containing internal vault (SDK auth) and external vault info+ pub vault_details: Option<VaultDetails>,}#[cfg(feature = "v2")]@@ -10903,7 +10921,7 @@ pub struct PaymentsSessionResponse {/// The list of session token objectpub session_token: Vec<SessionToken>,/// External vault session details- pub vault_details: Option<VaultSessionDetails>,+ pub vault_details: Option<VaultDetails>,}#[cfg(feature = "v1")]diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rsindex a71e9d06c0..ec1599a407 100644--- a/crates/hyperswitch_domain_models/src/payments.rs+++ b/crates/hyperswitch_domain_models/src/payments.rs@@ -2,7 +2,7 @@use std::marker::PhantomData;#[cfg(feature = "v2")]-use api_models::payments::{SessionToken, VaultSessionDetails};+use api_models::payments::{SessionToken, VaultDetails, VaultSessionDetails};use api_models::{customers::CustomerDocumentDetails, payments::ConnectorMetadata};use common_types::primitive_wrappers;#[cfg(feature = "v1")]@@ -1304,7 +1304,7 @@ wherepub payment_intent: PaymentIntent,pub sessions_token: Vec<SessionToken>,pub client_secret: Option<Secret<String>>,- pub vault_session_details: Option<VaultSessionDetails>,+ pub vault_session_details: Option<VaultDetails>,pub connector_customer_id: Option<String>,}diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex b7a838d50d..99d1cedc74 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -766,6 +766,8 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payments::AmazonPayDeliveryOptions,api_models::payments::AmazonPayDeliveryPrice,api_models::payments::AmazonPayShippingMethod,+ api_models::payments::VaultDetails,+ api_models::payments::InternalVaultSessionDetails,api_models::payment_methods::RequiredFieldInfo,api_models::payment_methods::DefaultPaymentMethod,api_models::payment_methods::MaskedBankDetails,diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rsindex 68d612e639..c59e17d6c4 100644--- a/crates/openapi/src/openapi_v2.rs+++ b/crates/openapi/src/openapi_v2.rs@@ -550,6 +550,8 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payments::AmountDetailsUpdate,api_models::payments::SessionToken,api_models::payments::VaultSessionDetails,+ api_models::payments::VaultDetails,+ api_models::payments::InternalVaultSessionDetails,api_models::payments::VgsSessionDetails,api_models::payments::HyperswitchVaultSessionDetails,api_models::payments::ApplePaySessionResponse,diff --git a/crates/payment_methods/src/client.rs b/crates/payment_methods/src/client.rsindex c378b967fc..a3c5cbfe0d 100644--- a/crates/payment_methods/src/client.rs+++ b/crates/payment_methods/src/client.rs@@ -11,6 +11,8 @@ pub mod list;#[cfg(feature = "v1")]/// Retrieve payment method flow.pub mod retrieve;+/// Payment method session create flow.+pub mod session;/// Update payment method flow.#[cfg(feature = "v1")]pub mod update;@@ -23,6 +25,10 @@ use hyperswitch_interfaces::micro_service::MicroserviceClient;#[cfg(feature = "v1")]pub use retrieve::{RetrievePaymentMethod, RetrievePaymentMethodV1Request};use router_env::RequestIdentifier;+pub use session::{+ CreatePaymentMethodSession, CreatePaymentMethodSessionResponse,+ CreatePaymentMethodSessionV1Request,+};#[cfg(feature = "v1")]pub use update::{BankDebitDetailUpdate, CardDetailUpdate, PaymentMethodUpdateData, UpdatePaymentMethod,diff --git a/crates/payment_methods/src/client/session.rs b/crates/payment_methods/src/client/session.rsnew file mode 100644index 0000000000..66f5459065--- /dev/null+++ b/crates/payment_methods/src/client/session.rs@@ -0,0 +1,158 @@+//! Payment method session create flow types and models.++use common_utils::{+ id_type,+ request::{Method, RequestContent},+};+use hyperswitch_interfaces::micro_service::MicroserviceClientError;+use hyperswitch_masking::Secret;+use serde::{Deserialize, Serialize};++/// Flow type for creating a payment method session via the internal PM service.+#[derive(Debug)]+pub struct CreatePaymentMethodSession;++/// Request sent to the internal PM service to create a payment method session.+#[derive(Debug)]+pub struct CreatePaymentMethodSessionV1Request {+ /// Customer id for which the session is created (v2 global customer id as string).+ pub customer_id: Option<id_type::CustomerId>,+ /// Prefix that forms part of the URL path (e.g. "v2").+ pub modular_service_prefix: String,+ /// Storage type for the session.+ pub storage_type: common_enums::StorageType,+}++/// Wire-level request body serialised as JSON.+#[derive(Debug, Clone, Serialize)]+pub struct ModularPMSessionCreateRequest {+ #[serde(skip_serializing_if = "Option::is_none")]+ pub customer_id: Option<id_type::CustomerId>,+ pub storage_type: common_enums::StorageType,+}++/// Local deserializable mirror of `api_models::payments::VgsSessionDetails`.+#[derive(Debug, Clone, Deserialize)]+pub struct VgsSessionDetailsResponse {+ pub external_vault_id: Secret<String>,+ pub sdk_env: String,+}++/// Local deserializable mirror of `api_models::payments::HyperswitchVaultSessionDetails`.+#[derive(Debug, Clone, Deserialize)]+pub struct HyperswitchVaultSessionDetailsResponse {+ pub payment_method_session_id: Secret<String>,+ pub client_secret: Secret<String>,+ pub publishable_key: Secret<String>,+ pub profile_id: Secret<String>,+}++/// Local deserializable mirror of `api_models::payments::VaultSessionDetails`.+#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum VaultSessionDetailsResponse {+ Vgs(VgsSessionDetailsResponse),+ HyperswitchVault(HyperswitchVaultSessionDetailsResponse),+}++impl From<VaultSessionDetailsResponse> for api_models::payments::VaultSessionDetails {+ fn from(resp: VaultSessionDetailsResponse) -> Self {+ match resp {+ VaultSessionDetailsResponse::Vgs(vgs) => {+ Self::Vgs(api_models::payments::VgsSessionDetails {+ external_vault_id: vgs.external_vault_id,+ sdk_env: vgs.sdk_env,+ })+ }+ VaultSessionDetailsResponse::HyperswitchVault(hsv) => {+ Self::HyperswitchVault(api_models::payments::HyperswitchVaultSessionDetails {+ payment_method_session_id: hsv.payment_method_session_id,+ client_secret: hsv.client_secret,+ publishable_key: hsv.publishable_key,+ profile_id: hsv.profile_id,+ })+ }+ }+ }+}++/// Minimal subset of the PM session response we care about.+#[derive(Debug, Clone, Deserialize)]+pub struct ModularPMSessionCreateResponse {+ /// The payment method session ID.+ pub id: String,+ /// The client secret for this session.+ pub client_secret: Option<Secret<String>>,+ /// The customer ID associated with this session.+ pub customer_id: Option<id_type::CustomerId>,+ /// The pre-computed SDK authorization string (base64-encoded).+ pub sdk_authorization: Option<String>,+ /// External vault session details returned by the PM service when an external vault is+ /// configured for the profile.+ pub external_vault_details: Option<VaultSessionDetailsResponse>,+}++/// V1-facing response (thin wrapper around the wire response).+#[derive(Debug, Clone)]+pub struct CreatePaymentMethodSessionResponse {+ pub id: String,+ pub client_secret: Option<Secret<String>>,+ pub customer_id: Option<id_type::CustomerId>,+ pub sdk_authorization: Option<String>,+ pub external_vault_details: Option<api_models::payments::VaultSessionDetails>,+}++// --- Conversions ---++impl TryFrom<&CreatePaymentMethodSessionV1Request> for ModularPMSessionCreateRequest {+ type Error = MicroserviceClientError;++ fn try_from(req: &CreatePaymentMethodSessionV1Request) -> Result<Self, Self::Error> {+ Ok(Self {+ customer_id: req.customer_id.clone(),+ storage_type: req.storage_type,+ })+ }+}++impl TryFrom<ModularPMSessionCreateResponse> for CreatePaymentMethodSessionResponse {+ type Error = MicroserviceClientError;++ fn try_from(resp: ModularPMSessionCreateResponse) -> Result<Self, Self::Error> {+ Ok(Self {+ id: resp.id,+ client_secret: resp.client_secret,+ customer_id: resp.customer_id,+ sdk_authorization: resp.sdk_authorization,+ external_vault_details: resp.external_vault_details.map(Into::into),+ })+ }+}++// --- Micro-service flow wiring ---++impl CreatePaymentMethodSession {+ fn build_body(&self, request: ModularPMSessionCreateRequest) -> Option<RequestContent> {+ Some(RequestContent::Json(Box::new(request)))+ }++ fn build_path_params(+ &self,+ request: &CreatePaymentMethodSessionV1Request,+ ) -> Vec<(&'static str, String)> {+ vec![("prefix", request.modular_service_prefix.clone())]+ }+}++hyperswitch_interfaces::impl_microservice_flow!(+ CreatePaymentMethodSession,+ method = Method::Post,+ path = "/{prefix}/payment-method-sessions",+ v1_request = CreatePaymentMethodSessionV1Request,+ v2_request = ModularPMSessionCreateRequest,+ v2_response = ModularPMSessionCreateResponse,+ v1_response = CreatePaymentMethodSessionResponse,+ client = crate::client::PaymentMethodClient<'_>,+ body = CreatePaymentMethodSession::build_body,+ path_params = CreatePaymentMethodSession::build_path_params+);diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex 355be673bb..110cc826c1 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -6012,17 +6012,21 @@ pub async fn payment_methods_session_create(let key_manager_state = &(&state).into();let provider = platform.get_provider();- if let (Some(customer_id)) = &request.customer_id {- db.find_customer_by_global_id_merchant_id(- customer_id,- platform.get_provider().get_account().get_id(),- platform.get_provider().get_key_store(),- platform.get_provider().get_account().storage_scheme,- )- .await- .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)- .attach_printable("Customer not found for the payment method")?;- }+ let customer = if let Some(customer_id) = &request.customer_id {+ let customer = db+ .find_customer_by_global_id_merchant_id(+ customer_id,+ platform.get_provider().get_account().get_id(),+ platform.get_provider().get_key_store(),+ platform.get_provider().get_account().storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)+ .attach_printable("Customer not found for the payment method")?;+ Some(customer)+ } else {+ None+ };let payment_methods_session_id =id_type::GlobalPaymentMethodSessionId::generate(&state.conf.cell_information.id)@@ -6091,6 +6095,18 @@ pub async fn payment_methods_session_create(.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to insert payment methods session in db")?;+ let external_vault_details = payments_core::vault_session::fetch_external_vault_details(+ &state, &platform, &profile, &customer,+ )+ .await+ .unwrap_or_else(|err| {+ router_env::logger::warn!(+ ?err,+ "Failed to fetch external vault details for payment method session"+ );+ None+ });+let sdk_authorization = Option::<hyperswitch_domain_models::sdk_auth::SdkAuthorization>::from(hyperswitch_domain_models::sdk_auth::SdkAuthorizationContext {platform,@@ -6111,6 +6127,7 @@ pub async fn payment_methods_session_create(None,None,None,+ external_vault_details,);Ok(services::ApplicationResponse::Json(response))@@ -6180,6 +6197,7 @@ pub async fn payment_methods_session_update(None,None,None,+ None,);Ok(services::ApplicationResponse::Json(response))@@ -6240,6 +6258,7 @@ pub async fn payment_methods_session_retrieve(}),None,None,+ None,);Ok(services::ApplicationResponse::Json(response))@@ -6342,6 +6361,7 @@ pub async fn payment_methods_session_update_payment_method(update_response.card_cvc_token_storage,update_response.payment_method_data.clone(),None,+ None,);Ok(services::ApplicationResponse::Json(response))@@ -6584,6 +6604,7 @@ pub async fn payment_methods_session_confirm(payment_method_response.card_cvc_token_storage,associated_pm_data,payment_method_response.network_token,+ None,);Ok(services::ApplicationResponse::Json(diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rsindex ab34bf35e6..04ac2982f0 100644--- a/crates/router/src/core/payment_methods/transformers.rs+++ b/crates/router/src/core/payment_methods/transformers.rs@@ -1197,6 +1197,7 @@ pub fn generate_payment_method_session_response(card_cvc_token_storage: Option<api_models::payment_methods::CardCVCTokenStorageDetails>,payment_method_data: Option<api_models::payment_methods::PaymentMethodResponseData>,network_tokenization_response: Option<api_models::payment_methods::NetworkTokenResponse>,+ external_vault_details: Option<api_models::payments::VaultSessionDetails>,) -> api_models::payment_methods::PaymentMethodSessionResponse {let next_action = associated_payment.as_ref()@@ -1238,6 +1239,7 @@ pub fn generate_payment_method_session_response(sdk_authorization,keep_alive: payment_method_session.keep_alive,network_tokenization_data: network_tokenization_response,+ external_vault_details,}}diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex d9e33d6cbf..daadafe690 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -8773,7 +8773,7 @@ wherepub card_testing_guard_data:Option<hyperswitch_domain_models::card_testing_guard_data::CardTestingGuardData>,pub vault_operation: Option<domain_payments::VaultOperation>,- pub vault_session_details: Option<api::VaultSessionDetails>,+ pub vault_session_details: Option<api::VaultDetails>,pub threeds_method_comp_ind: Option<api_models::payments::ThreeDsCompletionIndicator>,pub whole_connector_response: Option<Secret<String>>,pub is_manual_retry_enabled: Option<bool>,@@ -12688,7 +12688,7 @@ pub trait OperationSessionGetters<F> {&self,) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>>;- fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails>;+ fn get_optional_external_vault_session_details(&self) -> Option<api::VaultDetails>;#[cfg(feature = "v1")]fn get_click_to_pay_service_details(&self) -> Option<&api_models::payments::CtpServiceDetails>;@@ -12773,7 +12773,7 @@ pub trait OperationSessionSetters<F> {fn set_vault_session_details(&mut self,- external_vault_session_details: Option<api::VaultSessionDetails>,+ external_vault_session_details: Option<api::VaultDetails>,);fn set_routing_approach_in_attempt(&mut self, routing_approach: Option<enums::RoutingApproach>);@@ -12955,7 +12955,7 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentData<F> {self.client_session_id.clone()}- fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> {+ fn get_optional_external_vault_session_details(&self) -> Option<api::VaultDetails> {self.vault_session_details.clone()}@@ -13134,10 +13134,7 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentData<F> {self.vault_operation = Some(vault_operation);}- fn set_vault_session_details(- &mut self,- vault_session_details: Option<api::VaultSessionDetails>,- ) {+ fn set_vault_session_details(&mut self, vault_session_details: Option<api::VaultDetails>) {self.vault_session_details = vault_session_details;}@@ -13318,7 +13315,7 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentIntentData<F> {None}- fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> {+ fn get_optional_external_vault_session_details(&self) -> Option<api::VaultDetails> {self.vault_session_details.clone()}}@@ -13449,10 +13446,7 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> {todo!()}- fn set_vault_session_details(- &mut self,- vault_session_details: Option<api::VaultSessionDetails>,- ) {+ fn set_vault_session_details(&mut self, vault_session_details: Option<api::VaultDetails>) {self.vault_session_details = vault_session_details;}@@ -13634,7 +13628,7 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentConfirmData<F> {.and_then(|pre_routing_algorithm| pre_routing_algorithm.pre_routing_results)}- fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> {+ fn get_optional_external_vault_session_details(&self) -> Option<api::VaultDetails> {todo!()}}@@ -13769,7 +13763,7 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentConfirmData<F> {fn set_vault_session_details(&mut self,- external_vault_session_details: Option<api::VaultSessionDetails>,+ external_vault_session_details: Option<api::VaultDetails>,) {todo!()}@@ -13949,7 +13943,7 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentStatusData<F> {None}- fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> {+ fn get_optional_external_vault_session_details(&self) -> Option<api::VaultDetails> {todo!()}}@@ -14083,7 +14077,7 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentStatusData<F> {fn set_vault_session_details(&mut self,- external_vault_session_details: Option<api::VaultSessionDetails>,+ external_vault_session_details: Option<api::VaultDetails>,) {todo!()}@@ -14264,7 +14258,7 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentCaptureData<F> {None}- fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> {+ fn get_optional_external_vault_session_details(&self) -> Option<api::VaultDetails> {todo!()}}@@ -14398,7 +14392,7 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentCaptureData<F> {fn set_vault_session_details(&mut self,- external_vault_session_details: Option<api::VaultSessionDetails>,+ external_vault_session_details: Option<api::VaultDetails>,) {todo!()}@@ -14579,7 +14573,7 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentAttemptListData<F> {todo!()}- fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> {+ fn get_optional_external_vault_session_details(&self) -> Option<api::VaultDetails> {todo!()}}@@ -14740,7 +14734,7 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentCancelData<F> {None}- fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> {+ fn get_optional_external_vault_session_details(&self) -> Option<api::VaultDetails> {todo!()}}@@ -14875,7 +14869,7 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentCancelData<F> {fn set_vault_session_details(&mut self,- _external_vault_session_details: Option<api::VaultSessionDetails>,+ _external_vault_session_details: Option<api::VaultDetails>,) {todo!()}diff --git a/crates/router/src/core/payments/vault_session.rs b/crates/router/src/core/payments/vault_session.rsindex d4f94818b3..40802cce19 100644--- a/crates/router/src/core/payments/vault_session.rs+++ b/crates/router/src/core/payments/vault_session.rs@@ -1,4 +1,5 @@pub use common_enums::enums::CallConnectorAction;+use common_utils::id_type;use error_stack::{report, ResultExt};#[cfg(feature = "v2")]pub use hyperswitch_domain_models::payments::PaymentIntentData;@@ -15,19 +16,17 @@ pub use hyperswitch_domain_models::{use hyperswitch_interfaces::api::Connector as ConnectorTrait;#[cfg(feature = "v2")]use hyperswitch_interfaces::connector_integration_v2::{ConnectorIntegrationV2, ConnectorV2};+#[cfg(feature = "v1")]+use hyperswitch_masking::{ExposeInterface, Mask};use router_env::env::Env;-#[cfg(feature = "v1")]-use crate::core::payments::call_create_connector_customer_if_required;#[cfg(feature = "v2")]-use crate::core::payments::customers;+use crate::core::payments::{customers, gateway::context as gateway_context, helpers};use crate::{core::{errors::{self, RouterResult},payments::{flows::{ConstructFlowSpecificData, Feature},- gateway::context as gateway_context,- helpers,operations::BoxedOperation,OperationSessionGetters, OperationSessionSetters,},@@ -75,62 +74,99 @@ wherelet is_external_vault_sdk_enabled = profile.is_vault_sdk_enabled();if is_external_vault_sdk_enabled {- let external_vault_source = profile- .external_vault_connector_details- .as_ref()- .map(|details| &details.vault_connector_id);-- let merchant_connector_account =- domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(- helpers::get_merchant_connector_account_v2(- state,- platform.get_processor(),- external_vault_source,- )- .await?,- ));-- let updated_customer = call_create_connector_customer_if_required(- state,- customer,- platform.get_processor(),- platform.get_initiator(),- &merchant_connector_account,- payment_data,- )- .await?;-- if let Some((customer, updated_customer)) = customer.clone().zip(updated_customer) {- let db = &*state.store;- let customer_id = customer.get_id().clone();- let customer_merchant_id = customer.merchant_id.clone();-- let _updated_customer = db- .update_customer_by_global_id(- &customer_id,- customer,- updated_customer,- platform.get_processor().get_key_store(),- platform.get_processor().get_account().storage_scheme,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to update customer during Vault session")?;- };-- let vault_session_details = generate_vault_session_details(- state,- platform,- &merchant_connector_account,- payment_data.get_connector_customer_id(),- )- .await?;-- payment_data.set_vault_session_details(vault_session_details);+ let external_vault_details =+ fetch_external_vault_details(state, platform, profile, customer).await?;+ let vault_details = external_vault_details.map(|evd| api::VaultDetails {+ internal_vault: None,+ external_vault_details: Some(evd),+ });+ payment_data.set_vault_session_details(vault_details);}Ok(())}+/// Call the internal payment-methods service to create a PM session and extract both+/// `internal_vault` (sdk_authorization) and `external_vault_details` from the response.+#[cfg(feature = "v1")]+async fn call_internal_pm_session_create_for_vault(+ state: &SessionState,+ platform: &domain::Platform,+ profile: &domain::Profile,+ customer_id: Option<&id_type::CustomerId>,+) -> RouterResult<Option<api::VaultDetails>> {+ use common_utils::request::Headers;+ use payment_methods::client::{+ CreatePaymentMethodSession, CreatePaymentMethodSessionV1Request, PaymentMethodClient,+ };++ let processor_merchant_id = platform.get_processor().get_account().get_id();+ let profile_id = profile.get_id();+ let internal_api_key = &state+ .conf+ .internal_merchant_id_profile_id_auth+ .internal_api_key;++ let mut headers = Headers::new();+ headers.insert((+ crate::headers::X_PROFILE_ID.to_string(),+ profile_id.get_string_repr().to_string().into_masked(),+ ));+ headers.insert((+ crate::headers::X_MERCHANT_ID.to_string(),+ processor_merchant_id+ .get_string_repr()+ .to_string()+ .into_masked(),+ ));+ headers.insert((+ crate::headers::X_INTERNAL_API_KEY.to_string(),+ internal_api_key.clone().expose().to_string().into_masked(),+ ));++ let client = PaymentMethodClient::new(+ &state.conf.micro_services.payment_methods_base_url,+ &headers,+ &state.conf.trace_header.header_name,+ );++ let request = CreatePaymentMethodSessionV1Request {+ customer_id: customer_id.cloned(),+ modular_service_prefix: state.conf.micro_services.payment_methods_prefix.0.clone(),+ storage_type: common_enums::StorageType::Persistent,+ };++ let response = CreatePaymentMethodSession::call(state, &client, request)+ .await+ .map_err(|err| {+ router_env::logger::error!(?err, "Internal PM session create for vault failed");+ errors::ApiErrorResponse::InternalServerError+ })+ .attach_printable("Failed to create PM session via internal service for vault details")?;++ // Build the internal vault details from the sdk_authorization returned by the PM service.+ let internal_vault =+ response+ .sdk_authorization+ .map(|sdk_auth| api::InternalVaultSessionDetails {+ sdk_authorization: sdk_auth,+ });++ let external_vault_details = response.external_vault_details;++ // Only return Some if at least one of the two parts is present.+ if internal_vault.is_none() && external_vault_details.is_none() {+ router_env::logger::warn!(+ "Internal PM session create returned neither sdk_authorization nor external_vault_details"+ );+ return Ok(None);+ }++ Ok(Some(api::VaultDetails {+ internal_vault,+ external_vault_details,+ }))+}+#[cfg(feature = "v1")]#[allow(clippy::too_many_arguments)]pub async fn populate_vault_session_details<F, RouterDReq, ApiRequest, D>(@@ -155,86 +191,20 @@ wherelet is_external_vault_sdk_enabled = profile.external_vault_details.is_external_vault_enabled();if is_external_vault_sdk_enabled {- // Extract the vault connector id from the profile- let vault_connector_id = match &profile.external_vault_details {- domain::ExternalVaultDetails::ExternalVaultEnabled(details) => {- Some(&details.vault_connector_id)- }- domain::ExternalVaultDetails::Skip => None,- };-- // Fetch the vault MCA using the vault_connector_id from profile- let vault_mca_type = helpers::get_merchant_connector_account(- state,- platform.get_processor(),- None,- profile.get_id(),- "",- vault_connector_id,- )- .await?;-- let vault_mca = match vault_mca_type {- helpers::MerchantConnectorAccountType::DbVal(ref mca) => mca.clone(),- helpers::MerchantConnectorAccountType::CacheVal(_) => {- return Err(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Vault MCA must be a DB-backed account")- }- };- let connector_customer_map = customer- .as_ref()- .and_then(|customer| customer.connector_customer.as_ref());-- let default_gateway_context = gateway_context::RouterGatewayContext::direct(- platform.get_processor().clone(),- vault_mca_type.clone(),- payment_data.get_payment_intent().merchant_id.clone(),- profile.get_id().clone(),- payment_data.get_creds_identifier().map(|id| id.to_string()),- );+ let customer_id = customer.as_ref().map(|c| c.get_id());- let updated_customer = call_create_connector_customer_if_required(- state,- connector_customer_map,- platform.get_processor(),- platform.get_initiator(),- &vault_mca_type,- payment_data,- None,- &default_gateway_context,- )- .await?;-- if let Some((customer, updated_customer)) = customer.clone().zip(updated_customer) {- let db = &*state.store;- let customer_id = customer.get_id().clone();- let customer_merchant_id = customer.merchant_id.clone();-- let _updated_customer = db- .update_customer_by_customer_id_merchant_id(- customer_id,- customer_merchant_id,- customer,- updated_customer,- platform.get_provider().get_key_store(),- platform.get_provider().get_account().storage_scheme,- )+ let vault_details =+ call_internal_pm_session_create_for_vault(state, platform, profile, customer_id).await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to update customer during Vault session")?;- };-- let connector_customer_id = payment_data.get_connector_customer_id();-- let vault_session_details = generate_vault_session_details_v1(- state,- platform.get_processor(),- &vault_mca,- connector_customer_id,- )- .await?;-- payment_data.set_vault_session_details(vault_session_details);+ .unwrap_or_else(|err| {+ router_env::logger::warn!(+ ?err,+ "Failed to fetch vault details via internal PM session service"+ );+ None+ });++ payment_data.set_vault_session_details(vault_details);}Ok(())}@@ -660,3 +630,224 @@ where.await.to_vault_failed_response()}++#[cfg(feature = "v2")]+pub async fn fetch_external_vault_details(+ state: &SessionState,+ platform: &domain::Platform,+ profile: &domain::Profile,+ customer: &Option<domain::Customer>,+) -> RouterResult<Option<api::VaultSessionDetails>> {+ let external_vault_source = profile+ .external_vault_connector_details+ .as_ref()+ .map(|details| &details.vault_connector_id);++ let merchant_connector_account =+ domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(+ helpers::get_merchant_connector_account_v2(+ state,+ platform.get_processor(),+ external_vault_source,+ )+ .await?,+ ));++ // Retrieve the existing connector_customer_id from the customer record for this vault MCA.+ // If none exists, create a connector customer at the vault connector.+ let connector_customer_id = get_or_create_vault_connector_customer(+ state,+ platform,+ customer,+ &merchant_connector_account,+ profile.get_id(),+ )+ .await+ .map_err(|err| {+ router_env::logger::error!(?err, "Failed to get or create vault connector customer");+ err+ })?;++ generate_vault_session_details(+ state,+ platform,+ &merchant_connector_account,+ connector_customer_id,+ )+ .await+}++/// Returns the existing connector customer ID for the given vault MCA, or creates one if absent.+/// Returns `None` only if the connector does not require a customer.+#[cfg(feature = "v2")]+async fn get_or_create_vault_connector_customer(+ state: &SessionState,+ platform: &domain::Platform,+ customer: &Option<domain::Customer>,+ merchant_connector_account_type: &domain::MerchantConnectorAccountTypeDetails,+ profile_id: &id_type::ProfileId,+) -> RouterResult<Option<String>> {+ use hyperswitch_domain_models::router_request_types::ConnectorCustomerData;++ let db_mca = merchant_connector_account_type+ .get_inner_db_merchant_connector_account()+ .ok_or(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Vault MCA is missing, cannot create connector customer")?;++ let connector_name = db_mca.get_connector_name_as_string();+ let merchant_connector_id = db_mca.get_id();++ let connector = api::ConnectorData::get_connector_by_name(+ &state.conf.connectors,+ &connector_name,+ api::GetToken::Connector,+ Some(merchant_connector_id.clone()),+ )?;++ let (should_create, existing_id) = customers::should_call_connector_create_customer(+ &connector,+ customer,+ merchant_connector_account_type,+ );++ match should_create {+ false => {+ router_env::logger::info!(+ vault_mca_id = %merchant_connector_id.get_string_repr(),+ has_existing_connector_customer_id = existing_id.is_some(),+ "Vault connector customer already exists for MCA, skipping creation"+ );+ Ok(existing_id.map(ToOwned::to_owned))+ }+ true => {+ router_env::logger::info!(+ vault_mca_id = %merchant_connector_id.get_string_repr(),+ has_customer = customer.is_some(),+ "No existing vault connector customer for MCA, creating one now"+ );++ // No existing connector customer – create one now.+ let gateway_context = gateway_context::RouterGatewayContext::direct(+ platform.get_processor().clone(),+ merchant_connector_account_type.clone(),+ platform.get_processor().get_account().get_id().clone(),+ profile_id.clone(),+ None,+ );++ let vault_mca = match merchant_connector_account_type {+ domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(mca) => {+ Ok(mca.as_ref())+ }+ _ => Err(+ report!(errors::ApiErrorResponse::InternalServerError).attach_printable(+ "MerchantConnectorDetails not supported for vault operations",+ ),+ ),+ }?;++ // Construct vault router data, then convert to CreateConnectorCustomer flow+ let vault_router_data_v2 =+ core_utils::construct_vault_router_data::<ExternalVaultCreateFlow>(+ state,+ platform.get_processor().get_account().get_id(),+ vault_mca,+ None,+ None,+ None,+ None,+ )+ .await?;++ let old_vault_router_data =+ VaultConnectorFlowData::to_old_router_data(vault_router_data_v2)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Cannot convert vault router data for connector customer creation",+ )?;++ // Extract name and email from the customer record for the connector customer creation request.+ let (customer_name, customer_email) = if let Some(cust) = customer.as_ref() {+ let name = cust.name.clone().map(|n| n.into_inner());+ let email = cust.email.clone().map(common_utils::pii::Email::from);+ router_env::logger::info!(+ vault_customer_name_present = name.is_some(),+ vault_customer_email_present = email.is_some(),+ "Building vault connector customer request"+ );+ (name, email)+ } else {+ router_env::logger::warn!("No customer record available when creating vault connector customer; name will be None");+ (None, None)+ };++ let customer_request_data = ConnectorCustomerData {+ description: None,+ email: customer_email,+ phone: None,+ name: customer_name,+ preprocessing_id: None,+ payment_method_data: None,+ split_payments: None,+ setup_future_usage: None,+ customer_acceptance: None,+ customer_id: None,+ billing_address: None,+ metadata: None,+ currency: None,+ };++ let customer_response_data: Result<+ router_types::PaymentsResponseData,+ router_types::ErrorResponse,+ > = Err(router_types::ErrorResponse::default());++ let customer_router_data = helpers::router_data_type_conversion::<+ _,+ api::CreateConnectorCustomer,+ _,+ _,+ _,+ _,+ >(+ old_vault_router_data,+ customer_request_data,+ customer_response_data,+ );++ let new_connector_customer_id = customers::create_connector_customer(+ state,+ &connector,+ &customer_router_data,+ customer_router_data.request.clone(),+ &gateway_context,+ )+ .await?;++ // Persist the newly created connector customer ID back to the customer record.+ let customer_update = customers::update_connector_customer_in_customers(+ merchant_connector_account_type,+ customer.as_ref(),+ new_connector_customer_id.clone(),+ platform.get_initiator(),+ )+ .await;++ if let Some((cust, update)) = customer.clone().zip(customer_update) {+ let db = &*state.store;+ db.update_customer_by_global_id(+ &cust.get_id().clone(),+ cust,+ update,+ platform.get_processor().get_key_store(),+ platform.get_processor().get_account().storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to persist connector customer ID for vault session")?;+ }++ Ok(new_connector_customer_id)+ }+ }+}diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rsindex 80382043c1..075caee1bb 100644--- a/crates/router/src/routes/payment_methods.rs+++ b/crates/router/src/routes/payment_methods.rs@@ -1669,24 +1669,34 @@ pub async fn payment_methods_session_create(let flow = Flow::PaymentMethodSessionCreate;let payload = json_payload.into_inner();+ let api_auth = auth::V2ApiKeyAuth {+ allow_connected_scope_operation: true,+ allow_platform_self_operation: true,+ };+ let (auth_type, _api_key_type) = match auth::check_internal_api_key_auth_no_client_secret(+ req.headers(),+ api_auth,+ state.conf.internal_merchant_id_profile_id_auth.clone(),+ ) {+ Ok(auth) => auth,+ Err(err) => return api::log_and_return_error_response(error_stack::report!(err)),+ };+Box::pin(api::server_wrap(flow,state,&req,payload,|state, auth: auth::AuthenticationData, request, _| async move {- payment_methods_routes::payment_methods_session_create(+ Box::pin(payment_methods_routes::payment_methods_session_create(state,auth.platform,auth.profile,request,- )+ )).await},- &auth::V2ApiKeyAuth {- allow_connected_scope_operation: true,- allow_platform_self_operation: true,- },+ &*auth_type,api_locking::LockAction::NotApplicable,)).awaitdiff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rsindex 244aa8864c..7bea5dfd1a 100644--- a/crates/router/src/types/api/payments.rs+++ b/crates/router/src/types/api/payments.rs@@ -16,20 +16,21 @@ pub use api_models::{payments::{Address, AddressDetails, Amount, ApplepayPaymentMethod, AuthenticationForStartResponse,Card, CryptoData, CustomerDetails, CustomerDetailsResponse, HyperswitchVaultSessionDetails,- MandateAmountData, MandateData, MandateType, MandateValidationFields, NextActionType,- OpenBankingSessionToken, PayLaterData, PaymentIdType, PaymentListConstraints,- PaymentListFilters, PaymentListFiltersV2, PaymentMethodData, PaymentMethodDataRequest,- PaymentMethodDataResponse, PaymentOp, PaymentsAggregateResponse, PaymentsApproveRequest,- PaymentsCancelPostCaptureRequest, PaymentsCancelRequest, PaymentsCaptureRequest,- PaymentsCompleteAuthorizeRequest, PaymentsDynamicTaxCalculationRequest,- PaymentsDynamicTaxCalculationResponse, PaymentsExtendAuthorizationRequest,- PaymentsExternalAuthenticationRequest, PaymentsIncrementalAuthorizationRequest,- PaymentsManualUpdateRequest, PaymentsPostSessionTokensRequest,- PaymentsPostSessionTokensResponse, PaymentsRedirectRequest, PaymentsRedirectionResponse,- PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, PaymentsResponseForm,- PaymentsRetrieveRequest, PaymentsSessionRequest, PaymentsSessionResponse,- PaymentsStartRequest, PaymentsUpdateMetadataRequest, PaymentsUpdateMetadataResponse,- PgRedirectResponse, PhoneDetails, RedirectionResponse, SessionToken, UrlDetails,+ InternalVaultSessionDetails, MandateAmountData, MandateData, MandateType,+ MandateValidationFields, NextActionType, OpenBankingSessionToken, PayLaterData,+ PaymentIdType, PaymentListConstraints, PaymentListFilters, PaymentListFiltersV2,+ PaymentMethodData, PaymentMethodDataRequest, PaymentMethodDataResponse, PaymentOp,+ PaymentsAggregateResponse, PaymentsApproveRequest, PaymentsCancelPostCaptureRequest,+ PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest,+ PaymentsDynamicTaxCalculationRequest, PaymentsDynamicTaxCalculationResponse,+ PaymentsExtendAuthorizationRequest, PaymentsExternalAuthenticationRequest,+ PaymentsIncrementalAuthorizationRequest, PaymentsManualUpdateRequest,+ PaymentsPostSessionTokensRequest, PaymentsPostSessionTokensResponse,+ PaymentsRedirectRequest, PaymentsRedirectionResponse, PaymentsRejectRequest,+ PaymentsRequest, PaymentsResponse, PaymentsResponseForm, PaymentsRetrieveRequest,+ PaymentsSessionRequest, PaymentsSessionResponse, PaymentsStartRequest,+ PaymentsUpdateMetadataRequest, PaymentsUpdateMetadataResponse, PgRedirectResponse,+ PhoneDetails, RedirectionResponse, SessionToken, UrlDetails, VaultDetails,VaultSessionDetails, VerifyRequest, VerifyResponse, VgsSessionDetails, WalletData,},};