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(payouts): Add pre FRM support for payouts (#14189)

Saptak Duttac441a21d0abb
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index 3e6339a3ec..cf23c4d6f2 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -39393,6 +39393,14 @@
"example": "E0001",
"nullable": true
},
+ "frm_message": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/FrmMessage"
+ }
+ ],
+ "nullable": true
+ },
"profile_id": {
"type": "string",
"description": "The business profile that is associated with this payout"
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index b0ef8efefc..286275393b 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -27629,6 +27629,14 @@
"example": "E0001",
"nullable": true
},
+ "frm_message": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/FrmMessage"
+ }
+ ],
+ "nullable": true
+ },
"profile_id": {
"type": "string",
"description": "The business profile that is associated with this payout"
diff --git a/config/superposition_seed.toml b/config/superposition_seed.toml
index 5ab5920086..6976b6d5c4 100644
--- a/config/superposition_seed.toml
+++ b/config/superposition_seed.toml
@@ -2558,6 +2558,7 @@ client_session_validation_enabled = { value = true, schema = { type = "boolean"
"payments.block_implicit_customer_creation" = { value = false, schema = { type = "boolean" }, description = "Whether payments must reject implicit creation of a missing customer for an organization", change_reason = "Decouple implicit customer creation from PM modular eligibility" }
"webhooks.incoming_webhook_disabled_events" = { value = false, schema = { type = "boolean" }, description = "Whether a specific incoming webhook event is disabled for a given connector", change_reason = "Initial setup" }
"payouts.max_auto_payout_retries" = { value = 0, schema = { maximum = 4294967295, minimum = 0, type = "integer" }, description = "Maximum auto payout retries, differentiated by payout_retry_type dimension (single_connector or multi_connector)", change_reason = "Initial setup" }
+"payouts.payout_frm_call" = { value = false, schema = { type = "boolean" }, description = "Whether to call FRM for payouts", change_reason = "Initial setup" }
"payouts.payout_tracker_mapping" = { value = { frequencies = [
[
300,
diff --git a/crates/analytics/docs/clickhouse/scripts/fraud_check.sql b/crates/analytics/docs/clickhouse/scripts/fraud_check.sql
index fa0ab47b36..48e07f506c 100644
--- a/crates/analytics/docs/clickhouse/scripts/fraud_check.sql
+++ b/crates/analytics/docs/clickhouse/scripts/fraud_check.sql
@@ -1,6 +1,7 @@
CREATE TABLE fraud_check_queue (
`frm_id` String,
- `payment_id` String,
+ `payment_id` Nullable(String),
+ `payout_id` Nullable(String),
`merchant_id` String,
`attempt_id` String,
`created_at` DateTime CODEC(T64, LZ4),
@@ -31,7 +32,8 @@ kafka_handle_error_mode = 'stream';
CREATE TABLE fraud_check (
`frm_id` String,
- `payment_id` String,
+ `payment_id` Nullable(String),
+ `payout_id` Nullable(String),
`merchant_id` LowCardinality(String),
`attempt_id` String,
`created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
@@ -65,7 +67,8 @@ ORDER BY
CREATE MATERIALIZED VIEW fraud_check_mv TO fraud_check (
`frm_id` String,
- `payment_id` String,
+ `payment_id` Nullable(String),
+ `payout_id` Nullable(String),
`merchant_id` String,
`attempt_id` String,
`created_at` DateTime64(3),
@@ -92,6 +95,7 @@ CREATE MATERIALIZED VIEW fraud_check_mv TO fraud_check (
SELECT
frm_id,
payment_id,
+ payout_id,
merchant_id,
attempt_id,
created_at,
@@ -137,4 +141,4 @@ SELECT
FROM
fraud_check_queue
WHERE
- length(_error) > 0;
\ No newline at end of file
+ length(_error) > 0;
diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs
index e3dbe4d902..04b25f9a4b 100644
--- a/crates/api_models/src/payouts.rs
+++ b/crates/api_models/src/payouts.rs
@@ -16,6 +16,7 @@ use common_utils::{
use hyperswitch_masking::Secret;
#[cfg(feature = "v1")]
use payments::BrowserInformation;
+use payments::FrmMessage;
use router_derive::FlatStruct;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -941,6 +942,10 @@ pub struct PayoutCreateResponse {
#[schema(value_type = Option<String>, example = "E0001")]
pub error_code: Option<String>,
+ /// FRM response information when fraud checks were invoked for this payout
+ #[schema(value_type = Option<FrmMessage>)]
+ pub frm_message: Option<FrmMessage>,
+
/// The business profile that is associated with this payout
#[schema(value_type = String)]
pub profile_id: id_type::ProfileId,
diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs
index af48cb5f48..4c116dece8 100644
--- a/crates/diesel_models/src/enums.rs
+++ b/crates/diesel_models/src/enums.rs
@@ -175,6 +175,7 @@ pub enum FraudCheckLastStep {
CheckoutOrSale,
TransactionOrRecordRefund,
Fulfillment,
+ PoFrm,
}
#[derive(
diff --git a/crates/diesel_models/src/fraud_check.rs b/crates/diesel_models/src/fraud_check.rs
index d10531ae36..134c1be3f4 100644
--- a/crates/diesel_models/src/fraud_check.rs
+++ b/crates/diesel_models/src/fraud_check.rs
@@ -8,10 +8,10 @@ use crate::{
schema::fraud_check,
};
#[derive(Clone, Debug, Identifiable, Queryable, Selectable, Serialize, Deserialize)]
-#[diesel(table_name = fraud_check, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))]
+#[diesel(table_name = fraud_check, primary_key(frm_id), check_for_backend(diesel::pg::Pg))]
pub struct FraudCheck {
pub frm_id: String,
- pub payment_id: common_utils::id_type::PaymentId,
+ pub payment_id: Option<common_utils::id_type::PaymentId>,
pub merchant_id: common_utils::id_type::MerchantId,
pub attempt_id: String,
pub created_at: PrimitiveDateTime,
@@ -29,13 +29,14 @@ pub struct FraudCheck {
pub payment_capture_method: Option<storage_enums::CaptureMethod>, // In postFrm, we are updating capture method from automatic to manual. To store the merchant actual capture method, we are storing the actual capture method in payment_capture_method. It will be useful while approving the FRM decision.
pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,
pub created_by: Option<String>,
+ pub payout_id: Option<common_utils::id_type::PayoutId>,
}
#[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = fraud_check)]
pub struct FraudCheckNew {
pub frm_id: String,
- pub payment_id: common_utils::id_type::PaymentId,
+ pub payment_id: Option<common_utils::id_type::PaymentId>,
pub merchant_id: common_utils::id_type::MerchantId,
pub attempt_id: String,
pub created_at: PrimitiveDateTime,
@@ -53,6 +54,7 @@ pub struct FraudCheckNew {
pub payment_capture_method: Option<storage_enums::CaptureMethod>,
pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,
pub created_by: Option<String>,
+ pub payout_id: Option<common_utils::id_type::PayoutId>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index 10cc892247..e9155a8b0d 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -176,6 +176,7 @@ pub struct PaymentAttempt {
pub fingerprint_type: Option<common_enums::FingerprintType>,
/// Payment Account Reference (PAR) returned by the connector for the underlying payment method
pub payment_account_reference: Option<String>,
+ pub active_frm_id: Option<String>,
#[diesel(deserialize_as = RequiredFromNullable<storage_enums::PaymentMethod>)]
pub payment_method_type_v2: storage_enums::PaymentMethod,
pub connector_payment_id: Option<ConnectorTransactionId>,
@@ -318,6 +319,7 @@ pub struct PaymentAttempt {
pub fingerprint_type: Option<common_enums::FingerprintType>,
/// Payment Account Reference (PAR) returned by the connector for the underlying card
pub payment_account_reference: Option<String>,
+ pub active_frm_id: Option<String>,
}
#[cfg(feature = "v1")]
@@ -476,6 +478,7 @@ pub struct PaymentAttemptNew {
pub external_surcharge_details: Option<common_types::payments::ExternalSurchargeDetails>,
pub applied_offer_details: Option<common_types::payments::AppliedOfferDetails>,
pub payment_account_reference: Option<String>,
+ pub active_frm_id: Option<String>,
}
#[cfg(feature = "v1")]
@@ -577,6 +580,7 @@ pub struct PaymentAttemptNew {
pub external_threeds_authentication_type: Option<common_enums::DecoupledAuthenticationType>,
pub applied_offer_details: Option<common_types::payments::AppliedOfferDetails>,
pub payment_account_reference: Option<String>,
+ pub active_frm_id: Option<String>,
}
#[cfg(feature = "v1")]
@@ -668,6 +672,7 @@ pub enum PaymentAttemptUpdate {
request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
external_surcharge_details: Option<common_types::payments::ExternalSurchargeDetails>,
applied_offer_details: Option<common_types::payments::AppliedOfferDetails>,
+ active_frm_id: Option<String>,
},
VoidUpdate {
status: storage_enums::AttemptStatus,
@@ -832,6 +837,7 @@ pub enum PaymentAttemptUpdate {
error_reason: Option<String>,
updated_by: String,
connector_mandate_detail: Option<ConnectorMandateReferenceId>,
+ active_frm_id: Option<String>,
},
ExternalSurchargeUpdate {
external_surcharge_details: common_types::payments::ExternalSurchargeDetails,
@@ -1163,6 +1169,7 @@ pub struct PaymentAttemptUpdateInternal {
pub external_surcharge_details: Option<common_types::payments::ExternalSurchargeDetails>,
pub applied_offer_details: Option<common_types::payments::AppliedOfferDetails>,
pub payment_account_reference: Option<String>,
+ pub active_frm_id: Option<String>,
}
#[cfg(feature = "v1")]
@@ -2587,6 +2594,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
},
PaymentAttemptUpdate::AuthenticationTypeUpdate {
authentication_type,
@@ -2669,6 +2677,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
},
PaymentAttemptUpdate::ConfirmUpdate {
amount,
@@ -2716,6 +2725,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
request_extended_authorization,
external_surcharge_details,
applied_offer_details,
+ active_frm_id,
} => Self {
amount: Some(amount),
currency: Some(currency),
@@ -2794,6 +2804,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details,
applied_offer_details,
payment_account_reference: None,
+ active_frm_id,
},
PaymentAttemptUpdate::VoidUpdate {
status,
@@ -2877,6 +2888,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
},
PaymentAttemptUpdate::RejectUpdate {
status,
@@ -2961,6 +2973,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
},
PaymentAttemptUpdate::BlocklistUpdate {
status,
@@ -3045,6 +3058,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
},
PaymentAttemptUpdate::ConnectorMandateDetailUpdate {
connector_mandate_detail,
@@ -3128,6 +3142,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
},
PaymentAttemptUpdate::AssociatedDataUpdate {
sender_payment_instrument_id,
@@ -3210,6 +3225,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
},
PaymentAttemptUpdate::PaymentMethodDetailsUpdate {
payment_method_id,
@@ -3292,6 +3308,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
},
PaymentAttemptUpdate::ResponseUpdate {
status,
@@ -3413,6 +3430,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference,
+ active_frm_id: None,
}
}
PaymentAttemptUpdate::ErrorUpdate {
@@ -3519,6 +3537,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
}
}
PaymentAttemptUpdate::StatusUpdate { status, updated_by } => Self {
@@ -3599,6 +3618,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
},
PaymentAttemptUpdate::UpdateTrackers {
payment_token,
@@ -3689,6 +3709,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
},
PaymentAttemptUpdate::UnresolvedResponseUpdate {
status,
@@ -3786,6 +3807,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
}
}
PaymentAttemptUpdate::PreprocessingUpdate {
@@ -3880,6 +3902,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
}
}
PaymentAttemptUpdate::CaptureUpdate {
@@ -3964,6 +3987,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
},
PaymentAttemptUpdate::AmountToCaptureUpdate {
status,
@@ -4047,6 +4071,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
},
PaymentAttemptUpdate::ConnectorResponse {
authentication_data,
@@ -4139,6 +4164,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
}
}
PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate {
@@ -4222,6 +4248,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
},
PaymentAttemptUpdate::AuthenticationUpdate {
status,
@@ -4308,6 +4335,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
},
PaymentAttemptUpdate::ManualUpdate {
status,
@@ -4403,6 +4431,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
}
}
PaymentAttemptUpdate::PostSessionTokensUpdate {
@@ -4486,6 +4515,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
},
PaymentAttemptUpdate::RecurrenceUpdate {
status,
@@ -4494,6 +4524,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
error_reason,
updated_by,
connector_mandate_detail,
+ active_frm_id,
} => Self {
status: Some(status),
error_details: None,
@@ -4572,6 +4603,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id,
},
PaymentAttemptUpdate::ExternalSurchargeUpdate {
updated_by,
@@ -4654,6 +4686,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
external_threeds_authentication_type: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
},
}
}
diff --git a/crates/diesel_models/src/payout_attempt.rs b/crates/diesel_models/src/payout_attempt.rs
index c1276383e9..3d5f3018c5 100644
--- a/crates/diesel_models/src/payout_attempt.rs
+++ b/crates/diesel_models/src/payout_attempt.rs
@@ -45,6 +45,7 @@ pub struct PayoutAttempt {
pub additional_source_bank_data: Option<payout_method_utils::BankAdditionalData>,
pub connector_eligibility_reference_id: Option<String>,
pub connector_request_reference_id: Option<String>,
+ pub active_frm_id: Option<String>,
}
#[derive(
@@ -92,6 +93,7 @@ pub struct PayoutAttemptNew {
pub additional_source_bank_data: Option<payout_method_utils::BankAdditionalData>,
pub connector_eligibility_reference_id: Option<String>,
pub connector_request_reference_id: Option<String>,
+ pub active_frm_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -106,6 +108,7 @@ pub enum PayoutAttemptUpdate {
unified_message: Option<UnifiedMessage>,
payout_connector_metadata: Option<pii::SecretSerdeValue>,
connector_eligibility_reference_id: Option<String>,
+ active_frm_id: Option<String>,
},
PayoutTokenUpdate {
payout_token: String,
@@ -121,6 +124,7 @@ pub enum PayoutAttemptUpdate {
routing_info: Option<serde_json::Value>,
merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
connector_request_reference_id: String,
+ active_frm_id: Option<String>,
},
AdditionalPayoutDataUpdate {
additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>,
@@ -164,6 +168,7 @@ pub struct PayoutAttemptUpdateInternal {
pub additional_source_bank_data: Option<payout_method_utils::BankAdditionalData>,
pub connector_eligibility_reference_id: Option<String>,
pub connector_request_reference_id: Option<String>,
+ pub active_frm_id: Option<String>,
}
impl Default for PayoutAttemptUpdateInternal {
@@ -192,6 +197,7 @@ impl Default for PayoutAttemptUpdateInternal {
additional_source_bank_data: None,
connector_eligibility_reference_id: None,
connector_request_reference_id: None,
+ active_frm_id: None,
}
}
}
@@ -213,6 +219,7 @@ impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal {
unified_message,
payout_connector_metadata,
connector_eligibility_reference_id,
+ active_frm_id,
} => Self {
connector_payout_id,
status: Some(status),
@@ -223,6 +230,7 @@ impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal {
unified_message,
payout_connector_metadata,
connector_eligibility_reference_id,
+ active_frm_id,
..Default::default()
},
PayoutAttemptUpdate::BusinessUpdate {
@@ -242,11 +250,13 @@ impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal {
routing_info,
merchant_connector_id,
connector_request_reference_id,
+ active_frm_id,
} => Self {
connector: Some(connector),
routing_info,
merchant_connector_id,
connector_request_reference_id: Some(connector_request_reference_id),
+ active_frm_id,
..Default::default()
},
PayoutAttemptUpdate::AdditionalPayoutDataUpdate {
diff --git a/crates/diesel_models/src/query/fraud_check.rs b/crates/diesel_models/src/query/fraud_check.rs
index 0cc85c19c0..2b6a0391d7 100644
--- a/crates/diesel_models/src/query/fraud_check.rs
+++ b/crates/diesel_models/src/query/fraud_check.rs
@@ -1,4 +1,4 @@
-use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
+use diesel::{associations::HasTable, ExpressionMethods};
use crate::{
errors, fraud_check::*, query::generics, schema::fraud_check::dsl,
@@ -15,7 +15,7 @@ impl FraudCheckNew {
}
impl FraudCheck {
- pub async fn update_with_attempt_id(
+ pub async fn update_with_frm_id(
self,
conn: &DatabaseConnectionWithContext<'_>,
fraud_check: FraudCheckUpdate,
@@ -27,9 +27,7 @@ impl FraudCheck {
_,
>(
conn,
- dsl::attempt_id
- .eq(self.attempt_id.to_owned())
- .and(dsl::merchant_id.eq(self.merchant_id.to_owned())),
+ dsl::frm_id.eq(self.frm_id.to_owned()),
FraudCheckUpdateInternal::from(fraud_check),
)
.await
@@ -42,31 +40,11 @@ impl FraudCheck {
}
}
- pub async fn get_with_payment_id(
+ pub async fn get_with_frm_id(
conn: &DatabaseConnectionWithContext<'_>,
- payment_id: common_utils::id_type::PaymentId,
- merchant_id: common_utils::id_type::MerchantId,
+ frm_id: String,
) -> StorageResult<Self> {
- generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
- conn,
- dsl::payment_id
- .eq(payment_id)
- .and(dsl::merchant_id.eq(merchant_id)),
- )
- .await
- }
-
- pub async fn get_with_payment_id_if_present(
- conn: &DatabaseConnectionWithContext<'_>,
- payment_id: common_utils::id_type::PaymentId,
- merchant_id: common_utils::id_type::MerchantId,
- ) -> StorageResult<Option<Self>> {
- generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
- conn,
- dsl::payment_id
- .eq(payment_id)
- .and(dsl::merchant_id.eq(merchant_id)),
- )
- .await
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, dsl::frm_id.eq(frm_id))
+ .await
}
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 132a6faf7d..f4de2f1cde 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -697,11 +697,11 @@ diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
- fraud_check (frm_id, attempt_id, payment_id, merchant_id) {
+ fraud_check (frm_id) {
#[max_length = 64]
frm_id -> Varchar,
#[max_length = 64]
- payment_id -> Varchar,
+ payment_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
@@ -727,6 +727,8 @@ diesel::table! {
processor_merchant_id -> Nullable<Varchar>,
#[max_length = 255]
created_by -> Nullable<Varchar>,
+ #[max_length = 64]
+ payout_id -> Nullable<Varchar>,
}
}
@@ -1242,6 +1244,8 @@ diesel::table! {
fingerprint_type -> Nullable<Varchar>,
#[max_length = 255]
payment_account_reference -> Nullable<Varchar>,
+ #[max_length = 64]
+ active_frm_id -> Nullable<Varchar>,
}
}
@@ -1538,6 +1542,8 @@ diesel::table! {
connector_eligibility_reference_id -> Nullable<Varchar>,
#[max_length = 255]
connector_request_reference_id -> Nullable<Varchar>,
+ #[max_length = 64]
+ active_frm_id -> Nullable<Varchar>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 491d7ddd07..16fa953bcd 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -686,11 +686,11 @@ diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
- fraud_check (frm_id, attempt_id, payment_id, merchant_id) {
+ fraud_check (frm_id) {
#[max_length = 64]
frm_id -> Varchar,
#[max_length = 64]
- payment_id -> Varchar,
+ payment_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
@@ -716,6 +716,8 @@ diesel::table! {
processor_merchant_id -> Nullable<Varchar>,
#[max_length = 255]
created_by -> Nullable<Varchar>,
+ #[max_length = 64]
+ payout_id -> Nullable<Varchar>,
}
}
@@ -1161,6 +1163,8 @@ diesel::table! {
fingerprint_type -> Nullable<Varchar>,
#[max_length = 255]
payment_account_reference -> Nullable<Varchar>,
+ #[max_length = 64]
+ active_frm_id -> Nullable<Varchar>,
payment_method_type_v2 -> Nullable<Varchar>,
#[max_length = 128]
connector_payment_id -> Nullable<Varchar>,
@@ -1457,6 +1461,8 @@ diesel::table! {
connector_eligibility_reference_id -> Nullable<Varchar>,
#[max_length = 255]
connector_request_reference_id -> Nullable<Varchar>,
+ #[max_length = 64]
+ active_frm_id -> Nullable<Varchar>,
}
}
diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs
index f84f6cbdbd..b38b6f471a 100644
--- a/crates/diesel_models/src/user/sample_data.rs
+++ b/crates/diesel_models/src/user/sample_data.rs
@@ -332,6 +332,7 @@ impl PaymentAttemptBatchNew {
payment_account_reference: None,
sender_payment_instrument_id: None,
external_threeds_authentication_type: None,
+ active_frm_id: None,
}
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/absa_sanlam.rs b/crates/hyperswitch_connectors/src/connectors/absa_sanlam.rs
index 0436cec3d4..27fc8157d6 100644
--- a/crates/hyperswitch_connectors/src/connectors/absa_sanlam.rs
+++ b/crates/hyperswitch_connectors/src/connectors/absa_sanlam.rs
@@ -433,7 +433,7 @@ impl ConnectorSpecifications for AbsaSanlam {
}
#[cfg(feature = "frm")]
- fn get_frm_metadata(
+ fn get_payment_frm_metadata(
&self,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> CustomResult<Option<common_utils::pii::SecretSerdeValue>, errors::ConnectorError> {
diff --git a/crates/hyperswitch_connectors/src/connectors/gotyme_sanlam.rs b/crates/hyperswitch_connectors/src/connectors/gotyme_sanlam.rs
index f45c2b40f4..89a58b56f5 100644
--- a/crates/hyperswitch_connectors/src/connectors/gotyme_sanlam.rs
+++ b/crates/hyperswitch_connectors/src/connectors/gotyme_sanlam.rs
@@ -576,4 +576,22 @@ impl ConnectorSpecifications for GotymeSanlam {
) -> String {
common_utils::generate_uuid_v4().to_string()
}
+
+ #[cfg(feature = "frm")]
+ fn get_payout_frm_metadata(
+ &self,
+ payout_attempt: &hyperswitch_domain_models::payouts::payout_attempt::PayoutAttempt,
+ ) -> CustomResult<Option<common_utils::pii::SecretSerdeValue>, errors::ConnectorError> {
+ let metadata = gotyme_sanlam::GotymeSanlamFrmMetadata {
+ profile_id: payout_attempt.profile_id.get_string_repr().to_owned(),
+ connector_id: payout_attempt
+ .merchant_connector_id
+ .as_ref()
+ .map(|id| id.get_string_repr().to_owned()),
+ created_at: payout_attempt.created_at,
+ };
+ serde_json::to_value(metadata)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)
+ .map(|value| Some(hyperswitch_masking::Secret::new(value)))
+ }
}
diff --git a/crates/hyperswitch_connectors/src/connectors/gotyme_sanlam/transformers.rs b/crates/hyperswitch_connectors/src/connectors/gotyme_sanlam/transformers.rs
index 1374c3963f..c934d0dd7c 100644
--- a/crates/hyperswitch_connectors/src/connectors/gotyme_sanlam/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/gotyme_sanlam/transformers.rs
@@ -280,3 +280,10 @@ impl<F> TryFrom<PayoutsResponseRouterData<F, GotymeSanlamPayoutResponse>> for Pa
})
}
}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct GotymeSanlamFrmMetadata {
+ pub profile_id: String,
+ pub connector_id: Option<String>,
+ pub created_at: time::PrimitiveDateTime,
+}
diff --git a/crates/hyperswitch_connectors/src/connectors/sanlam_payshield.rs b/crates/hyperswitch_connectors/src/connectors/sanlam_payshield.rs
index e271629721..a83ed6894a 100644
--- a/crates/hyperswitch_connectors/src/connectors/sanlam_payshield.rs
+++ b/crates/hyperswitch_connectors/src/connectors/sanlam_payshield.rs
@@ -4,6 +4,7 @@ use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
+ types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
@@ -12,12 +13,12 @@ use hyperswitch_domain_models::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
- Checkout, Fulfillment, RecordReturn, Sale, Transaction,
+ Checkout, Fulfillment, PoFrm, RecordReturn, Sale, Transaction,
},
router_request_types::{
fraud_check::{
- FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData,
- FraudCheckSaleData, FraudCheckTransactionData,
+ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckPayoutData,
+ FraudCheckRecordReturnData, FraudCheckSaleData, FraudCheckTransactionData,
},
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
@@ -31,9 +32,9 @@ use hyperswitch_interfaces::{
api::{
ConnectorAccessToken, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration,
ConnectorSpecifications, ConnectorValidation, FraudCheck, FraudCheckCheckout,
- FraudCheckFulfillment, FraudCheckRecordReturn, FraudCheckSale, FraudCheckTransaction,
- MandateSetup, Payment, PaymentAuthorize, PaymentCapture, PaymentSession, PaymentSync,
- PaymentToken, PaymentVoid, Refund, RefundExecute, RefundSync,
+ FraudCheckFulfillment, FraudCheckPayout, FraudCheckRecordReturn, FraudCheckSale,
+ FraudCheckTransaction, MandateSetup, Payment, PaymentAuthorize, PaymentCapture,
+ PaymentSession, PaymentSync, PaymentToken, PaymentVoid, Refund, RefundExecute, RefundSync,
},
configs::Connectors,
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
@@ -47,15 +48,22 @@ use transformers as sanlam_payshield;
use crate::{
constants::headers,
- types::{FrmCheckoutRouterData, FrmCheckoutType, ResponseRouterData},
+ types::{
+ FrmCheckoutRouterData, FrmCheckoutType, PoFrmRouterData, PoFrmType, ResponseRouterData,
+ },
+ utils::convert_amount,
};
#[derive(Clone)]
-pub struct SanlamPayshield;
+pub struct SanlamPayshield {
+ amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
+}
impl SanlamPayshield {
pub fn new() -> &'static Self {
- &Self
+ &Self {
+ amount_converter: &StringMinorUnitForConnector,
+ }
}
}
@@ -171,9 +179,18 @@ impl ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseDa
req: &FrmCheckoutRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
- Ok(RequestContent::Json(Box::new(
- sanlam_payshield::SanlamPayshieldCheckoutRequest::try_from(req)?,
- )))
+ let amount = convert_amount(
+ self.amount_converter,
+ req.request.amount,
+ req.request
+ .currency
+ .ok_or(ConnectorError::MissingRequiredField {
+ field_name: "currency".into(),
+ })?,
+ )?;
+ let req_data = sanlam_payshield::SanlamPayshieldRouterData::from((amount, req));
+ let req_obj = sanlam_payshield::SanlamPayshieldCheckoutRequest::try_from(&req_data)?;
+ Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
@@ -206,7 +223,94 @@ impl ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseDa
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- FrmCheckoutRouterData::try_from(ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<PoFrm, FraudCheckPayoutData, FraudCheckResponseData> for SanlamPayshield {
+ fn get_headers(
+ &self,
+ req: &PoFrmRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &PoFrmRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<String, ConnectorError> {
+ let merchant_id = _req.merchant_id.get_string_repr();
+ Ok(format!(
+ "{}/payshield/v1/check/{}",
+ self.base_url(connectors).to_owned(),
+ merchant_id
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &PoFrmRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, ConnectorError> {
+ let amount = convert_amount(
+ self.amount_converter,
+ req.request.amount,
+ req.request.currency,
+ )?;
+ let req_data = sanlam_payshield::SanlamPayshieldRouterData::from((amount, req));
+ let req_obj = sanlam_payshield::SanlamPayshieldCheckoutRequest::try_from(&req_data)?;
+ Ok(RequestContent::Json(Box::new(req_obj)))
+ }
+
+ fn build_request(
+ &self,
+ req: &PoFrmRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PoFrmType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(PoFrmType::get_headers(self, req, connectors)?)
+ .set_body(PoFrmType::get_request_body(self, req, connectors)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PoFrmRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PoFrmRouterData, ConnectorError> {
+ let response: sanlam_payshield::SanlamPayshieldCheckoutResponse = res
+ .response
+ .parse_struct("SanlamPayshieldCheckoutResponse")
+ .change_context(ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|event| event.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -242,7 +346,7 @@ impl FraudCheckSale for SanlamPayshield {}
impl FraudCheckTransaction for SanlamPayshield {}
impl FraudCheckFulfillment for SanlamPayshield {}
impl FraudCheckRecordReturn for SanlamPayshield {}
-
+impl FraudCheckPayout for SanlamPayshield {}
impl Payment for SanlamPayshield {}
impl PaymentSession for SanlamPayshield {}
impl ConnectorAccessToken for SanlamPayshield {}
diff --git a/crates/hyperswitch_connectors/src/connectors/sanlam_payshield/transformers.rs b/crates/hyperswitch_connectors/src/connectors/sanlam_payshield/transformers.rs
index 32e1688d33..08e98f571e 100644
--- a/crates/hyperswitch_connectors/src/connectors/sanlam_payshield/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/sanlam_payshield/transformers.rs
@@ -1,9 +1,9 @@
-use api_models::payments::{additional_info::BankDebitAdditionalData, AdditionalPaymentData};
-use common_enums::FraudCheckStatus;
-use common_utils::{ext_traits::ValueExt, pii::SecretSerdeValue};
+use common_enums::{Currency, FraudCheckStatus};
+use common_utils::{ext_traits::ValueExt, pii::SecretSerdeValue, types::StringMinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
- router_data::ConnectorAuthType, router_request_types::ResponseId,
+ router_data::{ConnectorAuthType, RouterData},
+ router_request_types::ResponseId,
router_response_types::fraud_check::FraudCheckResponseData,
};
use hyperswitch_interfaces::errors::ConnectorError;
@@ -11,10 +11,24 @@ use hyperswitch_masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
- types::{FrmCheckoutRouterData, ResponseRouterData},
+ types::{FrmCheckoutRouterData, PoFrmRouterData, ResponseRouterData},
utils::get_unimplemented_payment_method_error_message,
};
+pub struct SanlamPayshieldRouterData<T> {
+ pub amount: StringMinorUnit,
+ pub router_data: T,
+}
+
+impl<T> From<(StringMinorUnit, T)> for SanlamPayshieldRouterData<T> {
+ fn from((amount, router_data): (StringMinorUnit, T)) -> Self {
+ Self {
+ amount,
+ router_data,
+ }
+ }
+}
+
pub struct SanlamPayshieldAuthType {
pub(super) api_key: Secret<String>,
}
@@ -47,6 +61,7 @@ pub struct SanlamPayshieldCheckoutRequest {
connector_id: String,
connector_type: ConnectorType,
transaction: Transaction,
+ #[serde(skip_serializing_if = "Option::is_none")]
metadata: Option<SecretSerdeValue>,
}
@@ -61,8 +76,8 @@ pub enum ConnectorType {
#[serde(rename_all = "camelCase")]
pub struct Transaction {
payment_id: String,
- amount_in_cents: String,
- currency: String,
+ amount_in_cents: StringMinorUnit,
+ currency: Currency,
payment_method_type: PaymentMethodType,
created_at: String,
}
@@ -71,12 +86,36 @@ pub struct Transaction {
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentMethodType {
EftDebitOrder,
+ Payshap,
+ PayshapProxy,
}
-impl TryFrom<&FrmCheckoutRouterData> for SanlamPayshieldCheckoutRequest {
+impl TryFrom<&common_enums::PaymentMethodType> for PaymentMethodType {
type Error = error_stack::Report<ConnectorError>;
- fn try_from(data: &FrmCheckoutRouterData) -> Result<Self, Self::Error> {
+ fn try_from(
+ payment_method_type: &common_enums::PaymentMethodType,
+ ) -> Result<Self, Self::Error> {
+ match payment_method_type {
+ common_enums::PaymentMethodType::EftDebitOrder => Ok(Self::EftDebitOrder),
+ common_enums::PaymentMethodType::Payshap => Ok(Self::Payshap),
+ common_enums::PaymentMethodType::PayshapProxy => Ok(Self::PayshapProxy),
+ _ => Err(ConnectorError::NotImplemented(
+ get_unimplemented_payment_method_error_message("sanlam_paysheild"),
+ ))?,
+ }
+ }
+}
+
+impl TryFrom<&SanlamPayshieldRouterData<&FrmCheckoutRouterData>>
+ for SanlamPayshieldCheckoutRequest
+{
+ type Error = error_stack::Report<ConnectorError>;
+
+ fn try_from(
+ item: &SanlamPayshieldRouterData<&FrmCheckoutRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let data = item.router_data;
let SanlamPayshieldFrmMetadata {
profile_id,
connector_id,
@@ -103,15 +142,14 @@ impl TryFrom<&FrmCheckoutRouterData> for SanlamPayshieldCheckoutRequest {
field_name: "currency".into(),
})?;
- let payment_method_type = match data.request.payment_method_data.as_ref() {
- Some(AdditionalPaymentData::BankDebit {
- details: Some(BankDebitAdditionalData::EftDebitOrder { .. }),
- }) => Ok(PaymentMethodType::EftDebitOrder),
-
- _ => Err(ConnectorError::NotImplemented(
- get_unimplemented_payment_method_error_message("sanlam_paysheild"),
- )),
- }?;
+ let payment_method_type = data
+ .payment_method_type
+ .as_ref()
+ .map(PaymentMethodType::try_from)
+ .transpose()?
+ .ok_or(ConnectorError::MissingRequiredField {
+ field_name: "payment_method_type".into(),
+ })?;
let created_at = created_at
.assume_utc()
@@ -128,8 +166,73 @@ impl TryFrom<&FrmCheckoutRouterData> for SanlamPayshieldCheckoutRequest {
connector_type: ConnectorType::Payin,
transaction: Transaction {
payment_id: data.payment_id.clone(),
- amount_in_cents: data.request.amount.to_string(),
- currency: currency.to_string(),
+ amount_in_cents: item.amount.clone(),
+ currency,
+ payment_method_type,
+ created_at,
+ },
+ metadata: data.frm_metadata.clone(),
+ })
+ }
+}
+
+impl TryFrom<&SanlamPayshieldRouterData<&PoFrmRouterData>> for SanlamPayshieldCheckoutRequest {
+ type Error = error_stack::Report<ConnectorError>;
+
+ fn try_from(item: &SanlamPayshieldRouterData<&PoFrmRouterData>) -> Result<Self, Self::Error> {
+ let data = item.router_data;
+ let SanlamPayshieldFrmMetadata {
+ profile_id,
+ connector_id,
+ created_at,
+ } = data
+ .request
+ .gateway_metadata
+ .clone()
+ .ok_or(ConnectorError::MissingRequiredField {
+ field_name: "gateway_metadata".into(),
+ })?
+ .parse_value("SanlamPayshieldFrmMetadata")
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to parse SanlamPayshieldFrmMetadata")?;
+
+ let connector_id = connector_id.ok_or(ConnectorError::MissingRequiredField {
+ field_name: "connector_id".into(),
+ })?;
+
+ let payment_method_type = data
+ .payment_method_type
+ .as_ref()
+ .map(PaymentMethodType::try_from)
+ .transpose()?
+ .ok_or(ConnectorError::MissingRequiredField {
+ field_name: "payment_method_type".into(),
+ })?;
+
+ let payout_id = data
+ .payout_id
+ .clone()
+ .ok_or(ConnectorError::MissingRequiredField {
+ field_name: "payout_id".into(),
+ })?;
+
+ let created_at = created_at
+ .assume_utc()
+ .to_offset(time::macros::offset!(+2))
+ .format(time::macros::format_description!(
+ "[year]-[month]-[day]T[hour]:[minute]:[second][offset_hour sign:mandatory]:[offset_minute]"
+ ))
+ .change_context(ConnectorError::RequestEncodingFailed)?;
+
+ Ok(Self {
+ request_id: data.connector_request_reference_id.clone(),
+ profile_id,
+ connector_id,
+ connector_type: ConnectorType::Payout,
+ transaction: Transaction {
+ payment_id: payout_id,
+ amount_in_cents: item.amount.clone(),
+ currency: data.request.currency,
payment_method_type,
created_at,
},
@@ -166,25 +269,14 @@ impl From<Decision> for FraudCheckStatus {
}
}
-impl
- TryFrom<
- ResponseRouterData<
- hyperswitch_domain_models::router_flow_types::Checkout,
- SanlamPayshieldCheckoutResponse,
- hyperswitch_domain_models::router_request_types::fraud_check::FraudCheckCheckoutData,
- FraudCheckResponseData,
- >,
- > for FrmCheckoutRouterData
+impl<F, T>
+ TryFrom<ResponseRouterData<F, SanlamPayshieldCheckoutResponse, T, FraudCheckResponseData>>
+ for RouterData<F, T, FraudCheckResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
- item: ResponseRouterData<
- hyperswitch_domain_models::router_flow_types::Checkout,
- SanlamPayshieldCheckoutResponse,
- hyperswitch_domain_models::router_request_types::fraud_check::FraudCheckCheckoutData,
- FraudCheckResponseData,
- >,
+ item: ResponseRouterData<F, SanlamPayshieldCheckoutResponse, T, FraudCheckResponseData>,
) -> Result<Self, Self::Error> {
let connector_metadata = serde_json::json!({
"reasonCodes": item.response.reason_codes,
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index 5192082540..807895a86e 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -104,10 +104,12 @@ use hyperswitch_domain_models::{
};
#[cfg(feature = "frm")]
use hyperswitch_domain_models::{
- router_flow_types::fraud_check::{Checkout, Fulfillment, RecordReturn, Sale, Transaction},
+ router_flow_types::fraud_check::{
+ Checkout, Fulfillment, PoFrm, RecordReturn, Sale, Transaction,
+ },
router_request_types::fraud_check::{
- FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData,
- FraudCheckSaleData, FraudCheckTransactionData,
+ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckPayoutData,
+ FraudCheckRecordReturnData, FraudCheckSaleData, FraudCheckTransactionData,
},
router_response_types::fraud_check::FraudCheckResponseData,
};
@@ -128,8 +130,8 @@ use hyperswitch_domain_models::{
};
#[cfg(feature = "frm")]
use hyperswitch_interfaces::api::fraud_check::{
- FraudCheck, FraudCheckCheckout, FraudCheckFulfillment, FraudCheckRecordReturn, FraudCheckSale,
- FraudCheckTransaction,
+ FraudCheck, FraudCheckCheckout, FraudCheckFulfillment, FraudCheckPayout,
+ FraudCheckRecordReturn, FraudCheckSale, FraudCheckTransaction,
};
#[cfg(feature = "payouts")]
use hyperswitch_interfaces::api::payouts::{
@@ -6961,6 +6963,181 @@ default_imp_for_frm_checkout!(
connectors::CtpMastercard
);
+#[cfg(feature = "frm")]
+macro_rules! default_imp_for_po_frm {
+ ($($path:ident::$connector:ident),*) => {
+ $(
+ impl FraudCheckPayout for $path::$connector {}
+ impl
+ ConnectorIntegration<
+ PoFrm,
+ FraudCheckPayoutData,
+ FraudCheckResponseData,
+ > for $path::$connector
+ {}
+ )*
+ };
+}
+
+#[cfg(feature = "frm")]
+default_imp_for_po_frm!(
+ connectors::Vgs,
+ connectors::AbsaSanlam,
+ connectors::Aci,
+ connectors::Adyen,
+ connectors::Adyenplatform,
+ connectors::Affirm,
+ connectors::Airwallex,
+ connectors::Amazonpay,
+ connectors::Archipel,
+ connectors::Authipay,
+ connectors::Authorizedotnet,
+ connectors::Bambora,
+ connectors::Bamboraapac,
+ connectors::Bankofamerica,
+ connectors::Barclaycard,
+ connectors::Billwerk,
+ connectors::Bitpay,
+ connectors::Blackhawknetwork,
+ connectors::Calida,
+ connectors::Bluesnap,
+ connectors::Braintree,
+ connectors::Boku,
+ connectors::Breadpay,
+ connectors::Cashtocode,
+ connectors::Celero,
+ connectors::Chargebee,
+ connectors::Checkbook,
+ connectors::Checkout,
+ connectors::Coinbase,
+ connectors::Coingate,
+ connectors::Cryptopay,
+ connectors::Custombilling,
+ connectors::Cybersource,
+ connectors::Cybersourcedecisionmanager,
+ connectors::Datatrans,
+ connectors::Deutschebank,
+ connectors::Digitalvirgo,
+ connectors::Dlocal,
+ connectors::Dwolla,
+ connectors::Ebanx,
+ connectors::Elavon,
+ connectors::Envoy,
+ connectors::Etisalat,
+ connectors::Facilitapay,
+ connectors::Finix,
+ connectors::Fiserv,
+ connectors::Fiservcommercehub,
+ connectors::Fiservemea,
+ connectors::Fiuu,
+ connectors::Flexiti,
+ connectors::Forte,
+ connectors::Getnet,
+ connectors::Gigadat,
+ connectors::Givepayments,
+ connectors::Globalpay,
+ connectors::Globepay,
+ connectors::Gocardless,
+ connectors::GotymeSanlam,
+ connectors::Gpayments,
+ connectors::Hipay,
+ connectors::Hyperpg,
+ connectors::Helcim,
+ connectors::HyperswitchVault,
+ connectors::Hyperwallet,
+ connectors::Iatapay,
+ connectors::Ilixium,
+ connectors::Imerchantsolutions,
+ connectors::Inespay,
+ connectors::Interpayments,
+ connectors::Itaubank,
+ connectors::Jpmorgan,
+ connectors::Juspaythreedsserver,
+ connectors::Katapult,
+ connectors::Klarna,
+ connectors::Loonio,
+ connectors::Merchante,
+ connectors::Netcetera,
+ connectors::Nmi,
+ connectors::Nomupay,
+ connectors::Noon,
+ connectors::Nordea,
+ connectors::Novalnet,
+ connectors::Nexinets,
+ connectors::Nexixpay,
+ connectors::Payconex,
+ connectors::Citigate,
+ connectors::Worldpayraft,
+ connectors::Opayo,
+ connectors::Opennode,
+ connectors::Nuvei,
+ connectors::Paybox,
+ connectors::Payeezy,
+ connectors::Payjustnow,
+ connectors::Payjustnowinstore,
+ connectors::Payload,
+ connectors::Payme,
+ connectors::Payone,
+ connectors::Paypal,
+ connectors::Paysafe,
+ connectors::Paystack,
+ connectors::Paytm,
+ connectors::Payu,
+ connectors::Peachpayments,
+ connectors::Phonepe,
+ connectors::Placetopay,
+ connectors::Plaid,
+ connectors::Powertranz,
+ connectors::Prophetpay,
+ connectors::Mifinity,
+ connectors::Mollie,
+ connectors::Moneris,
+ connectors::Mpgs,
+ connectors::Multisafepay,
+ connectors::Rapyd,
+ connectors::Razorpay,
+ connectors::Recurly,
+ connectors::Redsys,
+ connectors::Revolv3,
+ connectors::Riskified,
+ connectors::TsysTransit,
+ connectors::Santander,
+ connectors::Shift4,
+ connectors::Sift,
+ connectors::Silverflow,
+ connectors::Signifyd,
+ connectors::Stax,
+ connectors::Square,
+ connectors::Stripe,
+ connectors::Stripebilling,
+ connectors::Taxjar,
+ connectors::Tesouro,
+ connectors::Threedsecureio,
+ connectors::Thunes,
+ connectors::Tokenex,
+ connectors::Tokenio,
+ connectors::Truelayer,
+ connectors::Trustly,
+ connectors::Trustpay,
+ connectors::Trustpayments,
+ connectors::Tsys,
+ connectors::UnifiedAuthenticationService,
+ connectors::Wise,
+ connectors::Worldline,
+ connectors::Worldpay,
+ connectors::Worldpaymodular,
+ connectors::Worldpayvantiv,
+ connectors::Worldpayxml,
+ connectors::Wellsfargo,
+ connectors::Wellsfargopayout,
+ connectors::Volt,
+ connectors::Xendit,
+ connectors::Zift,
+ connectors::Zen,
+ connectors::Zsl,
+ connectors::CtpMastercard
+);
+
#[cfg(feature = "frm")]
macro_rules! default_imp_for_frm_transaction {
($($path:ident::$connector:ident),*) => {
@@ -8502,7 +8679,7 @@ macro_rules! default_imp_for_fraud_check {
($($path:ident::$connector:ident),*) => {
$(
impl FraudCheck for $path::$connector {}
- )*
+ )*
};
}
#[cfg(feature = "frm")]
@@ -11914,6 +12091,14 @@ impl<const T: u8> ConnectorIntegration<Reject, PaymentsRejectData, PaymentsRespo
#[cfg(all(feature = "frm", feature = "dummy_connector"))]
impl<const T: u8> FraudCheck for connectors::DummyConnector<T> {}
+#[cfg(all(feature = "frm", feature = "dummy_connector"))]
+impl<const T: u8> FraudCheckPayout for connectors::DummyConnector<T> {}
+#[cfg(all(feature = "frm", feature = "dummy_connector"))]
+impl<const T: u8> ConnectorIntegration<PoFrm, FraudCheckPayoutData, FraudCheckResponseData>
+ for connectors::DummyConnector<T>
+{
+}
+
#[cfg(all(feature = "frm", feature = "dummy_connector"))]
impl<const T: u8> FraudCheckSale for connectors::DummyConnector<T> {}
#[cfg(all(feature = "frm", feature = "dummy_connector"))]
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index 0307c0ad3d..e7e073ba7f 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -85,10 +85,12 @@ use hyperswitch_domain_models::{
#[cfg(feature = "frm")]
use hyperswitch_domain_models::{
router_data_v2::FrmFlowData,
- router_flow_types::fraud_check::{Checkout, Fulfillment, RecordReturn, Sale, Transaction},
+ router_flow_types::fraud_check::{
+ Checkout, Fulfillment, PoFrm, RecordReturn, Sale, Transaction,
+ },
router_request_types::fraud_check::{
- FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData,
- FraudCheckSaleData, FraudCheckTransactionData,
+ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckPayoutData,
+ FraudCheckRecordReturnData, FraudCheckSaleData, FraudCheckTransactionData,
},
router_response_types::fraud_check::FraudCheckResponseData,
};
@@ -104,8 +106,8 @@ use hyperswitch_domain_models::{
};
#[cfg(feature = "frm")]
use hyperswitch_interfaces::api::fraud_check_v2::{
- FraudCheckCheckoutV2, FraudCheckFulfillmentV2, FraudCheckRecordReturnV2, FraudCheckSaleV2,
- FraudCheckTransactionV2, FraudCheckV2,
+ FraudCheckCheckoutV2, FraudCheckFulfillmentV2, FraudCheckPayoutV2, FraudCheckRecordReturnV2,
+ FraudCheckSaleV2, FraudCheckTransactionV2, FraudCheckV2,
};
#[cfg(feature = "payouts")]
use hyperswitch_interfaces::api::payouts_v2::{
@@ -4742,6 +4744,154 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Zsl
);
+#[cfg(feature = "frm")]
+macro_rules! default_imp_for_new_connector_integration_frm_payout {
+ ($($path:ident::$connector:ident),*) => {
+ $(
+ impl FraudCheckPayoutV2 for $path::$connector {}
+ impl
+ ConnectorIntegrationV2<
+ PoFrm,
+ FrmFlowData,
+ FraudCheckPayoutData,
+ FraudCheckResponseData,
+ > for $path::$connector
+ {}
+ )*
+ };
+}
+
+#[cfg(feature = "frm")]
+default_imp_for_new_connector_integration_frm_payout!(
+ connectors::AbsaSanlam,
+ connectors::Imerchantsolutions,
+ connectors::Ilixium,
+ connectors::Loonio,
+ connectors::Merchante,
+ connectors::Gigadat,
+ connectors::Givepayments,
+ connectors::Affirm,
+ connectors::Paytm,
+ connectors::Airwallex,
+ connectors::Amazonpay,
+ connectors::Authipay,
+ connectors::Bambora,
+ connectors::Bamboraapac,
+ connectors::Barclaycard,
+ connectors::Billwerk,
+ connectors::Bitpay,
+ connectors::Blackhawknetwork,
+ connectors::Calida,
+ connectors::Bluesnap,
+ connectors::Boku,
+ connectors::Breadpay,
+ connectors::Cashtocode,
+ connectors::Celero,
+ connectors::Checkbook,
+ connectors::Coinbase,
+ connectors::Cryptopay,
+ connectors::CtpMastercard,
+ connectors::Custombilling,
+ connectors::Cybersourcedecisionmanager,
+ connectors::Datatrans,
+ connectors::Deutschebank,
+ connectors::Digitalvirgo,
+ connectors::Dlocal,
+ connectors::Dwolla,
+ connectors::Ebanx,
+ connectors::Elavon,
+ connectors::Envoy,
+ connectors::Etisalat,
+ connectors::Facilitapay,
+ connectors::Finix,
+ connectors::Fiserv,
+ connectors::Fiservcommercehub,
+ connectors::Fiservemea,
+ connectors::Fiuu,
+ connectors::Flexiti,
+ connectors::Forte,
+ connectors::Globepay,
+ connectors::Gocardless,
+ connectors::GotymeSanlam,
+ connectors::Gpayments,
+ connectors::Helcim,
+ connectors::Hipay,
+ connectors::Hyperpg,
+ connectors::HyperswitchVault,
+ connectors::Hyperwallet,
+ connectors::Inespay,
+ connectors::Interpayments,
+ connectors::Jpmorgan,
+ connectors::Juspaythreedsserver,
+ connectors::Katapult,
+ connectors::Mpgs,
+ connectors::Mollie,
+ connectors::Multisafepay,
+ connectors::Netcetera,
+ connectors::Nexinets,
+ connectors::Nexixpay,
+ connectors::Payconex,
+ connectors::Citigate,
+ connectors::Worldpayraft,
+ connectors::Nmi,
+ connectors::Nomupay,
+ connectors::Nordea,
+ connectors::Novalnet,
+ connectors::Paybox,
+ connectors::Payeezy,
+ connectors::Payjustnow,
+ connectors::Payjustnowinstore,
+ connectors::Payload,
+ connectors::Payone,
+ connectors::Paysafe,
+ connectors::Payu,
+ connectors::Peachpayments,
+ connectors::Phonepe,
+ connectors::Placetopay,
+ connectors::Plaid,
+ connectors::Powertranz,
+ connectors::Prophetpay,
+ connectors::Rapyd,
+ connectors::Razorpay,
+ connectors::Recurly,
+ connectors::Redsys,
+ connectors::Revolv3,
+ connectors::TsysTransit,
+ connectors::Riskified,
+ connectors::SanlamPayshield,
+ connectors::Santander,
+ connectors::Shift4,
+ connectors::Sift,
+ connectors::Silverflow,
+ connectors::Signifyd,
+ connectors::Stax,
+ connectors::Stripe,
+ connectors::Square,
+ connectors::Taxjar,
+ connectors::Tesouro,
+ connectors::Threedsecureio,
+ connectors::Thunes,
+ connectors::Tokenex,
+ connectors::Tokenio,
+ connectors::Truelayer,
+ connectors::Trustly,
+ connectors::Trustpayments,
+ connectors::Tsys,
+ connectors::UnifiedAuthenticationService,
+ connectors::Vgs,
+ connectors::Volt,
+ connectors::Wise,
+ connectors::Worldline,
+ connectors::Worldpay,
+ connectors::Worldpaymodular,
+ connectors::Worldpayvantiv,
+ connectors::Worldpayxml,
+ connectors::Xendit,
+ connectors::Zift,
+ connectors::Zen,
+ connectors::Zsl
+);
+
#[cfg(feature = "frm")]
macro_rules! default_imp_for_new_connector_integration_frm {
($($path:ident::$connector:ident),*) => {
diff --git a/crates/hyperswitch_connectors/src/types.rs b/crates/hyperswitch_connectors/src/types.rs
index fc557e1f1e..5c2cd32b8f 100644
--- a/crates/hyperswitch_connectors/src/types.rs
+++ b/crates/hyperswitch_connectors/src/types.rs
@@ -34,10 +34,10 @@ use hyperswitch_domain_models::{
};
#[cfg(feature = "frm")]
use hyperswitch_domain_models::{
- router_flow_types::{Checkout, Fulfillment, RecordReturn, Sale, Transaction},
+ router_flow_types::{Checkout, Fulfillment, PoFrm, RecordReturn, Sale, Transaction},
router_request_types::fraud_check::{
- FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData,
- FraudCheckSaleData, FraudCheckTransactionData,
+ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckPayoutData,
+ FraudCheckRecordReturnData, FraudCheckSaleData, FraudCheckTransactionData,
},
router_response_types::fraud_check::FraudCheckResponseData,
};
@@ -116,6 +116,11 @@ pub(crate) type FrmFulfillmentType =
#[cfg(feature = "frm")]
pub(crate) type FrmCheckoutRouterData =
RouterData<Checkout, FraudCheckCheckoutData, FraudCheckResponseData>;
+#[cfg(feature = "frm")]
+pub(crate) type PoFrmType =
+ dyn ConnectorIntegration<PoFrm, FraudCheckPayoutData, FraudCheckResponseData>;
+#[cfg(feature = "frm")]
+pub type PoFrmRouterData = RouterData<PoFrm, FraudCheckPayoutData, FraudCheckResponseData>;
#[cfg(feature = "v2")]
pub(crate) struct ResponseRouterDataV2<Flow, R, ResourceCommonData, Request, Response> {
pub response: R,
diff --git a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
index efdef3503b..884e64649c 100644
--- a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
+++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
@@ -85,6 +85,8 @@ pub enum ApiErrorResponse {
DuplicatePayout {
payout_id: common_utils::id_type::PayoutId,
},
+ #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The fraud check with the specified frm_id '{frm_id}' already exists in our records")]
+ DuplicateFraudCheck { frm_id: String },
#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The config with the specified key already exists in our records")]
DuplicateConfig,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Refund does not exist in our records")]
@@ -97,6 +99,8 @@ pub enum ApiErrorResponse {
ConfigNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment does not exist in our records")]
PaymentNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Fraud check does not exist in our records")]
+ FraudCheckNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment method does not exist in our records")]
PaymentMethodNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Merchant account does not exist in our records")]
@@ -433,6 +437,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon
Self::DuplicatePayout { payout_id } => {
AER::BadRequest(ApiError::new("HE", 1, format!("The payout with the specified payout_id '{payout_id:?}' already exists in our records"), None))
}
+ Self::DuplicateFraudCheck { frm_id } => {
+ AER::BadRequest(ApiError::new("HE", 1, format!("The fraud check with the specified frm_id '{frm_id}' already exists in our records"), None))
+ }
Self::DuplicateConfig => {
AER::BadRequest(ApiError::new("HE", 1, "The config with the specified key already exists in our records", None))
}
@@ -451,6 +458,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon
Self::PaymentNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Payment does not exist in our records", None))
}
+ Self::FraudCheckNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Fraud check does not exist in our records", None))
+ }
Self::PaymentMethodNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Payment method does not exist in our records", None))
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index cb4dce8aaf..89f17dafc5 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -828,6 +828,8 @@ pub struct PaymentAttempt {
pub applied_offer_details: Option<common_types::payments::AppliedOfferDetails>,
/// Payment Account Reference (PAR) returned by the connector for the underlying card
pub payment_account_reference: Option<String>,
+ /// Active fraud-check record associated with this payment attempt.
+ pub active_frm_id: Option<String>,
}
impl PaymentAttempt {
@@ -998,6 +1000,7 @@ impl PaymentAttempt {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
})
}
@@ -1095,6 +1098,7 @@ impl PaymentAttempt {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
})
}
@@ -1199,6 +1203,7 @@ impl PaymentAttempt {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
})
}
@@ -1331,6 +1336,7 @@ impl PaymentAttempt {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
})
}
@@ -1458,6 +1464,8 @@ pub struct PaymentAttempt {
pub payment_account_reference: Option<String>,
/// Sender payment instrument ID
pub sender_payment_instrument_id: Option<String>,
+ /// Fraud-check id currently associated with this attempt.
+ pub active_frm_id: Option<String>,
}
#[cfg(feature = "v1")]
@@ -2087,6 +2095,7 @@ pub enum PaymentAttemptUpdate {
request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
external_surcharge_details: Option<common_types::payments::ExternalSurchargeDetails>,
applied_offer_details: Option<common_types::payments::AppliedOfferDetails>,
+ active_frm_id: Option<String>,
},
RejectUpdate {
status: storage_enums::AttemptStatus,
@@ -2266,6 +2275,7 @@ pub enum PaymentAttemptUpdate {
error_reason: Option<String>,
updated_by: String,
connector_mandate_detail: Option<ConnectorMandateReferenceId>,
+ active_frm_id: Option<String>,
},
ExternalSurchargeUpdate {
external_surcharge_details: common_types::payments::ExternalSurchargeDetails,
@@ -2435,6 +2445,7 @@ impl PaymentAttemptUpdate {
request_extended_authorization,
external_surcharge_details,
applied_offer_details,
+ active_frm_id,
} => DieselPaymentAttemptUpdate::ConfirmUpdate {
amount: net_amount.get_order_amount(),
currency,
@@ -2488,6 +2499,7 @@ impl PaymentAttemptUpdate {
request_extended_authorization,
external_surcharge_details,
applied_offer_details,
+ active_frm_id,
},
Self::VoidUpdate {
status,
@@ -2861,6 +2873,7 @@ impl PaymentAttemptUpdate {
error_reason,
updated_by,
connector_mandate_detail,
+ active_frm_id,
} => DieselPaymentAttemptUpdate::RecurrenceUpdate {
status,
error_code,
@@ -2868,6 +2881,7 @@ impl PaymentAttemptUpdate {
error_reason,
updated_by,
connector_mandate_detail,
+ active_frm_id,
},
Self::ExternalSurchargeUpdate {
external_surcharge_details,
@@ -3120,6 +3134,7 @@ impl behaviour::Conversion for PaymentAttempt {
applied_offer_details: self.applied_offer_details,
payment_account_reference: self.payment_account_reference,
sender_payment_instrument_id: self.sender_payment_instrument_id,
+ active_frm_id: self.active_frm_id,
})
}
@@ -3265,6 +3280,7 @@ impl behaviour::Conversion for PaymentAttempt {
applied_offer_details: storage_model.applied_offer_details,
payment_account_reference: storage_model.payment_account_reference,
sender_payment_instrument_id: storage_model.sender_payment_instrument_id,
+ active_frm_id: storage_model.active_frm_id,
})
}
.await
@@ -3366,6 +3382,7 @@ impl behaviour::Conversion for PaymentAttempt {
applied_offer_details: self.applied_offer_details,
payment_account_reference: self.payment_account_reference,
sender_payment_instrument_id: self.sender_payment_instrument_id,
+ active_frm_id: self.active_frm_id,
})
}
}
diff --git a/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
index 4c4d2f870f..b0283acf90 100644
--- a/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
@@ -114,6 +114,7 @@ pub struct PayoutAttempt {
pub additional_source_bank_data: Option<payout_method_utils::BankAdditionalData>,
pub connector_eligibility_reference_id: Option<String>,
pub connector_request_reference_id: Option<String>,
+ pub active_frm_id: Option<String>,
}
impl PayoutAttempt {
@@ -171,6 +172,7 @@ pub struct PayoutAttemptNew {
pub additional_source_bank_data: Option<payout_method_utils::BankAdditionalData>,
pub connector_eligibility_reference_id: Option<String>,
pub connector_request_reference_id: Option<String>,
+ pub active_frm_id: Option<String>,
}
#[derive(Debug, Clone)]
@@ -181,11 +183,11 @@ pub enum PayoutAttemptUpdate {
error_message: Option<String>,
error_code: Option<String>,
is_eligible: Option<bool>,
-
unified_code: Option<UnifiedCode>,
unified_message: Option<UnifiedMessage>,
payout_connector_metadata: Option<pii::SecretSerdeValue>,
connector_eligibility_reference_id: Option<String>,
+ active_frm_id: Option<String>,
},
PayoutTokenUpdate {
payout_token: String,
@@ -201,6 +203,7 @@ pub enum PayoutAttemptUpdate {
routing_info: Option<serde_json::Value>,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
connector_request_reference_id: String,
+ active_frm_id: Option<String>,
},
AdditionalPayoutDataUpdate {
additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>,
@@ -240,6 +243,7 @@ pub struct PayoutAttemptUpdateInternal {
pub source_bank_data_token: Option<String>,
pub additional_source_bank_data: Option<payout_method_utils::BankAdditionalData>,
pub connector_eligibility_reference_id: Option<String>,
+ pub active_frm_id: Option<String>,
}
impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal {
@@ -259,6 +263,7 @@ impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal {
unified_message,
payout_connector_metadata,
connector_eligibility_reference_id,
+ active_frm_id,
} => Self {
connector_payout_id,
status: Some(status),
@@ -269,6 +274,7 @@ impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal {
unified_message,
payout_connector_metadata,
connector_eligibility_reference_id,
+ active_frm_id,
..Default::default()
},
PayoutAttemptUpdate::BusinessUpdate {
@@ -288,11 +294,13 @@ impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal {
routing_info,
merchant_connector_id,
connector_request_reference_id,
+ active_frm_id,
} => Self {
connector: Some(connector),
routing_info,
merchant_connector_id,
connector_request_reference_id: Some(connector_request_reference_id),
+ active_frm_id,
..Default::default()
},
PayoutAttemptUpdate::AdditionalPayoutDataUpdate {
diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/fraud_check.rs b/crates/hyperswitch_domain_models/src/router_flow_types/fraud_check.rs
index a7642ea7e4..381d0ffef6 100644
--- a/crates/hyperswitch_domain_models/src/router_flow_types/fraud_check.rs
+++ b/crates/hyperswitch_domain_models/src/router_flow_types/fraud_check.rs
@@ -12,3 +12,6 @@ pub struct Fulfillment;
#[derive(Debug, Clone)]
pub struct RecordReturn;
+
+#[derive(Debug, Clone)]
+pub struct PoFrm;
diff --git a/crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs b/crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs
index 096504c56c..d41e108476 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs
@@ -40,6 +40,14 @@ pub struct FraudCheckCheckoutData {
pub phone_country_code: Option<String>,
}
+#[derive(Debug, Clone)]
+pub struct FraudCheckPayoutData {
+ pub amount: MinorUnit,
+ pub currency: common_enums::Currency,
+ pub gateway: Option<String>,
+ pub gateway_metadata: Option<common_utils::pii::SecretSerdeValue>,
+}
+
#[derive(Debug, Clone)]
pub struct FraudCheckTransactionData {
pub amount: i64,
diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs
index 22f8caa813..c83b404cb7 100644
--- a/crates/hyperswitch_interfaces/src/api.rs
+++ b/crates/hyperswitch_interfaces/src/api.rs
@@ -543,16 +543,26 @@ pub trait ConnectorSpecifications {
ConnectorCustomerAction::NoAction
}
- /// Gateway specific metadata required for FRM requests.
+ /// Gateway specific metadata required for payment FRM requests.
/// Connectors should override this method if they need to send connector specific metadata as part of the FRM request.
#[cfg(feature = "frm")]
- fn get_frm_metadata(
+ fn get_payment_frm_metadata(
&self,
_payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> CustomResult<Option<common_utils::pii::SecretSerdeValue>, errors::ConnectorError> {
Ok(None)
}
+ /// Gateway specific metadata required for payout FRM requests.
+ /// Connectors should override this method if they need to send connector specific metadata as part of the FRM request.
+ #[cfg(feature = "frm")]
+ fn get_payout_frm_metadata(
+ &self,
+ _payout_attempt: &hyperswitch_domain_models::payouts::payout_attempt::PayoutAttempt,
+ ) -> CustomResult<Option<common_utils::pii::SecretSerdeValue>, errors::ConnectorError> {
+ Ok(None)
+ }
+
/// Validate if another operation is required
fn is_payment_recurrence_operation_needed(
&self,
diff --git a/crates/hyperswitch_interfaces/src/api/fraud_check.rs b/crates/hyperswitch_interfaces/src/api/fraud_check.rs
index d95a05b108..422fde404a 100644
--- a/crates/hyperswitch_interfaces/src/api/fraud_check.rs
+++ b/crates/hyperswitch_interfaces/src/api/fraud_check.rs
@@ -1,9 +1,9 @@
//! FRM interface
use hyperswitch_domain_models::{
- router_flow_types::{Checkout, Fulfillment, RecordReturn, Sale, Transaction},
+ router_flow_types::{Checkout, Fulfillment, PoFrm, RecordReturn, Sale, Transaction},
router_request_types::fraud_check::{
- FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData,
- FraudCheckSaleData, FraudCheckTransactionData,
+ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckPayoutData,
+ FraudCheckRecordReturnData, FraudCheckSaleData, FraudCheckTransactionData,
},
router_response_types::fraud_check::FraudCheckResponseData,
};
@@ -40,6 +40,12 @@ pub trait FraudCheckRecordReturn:
{
}
+/// Trait for payout fraud checks.
+pub trait FraudCheckPayout:
+ ConnectorIntegration<PoFrm, FraudCheckPayoutData, FraudCheckResponseData>
+{
+}
+
/// trait FraudCheck
pub trait FraudCheck:
super::ConnectorCommon
@@ -48,5 +54,6 @@ pub trait FraudCheck:
+ FraudCheckCheckout
+ FraudCheckFulfillment
+ FraudCheckRecordReturn
+ + FraudCheckPayout
{
}
diff --git a/crates/hyperswitch_interfaces/src/api/fraud_check_v2.rs b/crates/hyperswitch_interfaces/src/api/fraud_check_v2.rs
index 1baf725212..3c96795685 100644
--- a/crates/hyperswitch_interfaces/src/api/fraud_check_v2.rs
+++ b/crates/hyperswitch_interfaces/src/api/fraud_check_v2.rs
@@ -1,10 +1,10 @@
//! FRM V2 interface
use hyperswitch_domain_models::{
router_data_v2::flow_common_types::FrmFlowData,
- router_flow_types::{Checkout, Fulfillment, RecordReturn, Sale, Transaction},
+ router_flow_types::{Checkout, Fulfillment, PoFrm, RecordReturn, Sale, Transaction},
router_request_types::fraud_check::{
- FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData,
- FraudCheckSaleData, FraudCheckTransactionData,
+ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckPayoutData,
+ FraudCheckRecordReturnData, FraudCheckSaleData, FraudCheckTransactionData,
},
router_response_types::fraud_check::FraudCheckResponseData,
};
@@ -46,6 +46,12 @@ pub trait FraudCheckRecordReturnV2:
{
}
+/// Trait for payout fraud checks.
+pub trait FraudCheckPayoutV2:
+ ConnectorIntegrationV2<PoFrm, FrmFlowData, FraudCheckPayoutData, FraudCheckResponseData>
+{
+}
+
/// trait FraudCheckV2
pub trait FraudCheckV2:
super::ConnectorCommon
@@ -54,5 +60,6 @@ pub trait FraudCheckV2:
+ FraudCheckCheckoutV2
+ FraudCheckFulfillmentV2
+ FraudCheckRecordReturnV2
+ + FraudCheckPayoutV2
{
}
diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs
index 41e913d2c2..e02858a8e9 100644
--- a/crates/hyperswitch_interfaces/src/configs.rs
+++ b/crates/hyperswitch_interfaces/src/configs.rs
@@ -221,4 +221,11 @@ impl MerchantConnectorAccountType {
Self::CacheVal(_) => Ok(None),
}
}
+
+ pub fn get_frm_configs(&self) -> Option<Vec<Secret<serde_json::Value>>> {
+ match self {
+ Self::DbVal(val) => val.frm_configs.clone(),
+ Self::CacheVal(_) => None,
+ }
+ }
}
diff --git a/crates/hyperswitch_interfaces/src/connector_integration_interface.rs b/crates/hyperswitch_interfaces/src/connector_integration_interface.rs
index 03fad67173..1974f329d8 100644
--- a/crates/hyperswitch_interfaces/src/connector_integration_interface.rs
+++ b/crates/hyperswitch_interfaces/src/connector_integration_interface.rs
@@ -841,13 +841,24 @@ impl ConnectorSpecifications for ConnectorEnum {
}
#[cfg(feature = "frm")]
- fn get_frm_metadata(
+ fn get_payment_frm_metadata(
&self,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> CustomResult<Option<common_utils::pii::SecretSerdeValue>, errors::ConnectorError> {
match self {
- Self::Old(connector) => connector.get_frm_metadata(payment_attempt),
- Self::New(connector) => connector.get_frm_metadata(payment_attempt),
+ Self::Old(connector) => connector.get_payment_frm_metadata(payment_attempt),
+ Self::New(connector) => connector.get_payment_frm_metadata(payment_attempt),
+ }
+ }
+
+ #[cfg(feature = "frm")]
+ fn get_payout_frm_metadata(
+ &self,
+ payout_attempt: &hyperswitch_domain_models::payouts::payout_attempt::PayoutAttempt,
+ ) -> CustomResult<Option<common_utils::pii::SecretSerdeValue>, errors::ConnectorError> {
+ match self {
+ Self::Old(connector) => connector.get_payout_frm_metadata(payout_attempt),
+ Self::New(connector) => connector.get_payout_frm_metadata(payout_attempt),
}
}
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs
index 4ece22d204..66b9d577f5 100644
--- a/crates/router/src/compatibility/stripe/errors.rs
+++ b/crates/router/src/compatibility/stripe/errors.rs
@@ -102,6 +102,9 @@ pub enum StripeErrorCode {
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payment")]
PaymentNotFound,
+ #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such fraud check")]
+ FraudCheckNotFound,
+
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payment method")]
PaymentMethodNotFound,
@@ -138,6 +141,9 @@ pub enum StripeErrorCode {
#[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "Duplicate payout request")]
DuplicatePayout { payout_id: id_type::PayoutId },
+ #[error(error_type = StripeErrorType::InvalidRequestError, code = "duplicate_resource", message = "The fraud check with the specified frm_id '{frm_id}' already exists in our records")]
+ DuplicateFraudCheck { frm_id: String },
+
#[error(error_type = StripeErrorType::InvalidRequestError, code = "parameter_missing", message = "Return url is not available")]
ReturnUrlUnavailable,
@@ -551,9 +557,13 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {
errors::ApiErrorResponse::DuplicatePayout { payout_id } => {
Self::DuplicatePayout { payout_id }
}
+ errors::ApiErrorResponse::DuplicateFraudCheck { frm_id } => {
+ Self::DuplicateFraudCheck { frm_id }
+ }
errors::ApiErrorResponse::RefundNotFound => Self::RefundNotFound,
errors::ApiErrorResponse::CustomerNotFound => Self::CustomerNotFound,
errors::ApiErrorResponse::PaymentNotFound => Self::PaymentNotFound,
+ errors::ApiErrorResponse::FraudCheckNotFound => Self::FraudCheckNotFound,
errors::ApiErrorResponse::PaymentMethodNotFound => Self::PaymentMethodNotFound,
errors::ApiErrorResponse::ClientSecretNotGiven
| errors::ApiErrorResponse::ClientSecretExpired => Self::ClientSecretNotFound,
@@ -742,12 +752,14 @@ impl actix_web::ResponseError for StripeErrorCode {
| Self::InvalidCardType
| Self::DuplicateRefundRequest
| Self::DuplicatePayout { .. }
+ | Self::DuplicateFraudCheck { .. }
| Self::RefundNotFound
| Self::CustomerNotFound
| Self::ConfigNotFound
| Self::DuplicateConfig
| Self::ClientSecretNotFound
| Self::PaymentNotFound
+ | Self::FraudCheckNotFound
| Self::PaymentMethodNotFound
| Self::MerchantAccountNotFound
| Self::MerchantConnectorAccountNotFound { .. }
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index fa8abe6243..5265d3ef9d 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -529,6 +529,8 @@ pub mod superposition {
pub const CHECKOUT_SDK: &str = "checkout_sdk";
/// Pre-FRM failure handling mode
pub const PRE_FRM_FAILURE_MODE: &str = "frm.pre_frm_failure_mode";
+ /// Payout FRM call configuration key
+ pub const PAYOUT_FRM_CALL: &str = "payouts.payout_frm_call";
}
/// The value substituted for sensitive webhook header values in event retrieval responses.
diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rs
index 188f60660e..3ca35863e1 100644
--- a/crates/router/src/core/configs/dimension_config.rs
+++ b/crates/router/src/core/configs/dimension_config.rs
@@ -1029,3 +1029,21 @@ impl DatabaseBackedConfig for PreFrmFailureMode {
.map(|id| format!("{}_{}", Self::KEY, id.get_string_repr()))
}
}
+
+config! {
+ superposition_key = PAYOUT_FRM_CALL,
+ output = bool,
+ default = false,
+ requires = dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,
+ targeting_key = id_type::ProfileId
+}
+
+impl DatabaseBackedConfig for PayoutFrmCall {
+ const KEY: &'static str = "payout_frm_call";
+
+ fn db_key(dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {
+ dimensions
+ .get_profile_id()
+ .map(|id| format!("{}_{}", Self::KEY, id.get_string_repr()))
+ }
+}
diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs
index 6f43fc7f09..b8d138ed1c 100644
--- a/crates/router/src/core/fraud_check.rs
+++ b/crates/router/src/core/fraud_check.rs
@@ -1,9 +1,11 @@
+#[cfg(feature = "payouts")]
+use std::collections::HashSet;
use std::fmt::Debug;
use api_models::{self, enums as api_enums};
-use common_enums::{CaptureMethod, PreFrmFailureMode};
+use common_enums::{CaptureMethod, PaymentMethod, PreFrmFailureMode};
use error_stack::ResultExt;
-use hyperswitch_masking::PeekInterface;
+use hyperswitch_masking::{ExposeInterface, PeekInterface};
use router_env::{
logger,
tracing::{self, instrument},
@@ -13,15 +15,19 @@ use self::{
flows::{self as frm_flows, FeatureFrm},
types::{
self as frm_core_types, ConnectorDetailsCore, FrmConfigsObject, FrmData, FrmInfo,
- PaymentDetails, PaymentToFrmData,
+ PaymentDetails, PaymentToFrmData, PayoutFrmApplicability, PayoutFrmOutcome,
},
};
-use super::errors::{ConnectorErrorExt, RouterResponse};
+use super::errors::{ConnectorErrorExt, RouterResponse, StorageErrorExt};
use crate::{
core::{
configs::dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,
errors::{self, RouterResult},
- payments::{self, flows::ConstructFlowSpecificData, operations::BoxedOperation},
+ payments::{
+ self, flows::ConstructFlowSpecificData, helpers::get_merchant_connector_account,
+ operations::BoxedOperation,
+ },
+ payouts::PayoutData,
},
db::StorageInterface,
routes::{app::ReqState, metrics, SessionState},
@@ -29,7 +35,7 @@ use crate::{
types::{
self as oss_types,
api::{
- fraud_check as frm_api, routing::FrmRoutingAlgorithm, Connector,
+ fraud_check as frm_api, routing::FrmRoutingAlgorithm, Connector, ConnectorData,
FraudCheckConnectorData, Fulfillment,
},
domain, fraud_check as frm_types,
@@ -39,8 +45,9 @@ use crate::{
IntentStatus,
},
fraud_check::{FraudCheck, FraudCheckUpdate},
- PaymentIntent,
+ PaymentAttempt, PaymentIntent,
},
+ transformers::ForeignFrom,
},
utils::ValueExt,
};
@@ -165,6 +172,171 @@ where
Ok(router_data_res)
}
+#[cfg(all(feature = "payouts", feature = "v1"))]
+pub async fn get_frm_merchant_connector_account_and_routing_algorithm(
+ state: &SessionState,
+ platform: &domain::Platform,
+ payout_data: &PayoutData,
+) -> RouterResult<
+ Option<(
+ payments::helpers::MerchantConnectorAccountType,
+ FrmRoutingAlgorithm,
+ )>,
+> {
+ match &platform.get_processor().get_account().frm_routing_algorithm {
+ Some(frm_routing_algorithm_value) => {
+ let frm_routing_algorithm: FrmRoutingAlgorithm = frm_routing_algorithm_value
+ .to_owned()
+ .parse_value("FrmRoutingAlgorithm")
+ .change_context(errors::ApiErrorResponse::InvalidDataFormat {
+ field_name: "frm_routing_algorithm".into(),
+ expected_format: r#"{ "type": "single", "data": "signifyd" }"#.to_string(),
+ })?;
+
+ let mca = get_merchant_connector_account(
+ state,
+ platform.get_processor(),
+ None,
+ &payout_data.profile_id,
+ &frm_routing_algorithm.data,
+ None,
+ )
+ .await?;
+
+ Ok(Some((mca, frm_routing_algorithm)))
+ }
+ None => Ok(None),
+ }
+}
+
+#[cfg(all(feature = "payouts", feature = "v1"))]
+pub async fn get_payout_frm_applicability(
+ payout_data: &PayoutData,
+ frm_merchant_connector_account: payments::helpers::MerchantConnectorAccountType,
+ frm_routing_algorithm: FrmRoutingAlgorithm,
+) -> RouterResult<Option<PayoutFrmApplicability>> {
+ if !frm_merchant_connector_account.is_disabled() {
+ let frm_configs_value = frm_merchant_connector_account.get_frm_configs().ok_or(
+ errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "frm_configs".into(),
+ },
+ )?;
+
+ let payment_method = payout_data
+ .payouts
+ .payout_type
+ .map(PaymentMethod::foreign_from);
+
+ // Parse the frm_configs JSON value into a Vec<FrmConfigs>
+ let frm_configs = frm_configs_value
+ .into_iter()
+ .map(|config| {
+ config
+ .expose()
+ .parse_value::<api_models::admin::FrmConfigs>("FrmConfigs")
+ .change_context(errors::ApiErrorResponse::InvalidDataFormat {
+ field_name: "frm_configs".into(),
+ expected_format: r#"[{ "gateway": "gotyme_sanlam", "payment_methods": [{ "payment_method": "bank_transfer", "flow": "pre" }] }]"#.to_string(),
+ })
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+
+ // HashSet to store unique FRM check required connectors from the frm_configs
+ let mut connectors = HashSet::new();
+
+ // Iterate over the frm_configs and insert the gateways into the connectors HashSet if the payment_method matches
+ for mut config in frm_configs {
+ config.payment_methods.retain(|frm_payment_method| {
+ payment_method.is_some() && frm_payment_method.payment_method == payment_method
+ });
+
+ if !config.payment_methods.is_empty() {
+ if let Some(gateway) = config.gateway {
+ connectors.insert(gateway);
+ }
+ }
+ }
+
+ if connectors.is_empty() {
+ Ok(None)
+ } else {
+ Ok(Some(PayoutFrmApplicability {
+ connectors,
+ frm_merchant_connector_account: Box::new(frm_merchant_connector_account),
+ frm_routing_algorithm,
+ }))
+ }
+ } else {
+ Ok(None)
+ }
+}
+
+#[cfg(all(feature = "payouts", feature = "v1"))]
+pub async fn pre_payouts_frm_core(
+ state: &SessionState,
+ platform: &domain::Platform,
+ payout_data: &mut PayoutData,
+ connector_data: &ConnectorData,
+ applicability: PayoutFrmApplicability,
+ failure_mode: &PreFrmFailureMode,
+) -> RouterResult<PayoutFrmOutcome> {
+ if applicability
+ .connectors
+ .contains(&connector_data.connector_name)
+ {
+ let fraud_check_operation = operation::fraud_check_pre_payout::FraudCheckPrePayout;
+
+ let frm_data = fraud_check_operation
+ .get_tracker(
+ state,
+ payout_data,
+ &applicability.frm_routing_algorithm.data,
+ )
+ .await?;
+
+ payout_data.payout_attempt.active_frm_id = Some(frm_data.fraud_check.frm_id.clone());
+
+ let frm_connector = FraudCheckConnectorData::get_connector_by_name(
+ &applicability.frm_routing_algorithm.data,
+ )?;
+
+ let mut router_data: hyperswitch_connectors::types::PoFrmRouterData = frm_data
+ .construct_router_data(
+ state,
+ &applicability.frm_routing_algorithm.data,
+ platform.get_processor(),
+ &payout_data.business_profile,
+ applicability.frm_merchant_connector_account.as_ref(),
+ None,
+ None,
+ None,
+ None,
+ )
+ .await?;
+
+ router_data = router_data
+ .decide_frm_flows(
+ state,
+ &frm_connector,
+ payments::CallConnectorAction::Trigger,
+ platform,
+ )
+ .await?;
+
+ let frm_data = fraud_check_operation
+ .update_tracker(state, frm_data, router_data)
+ .await?;
+
+ payout_data.fraud_check = Some(frm_data.fraud_check.clone());
+
+ let outcome = frm_data.get_frm_outcome(failure_mode);
+
+ Ok(outcome)
+ } else {
+ Ok(PayoutFrmOutcome::Continue)
+ }
+}
+
#[cfg(feature = "v2")]
pub async fn should_call_frm<F, D>(
_platform: &domain::Platform,
@@ -185,6 +357,41 @@ where
todo!()
}
+#[cfg(all(feature = "payouts", feature = "v2"))]
+pub async fn get_frm_merchant_connector_account_and_routing_algorithm(
+ _state: &SessionState,
+ _platform: &domain::Platform,
+ _payout_data: &PayoutData,
+) -> RouterResult<
+ Option<(
+ payments::helpers::MerchantConnectorAccountType,
+ FrmRoutingAlgorithm,
+ )>,
+> {
+ todo!()
+}
+
+#[cfg(all(feature = "payouts", feature = "v2"))]
+pub async fn get_payout_frm_applicability(
+ _payout_data: &PayoutData,
+ _frm_merchant_connector_account: payments::helpers::MerchantConnectorAccountType,
+ _frm_routing_algorithm: FrmRoutingAlgorithm,
+) -> RouterResult<Option<PayoutFrmApplicability>> {
+ todo!()
+}
+
+#[cfg(all(feature = "payouts", feature = "v2"))]
+pub async fn pre_payouts_frm_core(
+ _state: &SessionState,
+ _platform: &domain::Platform,
+ _payout_data: &mut PayoutData,
+ _connector_data: &ConnectorData,
+ _applicability: PayoutFrmApplicability,
+ _failure_mode: &PreFrmFailureMode,
+) -> RouterResult<PayoutFrmOutcome> {
+ todo!()
+}
+
#[cfg(feature = "v1")]
pub async fn should_call_frm<F, D>(
platform: &domain::Platform,
@@ -201,7 +408,6 @@ where
D: payments::OperationSessionGetters<F> + Send + Sync + Clone,
{
use common_utils::ext_traits::OptionExt;
- use hyperswitch_masking::ExposeInterface;
let db = &*state.store;
match platform
@@ -629,6 +835,10 @@ where
))
.await?;
+ if let Some(frm_data) = updated_frm_info.frm_data.as_ref() {
+ payment_data.set_frm_message(frm_data.fraud_check.clone());
+ }
+
if is_frm_enabled {
Box::pin(pre_payment_frm_core(
state,
@@ -871,15 +1081,25 @@ pub async fn frm_fulfillment_core(
let invalid_request_error = errors::ApiErrorResponse::InvalidRequestData {
message: "no fraud check entry found for this payment_id".to_string(),
};
- let existing_fraud_check = db
- .find_fraud_check_by_payment_id_if_present(
- req.payment_id.clone(),
- platform.get_processor().get_account().get_id().clone(),
+
+ let payment_attempt = db
+ .find_payment_attempt_by_payment_id_processor_merchant_id_attempt_id(
+ &payment_intent.payment_id,
+ platform.get_processor().get_account().get_id(),
+ &payment_intent.active_attempt.get_id(),
+ platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
)
.await
- .change_context(invalid_request_error.to_owned())?;
- match existing_fraud_check {
- Some(fraud_check) => {
+ .change_context(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ match payment_attempt.active_frm_id.clone() {
+ Some(frm_id) => {
+ let fraud_check = db
+ .find_fraud_check_by_frm_id(frm_id)
+ .await
+ .change_context(invalid_request_error.to_owned())?;
+
if (matches!(fraud_check.frm_transaction_type, FraudCheckType::PreFrm)
&& fraud_check.last_step == FraudCheckLastStep::TransactionOrRecordRefund)
|| (matches!(fraud_check.frm_transaction_type, FraudCheckType::PostFrm)
@@ -889,6 +1109,7 @@ pub async fn frm_fulfillment_core(
db,
fraud_check,
payment_intent,
+ payment_attempt,
state,
platform,
req,
@@ -914,20 +1135,11 @@ pub async fn make_fulfillment_api_call(
db: &dyn StorageInterface,
fraud_check: FraudCheck,
payment_intent: PaymentIntent,
+ payment_attempt: PaymentAttempt,
state: SessionState,
platform: domain::Platform,
req: frm_core_types::FrmFulfillmentRequest,
) -> RouterResponse<frm_types::FraudCheckResponseData> {
- let payment_attempt = db
- .find_payment_attempt_by_payment_id_processor_merchant_id_attempt_id(
- &payment_intent.payment_id,
- platform.get_processor().get_account().get_id(),
- &payment_intent.active_attempt.get_id(),
- platform.get_processor().get_account().storage_scheme,
- platform.get_processor().get_key_store(),
- )
- .await
- .change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let connector_data = FraudCheckConnectorData::get_connector_by_name(&fraud_check.frm_name)?;
let connector_integration: services::BoxedFrmConnectorIntegrationInterface<
Fulfillment,
@@ -965,9 +1177,9 @@ pub async fn make_fulfillment_api_call(
payment_capture_method: fraud_check.payment_capture_method,
};
let _updated = db
- .update_fraud_check_response_with_attempt_id(fraud_check_copy, fraud_check_update)
+ .update_fraud_check_response_with_frm_id(fraud_check_copy, fraud_check_update)
.await
- .map_err(|error| error.change_context(errors::ApiErrorResponse::PaymentNotFound))?;
+ .to_not_found_response(errors::ApiErrorResponse::FraudCheckNotFound)?;
let fulfillment_response =
response
.response
diff --git a/crates/router/src/core/fraud_check/flows.rs b/crates/router/src/core/fraud_check/flows.rs
index 4a8b543727..e96b355a3e 100644
--- a/crates/router/src/core/fraud_check/flows.rs
+++ b/crates/router/src/core/fraud_check/flows.rs
@@ -1,5 +1,7 @@
pub mod checkout_flow;
pub mod fulfillment_flow;
+#[cfg(all(feature = "payouts", feature = "v1"))]
+pub mod po_frm_flow;
pub mod record_return;
pub mod sale_flow;
pub mod transaction_flow;
diff --git a/crates/router/src/core/fraud_check/flows/checkout_flow.rs b/crates/router/src/core/fraud_check/flows/checkout_flow.rs
index 3d0e96e80a..35bb25436e 100644
--- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs
@@ -142,7 +142,10 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC
email,
phone,
phone_country_code,
- gateway_metadata: get_gateway_frm_metadata(&state.conf, &self.payment_attempt)?,
+ gateway_metadata: get_gateway_frm_metadata(
+ &state.conf.connectors,
+ &self.payment_attempt,
+ )?,
},
response: Ok(FraudCheckResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId("".to_string()),
diff --git a/crates/router/src/core/fraud_check/flows/po_frm_flow.rs b/crates/router/src/core/fraud_check/flows/po_frm_flow.rs
new file mode 100644
index 0000000000..f5aa1ef648
--- /dev/null
+++ b/crates/router/src/core/fraud_check/flows/po_frm_flow.rs
@@ -0,0 +1,178 @@
+use async_trait::async_trait;
+use common_utils::ext_traits::ValueExt;
+use error_stack::ResultExt;
+use hyperswitch_connectors::types::PoFrmRouterData;
+
+use super::{ConstructFlowSpecificData, FeatureFrm};
+use crate::{
+ core::{
+ errors::{ConnectorErrorExt, RouterResult},
+ fraud_check::types::PayoutFrmData,
+ payments::{self, helpers},
+ utils::get_payout_gateway_frm_metadata,
+ },
+ errors, services,
+ types::{
+ api::fraud_check::{self as frm_api, FraudCheckConnectorData},
+ domain,
+ fraud_check::{FraudCheckPayoutData, FraudCheckResponseData},
+ storage::enums as storage_enums,
+ ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData,
+ },
+ SessionState,
+};
+
+#[async_trait]
+impl ConstructFlowSpecificData<frm_api::PoFrm, FraudCheckPayoutData, FraudCheckResponseData>
+ for PayoutFrmData
+{
+ async fn construct_router_data<'a>(
+ &self,
+ state: &SessionState,
+ connector_id: &str,
+ processor: &domain::Processor,
+ _business_profile: &domain::Profile,
+ merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ _merchant_recipient_data: Option<MerchantRecipientData>,
+ header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ _payment_method: Option<common_enums::PaymentMethod>,
+ _payment_method_type: Option<common_enums::PaymentMethodType>,
+ ) -> RouterResult<RouterData<frm_api::PoFrm, FraudCheckPayoutData, FraudCheckResponseData>>
+ {
+ let connector_auth_type: ConnectorAuthType = merchant_connector_account
+ .get_connector_account_details()
+ .parse_value("ConnectorAuthType")
+ .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ id: "ConnectorAuthType".to_string(),
+ })?;
+
+ let payment_method_type = self.payout_method_data.as_ref().map(From::from).or(self
+ .payout_attempt
+ .additional_payout_method_data
+ .as_ref()
+ .map(From::from));
+
+ let billing_address = self.billing_address.clone();
+ let address = hyperswitch_domain_models::payment_address::PaymentAddress::new(
+ None,
+ billing_address,
+ None,
+ None,
+ );
+
+ Ok(RouterData {
+ flow: std::marker::PhantomData,
+ merchant_id: processor.get_account().get_id().clone(),
+ customer_id: self.customer_details.as_ref().map(|c| c.get_id().clone()),
+ connector_customer: None,
+ connector: connector_id.to_string(),
+ payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("frm")
+ .get_string_repr()
+ .to_owned(),
+ attempt_id: self.payout_attempt.payout_attempt_id.clone(),
+ tenant_id: state.tenant.tenant_id.clone(),
+ status: storage_enums::AttemptStatus::Pending,
+ payment_method: storage_enums::PaymentMethod::default(),
+ payment_method_type,
+ connector_auth_type,
+ description: None,
+ address,
+ auth_type: storage_enums::AuthenticationType::default(),
+ connector_meta_data: None,
+ connector_wallets_details: None,
+ amount_captured: None,
+ access_token: None,
+ session_token: None,
+ reference_id: None,
+ payment_method_token: None,
+ recurring_mandate_payment_data: None,
+ preprocessing_id: None,
+ payment_method_balance: None,
+ connector_api_version: None,
+ request: FraudCheckPayoutData {
+ amount: self.amount,
+ currency: self.currency,
+ gateway: self.payout_attempt.connector.clone(),
+ gateway_metadata: get_payout_gateway_frm_metadata(
+ &state.conf.connectors,
+ &self.payout_attempt,
+ )?,
+ },
+ response: Ok(FraudCheckResponseData::TransactionResponse {
+ resource_id: ResponseId::NoResponseId,
+ status: storage_enums::FraudCheckStatus::Pending,
+ connector_metadata: None,
+ reason: None,
+ score: None,
+ }),
+ connector_request_reference_id: self.fraud_check.frm_id.clone(),
+ payout_method_data: None,
+ quote_id: None,
+ test_mode: merchant_connector_account.is_test_mode_on(),
+ connector_http_status_code: None,
+ external_latency: None,
+ apple_pay_flow: None,
+ frm_metadata: None,
+ dispute_id: None,
+ refund_id: None,
+ payout_id: Some(self.payout_attempt.payout_id.get_string_repr().to_owned()),
+ connector_response: None,
+ payment_method_status: None,
+ minor_amount_captured: None,
+ minor_amount_capturable: None,
+ authorized_amount: None,
+ integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload,
+ connector_mandate_request_reference_id: None,
+ l2_l3_data: None,
+ authentication_id: None,
+ psd2_sca_exemption_type: None,
+ raw_connector_response: None,
+ is_payment_id_from_merchant: None,
+ customer_document_details: None,
+ customer_date_of_birth: None,
+ feature_data: None,
+ sender_payment_instrument_id: None,
+ connector_returned_payment_method_details: None,
+ })
+ }
+}
+
+#[async_trait]
+impl FeatureFrm<frm_api::PoFrm, FraudCheckPayoutData> for PoFrmRouterData {
+ async fn decide_frm_flows<'a>(
+ mut self,
+ state: &SessionState,
+ connector: &FraudCheckConnectorData,
+ call_connector_action: payments::CallConnectorAction,
+ platform: &domain::Platform,
+ ) -> RouterResult<Self> {
+ decide_frm_flow(&mut self, state, connector, call_connector_action, platform).await
+ }
+}
+
+async fn decide_frm_flow(
+ router_data: &mut PoFrmRouterData,
+ state: &SessionState,
+ connector: &FraudCheckConnectorData,
+ call_connector_action: payments::CallConnectorAction,
+ _platform: &domain::Platform,
+) -> RouterResult<PoFrmRouterData> {
+ let connector_integration: services::BoxedFrmConnectorIntegrationInterface<
+ frm_api::PoFrm,
+ FraudCheckPayoutData,
+ FraudCheckResponseData,
+ > = connector.connector.get_connector_integration();
+
+ services::execute_connector_processing_step(
+ state,
+ connector_integration,
+ router_data,
+ call_connector_action,
+ None,
+ None,
+ )
+ .await
+ .to_payment_failed_response()
+}
diff --git a/crates/router/src/core/fraud_check/operation.rs b/crates/router/src/core/fraud_check/operation.rs
index 484eedfd3e..7b76bc99f3 100644
--- a/crates/router/src/core/fraud_check/operation.rs
+++ b/crates/router/src/core/fraud_check/operation.rs
@@ -1,5 +1,7 @@
pub mod fraud_check_post;
pub mod fraud_check_pre;
+#[cfg(all(feature = "payouts", feature = "v1"))]
+pub mod fraud_check_pre_payout;
use async_trait::async_trait;
use common_enums::FrmSuggestion;
use error_stack::{report, ResultExt};
diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
index 0cd0678e43..f6776b67fb 100644
--- a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
+++ b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
@@ -107,19 +107,12 @@ impl GetTracker<PaymentToFrmData> for FraudCheckPost {
let payment_details: Option<serde_json::Value> = PaymentDetails::from(payment_data.clone())
.encode_to_value()
.ok();
- let existing_fraud_check = db
- .find_fraud_check_by_payment_id_if_present(
- payment_data.payment_intent.get_id().to_owned(),
- payment_data.merchant_account.get_id().clone(),
- )
- .await
- .ok();
- let fraud_check = match existing_fraud_check {
- Some(Some(fraud_check)) => Ok(fraud_check),
- _ => {
+ let fraud_check = match payment_data.payment_attempt.active_frm_id.clone() {
+ Some(frm_id) => db.find_fraud_check_by_frm_id(frm_id).await,
+ None => {
db.insert_fraud_check_response(FraudCheckNew {
frm_id: utils::generate_id(consts::ID_LENGTH, "frm"),
- payment_id: payment_data.payment_intent.get_id().to_owned(),
+ payment_id: Some(payment_data.payment_intent.get_id().to_owned()),
merchant_id: payment_data.merchant_account.get_id().clone(),
processor_merchant_id: Some(
payment_data.payment_intent.processor_merchant_id.clone(),
@@ -139,6 +132,7 @@ impl GetTracker<PaymentToFrmData> for FraudCheckPost {
last_step: FraudCheckLastStep::Processing,
payment_capture_method: payment_data.payment_attempt.capture_method,
created_by: None,
+ payout_id: None,
})
.await
}
@@ -635,12 +629,12 @@ where
}
frm_data.fraud_check = match frm_check_update {
Some(fraud_check_update) => db
- .update_fraud_check_response_with_attempt_id(
+ .update_fraud_check_response_with_frm_id(
frm_data.fraud_check.clone(),
fraud_check_update,
)
.await
- .map_err(|error| error.change_context(errors::ApiErrorResponse::PaymentNotFound))?,
+ .to_not_found_response(errors::ApiErrorResponse::FraudCheckNotFound)?,
None => frm_data.fraud_check.clone(),
};
diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs b/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs
index b4dd592475..527d8a4932 100644
--- a/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs
+++ b/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs
@@ -7,7 +7,7 @@ use router_env::{instrument, tracing};
use super::{Domain, FraudCheckOperation, GetTracker, UpdateTracker};
use crate::{
core::{
- errors::RouterResult,
+ errors::{RouterResult, StorageErrorExt},
fraud_check::{
self as frm_core,
types::{FrmData, PaymentDetails, PaymentToFrmData},
@@ -95,20 +95,12 @@ impl GetTracker<PaymentToFrmData> for FraudCheckPre {
.encode_to_value()
.ok();
- let existing_fraud_check = db
- .find_fraud_check_by_payment_id_if_present(
- payment_data.payment_intent.get_id().to_owned(),
- payment_data.merchant_account.get_id().clone(),
- )
- .await
- .ok();
-
- let fraud_check = match existing_fraud_check {
- Some(Some(fraud_check)) => Ok(fraud_check),
- _ => {
+ let fraud_check = match payment_data.payment_attempt.active_frm_id.clone() {
+ Some(frm_id) => db.find_fraud_check_by_frm_id(frm_id).await,
+ None => {
db.insert_fraud_check_response(FraudCheckNew {
frm_id: common_utils::generate_uuid_v4().simple().to_string(),
- payment_id: payment_data.payment_intent.get_id().to_owned(),
+ payment_id: Some(payment_data.payment_intent.get_id().to_owned()),
merchant_id: payment_data.merchant_account.get_id().clone(),
processor_merchant_id: Some(
payment_data.payment_intent.processor_merchant_id.clone(),
@@ -128,6 +120,7 @@ impl GetTracker<PaymentToFrmData> for FraudCheckPre {
last_step: FraudCheckLastStep::Processing,
payment_capture_method: payment_data.payment_attempt.capture_method,
created_by: None,
+ payout_id: None,
})
.await
}
@@ -395,12 +388,12 @@ where
let db = &*state.store;
frm_data.fraud_check = match frm_check_update {
Some(fraud_check_update) => db
- .update_fraud_check_response_with_attempt_id(
+ .update_fraud_check_response_with_frm_id(
frm_data.clone().fraud_check,
fraud_check_update,
)
.await
- .map_err(|error| error.change_context(errors::ApiErrorResponse::PaymentNotFound))?,
+ .to_not_found_response(errors::ApiErrorResponse::FraudCheckNotFound)?,
None => frm_data.clone().fraud_check,
};
diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_pre_payout.rs b/crates/router/src/core/fraud_check/operation/fraud_check_pre_payout.rs
new file mode 100644
index 0000000000..31363ad49d
--- /dev/null
+++ b/crates/router/src/core/fraud_check/operation/fraud_check_pre_payout.rs
@@ -0,0 +1,130 @@
+use diesel_models::enums::FraudCheckLastStep;
+use error_stack::ResultExt;
+use hyperswitch_connectors::types::PoFrmRouterData;
+
+use crate::{
+ core::{
+ errors::{RouterResult, StorageErrorExt},
+ fraud_check::types::PayoutFrmData,
+ payouts::PayoutData,
+ },
+ errors,
+ types::{
+ fraud_check::FraudCheckResponseData,
+ storage::{
+ enums::{FraudCheckStatus, FraudCheckType},
+ fraud_check::{FraudCheckNew, FraudCheckUpdate},
+ },
+ },
+ SessionState,
+};
+
+#[derive(Debug, Clone, Copy)]
+pub struct FraudCheckPrePayout;
+
+impl FraudCheckPrePayout {
+ pub async fn get_tracker(
+ &self,
+ state: &SessionState,
+ payout_data: &PayoutData,
+ frm_connector_name: &str,
+ ) -> RouterResult<PayoutFrmData> {
+ let db = &*state.store;
+
+ let payout_id = payout_data.payouts.payout_id.clone();
+ let frm_id = common_utils::generate_uuid_v4().to_string();
+ let fraud_check_value = db
+ .insert_fraud_check_response(FraudCheckNew {
+ frm_id: frm_id.clone(),
+ payment_id: None,
+ payout_id: Some(payout_id.clone()),
+ merchant_id: payout_data.payouts.merchant_id.clone(),
+ processor_merchant_id: payout_data.payouts.processor_merchant_id.clone(),
+ attempt_id: payout_data.payout_attempt.payout_attempt_id.clone(),
+ created_at: common_utils::date_time::now(),
+ frm_name: frm_connector_name.to_owned(),
+ frm_transaction_id: None,
+ frm_transaction_type: FraudCheckType::PreFrm,
+ frm_status: FraudCheckStatus::Pending,
+ frm_score: None,
+ frm_reason: None,
+ frm_error: None,
+ payment_details: None,
+ metadata: None,
+ modified_at: common_utils::date_time::now(),
+ last_step: FraudCheckLastStep::Processing,
+ payment_capture_method: None,
+ created_by: None,
+ })
+ .await
+ .to_duplicate_response(errors::ApiErrorResponse::DuplicateFraudCheck { frm_id })?;
+
+ Ok(PayoutFrmData {
+ fraud_check: fraud_check_value,
+ amount: payout_data.payouts.amount,
+ currency: payout_data.payouts.destination_currency,
+ payout_attempt: payout_data.payout_attempt.clone(),
+ customer_details: payout_data.customer_details.clone(),
+ payout_method_data: payout_data.payout_method_data.clone(),
+ billing_address: payout_data.billing_address.clone(),
+ })
+ }
+
+ pub async fn update_tracker(
+ &self,
+ state: &SessionState,
+ mut frm_data: PayoutFrmData,
+ router_data: PoFrmRouterData,
+ ) -> RouterResult<PayoutFrmData> {
+ let db = &*state.store;
+
+ match router_data.response {
+ Ok(FraudCheckResponseData::TransactionResponse {
+ resource_id,
+ status,
+ connector_metadata,
+ reason,
+ score,
+ }) => {
+ let fraud_check_update = FraudCheckUpdate::ResponseUpdate {
+ frm_status: status,
+ frm_transaction_id: resource_id.get_optional_response_id(),
+ frm_reason: reason,
+ frm_score: score,
+ metadata: connector_metadata,
+ modified_at: common_utils::date_time::now(),
+ last_step: FraudCheckLastStep::PoFrm,
+ payment_capture_method: None,
+ };
+
+ frm_data.fraud_check = db
+ .update_fraud_check_response_with_frm_id(
+ frm_data.fraud_check.clone(),
+ fraud_check_update,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::FraudCheckNotFound)?;
+ }
+ Err(error) => {
+ let fraud_check_update = FraudCheckUpdate::ErrorUpdate {
+ status: FraudCheckStatus::TransactionFailure,
+ error_message: Some(Some(error.message)),
+ };
+
+ frm_data.fraud_check = db
+ .update_fraud_check_response_with_frm_id(
+ frm_data.fraud_check.clone(),
+ fraud_check_update,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::FraudCheckNotFound)?;
+ }
+ Ok(_) => {
+ Err(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unexpected response in po_frm flow")?;
+ }
+ }
+
+ Ok(frm_data)
+ }
+}
diff --git a/crates/router/src/core/fraud_check/types.rs b/crates/router/src/core/fraud_check/types.rs
index 28ee1dec6f..d3199f0a0e 100644
--- a/crates/router/src/core/fraud_check/types.rs
+++ b/crates/router/src/core/fraud_check/types.rs
@@ -1,26 +1,42 @@
+#[cfg(feature = "payouts")]
+use std::collections::HashSet;
+
+#[cfg(all(feature = "payouts", feature = "v1"))]
+use api_models::payouts::PayoutMethodData;
use api_models::{
enums as api_enums,
enums::{PaymentMethod, PaymentMethodType},
payments::Amount,
refunds::RefundResponse,
};
-use common_enums::FrmSuggestion;
+use common_enums::{FrmSuggestion, PreFrmFailureMode};
use common_utils::pii::SecretSerdeValue;
use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
+#[cfg(all(feature = "payouts", feature = "v1"))]
+use hyperswitch_domain_models::{
+ address::Address as PayoutAddress, customer::Customer, payouts::payout_attempt::PayoutAttempt,
+};
pub use hyperswitch_domain_models::{
+ merchant_connector_account::MerchantConnectorAccount,
router_request_types::fraud_check::{
Address, Destination, FrmFulfillmentRequest, FulfillmentStatus, Fulfillments, Product,
},
types::OrderDetailsWithAmount,
};
+#[cfg(feature = "payouts")]
+use hyperswitch_interfaces::configs::MerchantConnectorAccountType;
use hyperswitch_masking::Serialize;
use serde::Deserialize;
use utoipa::ToSchema;
use super::operation::BoxedFraudCheckOperation;
use crate::types::{
+ api::routing::FrmRoutingAlgorithm,
domain::MerchantAccount,
- storage::{enums as storage_enums, fraud_check::FraudCheck},
+ storage::{
+ enums::{self as storage_enums, FraudCheckStatus},
+ fraud_check::FraudCheck,
+ },
PaymentAddress,
};
@@ -86,6 +102,55 @@ pub struct PaymentToFrmData {
pub frm_metadata: Option<SecretSerdeValue>,
}
+#[cfg(all(feature = "payouts", feature = "v1"))]
+#[derive(Clone, Debug)]
+pub struct PayoutFrmData {
+ pub fraud_check: FraudCheck,
+ pub amount: common_utils::types::MinorUnit,
+ pub currency: storage_enums::Currency,
+ pub payout_attempt: PayoutAttempt,
+ pub payout_method_data: Option<PayoutMethodData>,
+ pub customer_details: Option<Customer>,
+ pub billing_address: Option<PayoutAddress>,
+}
+
+#[cfg(all(feature = "payouts", feature = "v1"))]
+impl PayoutFrmData {
+ pub fn should_cancel_payout(&self, failure_mode: &PreFrmFailureMode) -> bool {
+ matches!(
+ (self.fraud_check.frm_status, failure_mode),
+ (FraudCheckStatus::Fraud, _)
+ | (
+ FraudCheckStatus::TransactionFailure,
+ PreFrmFailureMode::FailClosed
+ )
+ )
+ }
+
+ pub fn get_frm_outcome(&self, failure_mode: &PreFrmFailureMode) -> PayoutFrmOutcome {
+ if self.should_cancel_payout(failure_mode) {
+ PayoutFrmOutcome::Blocked
+ } else {
+ PayoutFrmOutcome::Continue
+ }
+ }
+}
+
+#[cfg(feature = "payouts")]
+#[derive(Debug, Clone)]
+pub struct PayoutFrmApplicability {
+ pub connectors: HashSet<api_enums::Connector>,
+ pub frm_merchant_connector_account: Box<MerchantConnectorAccountType>,
+ pub frm_routing_algorithm: FrmRoutingAlgorithm,
+}
+
+#[cfg(feature = "payouts")]
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum PayoutFrmOutcome {
+ Continue,
+ Blocked,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FrmConfigsObject {
pub frm_enabled_pm: Option<PaymentMethod>,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index e22c4bf433..c82578a974 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -5779,6 +5779,7 @@ impl AttemptType {
applied_offer_details: None,
sender_payment_instrument_id: None,
payment_account_reference: None,
+ active_frm_id: None,
}
}
diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs
index c69b89b499..278dd1d383 100644
--- a/crates/router/src/core/payments/operations/payment_approve.rs
+++ b/crates/router/src/core/payments/operations/payment_approve.rs
@@ -4,7 +4,7 @@ use api_models::enums::{AttemptStatus, FrmSuggestion, IntentStatus};
use async_trait::async_trait;
use error_stack::ResultExt;
use router_derive::PaymentOperation;
-use router_env::{instrument, tracing};
+use router_env::{instrument, logger, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
@@ -145,17 +145,23 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCaptureR
payment_intent.shipping_address_id = shipping_address.clone().map(|i| i.address_id);
payment_intent.billing_address_id = billing_address.clone().map(|i| i.address_id);
- let frm_response = if cfg!(feature = "frm") {
- db.find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), platform.get_processor().get_account().get_id().clone())
+ #[cfg(feature = "frm")]
+ let frm_response = match payment_attempt.active_frm_id.clone() {
+ Some(frm_id) => db
+ .find_fraud_check_by_frm_id(frm_id)
.await
- .change_context(errors::ApiErrorResponse::PaymentNotFound)
+ .to_not_found_response(errors::ApiErrorResponse::FraudCheckNotFound)
.attach_printable_lazy(|| {
- format!("Error while retrieving frm_response, merchant_id: {}, payment_id: {attempt_id}", platform.get_processor().get_account().get_id().get_string_repr())
+ format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {payment_id:?}", platform.get_processor().get_account().get_id())
})
- .ok()
- } else {
- None
+ .inspect_err(|error| {
+ logger::error!(?error, "Failed to fetch fraud check record")
+ })
+ .ok(),
+ None => None,
};
+ #[cfg(not(feature = "frm"))]
+ let frm_response = None;
let payment_data = PaymentData {
flow: PhantomData,
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 1d875fcdc2..a35faa9525 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -2861,6 +2861,10 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for
payment_data.mandate_id.is_some(),
payment_data.payment_attempt.is_stored_credential,
);
+ let m_active_frm_id = payment_data
+ .frm_message
+ .as_ref()
+ .map(|fraud_check| fraud_check.frm_id.clone());
let cloned_key_store = key_store.clone();
let payment_attempt_fut = tokio::spawn(
async move {
@@ -2944,6 +2948,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for
.payment_attempt
.applied_offer_details
.clone(),
+ active_frm_id: m_active_frm_id,
},
storage_scheme,
&cloned_key_store,
diff --git a/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs b/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs
index 0a3f5c5e9e..237af2ccb7 100644
--- a/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs
@@ -627,6 +627,10 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, PaymentsRequest>
.payment_attempt
.applied_offer_details
.clone(),
+ active_frm_id: payment_data
+ .frm_message
+ .as_ref()
+ .map(|fraud_check| fraud_check.frm_id.clone()),
},
storage_scheme,
key_store,
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 0296a126a3..cd7c6825a2 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -1758,6 +1758,7 @@ impl PaymentCreate {
applied_offer_details: None,
sender_payment_instrument_id: None,
payment_account_reference: None,
+ active_frm_id: None,
},
additional_pm_data,
diff --git a/crates/router/src/core/payments/operations/payment_recurrence.rs b/crates/router/src/core/payments/operations/payment_recurrence.rs
index 9dc603d3a5..a9408620a8 100644
--- a/crates/router/src/core/payments/operations/payment_recurrence.rs
+++ b/crates/router/src/core/payments/operations/payment_recurrence.rs
@@ -610,6 +610,10 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for
let m_error_code = error_code.clone();
let m_error_message = error_message.clone();
let m_error_reason = error_message.clone();
+ let m_active_frm_id = payment_data
+ .frm_message
+ .as_ref()
+ .map(|fraud_check| fraud_check.frm_id.clone());
let m_db = state.clone().store;
let cloned_key_store = key_store.clone();
let payment_attempt_fut = tokio::spawn(
@@ -626,6 +630,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for
.payment_attempt
.connector_mandate_detail
.clone(),
+ active_frm_id: m_active_frm_id,
},
storage_scheme,
&cloned_key_store,
diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs
index 1f89bf1a67..dd743fe26f 100644
--- a/crates/router/src/core/payments/operations/payment_reject.rs
+++ b/crates/router/src/core/payments/operations/payment_reject.rs
@@ -3,7 +3,7 @@ use std::marker::PhantomData;
use api_models::{enums::FrmSuggestion, payments::PaymentsCancelRequest};
use async_trait::async_trait;
use error_stack::ResultExt;
-use router_env::{instrument, tracing};
+use router_env::{instrument, logger, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
@@ -123,17 +123,23 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest
let currency = payment_attempt.currency.get_required_value("currency")?;
let amount = payment_attempt.get_total_amount().into();
- let frm_response = if cfg!(feature = "frm") {
- db.find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), platform.get_processor().get_account().get_id().clone())
+ #[cfg(feature = "frm")]
+ let frm_response = match payment_attempt.active_frm_id.clone() {
+ Some(frm_id) => db
+ .find_fraud_check_by_frm_id(frm_id)
.await
- .change_context(errors::ApiErrorResponse::PaymentNotFound)
+ .to_not_found_response(errors::ApiErrorResponse::FraudCheckNotFound)
.attach_printable_lazy(|| {
- format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {attempt_id}", platform.get_processor().get_account().get_id())
+ format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {payment_id:?}", platform.get_processor().get_account().get_id())
})
- .ok()
- } else {
- None
+ .inspect_err(|error| {
+ logger::error!(?error, "Failed to fetch fraud check record")
+ })
+ .ok(),
+ None => None,
};
+ #[cfg(not(feature = "frm"))]
+ let frm_response = None;
let profile_id = payment_intent
.profile_id
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index a42aa09569..79558aee7a 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -410,17 +410,23 @@ async fn get_tracker_for_sync<
format!("Error while retrieving dispute list for, merchant_id: {:?}, payment_id: {payment_id:?}", platform.get_processor().get_account().get_id())
})?;
- let frm_response = if cfg!(feature = "frm") {
- db.find_fraud_check_by_payment_id(payment_id.to_owned(), platform.get_processor().get_account().get_id().clone())
+ #[cfg(feature = "frm")]
+ let frm_response = match payment_attempt.active_frm_id.clone() {
+ Some(frm_id) => db
+ .find_fraud_check_by_frm_id(frm_id)
.await
- .change_context(errors::ApiErrorResponse::PaymentNotFound)
+ .to_not_found_response(errors::ApiErrorResponse::FraudCheckNotFound)
.attach_printable_lazy(|| {
format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {payment_id:?}", platform.get_processor().get_account().get_id())
})
- .ok()
- } else {
- None
+ .inspect_err(|error| {
+ logger::error!(?error, "Failed to fetch fraud check record")
+ })
+ .ok(),
+ None => None,
};
+ #[cfg(not(feature = "frm"))]
+ let frm_response = None;
let contains_encoded_data = payment_attempt.encoded_data.is_some();
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
index 592e2b4a60..de3eec0006 100644
--- a/crates/router/src/core/payments/retry.rs
+++ b/crates/router/src/core/payments/retry.rs
@@ -887,6 +887,7 @@ pub fn make_new_auto_retry_payment_attempt(
applied_offer_details: old_payment_attempt.applied_offer_details,
sender_payment_instrument_id: Default::default(),
payment_account_reference: Default::default(),
+ active_frm_id: old_payment_attempt.active_frm_id,
}
}
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index baad040ce8..f1e285792c 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -55,6 +55,10 @@ use crate::{
errors::{
self, ConnectorErrorExt, CustomResult, RouterResponse, RouterResult, StorageErrorExt,
},
+ fraud_check::{
+ self, get_frm_merchant_connector_account_and_routing_algorithm,
+ get_payout_frm_applicability, types::PayoutFrmOutcome,
+ },
payments::{
self, customers, gateway::context as gateway_context, helpers as payment_helpers,
HeaderPayload,
@@ -63,7 +67,7 @@ use crate::{
utils as core_utils,
},
db::StorageInterface,
- routes::SessionState,
+ routes::{metrics, SessionState},
services,
types::{
self,
@@ -76,6 +80,39 @@ use crate::{
workflows::payout_sync,
};
+macro_rules! handle_payout_pre_frm_result {
+ ($result:expr, $failure_mode:expr, $platform:expr, $fail_open_value:expr) => {{
+ match $result {
+ Ok(value) => Ok(value),
+ Err(error) => match $failure_mode {
+ common_enums::PreFrmFailureMode::FailOpen => {
+ logger::info!(
+ "Payout pre FRM actions failed, continuing due to FailOpen mode. Error: {:?}",
+ error
+ );
+ metrics::FRM_FAILURE.add(
+ 1,
+ router_env::metric_attributes!(
+ (
+ "merchant_id",
+ $platform.get_processor().get_account().get_id().clone()
+ ),
+ ("error_type", error.current_context().to_string())
+ ),
+ );
+ Ok($fail_open_value)
+ }
+ common_enums::PreFrmFailureMode::FailClosed => {
+ logger::info!(
+ "Payout pre FRM actions failed, propagating error due to FailClosed mode"
+ );
+ Err(error)
+ }
+ },
+ }
+ }};
+}
+
// ********************************************** TYPES **********************************************
#[derive(Clone)]
pub struct PayoutData {
@@ -95,6 +132,7 @@ pub struct PayoutData {
pub browser_info: Option<domain_models::router_request_types::BrowserInformation>,
pub source_bank_data: Option<api_models::payouts::BankTransfer>,
pub attempts: Option<Vec<storage::PayoutAttempt>>,
+ pub fraud_check: Option<storage::FraudCheck>,
}
// ********************************************** CORE FLOWS **********************************************
@@ -146,7 +184,7 @@ pub async fn get_connector_choice(
pre_routing_results: None,
},
};
- helpers::decide_payout_connector(
+ let decided_connector = helpers::decide_payout_connector(
state,
processor,
dimensions,
@@ -155,7 +193,13 @@ pub async fn get_connector_choice(
payout_data,
eligible_routable_connectors,
)
- .await
+ .await?;
+
+ payout_data.payout_attempt.connector = routing_data.routed_through.clone();
+ payout_data.payout_attempt.merchant_connector_id =
+ routing_data.merchant_connector_id.clone();
+
+ Ok(decided_connector)
}
api::ConnectorChoice::Decide => {
@@ -168,7 +212,7 @@ pub async fn get_connector_choice(
pre_routing_results: None,
},
};
- helpers::decide_payout_connector(
+ let decided_connector = helpers::decide_payout_connector(
state,
processor,
dimensions,
@@ -177,7 +221,13 @@ pub async fn get_connector_choice(
payout_data,
eligible_routable_connectors,
)
- .await
+ .await?;
+
+ payout_data.payout_attempt.connector = routing_data.routed_through.clone();
+ payout_data.payout_attempt.merchant_connector_id =
+ routing_data.merchant_connector_id.clone();
+
+ Ok(decided_connector)
}
}
}
@@ -191,39 +241,93 @@ pub async fn make_connector_decision(
payout_data: &mut PayoutData,
dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,
) -> RouterResult<()> {
+ let profile_dimensions =
+ dimensions.with_profile_id(payout_data.business_profile.get_id().clone());
+
+ let pre_frm_failure_mode = profile_dimensions
+ .get_pre_frm_failure_mode(
+ state.store.as_ref(),
+ state.superposition_service.as_ref(),
+ None,
+ )
+ .await;
+
+ let payout_frm_call = profile_dimensions
+ .get_payout_frm_call(
+ state.store.as_ref(),
+ state.superposition_service.as_ref(),
+ None,
+ )
+ .await;
+
+ let frm_merchant_connector_account_and_routing_algorithm = if payout_frm_call {
+ handle_payout_pre_frm_result!(
+ get_frm_merchant_connector_account_and_routing_algorithm(state, platform, payout_data)
+ .await,
+ &pre_frm_failure_mode,
+ platform,
+ None
+ )?
+ } else {
+ None
+ };
+
+ let payout_frm_applicability = match frm_merchant_connector_account_and_routing_algorithm {
+ Some((mca, fra)) => handle_payout_pre_frm_result!(
+ get_payout_frm_applicability(payout_data, mca, fra).await,
+ &pre_frm_failure_mode,
+ platform,
+ None
+ )?,
+ None => None,
+ };
+
match connector_call_type {
api::ConnectorCallType::PreDetermined(routing_data) => {
- Box::pin(call_connector_payout(
- state,
- platform,
- header_payload.clone(),
- &routing_data.connector_data,
- payout_data,
- dimensions,
- ))
- .await?;
+ let frm_outcome = match payout_frm_applicability {
+ Some(applicability) => handle_payout_pre_frm_result!(
+ fraud_check::pre_payouts_frm_core(
+ state,
+ platform,
+ payout_data,
+ &routing_data.connector_data,
+ applicability,
+ &pre_frm_failure_mode,
+ )
+ .await,
+ &pre_frm_failure_mode,
+ platform,
+ PayoutFrmOutcome::Continue
+ )?,
+ None => PayoutFrmOutcome::Continue,
+ };
- #[cfg(feature = "payout_retry")]
- {
- let config_bool = retry::config_should_call_gsm_payout(
- state,
- dimensions,
- PayoutRetryType::SingleConnector,
- payout_data.payouts.customer_id.as_ref(),
- )
- .await;
+ match frm_outcome {
+ PayoutFrmOutcome::Continue => {
+ Box::pin(call_connector_payout(
+ state,
+ platform,
+ header_payload.clone(),
+ &routing_data.connector_data,
+ payout_data,
+ dimensions,
+ ))
+ .await?;
- if config_bool && payout_data.should_call_gsm() {
- Box::pin(retry::do_gsm_single_connector_actions(
+ #[cfg(feature = "payout_retry")]
+ predetermined_call_connector_type_payout_retry(
state,
routing_data.connector_data,
payout_data,
platform,
dimensions,
- header_payload.clone(),
- ))
+ header_payload,
+ )
.await?;
}
+ PayoutFrmOutcome::Blocked => {
+ update_frm_blocked_payout_tracker(state, platform, payout_data).await?;
+ }
}
Ok(())
@@ -233,58 +337,51 @@ pub async fn make_connector_decision(
let connector_data = get_next_connector(&mut routing_data)?.connector_data;
- Box::pin(call_connector_payout(
- state,
- platform,
- header_payload.clone(),
- &connector_data,
- payout_data,
- dimensions,
- ))
- .await?;
-
- #[cfg(feature = "payout_retry")]
- {
- let config_multiple_connector_bool = retry::config_should_call_gsm_payout(
- state,
- dimensions,
- PayoutRetryType::MultiConnector,
- payout_data.payouts.customer_id.as_ref(),
- )
- .await;
-
- if config_multiple_connector_bool && payout_data.should_call_gsm() {
- Box::pin(retry::do_gsm_multiple_connector_actions(
+ let frm_outcome = match payout_frm_applicability {
+ Some(applicability) => handle_payout_pre_frm_result!(
+ fraud_check::pre_payouts_frm_core(
state,
- routing_data,
- connector_data.clone(),
+ platform,
payout_data,
+ &connector_data,
+ applicability,
+ &pre_frm_failure_mode,
+ )
+ .await,
+ &pre_frm_failure_mode,
+ platform,
+ PayoutFrmOutcome::Continue
+ )?,
+ None => PayoutFrmOutcome::Continue,
+ };
+
+ match frm_outcome {
+ PayoutFrmOutcome::Continue => {
+ Box::pin(call_connector_payout(
+ state,
platform,
- dimensions,
header_payload.clone(),
+ &connector_data,
+ payout_data,
+ dimensions,
))
.await?;
- }
- let config_single_connector_bool = retry::config_should_call_gsm_payout(
- state,
- dimensions,
- PayoutRetryType::SingleConnector,
- payout_data.payouts.customer_id.as_ref(),
- )
- .await;
-
- if config_single_connector_bool && payout_data.should_call_gsm() {
- Box::pin(retry::do_gsm_single_connector_actions(
+ #[cfg(feature = "payout_retry")]
+ retryable_call_connector_type_payout_retry(
state,
+ routing_data,
connector_data,
payout_data,
platform,
dimensions,
header_payload,
- ))
+ )
.await?;
}
+ PayoutFrmOutcome::Blocked => {
+ update_frm_blocked_payout_tracker(state, platform, payout_data).await?;
+ }
}
Ok(())
@@ -295,6 +392,156 @@ pub async fn make_connector_decision(
}
}
+#[cfg(feature = "payout_retry")]
+async fn predetermined_call_connector_type_payout_retry(
+ state: &SessionState,
+ connector_data: api::ConnectorData,
+ payout_data: &mut PayoutData,
+ platform: &domain::Platform,
+ dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,
+ header_payload: HeaderPayload,
+) -> RouterResult<()> {
+ let config_bool = retry::config_should_call_gsm_payout(
+ state,
+ dimensions,
+ PayoutRetryType::SingleConnector,
+ payout_data.payouts.customer_id.as_ref(),
+ )
+ .await;
+
+ if config_bool && payout_data.should_call_gsm() {
+ Box::pin(retry::do_gsm_single_connector_actions(
+ state,
+ connector_data,
+ payout_data,
+ platform,
+ dimensions,
+ header_payload,
+ ))
+ .await?;
+ }
+
+ Ok(())
+}
+
+#[cfg(feature = "payout_retry")]
+async fn retryable_call_connector_type_payout_retry(
+ state: &SessionState,
+ routing_data: IntoIter<api::ConnectorRoutingData>,
+ connector_data: api::ConnectorData,
+ payout_data: &mut PayoutData,
+ platform: &domain::Platform,
+ dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,
+ header_payload: HeaderPayload,
+) -> RouterResult<()> {
+ let config_multiple_connector_bool = retry::config_should_call_gsm_payout(
+ state,
+ dimensions,
+ PayoutRetryType::MultiConnector,
+ payout_data.payouts.customer_id.as_ref(),
+ )
+ .await;
+
+ if config_multiple_connector_bool && payout_data.should_call_gsm() {
+ Box::pin(retry::do_gsm_multiple_connector_actions(
+ state,
+ routing_data,
+ connector_data.clone(),
+ payout_data,
+ platform,
+ dimensions,
+ header_payload.clone(),
+ ))
+ .await?;
+ }
+
+ let config_single_connector_bool = retry::config_should_call_gsm_payout(
+ state,
+ dimensions,
+ PayoutRetryType::SingleConnector,
+ payout_data.payouts.customer_id.as_ref(),
+ )
+ .await;
+
+ if config_single_connector_bool && payout_data.should_call_gsm() {
+ Box::pin(retry::do_gsm_single_connector_actions(
+ state,
+ connector_data,
+ payout_data,
+ platform,
+ dimensions,
+ header_payload,
+ ))
+ .await?;
+ }
+
+ Ok(())
+}
+
+#[instrument(skip_all)]
+async fn update_frm_blocked_payout_tracker(
+ state: &SessionState,
+ platform: &domain::Platform,
+ payout_data: &mut PayoutData,
+) -> RouterResult<()> {
+ let fraud_check = payout_data
+ .fraud_check
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Missing fraud_check on FRM blocked payout")?;
+
+ let db = &*state.store;
+ let storage_scheme = platform.get_processor().get_account().storage_scheme;
+
+ let active_frm_id = fraud_check.frm_id.clone();
+ let error_code = fraud_check.frm_status.to_string();
+ let error_message = fraud_check
+ .frm_reason
+ .as_ref()
+ .map(|reason| match reason {
+ serde_json::Value::String(value) => value.clone(),
+ other => other.to_string(),
+ })
+ .or(fraud_check.frm_error.clone());
+
+ payout_data.payout_attempt = db
+ .update_payout_attempt(
+ &payout_data.payout_attempt,
+ storage::PayoutAttemptUpdate::StatusUpdate {
+ status: common_enums::PayoutStatus::Failed,
+ error_code: Some(error_code),
+ error_message,
+ active_frm_id: Some(active_frm_id),
+ is_eligible: Some(false),
+ unified_code: None,
+ unified_message: None,
+ connector_eligibility_reference_id: None,
+ connector_payout_id: None,
+ payout_connector_metadata: None,
+ },
+ &payout_data.payouts,
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error updating payout attempt after FRM rejection")?;
+
+ payout_data.payouts = db
+ .update_payout(
+ &payout_data.payouts,
+ storage::PayoutsUpdate::StatusUpdate {
+ status: common_enums::PayoutStatus::Failed,
+ },
+ &payout_data.payout_attempt,
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error updating payout after FRM rejection")?;
+
+ Ok(())
+}
+
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn payouts_core(
@@ -666,6 +913,7 @@ pub async fn payouts_cancel_core(
unified_code: None,
unified_message: None,
payout_connector_metadata: None,
+ active_frm_id: None,
};
payout_data.payout_attempt = state
.store
@@ -1189,6 +1437,11 @@ pub async fn get_payout_filters_core(
}
// ********************************************** HELPERS **********************************************
+fn should_update_payout_attempt_routing(payout_attempt: &storage::PayoutAttempt) -> bool {
+ payout_attempt.connector_request_reference_id.is_none()
+ || payout_attempt.active_frm_id.is_some()
+}
+
pub async fn call_connector_payout(
state: &SessionState,
platform: &domain::Platform,
@@ -1224,21 +1477,17 @@ pub async fn call_connector_payout(
connector_data,
&payout_data.payout_attempt,
);
+ let connector_name = connector_data.connector_name.to_string();
// Update routing and persist the request reference ID before calling the connector.
- if payout_data.payout_attempt.connector.is_none()
- || payout_data.payout_attempt.connector != Some(connector_data.connector_name.to_string())
- || payout_data
- .payout_attempt
- .connector_request_reference_id
- .is_none()
- {
- payout_data.payout_attempt.connector = Some(connector_data.connector_name.to_string());
+ if should_update_payout_attempt_routing(&payout_data.payout_attempt) {
+ payout_data.payout_attempt.connector = Some(connector_name.clone());
let updated_payout_attempt = storage::PayoutAttemptUpdate::UpdateRouting {
- connector: connector_data.connector_name.to_string(),
+ connector: connector_name,
routing_info: payout_data.payout_attempt.routing_info.clone(),
merchant_connector_id: payout_data.payout_attempt.merchant_connector_id.clone(),
connector_request_reference_id,
+ active_frm_id: payout_data.payout_attempt.active_frm_id.clone(),
};
let db = &*state.store;
payout_data.payout_attempt = db
@@ -1511,6 +1760,7 @@ pub async fn create_recipient(
.payout_connector_metadata
.clone()
.or(payout_data.payout_attempt.payout_connector_metadata.clone()),
+ active_frm_id: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -1552,6 +1802,7 @@ pub async fn create_recipient(
.payout_connector_metadata
.clone()
.or(payout_data.payout_attempt.payout_connector_metadata.clone()),
+ active_frm_id: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -1617,6 +1868,7 @@ pub async fn create_recipient(
.payout_attempt
.payout_connector_metadata
.to_owned(),
+ active_frm_id: None,
};
let db = &*state.store;
payout_data.payout_attempt = db
@@ -1764,6 +2016,7 @@ pub async fn check_payout_eligibility(
unified_code: None,
unified_message: None,
payout_connector_metadata: payout_response_data.payout_connector_metadata,
+ active_frm_id: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -1828,6 +2081,7 @@ pub async fn check_payout_eligibility(
.payout_attempt
.payout_connector_metadata
.to_owned(),
+ active_frm_id: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -1890,6 +2144,7 @@ pub async fn complete_create_payout(
.payout_attempt
.payout_connector_metadata
.to_owned(),
+ active_frm_id: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -2012,6 +2267,7 @@ pub async fn create_payout(
unified_code: None,
unified_message: None,
payout_connector_metadata: connector_meta_data.clone(),
+ active_frm_id: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -2073,6 +2329,7 @@ pub async fn create_payout(
field_name: "unified_message".into(),
})?,
payout_connector_metadata: connector_meta_data,
+ active_frm_id: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -2300,6 +2557,7 @@ pub async fn update_retrieve_payout_tracker<F, T>(
payout_connector_metadata: payout_response_data
.payout_connector_metadata
.clone(),
+ active_frm_id: None,
}
} else {
storage::PayoutAttemptUpdate::StatusUpdate {
@@ -2314,6 +2572,7 @@ pub async fn update_retrieve_payout_tracker<F, T>(
payout_connector_metadata: payout_response_data
.payout_connector_metadata
.clone(),
+ active_frm_id: None,
}
};
@@ -2440,6 +2699,7 @@ pub async fn create_recipient_disburse_account(
unified_code: None,
unified_message: None,
payout_connector_metadata: payout_response_data.payout_connector_metadata,
+ active_frm_id: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -2580,6 +2840,7 @@ pub async fn create_recipient_disburse_account(
.payout_attempt
.payout_connector_metadata
.to_owned(),
+ active_frm_id: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -2656,6 +2917,7 @@ pub async fn cancel_payout(
unified_code: None,
unified_message: None,
payout_connector_metadata: payout_response_data.payout_connector_metadata,
+ active_frm_id: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -2720,6 +2982,7 @@ pub async fn cancel_payout(
.payout_attempt
.payout_connector_metadata
.to_owned(),
+ active_frm_id: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -2835,6 +3098,7 @@ pub async fn fulfill_payout(
unified_code: None,
unified_message: None,
payout_connector_metadata: payout_response_data.payout_connector_metadata,
+ active_frm_id: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -2879,7 +3143,12 @@ pub async fn fulfill_payout(
}
}
Err(err) => {
- let status = storage_enums::PayoutStatus::Failed;
+ // Only explicit client errors establish that the payout failed. Keep all other
+ // outcomes pending so the payout sync workflow can reconcile the final status.
+ let status = match err.status_code {
+ 400..=499 => storage_enums::PayoutStatus::Failed,
+ _ => storage_enums::PayoutStatus::Pending,
+ };
let (error_code, error_message) = (Some(err.code), Some(err.message));
let (unified_code, unified_message) = helpers::get_gsm_record(
&updated_state,
@@ -2920,6 +3189,7 @@ pub async fn fulfill_payout(
.payout_attempt
.payout_connector_metadata
.to_owned(),
+ active_frm_id: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -3002,6 +3272,11 @@ pub async fn response_handler(
let payout_method_data =
additional_payout_method_data.map(payouts::PayoutMethodDataResponse::from);
+ let frm_message = payout_data
+ .fraud_check
+ .clone()
+ .map(api_models::payments::FrmMessage::foreign_from);
+
let response = api::PayoutCreateResponse {
payout_id: payouts.payout_id.to_owned(),
merchant_id: platform.get_processor().get_account().get_id().to_owned(),
@@ -3037,6 +3312,7 @@ pub async fn response_handler(
status: payout_attempt.status.to_owned(),
error_message: payout_attempt.error_message.to_owned(),
error_code: payout_attempt.error_code,
+ frm_message,
profile_id: payout_attempt.profile_id,
created: Some(payouts.created_at),
connector_transaction_id: payout_attempt.connector_payout_id,
@@ -3312,6 +3588,7 @@ pub async fn payout_create_db_entries(
source_bank_data_token,
additional_source_bank_data,
connector_request_reference_id: None,
+ active_frm_id: None,
};
let payout_attempt = db
.insert_payout_attempt(
@@ -3347,6 +3624,7 @@ pub async fn payout_create_db_entries(
browser_info: req.browser_info.clone().map(Into::into),
source_bank_data: req.source_bank_data.clone(),
attempts: None,
+ fraud_check: None,
})
}
@@ -3674,6 +3952,16 @@ pub async fn make_payout_data(
.await
.transpose()?;
+ let fraud_check = match &payout_attempt.active_frm_id {
+ Some(active_frm_id) => db
+ .find_fraud_check_by_frm_id(active_frm_id.clone())
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::FraudCheckNotFound)
+ .inspect_err(|error| logger::error!(?error, "Failed to fetch fraud check record"))
+ .ok(),
+ None => None,
+ };
+
Ok(PayoutData {
billing_address,
business_profile,
@@ -3691,6 +3979,7 @@ pub async fn make_payout_data(
browser_info,
source_bank_data,
attempts,
+ fraud_check,
})
}
diff --git a/crates/router/src/core/payouts/retry.rs b/crates/router/src/core/payouts/retry.rs
index 89f72e57d7..e94359b847 100644
--- a/crates/router/src/core/payouts/retry.rs
+++ b/crates/router/src/core/payouts/retry.rs
@@ -301,6 +301,7 @@ pub async fn modify_trackers(
.additional_source_bank_data
.clone(),
connector_request_reference_id: None,
+ active_frm_id: payout_data.payout_attempt.active_frm_id.clone(),
};
payout_data.payout_attempt = db
.insert_payout_attempt(
diff --git a/crates/router/src/core/payouts/transformers.rs b/crates/router/src/core/payouts/transformers.rs
index 20ef2675dc..2c82045fe2 100644
--- a/crates/router/src/core/payouts/transformers.rs
+++ b/crates/router/src/core/payouts/transformers.rs
@@ -88,6 +88,7 @@ impl
status: payout_attempt.status,
error_message: payout_attempt.error_message,
error_code: payout_attempt.error_code,
+ frm_message: None,
profile_id: payout.profile_id,
created: Some(payout.created_at),
connector_transaction_id: attempt.connector_transaction_id.clone(),
diff --git a/crates/router/src/core/split_payments.rs b/crates/router/src/core/split_payments.rs
index a840105507..1c1ee92e8f 100644
--- a/crates/router/src/core/split_payments.rs
+++ b/crates/router/src/core/split_payments.rs
@@ -600,5 +600,6 @@ pub async fn create_domain_model_for_split_payment(
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference: None,
+ active_frm_id: None,
})
}
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index b1c4e25084..9e118d81d3 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -35,6 +35,8 @@ use hyperswitch_domain_models::{
types::{OrderDetailsWithAmount, VaultRouterDataV2},
};
use hyperswitch_interfaces::api::ConnectorSpecifications;
+#[cfg(feature = "frm")]
+use hyperswitch_interfaces::configs::Connectors;
#[cfg(feature = "v2")]
use hyperswitch_masking::ExposeOptionInterface;
use hyperswitch_masking::Secret;
@@ -2139,13 +2141,13 @@ pub fn get_payout_connector_request_reference_id(
#[cfg(feature = "frm")]
pub fn get_gateway_frm_metadata(
- conf: &Settings,
+ connectors: &Connectors,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> CustomResult<Option<common_utils::pii::SecretSerdeValue>, errors::ApiErrorResponse> {
match &payment_attempt.connector {
Some(connector_name) => {
let connector_data = api::ConnectorData::get_connector_by_name(
- &conf.connectors,
+ connectors,
connector_name,
api::GetToken::Connector,
payment_attempt.merchant_connector_id.clone(),
@@ -2155,7 +2157,33 @@ pub fn get_gateway_frm_metadata(
connector_data
.connector
- .get_frm_metadata(payment_attempt)
+ .get_payment_frm_metadata(payment_attempt)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable_lazy(|| "Failed to construct FRM gateway metadata")
+ }
+ None => Ok(None),
+ }
+}
+
+#[cfg(feature = "frm")]
+pub fn get_payout_gateway_frm_metadata(
+ connectors: &Connectors,
+ payout_attempt: &hyperswitch_domain_models::payouts::payout_attempt::PayoutAttempt,
+) -> CustomResult<Option<common_utils::pii::SecretSerdeValue>, errors::ApiErrorResponse> {
+ match &payout_attempt.connector {
+ Some(connector_name) => {
+ let connector_data = api::ConnectorData::get_connector_by_name(
+ connectors,
+ connector_name,
+ api::GetToken::Connector,
+ payout_attempt.merchant_connector_id.clone(),
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable_lazy(|| "Failed to construct connector data")?;
+
+ connector_data
+ .connector
+ .get_payout_frm_metadata(payout_attempt)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| "Failed to construct FRM gateway metadata")
}
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index cdd22a7ecc..70e242561f 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -1320,6 +1320,7 @@ async fn payout_incoming_webhook_update_status(
unified_code: None,
unified_message: None,
payout_connector_metadata: payout_attempt.payout_connector_metadata.clone(),
+ active_frm_id: None,
}
} else {
PayoutAttemptUpdate::StatusUpdate {
@@ -1332,6 +1333,7 @@ async fn payout_incoming_webhook_update_status(
unified_code: None,
unified_message: None,
payout_connector_metadata: payout_attempt.payout_connector_metadata.clone(),
+ active_frm_id: None,
}
};
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index ebc81311ad..8cc0ebabed 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -430,14 +430,14 @@ impl FraudCheckInterface for KafkaStore {
}
Ok(frm)
}
- async fn update_fraud_check_response_with_attempt_id(
+ async fn update_fraud_check_response_with_frm_id(
&self,
this: FraudCheck,
fraud_check: FraudCheckUpdate,
) -> CustomResult<FraudCheck, StorageError> {
let frm = self
.diesel_store
- .update_fraud_check_response_with_attempt_id(this, fraud_check)
+ .update_fraud_check_response_with_frm_id(this, fraud_check)
.await?;
if let Err(er) = self
.kafka_producer
@@ -448,15 +448,11 @@ impl FraudCheckInterface for KafkaStore {
}
Ok(frm)
}
- async fn find_fraud_check_by_payment_id(
+ async fn find_fraud_check_by_frm_id(
&self,
- payment_id: id_type::PaymentId,
- merchant_id: id_type::MerchantId,
+ frm_id: String,
) -> CustomResult<FraudCheck, StorageError> {
- let frm = self
- .diesel_store
- .find_fraud_check_by_payment_id(payment_id, merchant_id)
- .await?;
+ let frm = self.diesel_store.find_fraud_check_by_frm_id(frm_id).await?;
if let Err(er) = self
.kafka_producer
.log_fraud_check(&frm, None, self.tenant_id.clone())
@@ -466,27 +462,6 @@ impl FraudCheckInterface for KafkaStore {
}
Ok(frm)
}
- async fn find_fraud_check_by_payment_id_if_present(
- &self,
- payment_id: id_type::PaymentId,
- merchant_id: id_type::MerchantId,
- ) -> CustomResult<Option<FraudCheck>, StorageError> {
- let frm = self
- .diesel_store
- .find_fraud_check_by_payment_id_if_present(payment_id, merchant_id)
- .await?;
-
- if let Some(fraud_check) = frm.clone() {
- if let Err(er) = self
- .kafka_producer
- .log_fraud_check(&fraud_check, None, self.tenant_id.clone())
- .await
- {
- logger::error!(message="Failed to log analytics event for frm {frm:?}", error_message=?er);
- }
- }
- Ok(frm)
- }
}
#[async_trait::async_trait]
diff --git a/crates/router/src/db/fraud_check.rs b/crates/router/src/db/fraud_check.rs
index af4c4bdcff..8962de2300 100644
--- a/crates/router/src/db/fraud_check.rs
+++ b/crates/router/src/db/fraud_check.rs
@@ -16,23 +16,16 @@ pub trait FraudCheckInterface {
new: storage::FraudCheckNew,
) -> CustomResult<FraudCheck, errors::StorageError>;
- async fn update_fraud_check_response_with_attempt_id(
+ async fn update_fraud_check_response_with_frm_id(
&self,
this: FraudCheck,
fraud_check: FraudCheckUpdate,
) -> CustomResult<FraudCheck, errors::StorageError>;
- async fn find_fraud_check_by_payment_id(
+ async fn find_fraud_check_by_frm_id(
&self,
- payment_id: common_utils::id_type::PaymentId,
- merchant_id: common_utils::id_type::MerchantId,
+ frm_id: String,
) -> CustomResult<FraudCheck, errors::StorageError>;
-
- async fn find_fraud_check_by_payment_id_if_present(
- &self,
- payment_id: common_utils::id_type::PaymentId,
- merchant_id: common_utils::id_type::MerchantId,
- ) -> CustomResult<Option<FraudCheck>, errors::StorageError>;
}
#[async_trait::async_trait]
@@ -49,37 +42,24 @@ impl FraudCheckInterface for Store {
}
#[instrument(skip_all)]
- async fn update_fraud_check_response_with_attempt_id(
+ async fn update_fraud_check_response_with_frm_id(
&self,
this: FraudCheck,
fraud_check: FraudCheckUpdate,
) -> CustomResult<FraudCheck, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
- this.update_with_attempt_id(&conn, fraud_check)
+ this.update_with_frm_id(&conn, fraud_check)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
- async fn find_fraud_check_by_payment_id(
+ async fn find_fraud_check_by_frm_id(
&self,
- payment_id: common_utils::id_type::PaymentId,
- merchant_id: common_utils::id_type::MerchantId,
+ frm_id: String,
) -> CustomResult<FraudCheck, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
- FraudCheck::get_with_payment_id(&conn, payment_id, merchant_id)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- }
-
- #[instrument(skip_all)]
- async fn find_fraud_check_by_payment_id_if_present(
- &self,
- payment_id: common_utils::id_type::PaymentId,
- merchant_id: common_utils::id_type::MerchantId,
- ) -> CustomResult<Option<FraudCheck>, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- FraudCheck::get_with_payment_id_if_present(&conn, payment_id, merchant_id)
+ FraudCheck::get_with_frm_id(&conn, frm_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
@@ -93,26 +73,19 @@ impl FraudCheckInterface for MockDb {
) -> CustomResult<FraudCheck, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
- async fn update_fraud_check_response_with_attempt_id(
+
+ async fn update_fraud_check_response_with_frm_id(
&self,
_this: FraudCheck,
_fraud_check: FraudCheckUpdate,
) -> CustomResult<FraudCheck, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
- async fn find_fraud_check_by_payment_id(
- &self,
- _payment_id: common_utils::id_type::PaymentId,
- _merchant_id: common_utils::id_type::MerchantId,
- ) -> CustomResult<FraudCheck, errors::StorageError> {
- Err(errors::StorageError::MockDbError)?
- }
- async fn find_fraud_check_by_payment_id_if_present(
+ async fn find_fraud_check_by_frm_id(
&self,
- _payment_id: common_utils::id_type::PaymentId,
- _merchant_id: common_utils::id_type::MerchantId,
- ) -> CustomResult<Option<FraudCheck>, errors::StorageError> {
+ _frm_id: String,
+ ) -> CustomResult<FraudCheck, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
}
diff --git a/crates/router/src/services/kafka/fraud_check.rs b/crates/router/src/services/kafka/fraud_check.rs
index ca270f27cd..69cfdbdf95 100644
--- a/crates/router/src/services/kafka/fraud_check.rs
+++ b/crates/router/src/services/kafka/fraud_check.rs
@@ -10,7 +10,8 @@ use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct KafkaFraudCheck<'a> {
pub frm_id: &'a String,
- pub payment_id: &'a common_utils::id_type::PaymentId,
+ pub payment_id: Option<&'a common_utils::id_type::PaymentId>,
+ pub payout_id: Option<&'a common_utils::id_type::PayoutId>,
pub merchant_id: &'a common_utils::id_type::MerchantId,
pub attempt_id: &'a String,
#[serde(with = "time::serde::timestamp")]
@@ -36,7 +37,8 @@ impl<'a> KafkaFraudCheck<'a> {
pub fn from_storage(check: &'a FraudCheck) -> Self {
Self {
frm_id: &check.frm_id,
- payment_id: &check.payment_id,
+ payment_id: check.payment_id.as_ref(),
+ payout_id: check.payout_id.as_ref(),
merchant_id: &check.merchant_id,
attempt_id: &check.attempt_id,
created_at: check.created_at.assume_utc(),
@@ -64,9 +66,8 @@ impl<'a> KafkaFraudCheck<'a> {
impl super::KafkaMessage for KafkaFraudCheck<'_> {
fn key(&self) -> String {
format!(
- "{}_{}_{}_{}",
+ "{}_{}_{}",
self.merchant_id.get_string_repr(),
- self.payment_id.get_string_repr(),
self.attempt_id,
self.frm_id
)
diff --git a/crates/router/src/services/kafka/fraud_check_event.rs b/crates/router/src/services/kafka/fraud_check_event.rs
index 483949a092..96cb17264c 100644
--- a/crates/router/src/services/kafka/fraud_check_event.rs
+++ b/crates/router/src/services/kafka/fraud_check_event.rs
@@ -9,7 +9,8 @@ use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct KafkaFraudCheckEvent<'a> {
pub frm_id: &'a String,
- pub payment_id: &'a common_utils::id_type::PaymentId,
+ pub payment_id: Option<&'a common_utils::id_type::PaymentId>,
+ pub payout_id: Option<&'a common_utils::id_type::PayoutId>,
pub merchant_id: &'a common_utils::id_type::MerchantId,
pub attempt_id: &'a String,
#[serde(with = "time::serde::timestamp::nanoseconds")]
@@ -35,7 +36,8 @@ impl<'a> KafkaFraudCheckEvent<'a> {
pub fn from_storage(check: &'a FraudCheck) -> Self {
Self {
frm_id: &check.frm_id,
- payment_id: &check.payment_id,
+ payment_id: check.payment_id.as_ref(),
+ payout_id: check.payout_id.as_ref(),
merchant_id: &check.merchant_id,
attempt_id: &check.attempt_id,
created_at: check.created_at.assume_utc(),
@@ -63,9 +65,8 @@ impl<'a> KafkaFraudCheckEvent<'a> {
impl super::KafkaMessage for KafkaFraudCheckEvent<'_> {
fn key(&self) -> String {
format!(
- "{}_{}_{}_{}",
+ "{}_{}_{}",
self.merchant_id.get_string_repr(),
- self.payment_id.get_string_repr(),
self.attempt_id,
self.frm_id
)
diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rs
index 0b1d5da64b..0c8fed750c 100644
--- a/crates/router/src/services/kafka/payment_attempt.rs
+++ b/crates/router/src/services/kafka/payment_attempt.rs
@@ -285,6 +285,7 @@ impl<'a> KafkaPaymentAttempt<'a> {
external_surcharge_details: _,
applied_offer_details: _,
payment_account_reference: _,
+ active_frm_id: _,
} = attempt;
let (connector_payment_id, connector_payment_data) = connector_payment_id
diff --git a/crates/router/src/services/kafka/payment_attempt_event.rs b/crates/router/src/services/kafka/payment_attempt_event.rs
index 93874295ff..738b7f2fa5 100644
--- a/crates/router/src/services/kafka/payment_attempt_event.rs
+++ b/crates/router/src/services/kafka/payment_attempt_event.rs
@@ -287,6 +287,7 @@ impl<'a> KafkaPaymentAttemptEvent<'a> {
external_surcharge_details: _,
applied_offer_details: _,
payment_account_reference: _,
+ active_frm_id: _,
} = attempt;
let (connector_payment_id, connector_payment_data) = connector_payment_id
diff --git a/crates/router/src/types/api/fraud_check.rs b/crates/router/src/types/api/fraud_check.rs
index abcc3e1462..c37379b469 100644
--- a/crates/router/src/types/api/fraud_check.rs
+++ b/crates/router/src/types/api/fraud_check.rs
@@ -4,11 +4,11 @@ use api_models::enums;
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
pub use hyperswitch_domain_models::router_flow_types::fraud_check::{
- Checkout, Fulfillment, RecordReturn, Sale, Transaction,
+ Checkout, Fulfillment, PoFrm, RecordReturn, Sale, Transaction,
};
pub use hyperswitch_interfaces::api::fraud_check::{
- FraudCheckCheckout, FraudCheckFulfillment, FraudCheckRecordReturn, FraudCheckSale,
- FraudCheckTransaction,
+ FraudCheckCheckout, FraudCheckFulfillment, FraudCheckPayout, FraudCheckRecordReturn,
+ FraudCheckSale, FraudCheckTransaction,
};
pub use super::fraud_check_v2::{
diff --git a/crates/router/src/types/fraud_check.rs b/crates/router/src/types/fraud_check.rs
index 386c8a9cd9..030c53983c 100644
--- a/crates/router/src/types/fraud_check.rs
+++ b/crates/router/src/types/fraud_check.rs
@@ -1,7 +1,7 @@
pub use hyperswitch_domain_models::{
router_request_types::fraud_check::{
- FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData,
- FraudCheckSaleData, FraudCheckTransactionData, RefundMethod,
+ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckPayoutData,
+ FraudCheckRecordReturnData, FraudCheckSaleData, FraudCheckTransactionData, RefundMethod,
},
router_response_types::fraud_check::FraudCheckResponseData,
};
diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs
index 46a923ba12..b4ccc03104 100644
--- a/crates/router/src/types/storage/payment_attempt.rs
+++ b/crates/router/src/types/storage/payment_attempt.rs
@@ -251,6 +251,7 @@ mod tests {
external_surcharge_details: Default::default(),
sender_payment_instrument_id: Default::default(),
payment_account_reference: Default::default(),
+ active_frm_id: Default::default(),
};
let store = state
@@ -378,6 +379,7 @@ mod tests {
external_surcharge_details: Default::default(),
sender_payment_instrument_id: Default::default(),
payment_account_reference: Default::default(),
+ active_frm_id: Default::default(),
};
let store = state
.stores
@@ -519,6 +521,7 @@ mod tests {
external_surcharge_details: Default::default(),
sender_payment_instrument_id: Default::default(),
payment_account_reference: Default::default(),
+ active_frm_id: Default::default(),
};
let store = state
.stores
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index b229e7af22..3306cb1763 100644
--- a/crates/storage_impl/src/mock_db/payment_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs
@@ -258,6 +258,7 @@ impl PaymentAttemptInterface for MockDb {
applied_offer_details: payment_attempt.applied_offer_details,
sender_payment_instrument_id: payment_attempt.sender_payment_instrument_id,
payment_account_reference: payment_attempt.payment_account_reference,
+ active_frm_id: payment_attempt.active_frm_id,
};
payment_attempts.push(payment_attempt.clone());
Ok(payment_attempt)
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index f6a77959af..6d484f920d 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -823,6 +823,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
.sender_payment_instrument_id
.clone(),
payment_account_reference: payment_attempt.payment_account_reference.clone(),
+ active_frm_id: payment_attempt.active_frm_id.clone(),
};
let payment_attempt_new = payment_attempt
.clone()
@@ -2169,6 +2170,7 @@ impl Conversion for PaymentAttempt {
external_surcharge_details,
applied_offer_details,
payment_account_reference,
+ active_frm_id,
} = self;
let net_amount = amount_details.get_net_amount();
@@ -2283,6 +2285,7 @@ impl Conversion for PaymentAttempt {
fingerprint_type: None,
sender_payment_instrument_id: None,
payment_account_reference,
+ active_frm_id,
})
}
@@ -2416,6 +2419,7 @@ impl Conversion for PaymentAttempt {
external_surcharge_details: storage_model.external_surcharge_details,
applied_offer_details: storage_model.applied_offer_details,
payment_account_reference: storage_model.payment_account_reference,
+ active_frm_id: storage_model.active_frm_id,
})
}
.await
@@ -2488,6 +2492,7 @@ impl Conversion for PaymentAttempt {
external_surcharge_details: _,
applied_offer_details: _,
payment_account_reference,
+ active_frm_id,
} = self;
let error_details = error;
@@ -2587,6 +2592,7 @@ impl Conversion for PaymentAttempt {
external_surcharge_details: None,
applied_offer_details: None,
payment_account_reference,
+ active_frm_id,
})
}
}
diff --git a/crates/storage_impl/src/payouts/payout_attempt.rs b/crates/storage_impl/src/payouts/payout_attempt.rs
index 22b0305c63..750adca621 100644
--- a/crates/storage_impl/src/payouts/payout_attempt.rs
+++ b/crates/storage_impl/src/payouts/payout_attempt.rs
@@ -103,6 +103,7 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
connector_request_reference_id: new_payout_attempt
.connector_request_reference_id
.clone(),
+ active_frm_id: new_payout_attempt.active_frm_id.clone(),
};
let field = format!("poa_{}", created_attempt.payout_attempt_id);
@@ -491,8 +492,7 @@ impl<T: DatabaseStore> PayoutAttemptInterface for crate::RouterStore<T> {
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
let conn = pg_connection_write(self).await?;
- new.to_storage_model()
- .insert(&conn)
+ Box::pin(new.to_storage_model().insert(&conn))
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
@@ -510,15 +510,17 @@ impl<T: DatabaseStore> PayoutAttemptInterface for crate::RouterStore<T> {
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
let conn = pg_connection_write(self).await?;
- this.clone()
- .to_storage_model()
- .update_with_attempt_id(&conn, payout.to_storage_model())
- .await
- .map_err(|er| {
- let new_err = diesel_error_to_data_error(*er.current_context());
- er.change_context(new_err)
- })
- .map(PayoutAttempt::from_storage_model)
+ Box::pin(
+ this.clone()
+ .to_storage_model()
+ .update_with_attempt_id(&conn, payout.to_storage_model()),
+ )
+ .await
+ .map_err(|er| {
+ let new_err = diesel_error_to_data_error(*er.current_context());
+ er.change_context(new_err)
+ })
+ .map(PayoutAttempt::from_storage_model)
}
#[instrument(skip_all)]
@@ -706,6 +708,7 @@ impl DataModelExt for PayoutAttempt {
additional_source_bank_data: self.additional_source_bank_data,
connector_eligibility_reference_id: self.connector_eligibility_reference_id,
connector_request_reference_id: self.connector_request_reference_id,
+ active_frm_id: self.active_frm_id,
}
}
@@ -743,6 +746,7 @@ impl DataModelExt for PayoutAttempt {
additional_source_bank_data: storage_model.additional_source_bank_data,
connector_eligibility_reference_id: storage_model.connector_eligibility_reference_id,
connector_request_reference_id: storage_model.connector_request_reference_id,
+ active_frm_id: storage_model.active_frm_id,
}
}
}
@@ -781,6 +785,7 @@ impl DataModelExt for PayoutAttemptNew {
additional_source_bank_data: self.additional_source_bank_data,
connector_eligibility_reference_id: self.connector_eligibility_reference_id,
connector_request_reference_id: self.connector_request_reference_id,
+ active_frm_id: self.active_frm_id,
}
}
@@ -818,6 +823,7 @@ impl DataModelExt for PayoutAttemptNew {
additional_source_bank_data: storage_model.additional_source_bank_data,
connector_eligibility_reference_id: storage_model.connector_eligibility_reference_id,
connector_request_reference_id: storage_model.connector_request_reference_id,
+ active_frm_id: storage_model.active_frm_id,
}
}
}
@@ -835,6 +841,7 @@ impl DataModelExt for PayoutAttemptUpdate {
unified_message,
payout_connector_metadata,
connector_eligibility_reference_id,
+ active_frm_id,
} => DieselPayoutAttemptUpdate::StatusUpdate {
connector_payout_id,
status,
@@ -845,6 +852,7 @@ impl DataModelExt for PayoutAttemptUpdate {
unified_message,
payout_connector_metadata,
connector_eligibility_reference_id,
+ active_frm_id,
},
Self::PayoutTokenUpdate { payout_token } => {
DieselPayoutAttemptUpdate::PayoutTokenUpdate { payout_token }
@@ -865,11 +873,13 @@ impl DataModelExt for PayoutAttemptUpdate {
routing_info,
merchant_connector_id,
connector_request_reference_id,
+ active_frm_id,
} => DieselPayoutAttemptUpdate::UpdateRouting {
connector,
routing_info,
merchant_connector_id,
connector_request_reference_id,
+ active_frm_id,
},
Self::AdditionalPayoutDataUpdate {
additional_payout_method_data,
diff --git a/migrations/2026-09-08-110000_add_active_frm_id_to_payment_attempt_and_payout_attempt/down.sql b/migrations/2026-09-08-110000_add_active_frm_id_to_payment_attempt_and_payout_attempt/down.sql
new file mode 100644
index 0000000000..2fec6d11d8
--- /dev/null
+++ b/migrations/2026-09-08-110000_add_active_frm_id_to_payment_attempt_and_payout_attempt/down.sql
@@ -0,0 +1,5 @@
+ALTER TABLE payment_attempt
+ DROP COLUMN IF EXISTS active_frm_id;
+
+ALTER TABLE payout_attempt
+ DROP COLUMN IF EXISTS active_frm_id;
\ No newline at end of file
diff --git a/migrations/2026-09-08-110000_add_active_frm_id_to_payment_attempt_and_payout_attempt/up.sql b/migrations/2026-09-08-110000_add_active_frm_id_to_payment_attempt_and_payout_attempt/up.sql
new file mode 100644
index 0000000000..56a27d10fe
--- /dev/null
+++ b/migrations/2026-09-08-110000_add_active_frm_id_to_payment_attempt_and_payout_attempt/up.sql
@@ -0,0 +1,14 @@
+ALTER TABLE payment_attempt
+ ADD COLUMN IF NOT EXISTS active_frm_id VARCHAR(64);
+
+ALTER TABLE payout_attempt
+ ADD COLUMN IF NOT EXISTS active_frm_id VARCHAR(64);
+
+-- Existing fraud_check records are associated at the payment level. Backfill
+-- every attempt for that payment with the frm_id.
+UPDATE payment_attempt
+SET active_frm_id = fraud_check.frm_id
+FROM fraud_check
+WHERE payment_attempt.payment_id = fraud_check.payment_id
+ AND payment_attempt.merchant_id = fraud_check.merchant_id
+ AND payment_attempt.active_frm_id IS NULL;
diff --git a/migrations/2026-09-08-120000_add_payout_id_to_fraud_check/down.sql b/migrations/2026-09-08-120000_add_payout_id_to_fraud_check/down.sql
new file mode 100644
index 0000000000..8c31202959
--- /dev/null
+++ b/migrations/2026-09-08-120000_add_payout_id_to_fraud_check/down.sql
@@ -0,0 +1,15 @@
+-- This fails when payout fraud_check rows with a NULL payment_id
+-- still exist. Such rows must be deleted before rolling back this migration.
+ALTER TABLE fraud_check
+ ALTER COLUMN payment_id SET NOT NULL;
+
+ALTER TABLE fraud_check
+ DROP CONSTRAINT fraud_check_pkey;
+
+ALTER TABLE fraud_check ADD PRIMARY KEY (frm_id, attempt_id, payment_id, merchant_id);
+
+-- Restore the historical schema exactly, including its redundant unique index.
+CREATE UNIQUE INDEX frm_id_index ON fraud_check (frm_id, attempt_id, payment_id, merchant_id);
+
+ALTER TABLE fraud_check
+ DROP COLUMN payout_id;
diff --git a/migrations/2026-09-08-120000_add_payout_id_to_fraud_check/up.sql b/migrations/2026-09-08-120000_add_payout_id_to_fraud_check/up.sql
new file mode 100644
index 0000000000..7bcf2d6cfd
--- /dev/null
+++ b/migrations/2026-09-08-120000_add_payout_id_to_fraud_check/up.sql
@@ -0,0 +1,16 @@
+-- Add payout support to fraud_check while preserving the existing payment flow.
+ALTER TABLE fraud_check
+ ADD COLUMN IF NOT EXISTS payout_id VARCHAR(64);
+
+-- payment_id is part of the existing primary key. Replace the primary key
+-- before making payment_id nullable.
+ALTER TABLE fraud_check
+ DROP CONSTRAINT fraud_check_pkey;
+
+ALTER TABLE fraud_check ADD PRIMARY KEY (frm_id);
+
+ALTER TABLE fraud_check
+ ALTER COLUMN payment_id DROP NOT NULL;
+
+-- This index duplicates the original primary key index and is not useful.
+DROP INDEX IF EXISTS frm_id_index;