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 support for guest checkout flow in payment method service (#10487)
Prasunna Soppa5139ebbde30c
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex 5c3a443ed1..5d1bfaf359 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -18576,6 +18576,14 @@}],"nullable": true+ },+ "storage_type": {+ "allOf": [+ {+ "$ref": "#/components/schemas/StorageType"+ }+ ],+ "nullable": true}},"additionalProperties": false@@ -19283,6 +19291,14 @@}],"nullable": true+ },+ "storage_type": {+ "allOf": [+ {+ "$ref": "#/components/schemas/StorageType"+ }+ ],+ "nullable": true}}},@@ -19419,6 +19435,14 @@"type": "string","description": "The return url to which the customer should be redirected to after adding the payment method","nullable": true+ },+ "storage_type": {+ "allOf": [+ {+ "$ref": "#/components/schemas/StorageType"+ }+ ],+ "nullable": true}}},@@ -19578,6 +19602,14 @@"description": "The token-id created if there is tokenization_data present","example": "12345_tok_01926c58bc6e77c09e809964e72af8c8","nullable": true+ },+ "storage_type": {+ "allOf": [+ {+ "$ref": "#/components/schemas/StorageType"+ }+ ],+ "nullable": true}}},@@ -26466,6 +26498,13 @@"propertyName": "type"}},+ "StorageType": {+ "type": "string",+ "enum": [+ "volatile",+ "persistent"+ ]+ },"StraightThroughAlgorithm": {"oneOf": [{diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex 3abb5c5e6e..b78b6ebdce 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -122,7 +122,7 @@ pub struct PaymentMethodCreate {example = "12345_cus_01926c58bc6e77c09e809964e72af8c8",value_type = String)]- pub customer_id: id_type::GlobalCustomerId,+ pub customer_id: Option<id_type::GlobalCustomerId>,/// Payment method data to be passedpub payment_method_data: PaymentMethodCreateData,@@ -138,6 +138,10 @@ pub struct PaymentMethodCreate {/// The network tokenization configuration if applicable#[schema(value_type = Option<NetworkTokenization>)]pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,++ /// The storage type for the payment method+ #[schema(value_type = Option<StorageType>)]+ pub storage_type: Option<common_enums::StorageType>,}#[cfg(feature = "v2")]@@ -1077,7 +1081,7 @@ pub struct PaymentMethodResponse {example = "12345_cus_01926c58bc6e77c09e809964e72af8c8",value_type = String)]- pub customer_id: id_type::GlobalCustomerId,+ pub customer_id: Option<id_type::GlobalCustomerId>,/// The type of payment method use for the payment.#[schema(value_type = PaymentMethod, example = "card")]@@ -1107,7 +1111,12 @@ pub struct PaymentMethodResponse {/// The connector token details if availablepub connector_tokens: Option<Vec<ConnectorTokenDetails>>,+ /// Network token details if availablepub network_token: Option<NetworkTokenResponse>,++ /// The storage type for the payment method+ #[schema(value_type = Option<StorageType>)]+ pub storage_type: Option<common_enums::StorageType>,}#[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)]@@ -3360,6 +3369,10 @@ pub struct PaymentMethodSessionConfirmRequest {/// The return url to which the customer should be redirected to after adding the payment method#[schema(value_type = Option<String>)]pub return_url: Option<common_utils::types::Url>,++ /// The storage type for the payment method+ #[schema(value_type = Option<StorageType>)]+ pub storage_type: Option<common_enums::StorageType>,}#[cfg(feature = "v2")]@@ -3417,6 +3430,10 @@ pub struct PaymentMethodSessionResponse {/// The token-id created if there is tokenization_data present#[schema(value_type = Option<String>, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")]pub associated_token_id: Option<id_type::GlobalTokenId>,++ /// The storage type for the payment method+ #[schema(value_type = Option<StorageType>)]+ pub storage_type: Option<common_enums::StorageType>,}#[cfg(feature = "v2")]diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 1906645b7c..f99abcaea1 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -10342,3 +10342,26 @@ pub enum VaultTokenType {#[strum(serialize = "cryptogram")]NetworkTokenCryptogram,}++#[derive(+ Clone,+ Debug,+ Copy,+ Default,+ Eq,+ Hash,+ PartialEq,+ serde::Deserialize,+ serde::Serialize,+ strum::Display,+ strum::EnumString,+ ToSchema,+)]+#[router_derive::diesel_enum(storage_type = "text")]+#[serde(rename_all = "snake_case")]+#[strum(serialize_all = "snake_case")]+pub enum StorageType {+ Volatile,+ #[default]+ Persistent,+}diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rsindex bdf3dab705..334fb77ff9 100644--- a/crates/hyperswitch_domain_models/src/payment_methods.rs+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs@@ -9,7 +9,10 @@ use common_enums::enums::MerchantStorageScheme;#[cfg(feature = "v1")]use common_utils::crypto::OptionalEncryptableValue;#[cfg(feature = "v2")]-use common_utils::{crypto::Encryptable, encryption::Encryption, types::keymanager::ToEncryptable};+use common_utils::{+ crypto::Encryptable, encryption::Encryption, ext_traits::OptionExt,+ types::keymanager::ToEncryptable,+};use common_utils::{errors::{CustomResult, ParsingError, ValidationError},id_type, pii, type_name,@@ -95,13 +98,14 @@ pub struct PaymentMethod {}#[cfg(feature = "v2")]-#[derive(Clone, Debug, router_derive::ToEncryption)]+#[derive(Clone, Debug, router_derive::ToEncryption, serde::Serialize)]pub struct PaymentMethod {/// The identifier for the payment method. Using this recurring payments can be madepub id: id_type::GlobalPaymentMethodId,/// The customer id against which the payment method is saved- pub customer_id: id_type::GlobalCustomerId,+ /// It is made optional to support guest checkout tokenization+ pub customer_id: Option<id_type::GlobalCustomerId>,/// The merchant id against which the payment method is savedpub merchant_id: id_type::MerchantId,@@ -538,7 +542,7 @@ impl super::behaviour::Conversion for PaymentMethod {type NewDstType = diesel_models::payment_method::PaymentMethodNew;async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {Ok(Self::DstType {- customer_id: self.customer_id,+ customer_id: self.customer_id.get_required_value("GlobalCustomerId")?,merchant_id: self.merchant_id,id: self.id,created_at: self.created_at,@@ -651,7 +655,7 @@ impl super::behaviour::Conversion for PaymentMethod {.attach_printable("Error while deserializing External Vault Token Data")?;Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {- customer_id: storage_model.customer_id,+ customer_id: Some(storage_model.customer_id),merchant_id: storage_model.merchant_id,id: storage_model.id,created_at: storage_model.created_at,@@ -693,7 +697,7 @@ impl super::behaviour::Conversion for PaymentMethod {async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {Ok(Self::NewDstType {- customer_id: self.customer_id,+ customer_id: self.customer_id.get_required_value("GlobalCustomerId")?,merchant_id: self.merchant_id,id: self.id,created_at: self.created_at,diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rsindex 68624028cb..0046674a76 100644--- a/crates/openapi/src/openapi_v2.rs+++ b/crates/openapi/src/openapi_v2.rs@@ -352,6 +352,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::enums::OrganizationType,api_models::enums::GooglePayCardFundingSource,api_models::enums::VaultTokenType,+ api_models::enums::StorageType,api_models::admin::MerchantConnectorCreate,api_models::admin::AdditionalMerchantData,api_models::admin::CardTestingGuardConfig,diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex ecbd425563..482b0b3492 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -25,7 +25,7 @@ pub use api_models::{enums::PayoutConnectors, payouts as payout_types};use common_utils::{consts::DEFAULT_LOCALE, ext_traits::OptionExt};#[cfg(feature = "v2")]use common_utils::{- crypto::Encryptable,+ crypto::{EncodeMessage, Encryptable, GcmAes256},errors::CustomResult,ext_traits::{AsyncExt, ValueExt},fp_utils::when,@@ -702,9 +702,10 @@ pub(crate) fn get_payment_method_create_request(payment_method_data: &api_models::payments::PaymentMethodData,payment_method_type: storage_enums::PaymentMethod,payment_method_subtype: storage_enums::PaymentMethodType,- customer_id: id_type::GlobalCustomerId,+ customer_id: Option<id_type::GlobalCustomerId>,billing_address: Option<&api_models::payments::Address>,payment_method_session: Option<&domain::payment_methods::PaymentMethodSession>,+ storage_type: Option<common_enums::StorageType>,) -> RouterResult<payment_methods::PaymentMethodCreate> {match payment_method_data {api_models::payments::PaymentMethodData::Card(card) => {@@ -736,13 +737,14 @@ pub(crate) fn get_payment_method_create_request(payment_method_type,payment_method_subtype,metadata: None,- customer_id: customer_id.clone(),+ customer_id,payment_method_data: payment_methods::PaymentMethodCreateData::Card(card_detail),billing: billing_address.map(ToOwned::to_owned),psp_tokenization: payment_method_session.and_then(|pm_session| pm_session.psp_tokenization.clone()),network_tokenization: payment_method_session.and_then(|pm_session| pm_session.network_tokenization.clone()),+ storage_type,};Ok(payment_method_request)}@@ -896,7 +898,6 @@ pub async fn create_payment_method(Ok(services::ApplicationResponse::Json(response))}-#[cfg(feature = "v2")]#[instrument(skip_all)]pub async fn create_payment_method_core(@@ -906,13 +907,34 @@ pub async fn create_payment_method_core(platform: &domain::Platform,profile: &domain::Profile,) -> RouterResult<(api::PaymentMethodResponse, domain::PaymentMethod)> {- use common_utils::ext_traits::ValueExt;+ match req.storage_type {+ Some(common_enums::StorageType::Volatile) => {+ create_volatile_payment_method_core(state, _request_state, req, platform, profile).await+ }+ Some(common_enums::StorageType::Persistent) | None => {+ create_persistent_payment_method_core(state, _request_state, req, platform, profile)+ .await+ }+ }+}+#[cfg(feature = "v2")]+#[instrument(skip_all)]+pub async fn create_persistent_payment_method_core(+ state: &SessionState,+ _request_state: &routes::app::ReqState,+ req: api::PaymentMethodCreate,+ platform: &domain::Platform,+ profile: &domain::Profile,+) -> RouterResult<(api::PaymentMethodResponse, domain::PaymentMethod)> {req.validate()?;let db = &*state.store;let merchant_id = platform.get_provider().get_account().get_id();- let customer_id = req.customer_id.to_owned();+ let customer_id = req+ .customer_id+ .to_owned()+ .get_required_value("customer_id")?;let key_manager_state = &(state).into();db.find_customer_by_global_id(@@ -980,6 +1002,82 @@ pub async fn create_payment_method_core(}}+#[cfg(feature = "v2")]+#[instrument(skip_all)]+pub async fn create_volatile_payment_method_core(+ state: &SessionState,+ _request_state: &routes::app::ReqState,+ req: api::PaymentMethodCreate,+ platform: &domain::Platform,+ profile: &domain::Profile,+) -> RouterResult<(api::PaymentMethodResponse, domain::PaymentMethod)> {+ req.validate()?;++ let db = &*state.store;+ let merchant_id = platform.get_provider().get_account().get_id();+ let customer_id = req.customer_id.to_owned();+ let key_manager_state = &(state).into();++ if let Some(ref customer_id) = customer_id {+ db.find_customer_by_global_id(+ customer_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 payment_method_billing_address = req+ .billing+ .clone()+ .async_map(|billing| {+ cards::create_encrypted_data(+ key_manager_state,+ platform.get_provider().get_key_store(),+ billing,+ )+ })+ .await+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encrypt Payment method billing address")?+ .map(|encoded_address| {+ encoded_address.deserialize_inner_value(|value| value.parse_value("address"))+ })+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to parse Payment method billing address")?;++ let payment_method_id =+ id_type::GlobalPaymentMethodId::generate(&state.conf.cell_information.id)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to generate GlobalPaymentMethodId")?;++ match &req.payment_method_data {+ api::PaymentMethodCreateData::Card(_) => {+ logger::info!("Creating volatile card payment method");+ Box::pin(create_volatile_payment_method_card_core(+ state,+ req,+ platform,+ profile,+ merchant_id,+ &customer_id,+ payment_method_id,+ payment_method_billing_address,+ ))+ .await+ }+ api::PaymentMethodCreateData::ProxyCard(_) => {+ Err(report!(errors::ApiErrorResponse::UnprocessableEntity {+ message: "Proxy card payment method cannot be created as volatile".to_string()+ }))+ }+ }+}+#[cfg(feature = "v2")]#[allow(clippy::too_many_arguments)]#[instrument(skip_all)]@@ -1070,7 +1168,11 @@ pub async fn create_payment_method_card_core(.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to update payment method in db")?;- let resp = pm_transforms::generate_payment_method_response(&payment_method, &None)?;+ let resp = pm_transforms::generate_payment_method_response(+ &payment_method,+ &None,+ req.storage_type,+ )?;Ok((resp, payment_method))}@@ -1097,6 +1199,99 @@ pub async fn create_payment_method_card_core(Ok((response, payment_method))}+#[cfg(feature = "v2")]+#[allow(clippy::too_many_arguments)]+#[instrument(skip_all)]+pub async fn create_volatile_payment_method_card_core(+ state: &SessionState,+ req: api::PaymentMethodCreate,+ platform: &domain::Platform,+ profile: &domain::Profile,+ merchant_id: &id_type::MerchantId,+ customer_id: &Option<id_type::GlobalCustomerId>,+ payment_method_id: id_type::GlobalPaymentMethodId,+ payment_method_billing_address: Option<+ Encryptable<hyperswitch_domain_models::address::Address>,+ >,+) -> RouterResult<(api::PaymentMethodResponse, domain::PaymentMethod)> {+ let db = &*state.store;++ let payment_method_data = domain::PaymentMethodVaultingData::try_from(req.payment_method_data)?+ .populate_bin_details_for_payment_method(state)+ .await;++ let vaulting_result = vault_payment_method_in_volatile_storage(+ state,+ &payment_method_data,+ platform,+ profile,+ None,+ customer_id,+ )+ .await;++ let (response, payment_method) = match vaulting_result {+ Ok((+ pm_types::AddVaultResponse {+ vault_id,+ fingerprint_id,+ ..+ },+ external_vault_source,+ )) => {+ let locker_id = Some(vault_id.clone());+ let payment_method = construct_payment_method_object(+ req.metadata.clone(),+ customer_id,+ payment_method_id,+ merchant_id,+ payment_method_billing_address.clone(),+ state,+ platform.get_provider().get_key_store(),+ Some(&payment_method_data),+ Some(req.payment_method_type),+ Some(req.payment_method_subtype),+ locker_id,+ fingerprint_id,+ external_vault_source,+ )+ .await+ .attach_printable("failed to construct payment method")?;++ let redis_connection = state+ .store+ .get_redis_conn()+ .map_err(Into::<errors::StorageError>::into)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to get redis connection")?;++ logger::info!("Storing payment method id in redis");++ redis_connection+ .serialize_and_set_key_with_expiry(+ &payment_method.get_id().get_string_repr().to_string().into(),+ payment_method.clone(),+ consts::DEFAULT_PAYMENT_METHOD_STORE_TTL,+ )+ .await+ .map_err(Into::<errors::StorageError>::into)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to insert payment method id in redis")?;++ let resp = pm_transforms::generate_payment_method_response(+ &payment_method,+ &None,+ req.storage_type,+ )?;++ Ok((resp, payment_method))+ }+ Err(e) => Err(e),+ }?;++ Ok((response, payment_method))+}+// network tokenization and vaulting to locker is not required for proxy card since the card is already tokenized#[cfg(feature = "v2")]#[allow(clippy::too_many_arguments)]@@ -1192,7 +1387,7 @@ pub async fn create_payment_method_proxy_card_core(.await?;let payment_method_response =- pm_transforms::generate_payment_method_response(&payment_method, &None)?;+ pm_transforms::generate_payment_method_response(&payment_method, &None, req.storage_type)?;Ok((payment_method_response, payment_method))}@@ -1577,7 +1772,7 @@ pub async fn payment_method_intent_create(.await.attach_printable("Failed to add Payment method to DB")?;- let resp = pm_transforms::generate_payment_method_response(&payment_method, &None)?;+ let resp = pm_transforms::generate_payment_method_response(&payment_method, &None, None)?;Ok(services::ApplicationResponse::Json(resp))}@@ -1927,7 +2122,7 @@ pub async fn create_payment_method_for_intent(.insert_payment_method(key_store,domain::PaymentMethod {- customer_id: customer_id.to_owned(),+ customer_id: Some(customer_id.to_owned()),merchant_id: merchant_id.to_owned(),id: payment_method_id,locker_id: None,@@ -1964,6 +2159,78 @@ pub async fn create_payment_method_for_intent(Ok(response)}+#[cfg(feature = "v2")]+#[instrument(skip_all)]+#[allow(clippy::too_many_arguments)]+pub async fn construct_payment_method_object(+ _metadata: Option<common_utils::pii::SecretSerdeValue>,+ customer_id: &Option<id_type::GlobalCustomerId>,+ payment_method_id: id_type::GlobalPaymentMethodId,+ merchant_id: &id_type::MerchantId,+ payment_method_billing_address: Option<+ Encryptable<hyperswitch_domain_models::address::Address>,+ >,+ state: &SessionState,+ key_store: &domain::MerchantKeyStore,+ payment_method_vaulting_data: Option<&domain::PaymentMethodVaultingData>,+ payment_method_type: Option<common_enums::PaymentMethod>,+ payment_method_subtype: Option<common_enums::PaymentMethodType>,+ locker_id: Option<domain::VaultId>,+ locker_fingerprint_id: Option<String>,+ external_vault_source: Option<id_type::MerchantConnectorAccountId>,+) -> RouterResult<domain::PaymentMethod> {+ let current_time = common_utils::date_time::now();++ let encrypted_payment_method_data = payment_method_vaulting_data+ .map(|payment_method_vaulting_data| payment_method_vaulting_data.get_payment_methods_data())+ .async_map(|payment_method_details| async {+ let key_manager_state = &(state).into();++ cards::create_encrypted_data(key_manager_state, key_store, payment_method_details)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encrypt Payment method data")+ })+ .await+ .transpose()?+ .map(|encoded_data| {+ encoded_data.deserialize_inner_value(|value| value.parse_value("PaymentMethodsData"))+ })+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to parse Payment method data")?;++ Ok(domain::PaymentMethod {+ customer_id: customer_id.clone(),+ merchant_id: merchant_id.to_owned(),+ id: payment_method_id,+ locker_id,+ payment_method_type,+ payment_method_subtype,+ payment_method_data: encrypted_payment_method_data,+ connector_mandate_details: None,+ customer_acceptance: None,+ client_secret: None,+ status: enums::PaymentMethodStatus::Inactive,+ network_transaction_id: None,+ created_at: current_time,+ last_modified: current_time,+ last_used_at: current_time,+ payment_method_billing_address,+ updated_by: None,+ version: common_types::consts::API_VERSION,+ locker_fingerprint_id,+ network_token_locker_id: None,+ network_token_payment_method_data: None,+ network_token_requestor_reference_id: None,+ external_vault_source,+ external_vault_token_data: None,+ vault_type: None,+ created_by: None,+ last_modified_by: None,+ })+}+#[cfg(feature = "v2")]#[instrument(skip_all)]#[allow(clippy::too_many_arguments)]@@ -1993,7 +2260,7 @@ pub async fn create_payment_method_for_confirm(.insert_payment_method(key_store,domain::PaymentMethod {- customer_id: customer_id.to_owned(),+ customer_id: Some(customer_id.to_owned()),merchant_id: merchant_id.to_owned(),id: payment_method_id,locker_id: None,@@ -2205,6 +2472,14 @@ pub async fn create_pm_additional_data_update(}).await.transpose()?+ .map(|encoded_data| {+ encoded_data.deserialize_inner_value(|value| {+ value.parse_value::<payment_methods::PaymentMethodsData>("PaymentMethodsData")+ })+ })+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to parse Payment method data")?.map(From::from);let connector_mandate_details_update = connector_token_details@@ -2608,6 +2883,63 @@ pub async fn vault_payment_method(}}+#[cfg(feature = "v2")]+#[instrument(skip_all)]+pub async fn vault_payment_method_in_volatile_storage(+ state: &SessionState,+ pmd: &domain::PaymentMethodVaultingData,+ platform: &domain::Platform,+ _profile: &domain::Profile,+ _existing_vault_id: Option<domain::VaultId>,+ customer_id: &Option<id_type::GlobalCustomerId>,+) -> RouterResult<(+ pm_types::AddVaultResponse,+ Option<id_type::MerchantConnectorAccountId>,+)> {+ let vault_id = domain::VaultId::generate(generate_id(consts::ID_LENGTH, "vault"));+ let merchant_key_store = platform.get_provider().get_key_store();++ let payload = pmd+ .encode_to_string_of_json()+ .change_context(errors::ApiErrorResponse::InternalServerError)?;++ let encrypted_payload = GcmAes256+ .encode_message(+ merchant_key_store.key.get_inner().peek().as_ref(),+ payload.as_bytes(),+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to encode redis temp locker data")?;++ let redis_connection = state+ .store+ .get_redis_conn()+ .map_err(Into::<errors::StorageError>::into)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to get redis connection")?;++ logger::info!("Storing payment method vaulting data in redis");+ redis_connection+ .serialize_and_set_key_with_expiry(+ &vault_id.get_string_repr().into(),+ encrypted_payload,+ consts::DEFAULT_PAYMENT_METHOD_STORE_TTL,+ )+ .await+ .map_err(Into::<errors::StorageError>::into)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to insert payment method vaulting data to redis")?;++ Ok((+ pm_types::AddVaultResponse {+ entity_id: customer_id.clone(),+ vault_id,+ fingerprint_id: None,+ },+ None,+ ))+}+#[cfg(feature = "v2")]fn get_pm_list_context(payment_method_type: enums::PaymentMethod,@@ -2861,8 +3193,12 @@ pub async fn retrieve_payment_method(.await.unwrap_or_default();- transformers::generate_payment_method_response(&payment_method, &single_use_token_in_cache)- .map(services::ApplicationResponse::Json)+ transformers::generate_payment_method_response(+ &payment_method,+ &single_use_token_in_cache,+ Some(common_enums::StorageType::Persistent),+ )+ .map(services::ApplicationResponse::Json)}// TODO: When we separate out microservices, this function will be an endpoint in payment_methods@@ -2971,7 +3307,10 @@ pub async fn update_payment_method_core(// using current vault_id for now,// will have to refactor this to generate new one on each vaulting later oncurrent_vault_id,- &payment_method.customer_id,+ &payment_method+ .customer_id+ .clone()+ .get_required_value("GlobalCustomerId")?,).await.attach_printable("Failed to add payment method in vault")?;@@ -3016,7 +3355,11 @@ pub async fn update_payment_method_core(.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to update payment method in db")?;- let response = pm_transforms::generate_payment_method_response(&payment_method, &None)?;+ let response = pm_transforms::generate_payment_method_response(+ &payment_method,+ &None,+ Some(common_enums::StorageType::Persistent),+ )?;// Add a PT task to handle payment_method delete from vault@@ -3057,6 +3400,10 @@ pub async fn delete_payment_method_core().await.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;+ let customer_id = &payment_method+ .customer_id+ .clone()+ .get_required_value("GlobalCustomerId")?;when(payment_method.status == enums::PaymentMethodStatus::Inactive,@@ -3065,7 +3412,7 @@ pub async fn delete_payment_method_core(let _customer = db.find_customer_by_global_id(- &payment_method.customer_id,+ customer_id,platform.get_provider().get_key_store(),platform.get_provider().get_account().storage_scheme,)@@ -3273,7 +3620,7 @@ pub async fn payment_methods_session_create(let payment_method_session_domain_model =hyperswitch_domain_models::payment_methods::PaymentMethodSession {id: payment_methods_session_id,- customer_id: request.customer_id,+ customer_id: request.customer_id.clone(),billing,psp_tokenization: request.psp_tokenization,network_tokenization: request.network_tokenization,@@ -3299,6 +3646,7 @@ pub async fn payment_methods_session_create(client_secret.secret,None,None,+ None,);Ok(services::ApplicationResponse::Json(response))@@ -3363,6 +3711,7 @@ pub async fn payment_methods_session_update(Secret::new("CLIENT_SECRET_REDACTED".to_string()),None, // TODO: send associated payments response based on the expandable paramNone,+ None,);Ok(services::ApplicationResponse::Json(response))@@ -3388,6 +3737,7 @@ pub async fn payment_methods_session_retrieve(Secret::new("CLIENT_SECRET_REDACTED".to_string()),None, // TODO: send associated payments response based on the expandable paramNone,+ None,);Ok(services::ApplicationResponse::Json(response))@@ -3574,11 +3924,6 @@ pub async fn payment_methods_session_confirm(}).or_else(|| payment_method_session_billing.clone());- let customer_id = payment_method_session- .customer_id- .clone()- .get_required_value("customer_id")?;-let create_payment_method_request = get_payment_method_create_request(request.payment_method_data@@ -3587,9 +3932,10 @@ pub async fn payment_methods_session_confirm(.get_required_value("payment_method_data")?,request.payment_method_type,request.payment_method_subtype,- customer_id.clone(),+ payment_method_session.customer_id.clone(),unified_billing_address.as_ref(),Some(&payment_method_session),+ request.storage_type,).attach_printable("Failed to create payment method request")?;@@ -3685,8 +4031,11 @@ pub async fn payment_methods_session_confirm(None => None,};- let tokenization_response = match payment_method_session.tokenization_data.clone() {- Some(tokenization_data) => {+ let tokenization_response = match (+ payment_method_session.tokenization_data.clone(),+ payment_method_session.customer_id.clone(),+ ) {+ (Some(tokenization_data), Some(customer_id)) => {let tokenization_response = tokenization_core::create_vault_token_core(state.clone(),&platform.get_provider().get_account().clone(),@@ -3703,7 +4052,7 @@ pub async fn payment_methods_session_confirm(};Some(token)}- None => None,+ _ => None,};logger::debug!(?tokenization_response, "Tokenization response");@@ -3714,6 +4063,7 @@ pub async fn payment_methods_session_confirm(Secret::new("CLIENT_SECRET_REDACTED".to_string()),payments_response,(tokenization_response.flatten()),+ payment_method_response.storage_type,);Ok(services::ApplicationResponse::Json(@@ -4047,7 +4397,10 @@ pub async fn check_network_token_status(card_expiry_year: network_token_details.payload.card_expiry_year,token_last_four: network_token_details.payload.token_last_four,payment_method_id,- customer_id: payment_method.customer_id,+ customer_id: payment_method+ .customer_id+ .clone()+ .get_required_value("GlobalCustomerId")?,},)}diff --git a/crates/router/src/core/payment_methods/network_tokenization.rs b/crates/router/src/core/payment_methods/network_tokenization.rsindex 42a4ccf767..8b9b80db1c 100644--- a/crates/router/src/core/payment_methods/network_tokenization.rs+++ b/crates/router/src/core/payment_methods/network_tokenization.rs@@ -26,6 +26,8 @@ use josekit::jwe;use masking::{ErasedMaskSerialize, ExposeInterface, Mask, PeekInterface, Secret};use super::transformers::DeleteCardResp;+#[cfg(feature = "v2")]+use crate::utils::ext_traits::OptionExt;use crate::{core::{errors, payment_methods, payments::helpers},headers, logger,@@ -598,13 +600,17 @@ pub async fn get_token_from_tokenization_service(network_token_requestor_ref_id: String,pm_data: &domain::PaymentMethod,) -> errors::RouterResult<domain::NetworkTokenData> {+ let customer_id = &pm_data+ .customer_id+ .clone()+ .get_required_value("GlobalCustomerId")?;let token_response =if let Some(network_tokenization_service) = &state.conf.network_tokenization_service {record_operation_time(async {get_network_token(state,- &pm_data.customer_id,+ customer_id,network_token_requestor_ref_id,network_tokenization_service.get_inner(),)@@ -891,18 +897,22 @@ pub async fn check_token_status_with_tokenization_service(pub async fn do_status_check_for_network_token(state: &routes::SessionState,payment_method_info: &domain::PaymentMethod,-) -> CustomResult<pm_types::CheckTokenStatusResponse, errors::NetworkTokenizationError> {+) -> CustomResult<pm_types::CheckTokenStatusResponse, errors::ApiErrorResponse> {let network_token_requestor_reference_id = payment_method_info.network_token_requestor_reference_id.clone();+ let customer_id = &payment_method_info+ .customer_id+ .clone()+ .get_required_value("GlobalCustomerId")?;if let Some(ref_id) = network_token_requestor_reference_id {if let Some(network_tokenization_service) = &state.conf.network_tokenization_service {let network_token_details = record_operation_time(async {check_token_status_with_tokenization_service(state,- &payment_method_info.customer_id,+ customer_id,ref_id,network_tokenization_service.get_inner(),)@@ -910,8 +920,9 @@ pub async fn do_status_check_for_network_token(.inspect_err(|e| logger::error!(error=?e, "Error while fetching token from tokenization service"))+ .change_context(errors::ApiErrorResponse::InternalServerError).attach_printable(- "Check network token status with tokenization service failed",+ "Check network token status with tokenization service failed",)},&metrics::CHECK_NETWORK_TOKEN_STATUS_TIME,@@ -921,6 +932,7 @@ pub async fn do_status_check_for_network_token(Ok(network_token_details)} else {Err(errors::NetworkTokenizationError::NetworkTokenizationServiceNotConfigured)+ .change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Network Tokenization Service not configured").inspect_err(|_| {logger::error!("Network Tokenization Service not configured");@@ -928,6 +940,7 @@ pub async fn do_status_check_for_network_token(}} else {Err(errors::NetworkTokenizationError::FetchNetworkTokenFailed)+ .change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Check network token status failed")?}}diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rsindex d51910dd83..182fdc6d76 100644--- a/crates/router/src/core/payment_methods/transformers.rs+++ b/crates/router/src/core/payment_methods/transformers.rs@@ -537,6 +537,7 @@ pub fn generate_pm_vaulting_req_from_update_request(pub fn generate_payment_method_response(payment_method: &domain::PaymentMethod,single_use_token: &Option<payment_method_data::SingleUsePaymentMethodToken>,+ storage_type: Option<common_enums::StorageType>,) -> errors::RouterResult<api::PaymentMethodResponse> {let pmd = payment_method.payment_method_data@@ -598,6 +599,7 @@ pub fn generate_payment_method_response(payment_method_data: pmd,connector_tokens,network_token,+ storage_type,};Ok(resp)@@ -834,7 +836,12 @@ impl transformers::ForeignTryFrom<(domain::PaymentMethod, String)>Ok(Self {id: item.id,- customer_id: item.customer_id,+ customer_id: item+ .customer_id+ .get_required_value("GlobalCustomerId")+ .change_context(errors::ValidationError::MissingRequiredField {+ field_name: "customer_id".to_string(),+ })?,payment_method_type,payment_method_subtype,created: item.created_at,@@ -920,7 +927,12 @@ impl transformers::ForeignTryFrom<domain::PaymentMethod> for PaymentMethodResponOk(Self {id: item.id,- customer_id: item.customer_id,+ customer_id: item+ .customer_id+ .get_required_value("GlobalCustomerId")+ .change_context(errors::ValidationError::MissingRequiredField {+ field_name: "customer_id".to_string(),+ })?,payment_method_type,payment_method_subtype,created: item.created_at,@@ -943,6 +955,7 @@ pub fn generate_payment_method_session_response(client_secret: Secret<String>,associated_payment: Option<api_models::payments::PaymentsResponse>,tokenization_service_response: Option<api_models::tokenization::GenericTokenizationResponse>,+ storage_type: Option<common_enums::StorageType>,) -> api_models::payment_methods::PaymentMethodSessionResponse {let next_action = associated_payment.as_ref()@@ -977,6 +990,7 @@ pub fn generate_payment_method_session_response(associated_payment_methods: payment_method_session.associated_payment_methods,authentication_details,associated_token_id: token_id,+ storage_type,}}diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rsindex f7e381f99e..74a19366cb 100644--- a/crates/router/src/core/payment_methods/vault.rs+++ b/crates/router/src/core/payment_methods/vault.rs@@ -1932,7 +1932,11 @@ pub async fn retrieve_payment_method_from_vault(}).change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Missing locker_id for VaultRetrieveRequest")?;- retrieve_payment_method_from_vault_internal(state, platform, &vault_id, &pm.customer_id)+ let customer_id = pm+ .customer_id+ .clone()+ .get_required_value("GlobalCustomerId")?;+ retrieve_payment_method_from_vault_internal(state, platform, &vault_id, &customer_id).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to retrieve payment method from vault")@@ -2079,6 +2083,10 @@ pub async fn delete_payment_method_data_from_vault(.clone().get_required_value("locker_id").attach_printable("Missing locker_id in PaymentMethod")?;+ let customer_id = &pm+ .customer_id+ .clone()+ .get_required_value("GlobalCustomerId")?;match is_external_vault_enabled {true => {@@ -2102,19 +2110,16 @@ pub async fn delete_payment_method_data_from_vault(platform.get_provider().get_account(),merchant_connector_account,vault_id.clone(),- &pm.customer_id,+ customer_id,).await}- false => delete_payment_method_data_from_vault_internal(- state,- platform,- vault_id,- &pm.customer_id,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to delete payment method from vault"),+ false => {+ delete_payment_method_data_from_vault_internal(state, platform, vault_id, customer_id)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to delete payment method from vault")+ }}}diff --git a/crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs b/crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rsindex 121a0732af..52d46577d1 100644--- a/crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs+++ b/crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs@@ -377,11 +377,12 @@ impl<F: Clone + Send + Sync> Domain<F, ExternalVaultProxyPaymentsRequest, Paymenpayment_method_type: payment_data.payment_attempt.payment_method_type,payment_method_subtype: payment_data.payment_attempt.payment_method_subtype,metadata: None,- customer_id,+ customer_id: Some(customer_id),payment_method_data,billing,psp_tokenization: None,network_tokenization: None,+ storage_type: None, //this field is currently not being used in storing payment methods via external vault};let (_pm_response, payment_method) = Box::pin(payment_methods::create_payment_method_core(diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rsindex 65ede51957..f2393a7bb4 100644--- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs+++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs@@ -609,11 +609,12 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsConfirmIntentRequest, PaymentConfpayment_method_type: payment_data.payment_attempt.payment_method_type,payment_method_subtype: payment_data.payment_attempt.payment_method_subtype,metadata: None,- customer_id,+ customer_id: Some(customer_id),payment_method_data: pm_create_data,billing: None,psp_tokenization: None,network_tokenization: None,+ storage_type: Some(common_enums::StorageType::Persistent), //since customer acceptance is present, we always store it persistently};let (_pm_response, payment_method) =diff --git a/crates/router/src/core/proxy/utils.rs b/crates/router/src/core/proxy/utils.rsindex 0669172cf6..b70d1c0ccb 100644--- a/crates/router/src/core/proxy/utils.rs+++ b/crates/router/src/core/proxy/utils.rs@@ -111,11 +111,16 @@ impl ProxyRecord {}}- fn get_customer_id(&self) -> id_type::GlobalCustomerId {+ fn get_customer_id(&self) -> RouterResult<id_type::GlobalCustomerId> {match self {- Self::PaymentMethodRecord(payment_method) => payment_method.customer_id.clone(),+ Self::PaymentMethodRecord(payment_method) => payment_method+ .customer_id+ .clone()+ .get_required_value("customer_id")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Customer id not present in Payment Method Entry"),Self::TokenizationRecord(tokenization_record) => {- tokenization_record.customer_id.clone()+ Ok(tokenization_record.customer_id.clone())}}}@@ -131,7 +136,7 @@ impl ProxyRecord {state,&platform,&self.get_vault_id()?,- &self.get_customer_id(),+ &self.get_customer_id()?,).await.change_context(errors::ApiErrorResponse::InternalServerError)@@ -145,7 +150,7 @@ impl ProxyRecord {}Self::TokenizationRecord(_) => {let vault_request = pm_types::VaultRetrieveRequest {- entity_id: self.get_customer_id(),+ entity_id: self.get_customer_id()?,vault_id: self.get_vault_id()?,};