Skip to content

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

feat(payment-methods): add support to fetch raw payment method data in v2 payment methods retrieve api (#11015)

Shankar Singh C0531975f9904
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index e04377a8fd..efc77c8adf 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -19648,7 +19648,8 @@
"merchant_id",
"customer_id",
"payment_method_type",
- "network_transaction_id"
+ "network_transaction_id",
+ "raw_payment_method_data"
],
"properties": {
"id": {
@@ -19742,6 +19743,9 @@
"network_transaction_id": {
"type": "string",
"description": "The network transaction ID provided by the card network during a Customer Initiated Transaction (CIT)\nwhen `setup_future_usage` is set to `off_session`."
+ },
+ "raw_payment_method_data": {
+ "$ref": "#/components/schemas/RawPaymentMethodData"
}
}
},
@@ -19857,6 +19861,15 @@
}
}
},
+ "PaymentMethodRetrieveRequest": {
+ "type": "object",
+ "properties": {
+ "fetch_raw_detail": {
+ "type": "boolean"
+ }
+ },
+ "additionalProperties": false
+ },
"PaymentMethodSessionConfirmRequest": {
"type": "object",
"required": [
@@ -24515,6 +24528,21 @@
}
}
},
+ "RawPaymentMethodData": {
+ "oneOf": [
+ {
+ "type": "object",
+ "required": [
+ "card"
+ ],
+ "properties": {
+ "card": {
+ "$ref": "#/components/schemas/CardDetail"
+ }
+ }
+ }
+ ]
+ },
"RealTimePaymentData": {
"oneOf": [
{
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index ebb2fbc6ca..3c579c6232 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -99,6 +99,14 @@ pub struct PaymentMethodCreate {
pub network_transaction_id: Option<String>,
}
+#[cfg(feature = "v2")]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct PaymentMethodRetrieveRequest {
+ #[serde(default)]
+ pub fetch_raw_detail: bool,
+}
+
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
@@ -958,6 +966,14 @@ pub enum PaymentMethodResponseData {
Card(CardDetailFromLocker),
}
+#[cfg(feature = "v2")]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+#[serde(rename_all = "snake_case")]
+pub enum RawPaymentMethodData {
+ Card(CardDetail),
+}
+
#[cfg(feature = "v1")]
#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct PaymentMethodResponse {
@@ -1177,6 +1193,10 @@ pub struct PaymentMethodResponse {
/// when `setup_future_usage` is set to `off_session`.
#[schema(value_type = String)]
pub network_transaction_id: Option<masking::Secret<String>>,
+
+ /// The raw data associated with the payment method
+ #[schema(value_type = RawPaymentMethodData)]
+ pub raw_payment_method_data: Option<RawPaymentMethodData>,
}
#[cfg(feature = "v2")]
@@ -1211,6 +1231,15 @@ pub enum PaymentMethodsData {
WalletDetails(PaymentMethodDataWalletInfo),
}
+impl PaymentMethodsData {
+ pub fn get_card_details(&self) -> Option<CardDetailsPaymentMethod> {
+ match self {
+ Self::Card(card_details) => Some(card_details.clone()),
+ _ => None,
+ }
+ }
+}
+
#[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct ExternalVaultTokenData {
/// Tokenized reference for Card Number
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index a34f0422ef..371cc9c39b 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -343,6 +343,14 @@ pub enum GsmDecision {
DoDefault,
}
+#[derive(
+ Clone, Copy, Debug, strum::Display, PartialEq, Eq, serde::Serialize, serde::Deserialize,
+)]
+pub enum ApiKeyType {
+ Internal,
+ External,
+}
+
#[derive(
Clone,
Copy,
diff --git a/crates/common_utils/src/id_type/merchant.rs b/crates/common_utils/src/id_type/merchant.rs
index f91e5b0a89..941c79779f 100644
--- a/crates/common_utils/src/id_type/merchant.rs
+++ b/crates/common_utils/src/id_type/merchant.rs
@@ -257,4 +257,12 @@ impl MerchantId {
pub fn get_threeds_routing_region_uas_key(&self) -> String {
format!("threeds_routing_region_uas_{}", self.get_string_repr())
}
+
+ /// fetch should_return_raw_payment_method_details key for organization
+ pub fn should_return_raw_payment_method_details_key(&self) -> String {
+ format!(
+ "should_return_raw_payment_method_details_{}",
+ self.get_string_repr()
+ )
+ }
}
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index a1e744ef3e..acf295b266 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -2903,6 +2903,55 @@ pub struct CardDetailsPaymentMethod {
pub saved_to_locker: bool,
}
+#[cfg(feature = "v2")]
+pub struct CardNumberWithStoredDetails {
+ pub card_number: cards::CardNumber,
+ pub card_details: CardDetailsPaymentMethod,
+}
+
+#[cfg(feature = "v2")]
+impl CardNumberWithStoredDetails {
+ pub fn new(card_number: cards::CardNumber, card_details: CardDetailsPaymentMethod) -> Self {
+ Self {
+ card_number,
+ card_details,
+ }
+ }
+}
+
+#[cfg(feature = "v2")]
+impl TryFrom<CardNumberWithStoredDetails> for payment_methods::CardDetail {
+ type Error = error_stack::Report<common_utils::errors::ValidationError>;
+
+ fn try_from(testing: CardNumberWithStoredDetails) -> Result<Self, Self::Error> {
+ let card_number = testing.card_number;
+ let item = testing.card_details;
+ Ok(Self {
+ card_number,
+ card_exp_month: item
+ .expiry_month
+ .get_required_value("expiry_month")?
+ .clone(),
+ card_exp_year: item.expiry_year.get_required_value("expiry_year")?.clone(),
+ card_holder_name: item.card_holder_name,
+ nick_name: item.nick_name,
+ card_issuing_country: item
+ .issuer_country
+ .as_ref()
+ .map(|country| api_enums::CountryAlpha2::from_str(country))
+ .transpose()
+ .ok()
+ .flatten(),
+ card_network: item.card_network,
+ card_issuer: item.card_issuer,
+ card_type: item
+ .card_type
+ .and_then(|card_type| payment_methods::CardType::from_str(&card_type).ok()),
+ card_cvc: None,
+ })
+ }
+}
+
#[cfg(feature = "v2")]
impl CardDetailsPaymentMethod {
pub fn to_card_details_from_locker(self) -> payment_methods::CardDetailFromLocker {
@@ -2988,6 +3037,25 @@ impl
}
}
+#[cfg(feature = "v2")]
+impl From<payment_methods::CardDetailsPaymentMethod> for CardDetailsPaymentMethod {
+ fn from(item: payment_methods::CardDetailsPaymentMethod) -> Self {
+ Self {
+ issuer_country: item.issuer_country,
+ last4_digits: item.last4_digits,
+ expiry_month: item.expiry_month,
+ expiry_year: item.expiry_year,
+ nick_name: item.nick_name,
+ card_holder_name: item.card_holder_name,
+ card_isin: item.card_isin,
+ card_issuer: item.card_issuer,
+ card_network: item.card_network,
+ card_type: item.card_type,
+ saved_to_locker: item.saved_to_locker,
+ }
+ }
+}
+
#[cfg(feature = "v2")]
impl From<payment_methods::CardDetail> for CardDetailsPaymentMethod {
fn from(item: payment_methods::CardDetail) -> Self {
diff --git a/crates/hyperswitch_domain_models/src/vault.rs b/crates/hyperswitch_domain_models/src/vault.rs
index 38783ca64e..19ed9fb746 100644
--- a/crates/hyperswitch_domain_models/src/vault.rs
+++ b/crates/hyperswitch_domain_models/src/vault.rs
@@ -1,4 +1,8 @@
use api_models::payment_methods;
+#[cfg(feature = "v2")]
+use common_utils::{crypto::Encryptable, errors::CustomResult, ext_traits::OptionExt};
+#[cfg(feature = "v2")]
+use error_stack::ResultExt;
use serde::{Deserialize, Serialize};
#[cfg(feature = "v2")]
@@ -20,6 +24,83 @@ impl PaymentMethodVaultingData {
Self::CardNumber(_) => None,
}
}
+
+ pub fn set_card_cvc(&mut self, card_cvc: masking::Secret<String>) {
+ match self {
+ Self::Card(card_details) => {
+ card_details.card_cvc = Some(card_cvc);
+ }
+ Self::NetworkToken(_) => {}
+ Self::CardNumber(_) => {}
+ }
+ }
+
+ #[cfg(feature = "v2")]
+ pub fn convert_to_raw_payment_method_data(
+ &self,
+ ) -> Option<payment_methods::RawPaymentMethodData> {
+ match self {
+ Self::Card(card) => Some(payment_methods::RawPaymentMethodData::Card(card.clone())),
+ // Raw payment methods data is not available for network tokens
+ Self::NetworkToken(network_token) => None,
+ // When it is card number populated_payment_methods_data_and_get_payment_method_vaulting_data
+ // will be called which will populated the payment methods data for card number and convert it to type CardDetail
+ Self::CardNumber(card_number) => None,
+ }
+ }
+
+ #[cfg(feature = "v2")]
+ pub fn populated_payment_methods_data_and_get_payment_method_vaulting_data(
+ &self,
+ payment_methods_data_optional: Option<&Encryptable<payment_methods::PaymentMethodsData>>,
+ ) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> {
+ match self {
+ Self::Card(card_details) => Ok(self.clone()),
+ Self::NetworkToken(_) => Ok(self.clone()),
+ Self::CardNumber(card_number) => {
+ let payment_methods_data = payment_methods_data_optional
+ .get_required_value("payment methods data")
+ .change_context(
+ errors::api_error_response::ApiErrorResponse::InternalServerError,
+ )
+ .attach_printable("failed to get payment methods data for payment method vaulting data type card number")?;
+
+ let card_detail = Self::populated_payment_methods_data_for_payment_method_vaulting_data_card_number(
+ card_number,
+ payment_methods_data,
+ )?;
+
+ Ok(Self::Card(card_detail))
+ }
+ }
+ }
+
+ #[cfg(feature = "v2")]
+ pub fn populated_payment_methods_data_for_payment_method_vaulting_data_card_number(
+ card_number: &cards::CardNumber,
+ payment_methods_data: &Encryptable<payment_methods::PaymentMethodsData>,
+ ) -> CustomResult<payment_methods::CardDetail, errors::api_error_response::ApiErrorResponse>
+ {
+ let stored_card_metadata = payment_methods_data
+ .clone()
+ .into_inner()
+ .get_card_details()
+ .get_required_value("card payment methods data")
+ .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to get stored card payment methods details")?;
+
+ let card_with_details = payment_method_data::CardNumberWithStoredDetails::new(
+ card_number.clone(),
+ stored_card_metadata.into(),
+ );
+
+ payment_methods::CardDetail::try_from(card_with_details)
+ .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to create card details for payment method vaulting data type card number ",
+ )
+ }
+
pub fn get_payment_methods_data(&self) -> payment_method_data::PaymentMethodsData {
match self {
Self::Card(card) => payment_method_data::PaymentMethodsData::Card(
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 56f4e19775..ac39e72a81 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -261,6 +261,8 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payment_methods::PaymentMethodIntentConfirm,
api_models::payment_methods::AuthenticationDetails,
api_models::payment_methods::PaymentMethodResponse,
+ api_models::payment_methods::RawPaymentMethodData,
+ api_models::payment_methods::PaymentMethodRetrieveRequest,
api_models::payment_methods::PaymentMethodResponseData,
api_models::payment_methods::CustomerPaymentMethodResponseItem,
api_models::payment_methods::PaymentMethodResponseItem,
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index b5d5937828..07afd316ec 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -30,7 +30,7 @@ use common_utils::{
crypto::{EncodeMessage, Encryptable, GcmAes256},
encryption::Encryption,
errors::CustomResult,
- ext_traits::{AsyncExt, ValueExt},
+ ext_traits::{AsyncExt, BytesExt, ValueExt},
fp_utils::when,
generate_id, types as util_types,
};
@@ -1363,6 +1363,7 @@ pub async fn create_payment_method_card_core(
req.storage_type,
cvc_expiry_details,
req.customer_id,
+ None,
)?;
Ok((resp, payment_method))
@@ -1514,6 +1515,7 @@ pub async fn create_volatile_payment_method_card_core(
req.storage_type,
cvc_expiry_details,
req.customer_id,
+ None,
)?;
Ok((resp, domain_payment_method))
@@ -1624,6 +1626,7 @@ pub async fn create_payment_method_proxy_card_core(
req.storage_type,
None,
req.customer_id,
+ None,
)?;
Ok((payment_method_response, payment_method))
@@ -2015,6 +2018,7 @@ pub async fn payment_method_intent_create(
None,
None,
Some(customer_id),
+ None,
)?;
Ok(services::ApplicationResponse::Json(resp))
@@ -3218,6 +3222,7 @@ fn get_pm_list_context(
payment_method_type: enums::PaymentMethod,
payment_method: &domain::PaymentMethod,
is_payment_associated: bool,
+ storage_type: enums::StorageType,
) -> Result<Option<PaymentMethodListContext>, error_stack::Report<errors::ApiErrorResponse>> {
let payment_method_data = payment_method
.payment_method_data
@@ -3243,6 +3248,7 @@ fn get_pm_list_context(
.unwrap_or_else(|| {
payment_method.get_id().get_string_repr().to_owned()
}),
+ storage_type,
),
),
})
@@ -3300,9 +3306,11 @@ fn get_pm_list_context(
fn get_pm_list_token_data(
payment_method_type: enums::PaymentMethod,
payment_method: &domain::PaymentMethod,
+ storage_type: enums::StorageType,
) -> Result<Option<storage::PaymentTokenData>, error_stack::Report<errors::ApiErrorResponse>> {
- let pm_list_context = get_pm_list_context(payment_method_type, payment_method, true)?
- .get_required_value("PaymentMethodListContext")?;
+ let pm_list_context =
+ get_pm_list_context(payment_method_type, payment_method, true, storage_type)?
+ .get_required_value("PaymentMethodListContext")?;
match pm_list_context {
PaymentMethodListContext::Card {
@@ -3386,7 +3394,12 @@ pub async fn list_customer_payment_methods_core(
let intent_fulfillment_time = common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME;
- let token_data = get_pm_list_token_data(payment_method_type, &pm)?;
+ let token_data = get_pm_list_token_data(
+ payment_method_type,
+ &pm,
+ // storage type is hardcoded to Persistent as we are fetching saved payment methods from the database
+ enums::StorageType::Persistent,
+ )?;
if let Some(token_data) = token_data {
pm_routes::ParentPaymentMethodToken::create_key_for_token(
@@ -3442,48 +3455,324 @@ pub async fn get_total_payment_method_count_core(
pub async fn retrieve_payment_method(
state: SessionState,
pm: api::PaymentMethodId,
- provider: domain::Provider,
+ profile: domain::Profile,
+ platform: domain::Platform,
+ api_key_type: enums::ApiKeyType,
+ fetch_raw_detail_query_param: bool,
) -> RouterResponse<api::PaymentMethodResponse> {
let db = state.store.as_ref();
- let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(pm.payment_method_id)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to generate GlobalPaymentMethodId")?;
- let payment_method = db
- .find_payment_method(
- provider.get_key_store(),
- &pm_id,
- provider.get_account().storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+ // 1. Resolve parent token (if any) -> storage type & optional token data
+ let (storage_type, card_token_data_opt) =
+ resolve_storage_type_from_token(&state, &pm.payment_method_id).await?;
+
+ // 2. Fetch payment method record based on resolved storage type
+ let (storage_type, payment_method) =
+ fetch_payment_method_by_storage(&state, &platform, &pm, storage_type, card_token_data_opt)
+ .await
+ .change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
+ .attach_printable("Failed to fetch payment method by storage")?;
+
+ let raw_payment_method_fetch_access = get_raw_payment_method_data_fetch_access(
+ db,
+ platform.get_provider().get_account().get_id(),
+ api_key_type,
+ fetch_raw_detail_query_param,
+ )
+ .await
+ .attach_printable("Failed to get raw payment method fetch access")?;
let single_use_token_in_cache = get_single_use_token_from_store(
&state.clone(),
- domain::SingleUseTokenKey::store_key(&pm_id.clone()),
+ domain::SingleUseTokenKey::store_key(&payment_method.id.clone()),
)
.await
.unwrap_or_default();
- let card_cvc_expiry =
- vault::retrieve_key_and_ttl_for_cvc_from_payment_method_id(&state, pm_id.to_owned())
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to retrieve cvc from redis")
- .ok();
+ let card_cvc_expiry = vault::retrieve_key_and_ttl_for_cvc_from_payment_method_id(
+ &state,
+ payment_method.id.to_owned(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to retrieve cvc from redis")
+ .ok();
+
+ let raw_payment_method_data = raw_payment_method_fetch_access
+ .get_raw_payment_method_data(&state, &platform, &profile, &payment_method, storage_type)
+ .await
+ .attach_printable("Failed to get raw payment method data")?
+ .and_then(|data| data.convert_to_raw_payment_method_data());
transformers::generate_payment_method_response(
&payment_method,
&single_use_token_in_cache,
- Some(common_enums::StorageType::Persistent),
+ Some(storage_type),
card_cvc_expiry.map(|time| {
payment_methods::CardCVCTokenStorageDetails::generate_expiry_timestamp(time)
}),
payment_method.customer_id.clone(),
+ raw_payment_method_data,
)
.map(services::ApplicationResponse::Json)
}
+#[cfg(feature = "v2")]
+#[instrument(skip_all)]
+async fn fetch_payment_method_by_storage(
+ state: &SessionState,
+ platform: &domain::Platform,
+ pm_incoming: &api::PaymentMethodId,
+ storage_type: common_enums::StorageType,
+ card_token_data_opt: Option<storage::CardTokenData>,
+) -> RouterResult<(common_enums::StorageType, domain::PaymentMethod)> {
+ let db = state.store.as_ref();
+ match storage_type {
+ common_enums::StorageType::Volatile => {
+ logger::debug!("Fetching volatile payment method");
+ // When it is Volatile storage payment token data will be always present in redis
+ let token_data = card_token_data_opt
+ .as_ref()
+ .ok_or(report!(errors::ApiErrorResponse::PaymentMethodNotFound))
+ .attach_printable("Failed to get card token data for volatile storage")?;
+
+ let volatile_payment_method = fetch_volatile_payment_method_record(
+ state,
+ platform.get_provider().get_key_store(),
+ token_data.payment_method_id.get_string_repr(),
+ )
+ .await
+ .attach_printable("Failed to get volatile payment method record")?;
+ Ok((storage_type, volatile_payment_method))
+ }
+ common_enums::StorageType::Persistent => {
+ logger::debug!("Fetching persistent payment method with fallback");
+ // In S2S calls, id passed in the request could be payment method id as well
+ // If a temporary token is passed after the redis expiration it will also be treated as
+ // a persistent GlobalPaymentMethodId, but for temp tokens GlobalPaymentMethodId will fail
+ let pm_id = match card_token_data_opt {
+ Some(data) => data.payment_method_id.clone(),
+ None => id_type::GlobalPaymentMethodId::generate_from_string(
+ pm_incoming.payment_method_id.clone(),
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to generate GlobalPaymentMethodId")?,
+ };
+
+ fetch_payment_method_with_fallback(state, platform, &pm_id, storage_type)
+ .await
+ .attach_printable("Failed to get payment method with fallback")
+ }
+ }
+}
+
+#[cfg(feature = "v2")]
+pub async fn fetch_payment_method_with_fallback(
+ state: &SessionState,
+ platform: &domain::Platform,
+ pm_id: &id_type::GlobalPaymentMethodId,
+ storage_type: common_enums::StorageType,
+) -> RouterResult<(common_enums::StorageType, domain::PaymentMethod)> {
+ let volatile_payment_method = fetch_volatile_payment_method_record(
+ state,
+ platform.get_provider().get_key_store(),
+ pm_id.get_string_repr(),
+ )
+ .await
+ .attach_printable("Failed to get volatile payment method record");
+
+ match volatile_payment_method {
+ Ok(payment_method) => Ok((common_enums::StorageType::Volatile, payment_method)),
+ Err(err) => {
+ logger::warn!("Volatile payment method not found, falling back to persistent storage",);
+
+ when(
+ !matches!(
+ err.current_context(),
+ errors::ApiErrorResponse::GenericNotFoundError { .. }
+ ),
+ || Err(err),
+ )?;
+
+ logger::debug!("Redis lookup failed, falling back to DB");
+
+ let persistent_payment_method =
+ fetch_payment_method(state, platform.get_provider(), pm_id)
+ .await
+ .attach_printable("Failed to get payment method record from DB")?;
+
+ Ok((storage_type, persistent_payment_method))
+ }
+ }
+}
+
+#[cfg(feature = "v2")]
+async fn fetch_volatile_payment_method_record(
+ state: &SessionState,
+ key_store: &domain::MerchantKeyStore,
+ pm_id: &str,
+) -> RouterResult<domain::PaymentMethod> {
+ let redis_conn = state
+ .store
+ .get_redis_conn()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get redis connection")?;
+
+ let payment_method = redis_conn
+ .get_and_deserialize_key::<diesel_models::PaymentMethod>(&pm_id.into(), "PaymentMethod")
+ .await
+ .map_err(|e| error_stack::report!(storage_impl::StorageError::from(e)))
+ .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "Payment method token either expired or does not exist".to_string(),
+ })?;
+
+ let keymanager_state = &state.into();
+
+ let domain_payment_method = domain::PaymentMethod::convert_back(
+ keymanager_state,
+ payment_method,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::EncryptionError)
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+
+ Ok(domain_payment_method)
+}
+
+#[cfg(feature = "v2")]
+async fn resolve_storage_type_from_token(
+ state: &SessionState,
+ token: &String,
+) -> RouterResult<(common_enums::StorageType, Option<storage::CardTokenData>)> {
+ // Try redis lookup for parent token
+ let token_data_res = pm_routes::ParentPaymentMethodToken::create_key_for_token(token)
+ .get_data_for_token(state)
+ .await;
+
+ match token_data_res {
+ Ok(token_data) => {
+ // only Permanent/PermanentCard token variants carry storage type info relevant for saved PMs
+ match token_data {
+ storage::PaymentTokenData::PermanentCard(card) => {
+ let storage_type = card.storage_type;
+ Ok((storage_type, Some(card)))
+ }
+ // Any token kind other than PermanentCard is invalid for retrieving a saved payment method.
+ // Only PermanentCard is currently supported; all other enum variants should be removed.
+ storage::PaymentTokenData::TemporaryGeneric(_)
+ | storage::PaymentTokenData::AuthBankDebit(_) => {
+ Err(report!(errors::ApiErrorResponse::PaymentMethodNotFound))
+ }
+ }
+ }
+ Err(err) => {
+ // If token not found in redis treat incoming id as a persistent PM id as it could have been obtained from a S2S payment method retrieve call
+ // Or it would be an MIT case
+ if matches!(
+ err.current_context(),
+ errors::ApiErrorResponse::GenericNotFoundError { .. }
+ ) {
+ Ok((common_enums::StorageType::Persistent, None))
+ } else {
+ Err(err)
+ }
+ }
+ }
+}
+
+#[derive(
+ Clone, Copy, Debug, strum::Display, PartialEq, Eq, serde::Serialize, serde::Deserialize,
+)]
+pub enum RawPaymentMethodFetchAccess {
+ Allowed,
+ Denied,
+}
+
+#[cfg(feature = "v2")]
+impl RawPaymentMethodFetchAccess {
+ pub async fn get_raw_payment_method_data(
+ &self,
+ state: &SessionState,
+ platform: &domain::Platform,
+ profile: &domain::Profile,
+ payment_method: &domain::PaymentMethod,
+ storage_type: common_enums::StorageType,
+ ) -> RouterResult<Option<hyperswitch_domain_models::vault::PaymentMethodVaultingData>> {
+ match self {
+ Self::Denied => {
+ logger::debug!("Raw payment method fetch access denied");
+ Ok(None)
+ }
+
+ Self::Allowed => {
+ let vault_data = vault::retrieve_payment_method_data_from_storage(
+ state,
+ platform,
+ profile,
+ payment_method,
+ storage_type,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to retrieve payment method from vault")?
+ .data;
+
+ let payment_method_vault_data = vault_data
+ .populated_payment_methods_data_and_get_payment_method_vaulting_data(
+ payment_method.payment_method_data.as_ref(),
+ )
+ .attach_printable(
+ "Failed to get card details for payment method vaulting data",
+ )?;
+ Ok(Some(payment_method_vault_data))
+ }
+ }
+ }
+}
+
+pub async fn get_raw_payment_method_data_fetch_access(
+ db: &dyn StorageInterface,
+ merchant_id: &id_type::MerchantId,
+ api_key_type: enums::ApiKeyType,
+ fetch_raw_detail_query_param: bool,
+) -> RouterResult<RawPaymentMethodFetchAccess> {
+ // If query param not set, never allowed to fetch raw payment method details
+ let fetch_access = match fetch_raw_detail_query_param {
+ true => RawPaymentMethodFetchAccess::Allowed,
+ false => RawPaymentMethodFetchAccess::Denied,
+ };
+
+ match api_key_type {
+ // Internal API keys always allowed
+ enums::ApiKeyType::Internal => Ok(fetch_access),
+
+ // External API keys allowed only via org-level config
+ // This supports cases where a PCI-compliant entity needs to retrieve raw payment method details.
+ enums::ApiKeyType::External => {
+ let config = db
+ .find_config_by_key_unwrap_or(
+ &merchant_id.should_return_raw_payment_method_details_key(),
+ Some("false".to_string()),
+ )
+ .await;
+
+ match config {
+ Ok(conf) if conf.config.eq_ignore_ascii_case("true") => Ok(fetch_access),
+ Ok(_) => Ok(RawPaymentMethodFetchAccess::Denied),
+ Err(error) => {
+ router_env::logger::error!(
+ ?error,
+ "Failed to fetch raw payment method details config"
+ );
+ Ok(RawPaymentMethodFetchAccess::Denied)
+ }
+ }
+ }
+ }
+}
+
// TODO: When we separate out microservices, this function will be an endpoint in payment_methods
#[cfg(feature = "v2")]
#[instrument(skip_all)]
@@ -3674,6 +3963,7 @@ pub async fn update_payment_method_core(
Some(common_enums::StorageType::Persistent),
card_cvc_token_details,
updated_payment_method.customer_id.clone(),
+ None,
)?;
// Add a PT task to handle payment_method delete from vault
@@ -4360,7 +4650,13 @@ pub async fn payment_methods_session_confirm(
let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token");
- let token_data = get_pm_list_token_data(request.payment_method_type, &payment_method)?;
+ let token_data = get_pm_list_token_data(
+ request.payment_method_type,
+ &payment_method,
+ create_payment_method_request
+ .storage_type
+ .unwrap_or(enums::StorageType::Persistent),
+ )?;
// insert the token data into redis
if let Some(token_data) = token_data {
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 5dc3a69b74..c7ee5af23b 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -566,6 +566,7 @@ pub fn generate_payment_method_response(
storage_type: Option<common_enums::StorageType>,
card_cvc_token_storage: Option<api_models::payment_methods::CardCVCTokenStorageDetails>,
customer_id: Option<id_type::GlobalCustomerId>,
+ raw_payment_method_data: Option<api_models::payment_methods::RawPaymentMethodData>,
) -> errors::RouterResult<api::PaymentMethodResponse> {
let pmd = payment_method
.payment_method_data
@@ -633,6 +634,7 @@ pub fn generate_payment_method_response(
.network_transaction_id
.clone()
.map(Secret::new),
+ raw_payment_method_data,
};
Ok(resp)
diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs
index eec8b4126d..f9a05d235a 100644
--- a/crates/router/src/core/payment_methods/vault.rs
+++ b/crates/router/src/core/payment_methods/vault.rs
@@ -1825,17 +1825,16 @@ pub async fn insert_cvc_using_payment_token(
let payload_to_be_encrypted = TemporaryVaultCvc { card_cvc };
- let payload = payload_to_be_encrypted
- .encode_to_string_of_json()
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
-
// Encrypt the CVC and store it in Redis
- let encrypted_payload: Encryption =
- pm_cards::create_encrypted_data(&(state.into()), key_store, payload.clone())
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to encrypt TemporaryVaultCvc for vault")?
- .into();
+ let encrypted_payload: Encryption = pm_cards::create_encrypted_data(
+ &(state.into()),
+ key_store,
+ payload_to_be_encrypted.clone(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to encrypt TemporaryVaultCvc for vault")?
+ .into();
redis_conn
.serialize_and_set_key_with_expiry(
@@ -1951,6 +1950,96 @@ pub async fn delete_payment_token(
Ok(())
}
+#[cfg(feature = "v2")]
+pub async fn retrieve_payment_method_data_from_storage(
+ state: &routes::SessionState,
+ platform: &domain::Platform,
+ profile: &domain::Profile,
+ pm: &domain::PaymentMethod,
+ storage_type: enums::StorageType,
+) -> RouterResult<pm_types::VaultRetrieveResponse> {
+ let mut payment_method_data = match storage_type {
+ enums::StorageType::Persistent => {
+ retrieve_payment_method_from_vault(state, platform, profile, pm).await?
+ }
+ enums::StorageType::Volatile => {
+ retrieve_volatile_payment_method_from_redis(
+ state,
+ platform.get_provider().get_key_store(),
+ pm,
+ )
+ .await?
+ }
+ };
+
+ let card_cvc = retrieve_and_delete_cvc_from_payment_token(
+ state,
+ &pm.id.get_string_repr().to_string(),
+ platform.get_processor().get_key_store(),
+ )
+ .await
+ .inspect_err(|err| {
+ logger::warn!(
+ "Failed to retrieve CVC for payment method {}",
+ pm.id.get_string_repr()
+ );
+ });
+
+ if let Ok(card_cvc) = card_cvc {
+ payment_method_data.data.set_card_cvc(card_cvc);
+ }
+
+ Ok(payment_method_data)
+}
+
+#[cfg(feature = "v2")]
+pub async fn retrieve_volatile_payment_method_from_redis(
+ state: &routes::SessionState,
+ key_store: &domain::MerchantKeyStore,
+ pm: &domain::PaymentMethod,
+) -> RouterResult<pm_types::VaultRetrieveResponse> {
+ let vault_id = pm
+ .locker_id
+ .clone()
+ .ok_or(errors::VaultError::MissingRequiredField {
+ field_name: "locker_id",
+ })
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Missing locker_id for VaultRetrieveRequest")?;
+
+ let redis_conn = state
+ .store
+ .get_redis_conn()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get redis connection")?;
+
+ let response = redis_conn
+ .get_and_deserialize_key::<Encryption>(&vault_id.get_string_repr().into(), "Vec<u8>")
+ .await;
+
+ match response {
+ Ok(resp) => {
+ let decrypted_payload: domain::PaymentMethodVaultingData =
+ pm_cards::decrypt_generic_data(state, Some(resp), key_store)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to decrypt volatile payment method vault data")?
+ .get_required_value("PaymentMethodVaultingData")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to get required decrypted volatile payment method vault data",
+ )?;
+
+ Ok(pm_types::VaultRetrieveResponse {
+ data: decrypted_payload,
+ })
+ }
+ Err(err) => Err(err).change_context(errors::ApiErrorResponse::UnprocessableEntity {
+ message: "Token is invalid or expired".into(),
+ }),
+ }
+}
+
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn retrieve_payment_method_from_vault(
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index aec9ec880c..8f9f5f4f5b 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -230,6 +230,7 @@ pub async fn payment_method_update_api(
pub async fn payment_method_retrieve_api(
state: web::Data<AppState>,
req: HttpRequest,
+ query_payload: web::Query<api_models::payment_methods::PaymentMethodRetrieveRequest>,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsRetrieve;
@@ -238,6 +239,20 @@ pub async fn payment_method_retrieve_api(
})
.into_inner();
+ let api_auth = auth::V2ApiKeyAuth {
+ allow_connected_scope_operation: false,
+ allow_platform_self_operation: false,
+ };
+
+ 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,
@@ -247,13 +262,13 @@ pub async fn payment_method_retrieve_api(
payment_methods_routes::retrieve_payment_method(
state,
pm,
- auth.platform.get_provider().clone(),
+ auth.profile,
+ auth.platform,
+ api_key_type,
+ query_payload.fetch_raw_detail,
)
},
- &auth::V2ApiKeyAuth {
- allow_connected_scope_operation: false,
- allow_platform_self_operation: false,
- },
+ &*auth_type,
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 4aeb9c8125..b335ae15eb 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -76,6 +76,29 @@ pub struct AuthenticationData {
pub profile: domain::Profile,
}
+#[cfg(feature = "v1")]
+impl AuthenticationData {
+ pub fn construct_authentication_data_for_internal_merchant_id_profile_id_auth(
+ platform: domain::Platform,
+ profile: domain::Profile,
+ ) -> Self {
+ Self {
+ platform,
+ profile: Some(profile),
+ }
+ }
+}
+
+#[cfg(feature = "v2")]
+impl AuthenticationData {
+ pub fn construct_authentication_data_for_internal_merchant_id_profile_id_auth(
+ platform: domain::Platform,
+ profile: domain::Profile,
+ ) -> Self {
+ Self { platform, profile }
+ }
+}
+
#[derive(Clone, Debug)]
pub struct PlatformAccountWithKeyStore {
account: domain::MerchantAccount,
@@ -438,6 +461,13 @@ impl GetAuthType for ApiKeyAuth {
}
}
+#[cfg(all(feature = "partial-auth", feature = "v2"))]
+impl GetAuthType for V2ApiKeyAuth {
+ fn get_auth_type(&self) -> detached::PayloadType {
+ detached::PayloadType::ApiKey
+ }
+}
+
#[cfg(feature = "partial-auth")]
pub trait GetMerchantAccessFlags {
fn is_connected_scope_operation_allowed(&self) -> bool;
@@ -454,6 +484,16 @@ impl GetMerchantAccessFlags for ApiKeyAuth {
}
}
+#[cfg(all(feature = "partial-auth", feature = "v2"))]
+impl GetMerchantAccessFlags for V2ApiKeyAuth {
+ fn is_connected_scope_operation_allowed(&self) -> bool {
+ self.allow_connected_scope_operation
+ }
+ fn is_platform_self_operation_allowed(&self) -> bool {
+ self.allow_platform_self_operation
+ }
+}
+
//
// # Header Auth
//
@@ -2465,10 +2505,28 @@ where
/// InternalMerchantIdProfileIdAuth authentication which first tries to authenticate using `X-Internal-API-Key`,
/// `X-Merchant-Id` and `X-Profile-Id` headers. If any of these headers are missing,
/// it falls back to the provided authentication mechanism.
-#[cfg(feature = "v1")]
pub struct InternalMerchantIdProfileIdAuth<F>(pub F);
-#[cfg(feature = "v1")]
+pub fn is_internal_merchant_id_profile_id_auth(
+ request_headers: &HeaderMap,
+) -> common_enums::ApiKeyType {
+ let merchant_id = HeaderMapStruct::new(request_headers)
+ .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)
+ .ok();
+ let internal_api_key = HeaderMapStruct::new(request_headers)
+ .get_header_value_by_key(headers::X_INTERNAL_API_KEY)
+ .map(|internal_api_key| internal_api_key.to_string());
+ let profile_id = HeaderMapStruct::new(request_headers)
+ .get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)
+ .ok();
+
+ if merchant_id.is_some() && profile_id.is_some() && internal_api_key.is_some() {
+ common_enums::ApiKeyType::Internal
+ } else {
+ common_enums::ApiKeyType::External
+ }
+}
+
#[async_trait]
impl<A, F> AuthenticateAndFetch<AuthenticationData, A> for InternalMerchantIdProfileIdAuth<F>
where
@@ -2543,10 +2601,8 @@ where
initiator,
);
- let auth = AuthenticationData {
- platform,
- profile: Some(profile),
- };
+ let auth = AuthenticationData::construct_authentication_data_for_internal_merchant_id_profile_id_auth(platform, profile);
+
Ok((
auth.clone(),
AuthenticationType::InternalMerchantIdProfileId {
@@ -4989,6 +5045,33 @@ where
}
}
+#[cfg(feature = "v2")]
+pub fn check_internal_api_key_auth_no_client_secret<T>(
+ headers: &HeaderMap,
+ api_auth: V2ApiKeyAuth,
+ internal_api_key_auth: settings::InternalMerchantIdProfileIdAuthSettings,
+) -> RouterResult<(
+ Box<dyn AuthenticateAndFetch<AuthenticationData, T>>,
+ common_enums::ApiKeyType,
+)>
+where
+ T: SessionStateInfo + Sync + Send,
+ ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
+{
+ if is_internal_api_key_merchant_id_profile_id_auth(headers, internal_api_key_auth) {
+ Ok((
+ // HeaderAuth(api_auth) will never be called in this case as the internal auth will be checked first
+ Box::new(InternalMerchantIdProfileIdAuth(HeaderAuth(api_auth))),
+ common_enums::ApiKeyType::Internal,
+ ))
+ } else {
+ Ok((
+ Box::new(HeaderAuth(api_auth)),
+ common_enums::ApiKeyType::External,
+ ))
+ }
+}
+
pub async fn decode_jwt<T>(token: &str, state: &impl SessionStateInfo) -> RouterResult<T>
where
T: serde::de::DeserializeOwned,
diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs
index 0ea3ca1e2a..d6adba9456 100644
--- a/crates/router/src/types/storage/payment_method.rs
+++ b/crates/router/src/types/storage/payment_method.rs
@@ -35,6 +35,7 @@ pub struct CardTokenData {
pub payment_method_id: common_utils::id_type::GlobalPaymentMethodId,
pub locker_id: Option<String>,
pub token: String,
+ pub storage_type: enums::StorageType,
}
#[derive(Debug, Clone, serde::Serialize, Default, serde::Deserialize)]
@@ -99,11 +100,13 @@ impl PaymentTokenData {
payment_method_id: common_utils::id_type::GlobalPaymentMethodId,
locker_id: Option<String>,
token: String,
+ storage_type: enums::StorageType,
) -> Self {
Self::PermanentCard(CardTokenData {
payment_method_id,
locker_id,
token,
+ storage_type,
})
}