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(router): Improve blocklist error messages with specific reasons (#11870)
Ayush Anand1e72e698830e
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 46d5c06c3f..e053c169ea 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -675,6 +675,31 @@ pub enum BlocklistDataKind {ExtendedCardBin,}+/// Reasons for blocking a payment method.+#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]+#[serde(rename_all = "snake_case")]+pub enum BlockReason {+ BlockedBin,+ BlockedCardType(CardType),+ BlockedCardSubtype,+ BlockedIssuerCountry,+ BlockedIssuer,+}++impl BlockReason {+ pub fn error_message(&self) -> String {+ match self {+ Self::BlockedBin => "We're unable to accept this card, please try another card or a different payment method".to_string(),+ Self::BlockedCardType(card_type) => {+ format!("{} cards are not accepted for this transaction, please try a different card", card_type.title_case())+ }+ Self::BlockedCardSubtype => "This card is not accepted for this transaction, please try a different card".to_string(),+ Self::BlockedIssuerCountry => "Cards issued in your region aren't supported for this transaction, please try a different card".to_string(),+ Self::BlockedIssuer => "We can't process payments from this bank, please try another card or a different payment method".to_string(),+ }+ }+}+/// Specifies how the payment is captured./// - `automatic`: Funds are captured immediately after successful authorization. This is the default behavior if the field is omitted./// - `manual`: Funds are authorized but not captured. A separate request to the `/payments/{payment_id}/capture` endpoint is required to capture the funds.@@ -3206,6 +3231,15 @@ pub enum CardType {Debit,}+impl CardType {+ pub fn title_case(&self) -> &'static str {+ match self {+ Self::Credit => "Credit",+ Self::Debit => "Debit",+ }+ }+}+// TODO: This enum will be updated with all card subtype values#[derive(Clone,diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rsindex 81b23de883..75eaaca156 100644--- a/crates/router/src/core/blocklist/utils.rs+++ b/crates/router/src/core/blocklist/utils.rs@@ -1,5 +1,5 @@use api_models::blocklist as api_blocklist;-use common_enums::MerchantDecision;+use common_enums::{BlockReason, MerchantDecision};use common_utils::errors::CustomResult;use diesel_models::{business_profile::CardBlockingConfig, configs};use error_stack::ResultExt;@@ -311,7 +311,7 @@ pub async fn should_payment_be_blocked(processor: &domain::Processor,payment_method_data: &Option<domain::EligibilityPaymentMethodData>,business_profile: &domain::Profile,-) -> CustomResult<bool, errors::ApiErrorResponse> {+) -> CustomResult<Option<BlockReason>, errors::ApiErrorResponse> {let db = &state.store;let merchant_id = processor.get_account().get_id();let merchant_fingerprint_secret = get_merchant_fingerprint_secret(state, merchant_id).await?;@@ -386,11 +386,11 @@ pub async fn should_payment_be_blocked(let blocklist_lookups = futures::future::join_all(blocklist_futures).await;- let mut should_payment_be_blocked = false;+ let mut block_reason: Option<BlockReason> = None;for lookup in blocklist_lookups {match lookup {Ok(_) => {- should_payment_be_blocked = true;+ block_reason = Some(BlockReason::BlockedBin);}Err(e) => {logger::error!(blocklist_db_error=?e, "failed db operations for blocklist");@@ -398,12 +398,12 @@ pub async fn should_payment_be_blocked(}}- if !should_payment_be_blocked+ if block_reason.is_none()&& payment_method_data.as_ref().is_some_and(|pmd| pmd.is_eligible_for_profile_config_blocklist()){- should_payment_be_blocked = should_payment_be_blocked_by_profile_config(+ block_reason = should_payment_be_blocked_by_profile_config(state,payment_method_data,business_profile,@@ -411,7 +411,7 @@ pub async fn should_payment_be_blocked(.await?;}- Ok(should_payment_be_blocked)+ Ok(block_reason)}pub async fn validate_data_for_blocklist<F>(@@ -424,7 +424,7 @@ whereF: Send + Clone,{let db = &state.store;- let should_block = should_payment_be_blocked(+ let block_reason = should_payment_be_blocked(state,processor,&payment_data@@ -435,7 +435,9 @@ where).await?;- if should_block {+ if let Some(reason) = block_reason {+ let error_message = reason.error_message();+ logger::warn!(block_reason = ?reason, "Payment blocked by blocklist");db.update_payment_intent(payment_data.payment_intent.clone(),storage::PaymentIntentUpdate::RejectUpdate {@@ -456,7 +458,7 @@ wherelet attempt_update = storage::PaymentAttemptUpdate::BlocklistUpdate {status: common_enums::AttemptStatus::Failure,error_code: Some(Some("HE-03".to_string())),- error_message: Some(Some("This payment method is blocked".to_string())),+ error_message: Some(Some(error_message.clone())),updated_by: processor.get_account().storage_scheme.to_string(),};db.update_payment_attempt_with_attempt_id(@@ -473,7 +475,7 @@ whereErr(errors::ApiErrorResponse::PaymentBlockedError {code: 200,- message: "This payment method is blocked".to_string(),+ message: error_message,status: "Failed".to_string(),reason: "Blocked".to_string(),}@@ -493,8 +495,8 @@ pub async fn should_payment_be_blocked_by_profile_config(state: &SessionState,payment_method_data: &Option<domain::EligibilityPaymentMethodData>,business_profile: &domain::Profile,-) -> CustomResult<bool, errors::ApiErrorResponse> {- let mut should_block = false;+) -> CustomResult<Option<BlockReason>, errors::ApiErrorResponse> {+ let mut block_reason: Option<BlockReason> = None;let card_config = business_profile.payment_method_blocking@@ -521,22 +523,39 @@ pub async fn should_payment_be_blocked_by_profile_config(match card_info {None => {- should_block = card_config.should_block_if_bin_info_unavailable();+ if card_config.should_block_if_bin_info_unavailable() {+ block_reason = Some(BlockReason::BlockedBin);+ }}Some(info) => {- should_block = CardBlockingConfig::should_block_by_attribute(+ block_reason = CardBlockingConfig::should_block_by_attribute(&card_config.issuing_country,info.country_code.as_deref(),- ) || CardBlockingConfig::should_block_by_attribute(- &card_config.card_types,- info.card_type.as_deref(),- ) || CardBlockingConfig::should_block_by_attribute(- &card_config.card_subtypes,- info.card_subtype.as_deref(),- );+ )+ .then_some(BlockReason::BlockedIssuerCountry)+ .or_else(|| {+ CardBlockingConfig::should_block_by_attribute(+ &card_config.card_types,+ info.card_type.as_deref(),+ )+ .then(|| {+ info.card_type+ .as_deref()+ .and_then(|s| s.parse::<common_enums::CardType>().ok())+ .map(BlockReason::BlockedCardType)+ })+ .flatten()+ })+ .or_else(|| {+ CardBlockingConfig::should_block_by_attribute(+ &card_config.card_subtypes,+ info.card_subtype.as_deref(),+ )+ .then_some(BlockReason::BlockedCardSubtype)+ });// Check card issuer — profile stores IDs, cards_info has name- if !should_block {+ if block_reason.is_none() {if let (Some(blocked_ids), Some(issuer_name)) =(&card_config.issuers, &info.card_issuer){@@ -557,7 +576,7 @@ pub async fn should_payment_be_blocked_by_profile_config(.map(|i| i.issuer_name).collect::<std::collections::HashSet<_>>();if resolved_names.contains(issuer_name.as_str()) {- should_block = true;+ block_reason = Some(BlockReason::BlockedIssuer);}}}@@ -565,7 +584,7 @@ pub async fn should_payment_be_blocked_by_profile_config(}}- Ok(should_block)+ Ok(block_reason)}pub async fn generate_payment_fingerprint(diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex e46f315f67..5688c20905 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -11995,19 +11995,21 @@ impl EligibilityCheck for BlockListCheck {payment_elgibility_data: &PaymentEligibilityData,business_profile: &domain::Profile,) -> CustomResult<CheckResult, errors::ApiErrorResponse> {- let should_payment_be_blocked = blocklist_utils::should_payment_be_blocked(+ let block_reason = blocklist_utils::should_payment_be_blocked(state,platform.get_processor(),&payment_elgibility_data.payment_method_data,business_profile,).await?;- if should_payment_be_blocked {- Ok(CheckResult::Deny {- message: "Card number is blocklisted".to_string(),- })- } else {- Ok(CheckResult::Allow)+ match block_reason {+ Some(reason) => {+ logger::warn!(block_reason = ?reason, "Payment blocked by blocklist");+ Ok(CheckResult::Deny {+ message: reason.error_message(),+ })+ }+ None => Ok(CheckResult::Allow),}}diff --git a/cypress-tests/cypress/e2e/configs/Payment/Commons.js b/cypress-tests/cypress/e2e/configs/Payment/Commons.jsindex 6bf50fd4af..4a55e24dcd 100644--- a/cypress-tests/cypress/e2e/configs/Payment/Commons.js+++ b/cypress-tests/cypress/e2e/configs/Payment/Commons.js@@ -1,13 +1,56 @@// This file is the default. To override, add to connector.jsimport { getCurrency, getCustomExchange } from "./Modifiers";-export const blockedPaymentErrorBody = {+export const blockedPaymentErrorBodyForIssuingCountry = {status: 200,expectBlockedPayment: true,body: {error: {type: "blocked",- message: "This payment method is blocked",+ message:+ "Cards issued in your region aren't supported for this transaction, please try a different card",+ code: "HE_03",+ reason: "Blocked",+ },+ },+};++export const blockedPaymentErrorBodyForDebitCard = {+ status: 200,+ expectBlockedPayment: true,+ body: {+ error: {+ type: "blocked",+ message:+ "Debit cards are not accepted for this transaction, please try a different card",+ code: "HE_03",+ reason: "Blocked",+ },+ },+};++export const blockedPaymentErrorBodyForCardSubtype = {+ status: 200,+ expectBlockedPayment: true,+ body: {+ error: {+ type: "blocked",+ message:+ "This card is not accepted for this transaction, please try a different card",+ code: "HE_03",+ reason: "Blocked",+ },+ },+};++export const blockedPaymentErrorBodyForBinUnavailable = {+ status: 200,+ expectBlockedPayment: true,+ body: {+ error: {+ type: "blocked",+ message:+ "We're unable to accept this card, please try another card or a different payment method",code: "HE_03",reason: "Blocked",},@@ -2339,7 +2382,8 @@ export const connectorDetails = {sdk_next_action: {next_action: {deny: {- message: "Card number is blocklisted",+ message:+ "We're unable to accept this card, please try another card or a different payment method",},},},@@ -2394,7 +2438,7 @@ export const connectorDetails = {},},},- Response: blockedPaymentErrorBody,+ Response: blockedPaymentErrorBodyForIssuingCountry,}),BlockCardType: getCustomExchange({Request: {@@ -2410,7 +2454,7 @@ export const connectorDetails = {},},},- Response: blockedPaymentErrorBody,+ Response: blockedPaymentErrorBodyForDebitCard,}),BlockCardSubtype: getCustomExchange({Request: {@@ -2426,7 +2470,7 @@ export const connectorDetails = {},},},- Response: blockedPaymentErrorBody,+ Response: blockedPaymentErrorBodyForCardSubtype,}),BlockIfBinInfoUnavailable: getCustomExchange({Request: {@@ -2442,7 +2486,7 @@ export const connectorDetails = {},},},- Response: blockedPaymentErrorBody,+ Response: blockedPaymentErrorBodyForBinUnavailable,}),},};diff --git a/cypress-tests/cypress/e2e/configs/Payment/Fiservemea.js b/cypress-tests/cypress/e2e/configs/Payment/Fiservemea.jsindex d8989e7f8c..f35b8f5767 100644--- a/cypress-tests/cypress/e2e/configs/Payment/Fiservemea.js+++ b/cypress-tests/cypress/e2e/configs/Payment/Fiservemea.js@@ -1,4 +1,10 @@-import { customerAcceptance } from "./Commons";+import {+ customerAcceptance,+ blockedPaymentErrorBodyForIssuingCountry,+ blockedPaymentErrorBodyForDebitCard,+ blockedPaymentErrorBodyForCardSubtype,+ blockedPaymentErrorBodyForBinUnavailable,+} from "./Commons";const successfulNo3DSCardDetails = {card_number: "5204740000001002",@@ -16,19 +22,6 @@ const failedNo3DSCardDetails = {card_cvc: "123",};-const blockedPaymentErrorBody = {- status: 200,- expectBlockedPayment: true,- body: {- error: {- type: "blocked",- message: "This payment method is blocked",- code: "HE_03",- reason: "Blocked",- },- },-};-const billingAddress = {address: {state: "New York",@@ -755,7 +748,7 @@ export const connectorDetails = {billing: billingAddress,currency: "EUR",},- Response: blockedPaymentErrorBody,+ Response: blockedPaymentErrorBodyForIssuingCountry,},BlockCardType: {Request: {@@ -773,7 +766,7 @@ export const connectorDetails = {billing: billingAddress,currency: "EUR",},- Response: blockedPaymentErrorBody,+ Response: blockedPaymentErrorBodyForDebitCard,},BlockCardSubtype: {Request: {@@ -791,7 +784,7 @@ export const connectorDetails = {currency: "EUR",billing: billingAddress,},- Response: blockedPaymentErrorBody,+ Response: blockedPaymentErrorBodyForCardSubtype,},BlockIfBinInfoUnavailable: {Request: {@@ -809,7 +802,7 @@ export const connectorDetails = {billing: billingAddress,currency: "EUR",},- Response: blockedPaymentErrorBody,+ Response: blockedPaymentErrorBodyForBinUnavailable,},},};diff --git a/cypress-tests/cypress/e2e/configs/Payment/Fiuu.js b/cypress-tests/cypress/e2e/configs/Payment/Fiuu.jsindex d5b70abb01..f8e1e7b5fe 100644--- a/cypress-tests/cypress/e2e/configs/Payment/Fiuu.js+++ b/cypress-tests/cypress/e2e/configs/Payment/Fiuu.js@@ -1,4 +1,11 @@-import { cardRequiredField, customerAcceptance } from "./Commons";+import {+ cardRequiredField,+ customerAcceptance,+ blockedPaymentErrorBodyForIssuingCountry,+ blockedPaymentErrorBodyForDebitCard,+ blockedPaymentErrorBodyForCardSubtype,+ blockedPaymentErrorBodyForBinUnavailable,+} from "./Commons";const successfulNo3DSCardDetails = {card_number: "5105105105105100",@@ -59,19 +66,6 @@ const billingAddress = {email: "[email protected]",};-const blockedPaymentErrorBody = {- status: 200,- expectBlockedPayment: true,- body: {- error: {- type: "blocked",- message: "This payment method is blocked",- code: "HE_03",- reason: "Blocked",- },- },-};-const requiredFields = {payment_methods: [{@@ -1019,7 +1013,7 @@ export const connectorDetails = {billing: billingAddress,currency: "MYR",},- Response: blockedPaymentErrorBody,+ Response: blockedPaymentErrorBodyForIssuingCountry,},BlockCardType: {Request: {@@ -1037,7 +1031,7 @@ export const connectorDetails = {billing: billingAddress,currency: "MYR",},- Response: blockedPaymentErrorBody,+ Response: blockedPaymentErrorBodyForDebitCard,},BlockCardSubtype: {Request: {@@ -1055,7 +1049,7 @@ export const connectorDetails = {currency: "MYR",billing: billingAddress,},- Response: blockedPaymentErrorBody,+ Response: blockedPaymentErrorBodyForCardSubtype,},BlockIfBinInfoUnavailable: {Request: {@@ -1073,7 +1067,7 @@ export const connectorDetails = {billing: billingAddress,currency: "MYR",},- Response: blockedPaymentErrorBody,+ Response: blockedPaymentErrorBodyForBinUnavailable,},},};diff --git a/cypress-tests/cypress/e2e/configs/Payment/Redsys.js b/cypress-tests/cypress/e2e/configs/Payment/Redsys.jsindex 5f19a18cef..6626321cf6 100644--- a/cypress-tests/cypress/e2e/configs/Payment/Redsys.js+++ b/cypress-tests/cypress/e2e/configs/Payment/Redsys.js@@ -1,4 +1,10 @@import { getCustomExchange } from "./Modifiers";+import {+ blockedPaymentErrorBodyForIssuingCountry,+ blockedPaymentErrorBodyForDebitCard,+ blockedPaymentErrorBodyForCardSubtype,+ blockedPaymentErrorBodyForBinUnavailable,+} from "./Commons";const ThreeDSChallengeTestCardDetails = {card_number: "4548817212493017",@@ -16,19 +22,6 @@ const threeDSFrictionlessTestCardDetails = {card_cvc: "123",};-const blockedPaymentErrorBody = {- status: 200,- expectBlockedPayment: true,- body: {- error: {- type: "blocked",- message: "This payment method is blocked",- code: "HE_03",- reason: "Blocked",- },- },-};-const Address = {address: {line1: "1467",@@ -554,7 +547,7 @@ export const connectorDetails = {shipping: Address,currency: "EUR",},- Response: blockedPaymentErrorBody,+ Response: blockedPaymentErrorBodyForIssuingCountry,},BlockCardType: {Request: {@@ -573,7 +566,7 @@ export const connectorDetails = {shipping: Address,currency: "EUR",},- Response: blockedPaymentErrorBody,+ Response: blockedPaymentErrorBodyForDebitCard,},BlockCardSubtype: {Request: {@@ -592,7 +585,7 @@ export const connectorDetails = {shipping: Address,currency: "EUR",},- Response: blockedPaymentErrorBody,+ Response: blockedPaymentErrorBodyForCardSubtype,},BlockIfBinInfoUnavailable: {Request: {@@ -611,7 +604,7 @@ export const connectorDetails = {shipping: Address,currency: "EUR",},- Response: blockedPaymentErrorBody,+ Response: blockedPaymentErrorBodyForBinUnavailable,},},};diff --git a/cypress-tests/cypress/e2e/spec/Payment/41-CardPaymentBlocking.cy.js b/cypress-tests/cypress/e2e/spec/Payment/41-CardPaymentBlocking.cy.jsindex be411ac87b..c28791892c 100644--- a/cypress-tests/cypress/e2e/spec/Payment/41-CardPaymentBlocking.cy.js+++ b/cypress-tests/cypress/e2e/spec/Payment/41-CardPaymentBlocking.cy.js@@ -80,7 +80,7 @@ describe("Business Profile Payment Method Blocking", () => {});});- context("Card Type Blocking", () => {+ context("Debit Card Blocking", () => {it("should block payment when debit cards are blocked", () => {let shouldContinue = true;