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(offers): once-per-card velocity via card_alias (#13766)
Apoorv Dixitfccb30306613
diff --git a/crates/router/src/core/blocklist/transformers.rs b/crates/router/src/core/blocklist/transformers.rsindex 79241bed37..16617a3c09 100644--- a/crates/router/src/core/blocklist/transformers.rs+++ b/crates/router/src/core/blocklist/transformers.rs@@ -26,7 +26,7 @@ impl ForeignFrom<storage::Blocklist> for blocklist::AddToBlocklistResponse {}#[instrument(skip_all)]-pub async fn generate_fingerprint(+pub async fn generate_fingerprint_and_get_id(state: &routes::SessionState,card_number: StrongSecret<String>,hash_key: StrongSecret<String>,diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rsindex 372fadce6a..028b398d67 100644--- a/crates/router/src/core/blocklist/utils.rs+++ b/crates/router/src/core/blocklist/utils.rs@@ -10,7 +10,7 @@ use diesel_models::{use error_stack::ResultExt;use hyperswitch_masking::{PeekInterface, StrongSecret};-use super::{errors, transformers::generate_fingerprint, SessionState};+use super::{errors, transformers::generate_fingerprint_and_get_id, SessionState};use crate::{core::{configs::dimension_state,@@ -403,7 +403,7 @@ pub async fn should_payment_be_blocked(// Hashed Fingerprint to check whether or not this payment should be blocked.let card_number_fingerprint =if let Some(domain::EligibilityPaymentMethodData::Card(card)) = payment_method_data {- generate_fingerprint(+ generate_fingerprint_and_get_id(state,StrongSecret::new(card.card_number.get_card_no()),StrongSecret::new(merchant_fingerprint_secret.clone()),@@ -778,7 +778,7 @@ pub async fn generate_payment_fingerprint(Ok(if let Some(domain::PaymentMethodData::Card(card)) = payment_method_data.as_ref() {- generate_fingerprint(+ generate_fingerprint_and_get_id(state,StrongSecret::new(card.card_number.get_card_no()),StrongSecret::new(merchant_fingerprint_secret),diff --git a/crates/router/src/core/offer_engine.rs b/crates/router/src/core/offer_engine.rsindex 98527b4c0d..d1f3191e07 100644--- a/crates/router/src/core/offer_engine.rs+++ b/crates/router/src/core/offer_engine.rs@@ -5,6 +5,8 @@ pub mod config;pub mod connectivity;pub mod eligibility;pub mod types;+#[cfg(feature = "v1")]+pub mod velocity;pub use client::OfferEngineClient;pub use config::resolve_offer_engine_config;diff --git a/crates/router/src/core/offer_engine/apply.rs b/crates/router/src/core/offer_engine/apply.rsindex 270d0aa1c8..f4257f8d2b 100644--- a/crates/router/src/core/offer_engine/apply.rs+++ b/crates/router/src/core/offer_engine/apply.rs@@ -40,6 +40,8 @@ pub struct OfferApplyContext {pub bank_code: Option<String>,/// Card issuing country, if available.pub card_country: Option<String>,+ /// Card fingerprint for once-per-card offer velocity, if available.+ pub card_alias: Option<String>,}#[derive(Debug, Clone)]@@ -82,6 +84,7 @@ pub async fn run_offer_apply(card_type: ctx.card_type.clone(),bank_code: ctx.bank_code.clone(),card_country: ctx.card_country.clone(),+ card_alias: ctx.card_alias.clone(),},customer: ctx.customer_id.map(|id| OfferCustomer {id: id.get_string_repr().to_string(),diff --git a/crates/router/src/core/offer_engine/eligibility.rs b/crates/router/src/core/offer_engine/eligibility.rsindex e9f813bb00..612e77aab4 100644--- a/crates/router/src/core/offer_engine/eligibility.rs+++ b/crates/router/src/core/offer_engine/eligibility.rs@@ -33,6 +33,8 @@ pub struct OfferEligibilityContext {pub bank_code: Option<String>,/// Card issuing country, if available.pub card_country: Option<String>,+ /// Card fingerprint for once-per-card offer velocity, if available.+ pub card_alias: Option<String>,}impl OfferEligibilityContext {@@ -45,6 +47,7 @@ impl OfferEligibilityContext {card_type: self.card_type.clone(),bank_code: self.bank_code.clone(),card_country: self.card_country.clone(),+ card_alias: self.card_alias.clone(),}}diff --git a/crates/router/src/core/offer_engine/types.rs b/crates/router/src/core/offer_engine/types.rsindex 50ee702988..4da337e71e 100644--- a/crates/router/src/core/offer_engine/types.rs+++ b/crates/router/src/core/offer_engine/types.rs@@ -74,6 +74,8 @@ pub struct OfferPaymentMethodInfo {pub bank_code: Option<String>,#[serde(skip_serializing_if = "Option::is_none")]pub card_country: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub card_alias: Option<String>,}/// Customer sent to Offer Engine.diff --git a/crates/router/src/core/offer_engine/velocity.rs b/crates/router/src/core/offer_engine/velocity.rsnew file mode 100644index 0000000000..b7dc8ef053--- /dev/null+++ b/crates/router/src/core/offer_engine/velocity.rs@@ -0,0 +1,34 @@+use cards::CardNumber;+use error_stack::ResultExt;+use hyperswitch_masking::StrongSecret;++use crate::{+ core::{+ blocklist::{+ transformers::generate_fingerprint_and_get_id, utils::get_merchant_fingerprint_secret,+ },+ errors::{self, RouterResult},+ },+ routes::SessionState,+ types::domain,+};++/// PAN-free per-merchant card fingerprint sent to Offer Engine as `card_alias`,+/// the once-per-card velocity key. Errors when the key can't be generated, so+/// callers can fail closed rather than let a card bypass velocity.+pub async fn generate_card_alias(+ state: &SessionState,+ merchant_account: &domain::MerchantAccount,+ card_number: &CardNumber,+) -> RouterResult<String> {+ let secret = get_merchant_fingerprint_secret(state, merchant_account).await?;+ generate_fingerprint_and_get_id(+ state,+ StrongSecret::new(card_number.get_card_no()),+ StrongSecret::new(secret),+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("offer velocity: card fingerprint generation failed")+ .map(|payload| payload.fingerprint_id)+}diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex ca32286e40..9c01e19a4e 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -67,6 +67,8 @@ use super::surcharge_decision_configs::{#[cfg(feature = "v1")]use super::tokenize::NetworkTokenizationProcess;#[cfg(feature = "v1")]+use crate::core::offer_engine;+#[cfg(feature = "v1")]use crate::core::payment_methods::{add_payment_method_status_update_task, get_payment_method_create_request, tokenize,utils::{get_merchant_pm_filter_graph, make_pm_graph, refresh_pm_filters_cache},@@ -4916,11 +4918,17 @@ pub async fn build_merchant_enabled_pms_context(None => false,};+ let offers_enabled = matches!(+ offer_engine::resolve_offer_engine_config(state, &dimensions).await,+ Ok(Some(_))+ );+let sdk_next_action = payment_method_utils::get_sdk_next_action_for_payment_method_list(state,&dimensions,payment_intent.and_then(|pi| pi.customer_id.as_ref()),has_surcharge_processor,+ offers_enabled,).await;diff --git a/crates/router/src/core/payment_methods/utils.rs b/crates/router/src/core/payment_methods/utils.rsindex 0a4b533980..8198c953a7 100644--- a/crates/router/src/core/payment_methods/utils.rs+++ b/crates/router/src/core/payment_methods/utils.rs@@ -930,6 +930,7 @@ pub async fn get_sdk_next_action_for_payment_method_list(dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,customer_id: Option<&common_utils::id_type::CustomerId>,has_surcharge_processor: bool,+ offers_enabled: bool,) -> api_models::payments::SdkNextAction {let should_perform_eligibility = dimensions.get_should_perform_eligibility(@@ -942,7 +943,7 @@ pub async fn get_sdk_next_action_for_payment_method_list(if should_perform_eligibility {api_models::payments::SdkNextAction {next_action: api_models::payments::NextActionCall::EligibilityCheck,- should_block_confirm: Some(has_surcharge_processor),+ should_block_confirm: Some(has_surcharge_processor || offers_enabled),}} else {api_models::payments::SdkNextAction {diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex e5b7055530..b2777e28d9 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -14865,6 +14865,7 @@ pub async fn payments_submit_eligibility(let offer_card_type = offer_card.and_then(|card| card.card_type.clone());let offer_bank_code = offer_card.and_then(|card| card.bank_code.clone());let offer_card_country = offer_card.and_then(|card| card.card_issuing_country.clone());+ let offer_card_number = offer_card.map(|card| card.card_number.clone());let offer_payment_method_type = eligibility_req.payment_method_type.to_string()@@ -14907,6 +14908,7 @@ pub async fn payments_submit_eligibility(offer_card_type,offer_bank_code,offer_card_country,+ offer_card_number,).await?;@@ -14946,6 +14948,7 @@ async fn resolve_offer_eligibility_details(card_type: Option<String>,bank_code: Option<String>,card_country: Option<String>,+ card_number: Option<::cards::CardNumber>,) -> RouterResult<(Option<api_models::payments::EligibilityAmountDetails>,Option<api_models::payments::EligibilityOfferDetails>,@@ -14975,6 +14978,25 @@ async fn resolve_offer_eligibility_details(match offer_context {None => Ok((None, None)),Some((offer_config, currency)) => {+ let card_alias = match card_number.as_ref() {+ Some(card_number) => match offer_engine::velocity::generate_card_alias(+ state,+ processor.get_account(),+ card_number,+ )+ .await+ {+ Ok(alias) => Some(alias),+ Err(error) => {+ logger::warn!(+ ?error,+ "offer velocity: card_alias unavailable; treating offers as unavailable"+ );+ return Ok((None, None));+ }+ },+ None => None,+ };let ctx = offer_engine::eligibility::OfferEligibilityContext {payment_id: payment_id.clone(),order_amount,@@ -14987,6 +15009,7 @@ async fn resolve_offer_eligibility_details(card_type,bank_code,card_country,+ card_alias,};// A `/list` failure while Offer Engine is enabled fails eligibility.diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex ab0f2a1004..9159b80faf 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -3253,6 +3253,21 @@ async fn apply_selected_offer<F: Clone + Send + Sync>(.as_ref().and_then(|payment_method_data| payment_method_data.get_card_data());+ let card_alias = match offer_card.map(|card| &card.card_number) {+ Some(card_number) => Some(+ offer_engine::velocity::generate_card_alias(+ state,+ processor.get_account(),+ card_number,+ )+ .await+ .change_context(errors::ApiErrorResponse::PreconditionFailed {+ message: "Cannot apply offer: card velocity key unavailable".to_string(),+ })?,+ ),+ None => None,+ };+let ctx = offer_engine::apply::OfferApplyContext {payment_id,attempt_id: payment_data.payment_attempt.attempt_id.clone(),@@ -3272,6 +3287,7 @@ async fn apply_selected_offer<F: Clone + Send + Sync>(card_type: offer_card.and_then(|card| card.card_type.clone()),bank_code: offer_card.and_then(|card| card.bank_code.clone()),card_country: offer_card.and_then(|card| card.card_issuing_country.clone()),+ card_alias,};let applied = Box::pin(offer_engine::apply::run_offer_apply(