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(payments): add support for eligibility based on bin (#13967)
Prasunna Soppab4e16edf7594
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex 5b2556a0e9..a08f3ac420 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -22033,6 +22033,20 @@}}},+ "EligibilityCardBin": {+ "type": "object",+ "description": "BIN-only input for the eligibility check. Enables BIN-level blocklist and profile-config\nblocking without the client having to share the full card number; fingerprint-level\n(exact-card) blocking requires the full card number via the `card` variant instead.",+ "required": [+ "card_bin"+ ],+ "properties": {+ "card_bin": {+ "type": "string",+ "description": "The card BIN: the leading 6 to 10 digits of the card number",+ "example": "42424242"+ }+ }+ },"EligibilityOfferDetails": {"type": "object","description": "Offer Engine eligibility details returned to the client.",@@ -22067,6 +22081,18 @@}}},+ {+ "type": "object",+ "title": "EligibilityCardBin",+ "required": [+ "card_bin"+ ],+ "properties": {+ "card_bin": {+ "$ref": "#/components/schemas/EligibilityCardBin"+ }+ }+ },{"type": "object","title": "CardRedirect",diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex 946a0a5f10..67e48088b6 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -7,7 +7,7 @@ use std::{pub mod additional_info;pub mod recipient;pub mod trait_impls;-use cards::{CardNumber, NetworkToken};+use cards::{CardBin, CardNumber, NetworkToken};#[cfg(feature = "v2")]use common_enums::enums::PaymentConnectorTransmission;#[cfg(feature = "v1")]@@ -13214,6 +13214,16 @@ pub struct EligibilityCard {pub nick_name: Option<Secret<String>>,}+/// BIN-only input for the eligibility check. Enables BIN-level blocklist and profile-config+/// blocking without the client having to share the full card number; fingerprint-level+/// (exact-card) blocking requires the full card number via the `card` variant instead.+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)]+pub struct EligibilityCardBin {+ /// The card BIN: the leading 6 to 10 digits of the card number+ #[schema(value_type = String, example = "42424242")]+ pub card_bin: CardBin,+}+/// Payment method data for eligibility check#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq, SmithyModel,@@ -13224,6 +13234,9 @@ pub enum EligibilityPaymentMethodData {#[schema(title = "EligibilityCard")]#[smithy(value_type = "EligibilityCard")]Card(EligibilityCard),+ #[schema(title = "EligibilityCardBin")]+ #[smithy(value_type = "EligibilityCardBin")]+ CardBin(EligibilityCardBin),#[schema(title = "CardRedirect")]#[smithy(value_type = "CardRedirectData")]CardRedirect(CardRedirectData),diff --git a/crates/cards/src/lib.rs b/crates/cards/src/lib.rsindex 77d1d25a5c..48b20aaa3a 100644--- a/crates/cards/src/lib.rs+++ b/crates/cards/src/lib.rs@@ -7,7 +7,9 @@ use hyperswitch_masking::{PeekInterface, StrongSecret};use serde::{de, Deserialize, Serialize};use time::{Date, Duration, PrimitiveDateTime, Time};-pub use crate::validate::{CardNumber, CardNumberStrategy, CardNumberValidationErr, NetworkToken};+pub use crate::validate::{+ CardBin, CardNumber, CardNumberStrategy, CardNumberValidationErr, NetworkToken,+};#[derive(Serialize)]pub struct CardSecurityCode(StrongSecret<u16>);diff --git a/crates/cards/src/validate.rs b/crates/cards/src/validate.rsindex d7df302d2b..7050d7dbe4 100644--- a/crates/cards/src/validate.rs+++ b/crates/cards/src/validate.rs@@ -34,6 +34,51 @@ pub struct CardNumber(StrongSecret<String, CardNumberStrategy>);#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]pub struct NetworkToken(StrongSecret<String, CardNumberStrategy>);+/// Card BIN — the leading 6 to 10 digits of a card number. Not a full PAN, so it is+/// stored and serialized in plain text (matching how BIN blocklist entries are stored).+#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]+pub struct CardBin(String);++impl CardBin {+ /// The 6-digit ISIN prefix of the BIN+ pub fn get_card_isin(&self) -> String {+ self.0.chars().take(6).collect()+ }++ /// Every blocklist-relevant prefix derivable from this BIN: lengths+ /// [`MIN_CARD_BIN_LENGTH`] up to the number of digits actually provided+ /// (capped at [`MAX_CARD_BIN_LENGTH`]).+ pub fn get_blocklist_bin_prefixes(&self) -> Vec<String> {+ (MIN_CARD_BIN_LENGTH..=self.0.len().min(MAX_CARD_BIN_LENGTH))+ .map(|len| self.0.chars().take(len).collect())+ .collect()+ }+}++impl FromStr for CardBin {+ type Err = CardNumberValidationErr;++ fn from_str(card_bin: &str) -> Result<Self, Self::Err> {+ let is_valid = (MIN_CARD_BIN_LENGTH..=MAX_CARD_BIN_LENGTH).contains(&card_bin.len())+ && card_bin.chars().all(|character| character.is_ascii_digit());++ if is_valid {+ Ok(Self(card_bin.to_string()))+ } else {+ Err(CardNumberValidationErr(+ "card_bin must be the leading 6 to 10 digits of the card number",+ ))+ }+ }+}++impl<'de> Deserialize<'de> for CardBin {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let s = String::deserialize(d)?;+ Self::from_str(&s).map_err(serde::de::Error::custom)+ }+}+impl CardNumber {fn get_bin_prefix(&self, len: usize) -> String {self.0.peek().chars().take(len).collect::<String>()diff --git a/crates/diesel_models/src/query/blocklist.rs b/crates/diesel_models/src/query/blocklist.rsindex ab8edefc42..2efac80cd4 100644--- a/crates/diesel_models/src/query/blocklist.rs+++ b/crates/diesel_models/src/query/blocklist.rs@@ -137,6 +137,40 @@ impl Blocklist {.await}+ /// Batched BIN-only lookup: all BIN-kind blocklist entries for this merchant/profile whose+ /// stored BIN is in `card_bins`. PAN-fingerprint entries (`data_kind = payment_method`) are+ /// excluded — they hold vault HMACs of full card numbers, which cannot be matched from a+ /// BIN. Uses the same processor-merchant-with-legacy-fallback and profile-or-merchant-wide+ /// predicates as the single-entry lookups.+ pub async fn find_by_processor_merchant_id_profile_id_card_bins(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ card_bins: Vec<String>,+ ) -> StorageResult<Vec<Self>> {+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(+ conn,+ dsl::processor_merchant_id+ .eq(processor_merchant_id.to_owned())+ .or(dsl::processor_merchant_id+ .is_null()+ .and(dsl::merchant_id.eq(processor_merchant_id.to_owned())))+ .and(dsl::data_kind.eq_any(equivalent_data_kinds(+ common_enums::BlocklistDataKind::GenericCardBin,+ )))+ .and(dsl::fingerprint_id.eq_any(card_bins))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ),+ None,+ None,+ Some(dsl::created_at.desc()),+ )+ .await+ }+// Fallback function for stagger release - finds by merchant_id when processor_merchant_id is NULLpub async fn find_by_merchant_id_fingerprint_id(conn: &DatabaseConnectionWithContext<'_>,diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rsindex b27bbea94a..ce1bd667fb 100644--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs@@ -374,10 +374,32 @@ pub struct EligibilityCard {pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>,}+/// BIN-only card data for eligibility/blocklist checks. Only BIN-level blocking (blocklist+/// bin entries and profile-config rules) can run against this — fingerprint-level blocking+/// needs the full card number.+#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]+pub struct EligibilityCardBin {+ pub card_bin: cards::CardBin,+}++impl EligibilityCardBin {+ /// The 6-digit ISIN prefix of the BIN+ pub fn get_card_isin(&self) -> String {+ self.card_bin.get_card_isin()+ }++ /// Every blocklist-relevant prefix derivable from this BIN (lengths 6 up to the+ /// number of digits provided)+ pub fn get_blocklist_bin_prefixes(&self) -> Vec<String> {+ self.card_bin.get_blocklist_bin_prefixes()+ }+}+/// Payment method data for eligibility/blocklist checks — mirrors PaymentMethodData but uses EligibilityCard#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]pub enum EligibilityPaymentMethodData {Card(EligibilityCard),+ CardBin(EligibilityCardBin),CardRedirect(CardRedirectData),Wallet(WalletData),PayLater(PayLaterData),@@ -399,12 +421,13 @@ pub enum EligibilityPaymentMethodData {impl EligibilityPaymentMethodData {pub fn is_eligible_for_profile_config_blocklist(&self) -> bool {- matches!(self, Self::Card(_) | Self::Wallet(_))+ matches!(self, Self::Card(_) | Self::CardBin(_) | Self::Wallet(_))}pub fn get_card_iin(&self) -> Option<String> {match self {Self::Card(card) => Some(card.card_number.get_card_isin()),+ Self::CardBin(card_bin) => Some(card_bin.get_card_isin()),_ => None,}}@@ -2334,6 +2357,11 @@ impl From<api_models::payments::EligibilityPaymentMethodData> for EligibilityPayapi_models::payments::EligibilityPaymentMethodData::Card(eligibility_card) => {Self::Card(EligibilityCard::from((eligibility_card, None)))}+ api_models::payments::EligibilityPaymentMethodData::CardBin(card_bin) => {+ Self::CardBin(EligibilityCardBin {+ card_bin: card_bin.card_bin,+ })+ }api_models::payments::EligibilityPaymentMethodData::CardRedirect(card_redirect) => {Self::CardRedirect(From::from(card_redirect))}diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex dd2e5c346c..f15933234e 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -676,6 +676,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payments::FingerprintType,api_models::payments::PaymentsCreateResponseOpenApi,api_models::payments::EligibilityCard,+ api_models::payments::EligibilityCardBin,api_models::payments::EligibilityPaymentMethodData,api_models::payments::EligibilityPaymentMethodDataRequest,api_models::payments::PaymentsEligibilityCheckRequest,diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rsindex 4674c6f206..74869b968c 100644--- a/crates/router/src/core/blocklist/utils.rs+++ b/crates/router/src/core/blocklist/utils.rs@@ -559,10 +559,15 @@ pub async fn should_payment_be_blocked(let card_bin_prefixes = payment_method_data.as_ref().and_then(|pm_data| match pm_data {- domain::EligibilityPaymentMethodData::Card(card) => Some(&card.card_number),+ domain::EligibilityPaymentMethodData::Card(card) => {+ Some(card.card_number.get_blocklist_bin_prefixes())+ }+ // BIN-only eligibility input: probe every prefix derivable from the provided BIN+ domain::EligibilityPaymentMethodData::CardBin(card_bin) => {+ Some(card_bin.get_blocklist_bin_prefixes())+ }_ => None,})- .map(cards::CardNumber::get_blocklist_bin_prefixes).unwrap_or_default();// Extended bin of the wallet's decrypted token, to check whether or not this payment should be blocked.@@ -613,6 +618,60 @@ pub async fn should_payment_be_blocked(Ok(block_reason)}+/// Whether the merchant has enabled the blocklist guard (the same config key that gates+/// confirm-time and eligibility-time blocklist checks). Defaults to `false` when unset.+pub async fn is_blocklist_guard_enabled(+ state: &SessionState,+ processor_merchant_id: &common_utils::id_type::MerchantId,+) -> bool {+ let blocklist_enabled_key = processor_merchant_id.get_blocklist_guard_key();+ match state+ .store+ .find_config_by_key_unwrap_or(&blocklist_enabled_key, Some("false".to_string()))+ .await+ {+ Ok(config) => serde_json::from_str(&config.config).unwrap_or(false),+ Err(error) => {+ if !error.current_context().is_db_not_found() {+ logger::error!(?error, "Error fetching blocklist guard enabled config");+ }+ false+ }+ }+}++/// Returns the subset of `bins` (card ISINs / extended BINs) that have an active BIN+/// blocklist entry (BIN kinds only — PAN-fingerprint entries cannot be matched from a+/// BIN) for this merchant/profile, resolved with a single batched query. Merchant-wide+/// entries (NULL `profile_id`) match every profile. DB errors are logged and treated as+/// not blocked, mirroring [`should_payment_be_blocked`].+pub async fn get_blocked_bins(+ state: &SessionState,+ processor: &domain::Processor,+ profile_id: &common_utils::id_type::ProfileId,+ bins: HashSet<String>,+) -> HashSet<String> {+ let lookup_result = state+ .store+ .list_blocklist_entries_by_processor_merchant_id_profile_id_card_bins(+ processor.get_account().get_id(),+ profile_id,+ bins.into_iter().collect(),+ )+ .await;++ match lookup_result {+ Ok(blocklist_entries) => blocklist_entries+ .into_iter()+ .map(|blocklist_entry| blocklist_entry.fingerprint_id)+ .collect(),+ Err(error) => {+ logger::error!(blocklist_db_error=?error, "failed db operations for blocklist");+ HashSet::new()+ }+ }+}+pub async fn validate_data_for_blocklist<F>(state: &SessionState,processor: &domain::Processor,@@ -704,6 +763,11 @@ fn resolve_blocking_config_and_bin<'a>(.as_ref().map(|card_config| (card_config, card.card_number.get_card_isin())),+ domain::EligibilityPaymentMethodData::CardBin(card_bin) => blocking_config+ .card+ .as_ref()+ .map(|card_config| (card_config, card_bin.get_card_isin())),+domain::EligibilityPaymentMethodData::Wallet(domain::WalletData::ApplePay(_)) => {blocking_config.walletdiff --git a/crates/router/src/core/payment_methods/client.rs b/crates/router/src/core/payment_methods/client.rsindex edcd3efe15..5e0d5d64bb 100644--- a/crates/router/src/core/payment_methods/client.rs+++ b/crates/router/src/core/payment_methods/client.rs@@ -20,6 +20,7 @@ use router_env::{instrument, logger, tracing, Flow};use crate::{core::{+ blocklist::utils as blocklist_utils,configs::dimension_state,errors::{self, StorageErrorExt},payment_methods::{@@ -488,6 +489,68 @@ fn filter_customer_pms_by_enabled(.collect()}+/// Filter out saved cards whose BIN (`card_isin`) has an active blocklist entry for this+/// merchant/profile (merchant-wide entries with a NULL `profile_id` match every profile).+/// Runs only when the merchant has enabled the blocklist guard (the same config+/// key that gates confirm-time and eligibility-time blocklist checks). BIN lookups are+/// deduplicated across the list and run concurrently. Non-card payment methods and cards+/// without a stored `card_isin` are passed through unchanged — fingerprint-level (exact+/// card) blocklist entries cannot be evaluated at list time since the stored record does+/// not carry a blocklist-comparable fingerprint.+async fn filter_customer_pms_by_blocklist(+ state: &routes::SessionState,+ platform: &domain::Platform,+ profile_id: &id_type::ProfileId,+ customer_pms: Vec<CustomerPaymentMethodForClient>,+) -> Vec<CustomerPaymentMethodForClient> {+ let processor = platform.get_processor();+ let guard_enabled =+ blocklist_utils::is_blocklist_guard_enabled(state, processor.get_account().get_id()).await;++ let bins: std::collections::HashSet<String> = if guard_enabled {+ customer_pms+ .iter()+ .filter_map(+ |customer_pm| match customer_pm.payment_method_data.as_ref() {+ Some(CustomerPaymentMethodDataForClient::Card(card)) => card.card_isin.clone(),+ _ => None,+ },+ )+ .collect()+ } else {+ std::collections::HashSet::new()+ };++ let blocked_bins = if bins.is_empty() {+ std::collections::HashSet::new()+ } else {+ blocklist_utils::get_blocked_bins(state, processor, profile_id, bins).await+ };++ if blocked_bins.is_empty() {+ customer_pms+ } else {+ let initial_count = customer_pms.len();+ let filtered: Vec<CustomerPaymentMethodForClient> = customer_pms+ .into_iter()+ .filter(+ |customer_pm| match customer_pm.payment_method_data.as_ref() {+ Some(CustomerPaymentMethodDataForClient::Card(card)) => !card+ .card_isin+ .as_ref()+ .is_some_and(|card_isin| blocked_bins.contains(card_isin)),+ _ => true,+ },+ )+ .collect();+ logger::info!(+ filtered_out = initial_count - filtered.len(),+ "Filtered blocklisted saved cards from the payment method list"+ );+ filtered+ }+}+async fn fetch_customer_payment_methods(state: &routes::SessionState,platform: &domain::Platform,@@ -603,7 +666,17 @@ pub async fn list_payment_methods_client(let customer_payment_methods_filtered =filter_customer_pms_by_enabled(customer_payment_methods, &payment_methods_enabled);- // 5. Build intent_data+ // 5. Drop saved cards whose BIN is blocklisted for this merchant/profile (no-op unless+ // the merchant has the blocklist guard enabled).+ let customer_payment_methods_filtered = filter_customer_pms_by_blocklist(+ &state,+ &platform,+ payment_intent_context.business_profile.get_id(),+ customer_payment_methods_filtered,+ )+ .await;++ // 6. Build intent_datalet net_amount = payment_intent_context.payment_attempt.net_amountdiff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 0028f6250e..68ca389b02 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -14121,23 +14121,7 @@ impl EligibilityCheck for BlockListCheck {platform: &domain::Platform,) -> CustomResult<bool, errors::ApiErrorResponse> {let merchant_id = platform.get_processor().get_account().get_id();- let blocklist_enabled_key = merchant_id.get_blocklist_guard_key();- let blocklist_guard_enabled = state- .store- .find_config_by_key_unwrap_or(&blocklist_enabled_key, Some("false".to_string()))- .await;-- Ok(match blocklist_guard_enabled {- Ok(config) => serde_json::from_str(&config.config).unwrap_or(false),-- // If it is not present in db we are defaulting it to false- Err(inner) => {- if !inner.current_context().is_db_not_found() {- logger::error!("Error fetching guard blocklist enabled config {:?}", inner);- }- false- }- })+ Ok(blocklist_utils::is_blocklist_guard_enabled(state, merchant_id).await)}async fn execute_check(diff --git a/crates/router/src/db/blocklist.rs b/crates/router/src/db/blocklist.rsindex cdccaf0258..88302afaef 100644--- a/crates/router/src/db/blocklist.rs+++ b/crates/router/src/db/blocklist.rs@@ -37,6 +37,15 @@ pub trait BlocklistInterface {fingerprint_ids: Vec<String>,) -> CustomResult<Option<storage::Blocklist>, errors::StorageError>;+ /// Batched BIN-only lookup: every BIN-kind blocklist entry for this merchant/profile+ /// whose BIN is in `card_bins`, in a single query. PAN-fingerprint entries are excluded.+ async fn list_blocklist_entries_by_processor_merchant_id_profile_id_card_bins(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ card_bins: Vec<String>,+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>;+async fn delete_blocklist_entry_by_processor_merchant_id_fingerprint_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,@@ -214,6 +223,24 @@ impl BlocklistInterface for Store {.map_err(|error| report!(errors::StorageError::from(error)))}+ #[instrument(skip_all)]+ async fn list_blocklist_entries_by_processor_merchant_id_profile_id_card_bins(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ card_bins: Vec<String>,+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {+ let conn = connection::pg_connection_read(self).await?;+ storage::Blocklist::find_by_processor_merchant_id_profile_id_card_bins(+ &conn,+ processor_merchant_id,+ profile_id,+ card_bins,+ )+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))+ }+#[instrument(skip_all)]async fn list_blocklist_entries_by_processor_merchant_id(&self,@@ -478,6 +505,15 @@ impl BlocklistInterface for MockDb {Err(errors::StorageError::MockDbError)?}+ async fn list_blocklist_entries_by_processor_merchant_id_profile_id_card_bins(+ &self,+ _processor_merchant_id: &common_utils::id_type::MerchantId,+ _profile_id: &common_utils::id_type::ProfileId,+ _card_bins: Vec<String>,+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {+ Err(errors::StorageError::MockDbError)?+ }+async fn list_blocklist_entries_by_processor_merchant_id(&self,_processor_merchant_id: &common_utils::id_type::MerchantId,@@ -635,6 +671,22 @@ impl BlocklistInterface for KafkaStore {.await}+ #[instrument(skip_all)]+ async fn list_blocklist_entries_by_processor_merchant_id_profile_id_card_bins(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ card_bins: Vec<String>,+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {+ self.diesel_store+ .list_blocklist_entries_by_processor_merchant_id_profile_id_card_bins(+ processor_merchant_id,+ profile_id,+ card_bins,+ )+ .await+ }+#[instrument(skip_all)]async fn delete_blocklist_entry_by_processor_merchant_id_fingerprint_id(&self,