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(core): propagate metadata from locker response to payment method response (#10645)

Sakil Mostaka9aecaa5bd76
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 0e588d5637..61002d030f 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -1324,6 +1324,26 @@ pub enum BankAccountAccessCreds {
AccessToken(masking::Secret<String>),
}
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
+pub struct LockerCardResponse {
+ card: Card,
+ metadata: Option<pii::SecretSerdeValue>,
+}
+
+impl LockerCardResponse {
+ pub fn new(card: Card, metadata: Option<pii::SecretSerdeValue>) -> Self {
+ Self { card, metadata }
+ }
+
+ pub fn get_card(&self) -> Card {
+ self.card.clone()
+ }
+
+ pub fn get_metadata(&self) -> Option<pii::SecretSerdeValue> {
+ self.metadata.clone()
+ }
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct Card {
pub card_number: CardNumber,
diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs
index 32ff6c9ace..1c69429dfa 100644
--- a/crates/common_utils/src/lib.rs
+++ b/crates/common_utils/src/lib.rs
@@ -1,7 +1,7 @@
#![warn(missing_docs, missing_debug_implementations)]
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))]
-use masking::{PeekInterface, Secret};
+use masking::{ExposeInterface, PeekInterface, Secret};
pub mod access_token;
pub mod consts;
@@ -329,6 +329,38 @@ mod base64_serializer {
base64_serde_type!(pub Base64Serializer, crate::consts::BASE64_ENGINE);
}
+/// Merges two optional JSON values into a single JSON object.
+/// If both values are objects, their key-value pairs are merged.
+/// If only one value exists, it is returned.
+/// If neither exists, None is returned.
+pub fn merge_json_values(
+ first: Option<pii::SecretSerdeValue>,
+ second: Option<pii::SecretSerdeValue>,
+) -> Option<pii::SecretSerdeValue> {
+ match first.clone().zip(second.clone()) {
+ Some((first, second)) => {
+ let first_value = first.expose();
+ let second_value = second.expose();
+
+ match (first_value, second_value) {
+ (
+ serde_json::Value::Object(mut first_map),
+ serde_json::Value::Object(second_map),
+ ) => {
+ // if the first and second has the same keys then the value will be updated with that of the second
+ first_map.extend(second_map);
+ Some(pii::SecretSerdeValue::new(serde_json::Value::Object(
+ first_map,
+ )))
+ }
+ // ideally both Value should of variant Object but if one of them is not an object, it follows the previous behaviour i.e pass payment method metadata
+ (first_val, _) => Some(pii::SecretSerdeValue::new(first_val)),
+ }
+ }
+ None => first.or(second),
+ }
+}
+
#[cfg(test)]
mod nanoid_tests {
use super::*;
diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs
index 493a479dff..7eb54a03d3 100644
--- a/crates/hyperswitch_domain_models/src/payment_methods.rs
+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs
@@ -285,6 +285,14 @@ impl PaymentMethod {
.and_then(|record| record.connector_customer_id.clone()))
}
+ #[cfg(feature = "v1")]
+ pub fn get_payment_method_metadata(
+ &self,
+ optional_metadata: Option<pii::SecretSerdeValue>,
+ ) -> Option<pii::SecretSerdeValue> {
+ common_utils::merge_json_values(self.metadata.clone(), optional_metadata)
+ }
+
#[cfg(feature = "v2")]
pub fn get_payout_connector_customer_id(
&self,
diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs
index aacb460916..62bf2eeda4 100644
--- a/crates/router/src/core/locker_migration.rs
+++ b/crates/router/src/core/locker_migration.rs
@@ -121,7 +121,7 @@ pub async fn call_to_locker(
.await;
let card = match card {
- Ok(card) => card,
+ Ok(card) => card.get_card(),
Err(err) => {
logger::error!("Failed to fetch card from Basilisk HS locker : {:?}", err);
continue;
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 8862d4f3a1..9bae249c73 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -17,9 +17,9 @@ use api_models::{
payment_methods::{
BankAccountTokenData, Card, CardDetailUpdate, CardDetailsPaymentMethod, CardNetworkTypes,
CountryCodeWithName, ListCountriesCurrenciesRequest, ListCountriesCurrenciesResponse,
- MaskedBankDetails, PaymentExperienceTypes, PaymentMethodsData, RequestPaymentMethodTypes,
- RequiredFieldInfo, ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes,
- ResponsePaymentMethodsEnabled,
+ LockerCardResponse, MaskedBankDetails, PaymentExperienceTypes, PaymentMethodsData,
+ RequestPaymentMethodTypes, RequiredFieldInfo, ResponsePaymentMethodIntermediate,
+ ResponsePaymentMethodTypes, ResponsePaymentMethodsEnabled,
},
payments::BankCodeResponse,
pm_auth::PaymentMethodAuthConfig,
@@ -907,27 +907,35 @@ impl PaymentMethodsController for PmCards<'_> {
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
- let card = if pm.get_payment_method_type() == Some(enums::PaymentMethod::Card) {
- let card_detail = if self.state.conf.locker.locker_enabled {
- let card = get_card_from_locker(
- self.state,
- &pm.customer_id,
- &pm.merchant_id,
- pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error getting card from card vault")?;
- payment_methods::get_card_detail(&pm, card)
+ let (card, locker_metadata) =
+ if pm.get_payment_method_type() == Some(enums::PaymentMethod::Card) {
+ let (card_detail, locker_metadata) = if self.state.conf.locker.locker_enabled {
+ let locker_card_response = get_card_from_locker(
+ self.state,
+ &pm.customer_id,
+ &pm.merchant_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
+ )
+ .await
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed while getting card details from locker")?
+ .attach_printable("Error getting card from card vault")?;
+
+ (
+ payment_methods::get_card_detail(&pm, locker_card_response.get_card())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while getting card details from locker")?,
+ locker_card_response.get_metadata(),
+ )
+ } else {
+ (
+ self.get_card_details_without_locker_fallback(&pm).await?,
+ None,
+ )
+ };
+ (Some(card_detail), locker_metadata)
} else {
- self.get_card_details_without_locker_fallback(&pm).await?
+ (None, None)
};
- Some(card_detail)
- } else {
- None
- };
Ok(services::ApplicationResponse::Json(
api::PaymentMethodResponse {
merchant_id: pm.merchant_id.clone(),
@@ -938,7 +946,8 @@ impl PaymentMethodsController for PmCards<'_> {
#[cfg(feature = "payouts")]
bank_transfer: None,
card,
- metadata: pm.metadata,
+ // merge payload metadata with pm metadata
+ metadata: pm.get_payment_method_metadata(locker_metadata),
created: Some(pm.created_at),
recurring_enabled: Some(false),
installment_payment_enabled: Some(false),
@@ -1676,7 +1685,7 @@ pub async fn update_customer_payment_method(
let response = if is_card_updation_required {
// Fetch the existing card data from locker for getting card number
- let card_data_from_locker = get_card_from_locker(
+ let locker_card_response = get_card_from_locker(
&state,
&pm.customer_id,
&pm.merchant_id,
@@ -1685,6 +1694,8 @@ pub async fn update_customer_payment_method(
.await
.attach_printable("Error getting card from locker")?;
+ let card_data_from_locker = locker_card_response.get_card();
+
if card_update.card_exp_month.is_some() || card_update.card_exp_year.is_some() {
helpers::validate_card_expiry(
card_update
@@ -1799,7 +1810,7 @@ pub async fn update_customer_payment_method(
db.update_payment_method(
provider.get_key_store(),
- pm,
+ pm.clone(),
pm_update,
provider.get_account().storage_scheme,
)
@@ -1817,7 +1828,7 @@ pub async fn update_customer_payment_method(
bank_transfer: add_card_resp.bank_transfer,
card: add_card_resp.card,
wallet: None,
- metadata: add_card_resp.metadata,
+ metadata: pm.get_payment_method_metadata(locker_card_response.get_metadata()),
created: add_card_resp.created,
recurring_enabled: add_card_resp.recurring_enabled,
installment_payment_enabled: add_card_resp.installment_payment_enabled,
@@ -1837,7 +1848,8 @@ pub async fn update_customer_payment_method(
bank_transfer: None,
card: Some(existing_card_data),
wallet: None,
- metadata: pm.metadata,
+ // since locker is not called, no metadata is merged to payment method metadata
+ metadata: pm.get_payment_method_metadata(None),
created: Some(pm.created_at),
recurring_enabled: Some(false),
installment_payment_enabled: Some(false),
@@ -1971,7 +1983,7 @@ pub async fn get_card_from_locker(
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &str,
-) -> errors::RouterResult<Card> {
+) -> errors::RouterResult<LockerCardResponse> {
metrics::GET_FROM_LOCKER.add(1, &[]);
let get_card_from_rs_locker_resp = common_utils::metrics::utils::record_operation_time(
@@ -2273,7 +2285,7 @@ pub async fn get_card_from_vault<'a>(
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &'a str,
-) -> errors::CustomResult<Card, errors::VaultError> {
+) -> errors::CustomResult<LockerCardResponse, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = &state.conf.jwekey.get_inner();
@@ -2301,14 +2313,22 @@ pub async fn get_card_from_vault<'a>(
.payload
.get_required_value("RetrieveCardRespPayload")
.change_context(errors::VaultError::FetchCardFailed)?;
- retrieve_card_resp
- .card
- .get_required_value("Card")
- .change_context(errors::VaultError::FetchCardFailed)
+
+ Ok(LockerCardResponse::new(
+ retrieve_card_resp
+ .card
+ .get_required_value("Card")
+ .change_context(errors::VaultError::FetchCardFailed)?,
+ retrieve_card_resp.metadata,
+ ))
} else {
let (get_card_resp, _) = mock_get_card(&*state.store, card_reference).await?;
- payment_methods::mk_get_card_response(get_card_resp)
- .change_context(errors::VaultError::ResponseDeserializationFailed)
+
+ Ok(LockerCardResponse::new(
+ payment_methods::mk_get_card_response(get_card_resp)
+ .change_context(errors::VaultError::ResponseDeserializationFailed)?,
+ None,
+ ))
}
}
@@ -4637,7 +4657,8 @@ pub async fn get_card_details_from_locker(
pm.locker_id.as_ref().unwrap_or(pm.get_id()),
)
.await
- .attach_printable("Error getting card from card vault")?;
+ .attach_printable("Error getting card from card vault")?
+ .get_card();
payment_methods::get_card_detail(pm, card)
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -5204,7 +5225,8 @@ pub async fn execute_payment_method_tokenization(
executor.merchant_account.get_id(),
&locker_id,
)
- .await?;
+ .await?
+ .get_card();
// Perform BIN lookup and validate card network
let optional_card_info = executor
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 182fdc6d76..f26d4ba200 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -6,7 +6,7 @@ use common_enums::CardNetwork;
use common_utils::{
ext_traits::{Encode, StringExt},
id_type,
- pii::Email,
+ pii::{Email, SecretSerdeValue},
request::RequestContent,
};
use error_stack::ResultExt;
@@ -111,6 +111,8 @@ pub struct RetrieveCardResp {
pub struct RetrieveCardRespPayload {
pub card: Option<Card>,
pub enc_card_data: Option<Secret<String>>,
+ /// Additional metadata containing PAR, UPT, and other tokens
+ pub metadata: Option<SecretSerdeValue>,
}
#[derive(Debug, Deserialize, Serialize)]
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 59cce629f0..fbf887a0b5 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -2606,7 +2606,8 @@ pub async fn fetch_card_details_from_internal_locker(
let card = cards::get_card_from_locker(state, customer_id, merchant_id, locker_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("failed to fetch card information from the permanent locker")?;
+ .attach_printable("failed to fetch card information from the permanent locker")?
+ .get_card();
// The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked
// from payment_method_data.card_token object
@@ -2725,7 +2726,8 @@ pub async fn fetch_network_token_details_from_locker(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"failed to fetch network token information from the permanent locker",
- )?;
+ )?
+ .get_card();
let expiry = network_transaction_data
.token_exp_month
.zip(network_transaction_data.token_exp_year);
@@ -2771,7 +2773,8 @@ pub async fn fetch_card_details_for_network_transaction_flow_from_locker(
cards::get_card_from_locker(state, customer_id, merchant_id, locker_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("failed to fetch card details from locker")?;
+ .attach_printable("failed to fetch card details from locker")?
+ .get_card();
let card_network = card_details_from_locker
.card_brand
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 4a0625bfaa..2755809793 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -146,7 +146,8 @@ pub async fn make_payout_method_data(
payout_token.as_ref(),
)
.await
- .attach_printable("Payout method [card] could not be fetched from HS locker")?;
+ .attach_printable("Payout method [card] could not be fetched from HS locker")?
+ .get_card();
Ok(Some({
api::PayoutMethodData::Card(api::CardPayout {
card_number: resp.card_number,
diff --git a/crates/router/src/core/webhooks/network_tokenization_incoming.rs b/crates/router/src/core/webhooks/network_tokenization_incoming.rs
index 160bebc265..77a83c7b03 100644
--- a/crates/router/src/core/webhooks/network_tokenization_incoming.rs
+++ b/crates/router/src/core/webhooks/network_tokenization_incoming.rs
@@ -266,7 +266,8 @@ pub async fn handle_metadata_update(
let mut card = cards::get_card_from_locker(state, customer_id, merchant_id, &locker_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to fetch token information from the locker")?;
+ .attach_printable("Failed to fetch token information from the locker")?
+ .get_card();
card.card_exp_year = metadata.expiry_year.clone();
card.card_exp_month = metadata.expiry_month.clone();
diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs
index 9032239187..d90b5a12d4 100644
--- a/crates/router/src/types/api/mandates.rs
+++ b/crates/router/src/types/api/mandates.rs
@@ -70,7 +70,8 @@ impl MandateResponseExt for MandateResponse {
.as_ref()
.unwrap_or(payment_method.get_id()),
)
- .await?;
+ .await?
+ .get_card();
payment_methods::transformers::get_card_detail(&payment_method, card)
.change_context(errors::ApiErrorResponse::InternalServerError)