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

refactor(frm): align Sale/Checkout request types with router conventions (#12274)

awasthi21ab757b6c9156
diff --git a/crates/hyperswitch_connectors/src/connectors/cybersourcedecisionmanager.rs b/crates/hyperswitch_connectors/src/connectors/cybersourcedecisionmanager.rs
index ab73bf7e11..1d35c8f23c 100644
--- a/crates/hyperswitch_connectors/src/connectors/cybersourcedecisionmanager.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cybersourcedecisionmanager.rs
@@ -9,7 +9,7 @@ use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
- types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector},
+ types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{report, Report, ResultExt};
use hyperswitch_domain_models::{
@@ -474,11 +474,7 @@ impl ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseDa
.ok_or(ConnectorError::MissingRequiredField {
field_name: "Currency",
})?;
- let amount = convert_amount(
- self.amount_converter,
- MinorUnit::new(req.request.amount),
- currency,
- )?;
+ let amount = convert_amount(self.amount_converter, req.request.amount, currency)?;
let connector_router_data =
cybersourcedecisionmanager::CybersourcedecisionmanagerRouterData::from((amount, req));
diff --git a/crates/hyperswitch_connectors/src/connectors/riskified.rs b/crates/hyperswitch_connectors/src/connectors/riskified.rs
index 071a521d27..593977c6f7 100644
--- a/crates/hyperswitch_connectors/src/connectors/riskified.rs
+++ b/crates/hyperswitch_connectors/src/connectors/riskified.rs
@@ -232,7 +232,7 @@ impl ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseDa
) -> CustomResult<RequestContent, ConnectorError> {
let amount = convert_amount(
self.amount_converter,
- MinorUnit::new(req.request.amount),
+ req.request.amount,
req.request
.currency
.ok_or(ConnectorError::MissingRequiredField {
diff --git a/crates/hyperswitch_connectors/src/connectors/signifyd.rs b/crates/hyperswitch_connectors/src/connectors/signifyd.rs
index 8fb0ae0c17..1baa723f60 100644
--- a/crates/hyperswitch_connectors/src/connectors/signifyd.rs
+++ b/crates/hyperswitch_connectors/src/connectors/signifyd.rs
@@ -1,11 +1,12 @@
pub mod transformers;
-use std::fmt::Debug;
#[cfg(feature = "frm")]
use api_models::webhooks::IncomingWebhookEvent;
#[cfg(feature = "frm")]
use base64::Engine;
#[cfg(feature = "frm")]
+use common_utils::types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector};
+#[cfg(feature = "frm")]
use common_utils::{
consts,
request::{Method, RequestBuilder},
@@ -71,17 +72,28 @@ use transformers as signifyd;
use crate::constants::headers;
#[cfg(feature = "frm")]
-use crate::{
- types::{
- FrmCheckoutRouterData, FrmCheckoutType, FrmFulfillmentRouterData, FrmFulfillmentType,
- FrmRecordReturnRouterData, FrmRecordReturnType, FrmSaleRouterData, FrmSaleType,
- FrmTransactionRouterData, FrmTransactionType, ResponseRouterData,
- },
- utils::get_header_key_value,
+use crate::types::{
+ FrmCheckoutRouterData, FrmCheckoutType, FrmFulfillmentRouterData, FrmFulfillmentType,
+ FrmRecordReturnRouterData, FrmRecordReturnType, FrmSaleRouterData, FrmSaleType,
+ FrmTransactionRouterData, FrmTransactionType, ResponseRouterData,
};
+#[cfg(feature = "frm")]
+use crate::utils::{convert_amount, get_header_key_value};
+
+#[derive(Clone)]
+pub struct Signifyd {
+ #[cfg(feature = "frm")]
+ amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
+}
-#[derive(Debug, Clone)]
-pub struct Signifyd;
+impl Signifyd {
+ pub fn new() -> &'static Self {
+ &Self {
+ #[cfg(feature = "frm")]
+ amount_converter: &FloatMajorUnitForConnector,
+ }
+ }
+}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Signifyd
where
@@ -255,7 +267,15 @@ impl ConnectorIntegration<Sale, FraudCheckSaleData, FraudCheckResponseData> for
req: &FrmSaleRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
- let req_obj = signifyd::SignifydPaymentsSaleRequest::try_from(req)?;
+ let currency = req
+ .request
+ .currency
+ .ok_or(ConnectorError::MissingRequiredField {
+ field_name: "currency",
+ })?;
+ let amount = convert_amount(self.amount_converter, req.request.amount, currency)?;
+ let req_data = signifyd::SignifydRouterData::new(amount, req);
+ let req_obj = signifyd::SignifydPaymentsSaleRequest::try_from(&req_data)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
@@ -335,7 +355,15 @@ impl ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseDa
req: &FrmCheckoutRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
- let req_obj = signifyd::SignifydPaymentsCheckoutRequest::try_from(req)?;
+ let currency = req
+ .request
+ .currency
+ .ok_or(ConnectorError::MissingRequiredField {
+ field_name: "currency",
+ })?;
+ let amount = convert_amount(self.amount_converter, req.request.amount, currency)?;
+ let req_data = signifyd::SignifydRouterData::new(amount, req);
+ let req_obj = signifyd::SignifydPaymentsCheckoutRequest::try_from(&req_data)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
@@ -709,7 +737,10 @@ impl IncomingWebhook for Signifyd {
.body
.parse_struct("SignifydWebhookBody")
.change_context(ConnectorError::WebhookEventTypeNotFound)?;
- Ok(IncomingWebhookEvent::from(resource.review_disposition))
+ Ok(resource
+ .review_disposition
+ .map(IncomingWebhookEvent::from)
+ .unwrap_or(IncomingWebhookEvent::EventNotSupported))
}
fn get_webhook_resource_object(
diff --git a/crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs b/crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs
index 52cc789a72..5ca8f75321 100644
--- a/crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs
+++ b/crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs
@@ -1,9 +1,17 @@
-use api_models::webhooks::IncomingWebhookEvent;
-use common_enums::{AttemptStatus, Currency, FraudCheckStatus, PaymentMethod};
-use common_utils::{ext_traits::ValueExt, pii::Email};
+use std::net::IpAddr;
+
+use api_models::{payments::AdditionalPaymentData, webhooks::IncomingWebhookEvent};
+use common_enums::{AttemptStatus, Currency, FraudCheckStatus, PaymentMethod, PaymentMethodType};
+use common_utils::{
+ ext_traits::ValueExt,
+ id_type,
+ pii::Email,
+ types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector, MinorUnit},
+};
use error_stack::{self, ResultExt};
pub use hyperswitch_domain_models::router_request_types::fraud_check::RefundMethod;
use hyperswitch_domain_models::{
+ address::Address as DomainAddress,
router_data::RouterData,
router_flow_types::Fulfillment,
router_request_types::{
@@ -13,7 +21,7 @@ use hyperswitch_domain_models::{
router_response_types::fraud_check::FraudCheckResponseData,
};
use hyperswitch_interfaces::errors::ConnectorError;
-use hyperswitch_masking::Secret;
+use hyperswitch_masking::{PeekInterface, Secret};
use num_traits::ToPrimitive;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -25,10 +33,27 @@ use crate::{
FrmSaleRouterData, FrmTransactionRouterData, ResponseRouterData,
},
utils::{
- AddressDetailsData as _, FraudCheckCheckoutRequest, FraudCheckRecordReturnRequest as _,
- FraudCheckSaleRequest as _, FraudCheckTransactionRequest as _, RouterData as _,
+ convert_amount, AddressDetailsData as _, FraudCheckCheckoutRequest,
+ FraudCheckRecordReturnRequest as _, FraudCheckSaleRequest as _,
+ FraudCheckTransactionRequest as _, RouterData as _,
},
};
+pub struct SignifydRouterData<T> {
+ pub amount: FloatMajorUnit,
+ pub router_data: T,
+ pub(crate) amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
+}
+
+impl<T> SignifydRouterData<T> {
+ pub fn new(amount: FloatMajorUnit, router_data: T) -> Self {
+ Self {
+ amount,
+ router_data,
+ amount_converter: &FloatMajorUnitForConnector,
+ }
+ }
+}
+
#[allow(dead_code)]
#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
@@ -37,17 +62,17 @@ pub enum DecisionDelivery {
AsyncOnly,
}
-#[derive(Debug, Serialize, Eq, PartialEq)]
+#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Purchase {
#[serde(with = "common_utils::custom_serde::iso8601")]
created_at: PrimitiveDateTime,
order_channel: OrderChannel,
- total_price: i64,
+ total_price: FloatMajorUnit,
products: Vec<Products>,
shipments: Shipments,
currency: Option<Currency>,
- total_shipping_cost: Option<i64>,
+ total_shipping_cost: Option<FloatMajorUnit>,
confirmation_email: Option<Email>,
confirmation_phone: Option<Secret<String>>,
}
@@ -79,11 +104,11 @@ pub enum FulfillmentMethod {
ScheduledDelivery,
}
-#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
+#[derive(Debug, Serialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Products {
item_name: String,
- item_price: i64,
+ item_price: FloatMajorUnit,
item_quantity: i32,
item_id: Option<String>,
item_category: Option<String>,
@@ -128,13 +153,163 @@ pub enum CoverageRequests {
None, // use when you do not need a financial guarantee. Suggested actions in decision.checkpointAction are recommendations.
}
-#[derive(Debug, Serialize, Eq, PartialEq)]
+#[serde_with::skip_serializing_none]
+#[derive(Debug, Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct Device {
+ client_ip_address: Option<IpAddr>,
+ session_id: Option<Secret<String>>,
+}
+
+#[serde_with::skip_serializing_none]
+#[derive(Debug, Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct UserAccount {
+ // `username` (Required - Technical) and `account_number` (Required - Risk)
+ // are both populated from Hyperswitch's `customer_id` — HS only carries one
+ // customer identifier, and Signifyd's cert kit explicitly requires `username`
+ // to be supplied even when it duplicates another field on the same payload.
+ username: Option<id_type::CustomerId>,
+ email: Option<Email>,
+ phone: Option<Secret<String>>,
+ account_number: Option<id_type::CustomerId>,
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum PaymentMethodKind {
+ CreditCard,
+ DebitCard,
+ GiftCard,
+ PrepaidCard,
+ SnapCard,
+ Other,
+}
+
+#[derive(Debug, Serialize, PartialEq, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct BillingAddress {
+ street_address: Option<Secret<String>>,
+ unit: Option<Secret<String>>,
+ postal_code: Option<Secret<String>>,
+ city: Option<String>,
+ province_code: Option<Secret<String>>,
+ country_code: Option<common_enums::CountryAlpha2>,
+}
+
+impl From<&DomainAddress> for BillingAddress {
+ fn from(address: &DomainAddress) -> Self {
+ let details = address.address.as_ref();
+ Self {
+ street_address: details.and_then(|d| d.line1.clone()),
+ unit: details.and_then(|d| d.line2.clone()),
+ postal_code: details.and_then(|d| d.zip.clone()),
+ city: details.and_then(|d| d.city.clone()),
+ province_code: details.and_then(|d| d.state.clone()),
+ country_code: details.and_then(|d| d.country),
+ }
+ }
+}
+
+#[derive(Debug, Serialize, PartialEq, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct CheckoutPaymentDetails {
+ account_holder_name: Option<Secret<String>>,
+ card_bin: Option<String>,
+ // Signifyd's schema (cert kit "signifyd-required-data.csv": "integer")
+ // requires `cardExpiryMonth` / `cardExpiryYear` as integers, not strings.
+ // HS' `CardData` trait helpers (`get_expiry_month_as_i8`,
+ // `get_expiry_year_as_4_digit_i32`) target `Card`, not `AdditionalCardInfo`,
+ // so we parse once via `parse_card_digits` at struct construction.
+ card_expiry_month: Option<Secret<i32>>,
+ card_expiry_year: Option<Secret<i32>>,
+ card_last4: Option<String>,
+ billing_address: Option<BillingAddress>,
+}
+
+#[derive(Debug, Serialize, PartialEq, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct Transaction {
+ payment_method: PaymentMethodKind,
+ amount: FloatMajorUnit,
+ currency: Currency,
+ gateway: Option<String>,
+ checkout_payment_details: CheckoutPaymentDetails,
+}
+
+fn map_payment_method_kind(value: Option<PaymentMethodType>) -> PaymentMethodKind {
+ match value {
+ Some(PaymentMethodType::Credit) => PaymentMethodKind::CreditCard,
+ Some(PaymentMethodType::Debit) => PaymentMethodKind::DebitCard,
+ _ => PaymentMethodKind::Other,
+ }
+}
+
+/// Parse an `Option<Secret<String>>` card-expiry field to `i32`. Used for
+/// Signifyd's integer-typed `cardExpiryMonth` / `cardExpiryYear`. Mirrors HS'
+/// `CardData::get_expiry_year_as_4_digit_i32` but works on `AdditionalCardInfo`'s
+/// `Option<Secret<String>>` (the `CardData` trait targets `Card`, not
+/// `AdditionalCardInfo`). Returns `None` if missing or unparseable.
+fn parse_card_digits(value: Option<&Secret<String>>) -> Option<Secret<i32>> {
+ value.and_then(|s| s.peek().trim().parse::<i32>().ok().map(Secret::new))
+}
+
+/// Parse a card-expiry year to a 4-digit `i32`. Mirrors the canonical
+/// `CardData::get_expiry_year_4_digit` heuristic (string-length check) before
+/// parsing.
+fn parse_card_year_4_digit(value: Option<&Secret<String>>) -> Option<Secret<i32>> {
+ value.and_then(|s| {
+ let raw = s.peek().trim();
+ let four_digit = if raw.len() == 2 {
+ format!("20{raw}")
+ } else {
+ raw.to_string()
+ };
+ four_digit.parse::<i32>().ok().map(Secret::new)
+ })
+}
+
+fn build_transaction(
+ payment_method_data: Option<&AdditionalPaymentData>,
+ payment_method_type: Option<PaymentMethodType>,
+ amount: FloatMajorUnit,
+ currency: Currency,
+ gateway: Option<&String>,
+ billing_address: Option<&DomainAddress>,
+) -> Option<Transaction> {
+ let card_info = payment_method_data?.get_additional_card_info()?;
+
+ let checkout_payment_details = CheckoutPaymentDetails {
+ account_holder_name: card_info.card_holder_name.clone(),
+ card_bin: card_info.card_isin.clone(),
+ card_expiry_month: parse_card_digits(card_info.card_exp_month.as_ref()),
+ card_expiry_year: parse_card_year_4_digit(card_info.card_exp_year.as_ref()),
+ card_last4: card_info.last4.clone(),
+ billing_address: billing_address.map(BillingAddress::from),
+ };
+
+ Some(Transaction {
+ payment_method: map_payment_method_kind(payment_method_type),
+ amount,
+ currency,
+ gateway: gateway.cloned(),
+ checkout_payment_details,
+ })
+}
+
+#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SignifydPaymentsSaleRequest {
order_id: String,
purchase: Purchase,
decision_delivery: DecisionDelivery,
coverage_requests: Option<CoverageRequests>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ device: Option<Device>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ user_account: Option<UserAccount>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ transactions: Option<Vec<Transaction>>,
}
#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
@@ -144,28 +319,68 @@ pub struct SignifydFrmMetadata {
pub fulfillment_method: Option<FulfillmentMethod>,
pub coverage_request: Option<CoverageRequests>,
pub order_channel: OrderChannel,
+ #[serde(default)]
+ pub session_id: Option<Secret<String>>,
}
-impl TryFrom<&FrmSaleRouterData> for SignifydPaymentsSaleRequest {
+fn build_user_account(
+ customer_id: Option<&id_type::CustomerId>,
+ email: Option<&Email>,
+ phone: Option<&Secret<String>>,
+) -> Option<UserAccount> {
+ let username = customer_id.cloned();
+ let account_number = customer_id.cloned();
+ let email = email.cloned();
+ let phone = phone.cloned();
+
+ if [username.is_none(), email.is_none(), phone.is_none()]
+ .iter()
+ .all(|is_none| *is_none)
+ {
+ return None;
+ }
+
+ Some(UserAccount {
+ username,
+ email,
+ phone,
+ account_number,
+ })
+}
+
+impl TryFrom<&SignifydRouterData<&FrmSaleRouterData>> for SignifydPaymentsSaleRequest {
type Error = error_stack::Report<ConnectorError>;
- fn try_from(item: &FrmSaleRouterData) -> Result<Self, Self::Error> {
+ fn try_from(data: &SignifydRouterData<&FrmSaleRouterData>) -> Result<Self, Self::Error> {
+ let item = data.router_data;
+ let currency = item
+ .request
+ .currency
+ .ok_or(ConnectorError::MissingRequiredField {
+ field_name: "currency",
+ })?;
let products = item
.request
.get_order_details()?
.iter()
- .map(|order_detail| Products {
- item_name: order_detail.product_name.clone(),
- item_price: order_detail.amount.get_amount_as_i64(), // This should be changed to MinorUnit when we implement amount conversion for this connector. Additionally, the function get_amount_as_i64() should be avoided in the future.
- item_quantity: i32::from(order_detail.quantity),
- item_id: order_detail.product_id.clone(),
- item_category: order_detail.category.clone(),
- item_sub_category: order_detail.sub_category.clone(),
- item_is_digital: order_detail
- .product_type
- .as_ref()
- .map(|product| product == &common_enums::ProductType::Digital),
+ .map(|order_detail| {
+ Ok::<_, error_stack::Report<ConnectorError>>(Products {
+ item_name: order_detail.product_name.clone(),
+ item_price: convert_amount(
+ data.amount_converter,
+ order_detail.amount,
+ currency,
+ )?,
+ item_quantity: i32::from(order_detail.quantity),
+ item_id: order_detail.product_id.clone(),
+ item_category: order_detail.category.clone(),
+ item_sub_category: order_detail.sub_category.clone(),
+ item_is_digital: order_detail
+ .product_type
+ .as_ref()
+ .map(|product| product == &common_enums::ProductType::Digital),
+ })
})
- .collect::<Vec<_>>();
+ .collect::<Result<Vec<_>, _>>()?;
let metadata: SignifydFrmMetadata = item
.frm_metadata
.clone()
@@ -178,52 +393,79 @@ impl TryFrom<&FrmSaleRouterData> for SignifydPaymentsSaleRequest {
})?;
let ship_address = item.get_shipping_address()?;
let billing_address = item.get_billing()?;
- let street_addr = ship_address.get_line1()?;
- let city_addr = ship_address.get_city()?;
- let zip_code_addr = ship_address.get_zip()?;
- let country_code_addr = ship_address.get_country()?;
- let _first_name_addr = ship_address.get_first_name()?;
- let _last_name_addr = ship_address.get_last_name()?;
let address: Address = Address {
- street_address: street_addr.clone(),
+ street_address: ship_address.get_line1()?.clone(),
unit: None,
- postal_code: zip_code_addr.clone(),
- city: city_addr.clone(),
- province_code: zip_code_addr.clone(),
- country_code: country_code_addr.to_owned(),
+ postal_code: ship_address.get_zip()?.clone(),
+ city: ship_address.get_city()?.clone(),
+ province_code: ship_address.get_state()?.clone(),
+ country_code: ship_address.get_country()?.to_owned(),
};
let destination: Destination = Destination {
- full_name: ship_address.get_full_name().unwrap_or_default(),
+ full_name: ship_address.get_full_name()?,
organization: None,
email: None,
address,
};
+ let total_price = data.amount;
+ let total_shipping_cost = metadata
+ .total_shipping_cost
+ .map(|cost| convert_amount(data.amount_converter, MinorUnit::new(cost), currency))
+ .transpose()?;
+
let created_at = common_utils::date_time::now();
let order_channel = metadata.order_channel;
let shipments = Shipments {
destination,
fulfillment_method: metadata.fulfillment_method,
};
+ let confirmation_email = item.request.email.clone();
let purchase = Purchase {
created_at,
order_channel,
- total_price: item.request.amount,
+ total_price,
products,
shipments,
currency: item.request.currency,
- total_shipping_cost: metadata.total_shipping_cost,
- confirmation_email: item.request.email.clone(),
+ total_shipping_cost,
+ confirmation_email,
confirmation_phone: billing_address
.clone()
.phone
.and_then(|phone_data| phone_data.number),
};
+ let client_ip_address = item.request.client_ip;
+ let session_id = metadata.session_id.clone();
+ let device = match (client_ip_address, session_id.clone()) {
+ (None, None) => None,
+ _ => Some(Device {
+ client_ip_address,
+ session_id,
+ }),
+ };
+ let user_account = build_user_account(
+ item.request.customer_id.as_ref(),
+ item.request.email.as_ref(),
+ item.request.phone.as_ref(),
+ );
+ let transactions = build_transaction(
+ item.request.payment_method_data.as_ref(),
+ item.payment_method_type,
+ data.amount,
+ currency,
+ item.request.gateway.as_ref(),
+ item.get_optional_billing(),
+ )
+ .map(|t| vec![t]);
Ok(Self {
order_id: item.attempt_id.clone(),
purchase,
decision_delivery: DecisionDelivery::Sync, // Specify SYNC if you require the Response to contain a decision field. If you have registered for a webhook associated with this checkpoint, then the webhook will also be sent when SYNC is specified. If ASYNC_ONLY is specified, then the decision field in the response will be null, and you will require a Webhook integration to receive Signifyd's final decision
coverage_requests: metadata.coverage_request,
+ device,
+ user_account,
+ transactions,
})
}
}
@@ -371,35 +613,54 @@ pub enum GatewayStatusCode {
SoftDecline,
}
-#[derive(Debug, Serialize, Eq, PartialEq)]
+#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SignifydPaymentsCheckoutRequest {
checkout_id: String,
order_id: String,
purchase: Purchase,
coverage_requests: Option<CoverageRequests>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ device: Option<Device>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ user_account: Option<UserAccount>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ transactions: Option<Vec<Transaction>>,
}
-impl TryFrom<&FrmCheckoutRouterData> for SignifydPaymentsCheckoutRequest {
+impl TryFrom<&SignifydRouterData<&FrmCheckoutRouterData>> for SignifydPaymentsCheckoutRequest {
type Error = error_stack::Report<ConnectorError>;
- fn try_from(item: &FrmCheckoutRouterData) -> Result<Self, Self::Error> {
+ fn try_from(data: &SignifydRouterData<&FrmCheckoutRouterData>) -> Result<Self, Self::Error> {
+ let item = data.router_data;
+ let currency = item
+ .request
+ .currency
+ .ok_or(ConnectorError::MissingRequiredField {
+ field_name: "currency",
+ })?;
let products = item
.request
.get_order_details()?
.iter()
- .map(|order_detail| Products {
- item_name: order_detail.product_name.clone(),
- item_price: order_detail.amount.get_amount_as_i64(), // This should be changed to MinorUnit when we implement amount conversion for this connector. Additionally, the function get_amount_as_i64() should be avoided in the future.
- item_quantity: i32::from(order_detail.quantity),
- item_id: order_detail.product_id.clone(),
- item_category: order_detail.category.clone(),
- item_sub_category: order_detail.sub_category.clone(),
- item_is_digital: order_detail
- .product_type
- .as_ref()
- .map(|product| product == &common_enums::ProductType::Digital),
+ .map(|order_detail| {
+ Ok::<_, error_stack::Report<ConnectorError>>(Products {
+ item_name: order_detail.product_name.clone(),
+ item_price: convert_amount(
+ data.amount_converter,
+ order_detail.amount,
+ currency,
+ )?,
+ item_quantity: i32::from(order_detail.quantity),
+ item_id: order_detail.product_id.clone(),
+ item_category: order_detail.category.clone(),
+ item_sub_category: order_detail.sub_category.clone(),
+ item_is_digital: order_detail
+ .product_type
+ .as_ref()
+ .map(|product| product == &common_enums::ProductType::Digital),
+ })
})
- .collect::<Vec<_>>();
+ .collect::<Result<Vec<_>, _>>()?;
let metadata: SignifydFrmMetadata = item
.frm_metadata
.clone()
@@ -411,52 +672,80 @@ impl TryFrom<&FrmCheckoutRouterData> for SignifydPaymentsCheckoutRequest {
field_name: "frm_metadata",
})?;
let ship_address = item.get_shipping_address()?;
- let street_addr = ship_address.get_line1()?;
- let city_addr = ship_address.get_city()?;
- let zip_code_addr = ship_address.get_zip()?;
- let country_code_addr = ship_address.get_country()?;
- let _first_name_addr = ship_address.get_first_name()?;
- let _last_name_addr = ship_address.get_last_name()?;
let billing_address = item.get_billing()?;
let address: Address = Address {
- street_address: street_addr.clone(),
+ street_address: ship_address.get_line1()?.clone(),
unit: None,
- postal_code: zip_code_addr.clone(),
- city: city_addr.clone(),
- province_code: zip_code_addr.clone(),
- country_code: country_code_addr.to_owned(),
+ postal_code: ship_address.get_zip()?.clone(),
+ city: ship_address.get_city()?.clone(),
+ province_code: ship_address.get_state()?.clone(),
+ country_code: ship_address.get_country()?.to_owned(),
};
let destination: Destination = Destination {
- full_name: ship_address.get_full_name().unwrap_or_default(),
+ full_name: ship_address.get_full_name()?,
organization: None,
email: None,
address,
};
+
+ let total_price = data.amount;
+ let total_shipping_cost = metadata
+ .total_shipping_cost
+ .map(|cost| convert_amount(data.amount_converter, MinorUnit::new(cost), currency))
+ .transpose()?;
+
let created_at = common_utils::date_time::now();
let order_channel = metadata.order_channel;
let shipments: Shipments = Shipments {
destination,
fulfillment_method: metadata.fulfillment_method,
};
+ let confirmation_email = item.request.email.clone();
let purchase = Purchase {
created_at,
order_channel,
- total_price: item.request.amount,
+ total_price,
products,
shipments,
currency: item.request.currency,
- total_shipping_cost: metadata.total_shipping_cost,
- confirmation_email: item.request.email.clone(),
+ total_shipping_cost,
+ confirmation_email,
confirmation_phone: billing_address
.clone()
.phone
.and_then(|phone_data| phone_data.number),
};
+ let client_ip_address = item.request.client_ip;
+ let session_id = metadata.session_id.clone();
+ let device = match (client_ip_address, session_id.clone()) {
+ (None, None) => None,
+ _ => Some(Device {
+ client_ip_address,
+ session_id,
+ }),
+ };
+ let user_account = build_user_account(
+ item.request.customer_id.as_ref(),
+ item.request.email.as_ref(),
+ item.request.phone.as_ref(),
+ );
+ let transactions = build_transaction(
+ item.request.payment_method_data.as_ref(),
+ item.payment_method_type,
+ data.amount,
+ currency,
+ item.request.gateway.as_ref(),
+ item.get_optional_billing(),
+ )
+ .map(|t| vec![t]);
Ok(Self {
checkout_id: item.payment_id.clone(),
order_id: item.attempt_id.clone(),
purchase,
coverage_requests: metadata.coverage_request,
+ device,
+ user_account,
+ transactions,
})
}
}
@@ -701,7 +990,11 @@ impl TryFrom<&FrmRecordReturnRouterData> for SignifydPaymentsRecordReturnRequest
#[serde(rename_all = "camelCase")]
pub struct SignifydWebhookBody {
pub order_id: String,
- pub review_disposition: ReviewDisposition,
+ // Signifyd may emit dispositions like UNSET / IN_REVIEW / UNCONFIRMED for
+ // in-flight or manually-reviewed cases. Make the field tolerant so the
+ // webhook deserializes even when the disposition is not yet a final
+ // GOOD/FRAUDULENT decision.
+ pub review_disposition: Option<ReviewDisposition>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
@@ -709,13 +1002,24 @@ pub struct SignifydWebhookBody {
pub enum ReviewDisposition {
Fraudulent,
Good,
+ Unset,
+ Unconfirmed,
+ InReview,
+ Approved,
+ Declined,
+ #[serde(other)]
+ Unknown,
}
impl From<ReviewDisposition> for IncomingWebhookEvent {
fn from(value: ReviewDisposition) -> Self {
match value {
- ReviewDisposition::Fraudulent => Self::FrmRejected,
- ReviewDisposition::Good => Self::FrmApproved,
+ ReviewDisposition::Fraudulent | ReviewDisposition::Declined => Self::FrmRejected,
+ ReviewDisposition::Good | ReviewDisposition::Approved => Self::FrmApproved,
+ ReviewDisposition::Unset
+ | ReviewDisposition::Unconfirmed
+ | ReviewDisposition::InReview
+ | ReviewDisposition::Unknown => Self::EventNotSupported,
}
}
}
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 f6cd17768b..3879ca751c 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
@@ -1,6 +1,7 @@
use common_utils::{
events::{ApiEventMetric, ApiEventsType},
pii::Email,
+ types::MinorUnit,
};
use diesel_models::types::OrderDetailsWithAmount;
use hyperswitch_masking::Secret;
@@ -8,23 +9,34 @@ use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::router_request_types;
+
#[derive(Debug, Clone)]
pub struct FraudCheckSaleData {
- pub amount: i64,
+ pub amount: MinorUnit,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub currency: Option<common_enums::Currency>,
+ pub gateway: Option<String>,
+ pub client_ip: Option<std::net::IpAddr>,
+ pub customer_id: Option<common_utils::id_type::CustomerId>,
pub email: Option<Email>,
+ pub phone: Option<Secret<String>>,
+ pub phone_country_code: Option<String>,
+ pub payment_method_data: Option<api_models::payments::AdditionalPaymentData>,
}
#[derive(Debug, Clone)]
pub struct FraudCheckCheckoutData {
- pub amount: i64,
+ pub amount: MinorUnit,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub currency: Option<common_enums::Currency>,
pub browser_info: Option<router_request_types::BrowserInformation>,
pub payment_method_data: Option<api_models::payments::AdditionalPaymentData>,
- pub email: Option<Email>,
pub gateway: Option<String>,
+ pub client_ip: Option<std::net::IpAddr>,
+ pub customer_id: Option<common_utils::id_type::CustomerId>,
+ pub email: Option<Email>,
+ pub phone: Option<Secret<String>>,
+ pub phone_country_code: Option<String>,
}
#[derive(Debug, Clone)]
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 af5ed50a57..90c8feab12 100644
--- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs
@@ -66,6 +66,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC
})?;
let browser_info: Option<BrowserInformation> = self.payment_attempt.get_browser_info().ok();
+ let client_ip = browser_info.as_ref().and_then(|info| info.ip_address);
let customer_id = self.payment_intent.customer_id.clone();
let customer_details = self
@@ -83,10 +84,16 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC
.attach_printable("Failed to parse customer data from payment intent")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
+ let email = customer_details.as_ref().and_then(|c| c.email.clone());
+ let phone = customer_details.as_ref().and_then(|c| c.phone.clone());
+ let phone_country_code = customer_details
+ .as_ref()
+ .and_then(|c| c.phone_country_code.clone());
+
let router_data = RouterData {
flow: std::marker::PhantomData,
merchant_id: processor.get_account().get_id().clone(),
- customer_id,
+ customer_id: customer_id.clone(),
tenant_id: state.tenant.tenant_id.clone(),
connector: connector_id.to_string(),
payment_id: self.payment_intent.payment_id.get_string_repr().to_owned(),
@@ -107,32 +114,33 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC
amount_captured: None,
minor_amount_captured: None,
request: FraudCheckCheckoutData {
- amount: self
- .payment_attempt
- .net_amount
- .get_total_amount()
- .get_amount_as_i64(),
+ amount: self.payment_attempt.net_amount.get_total_amount(),
order_details: self.order_details.clone(),
currency: self.payment_attempt.currency,
browser_info,
- payment_method_data: self
- .payment_attempt
- .payment_method_data
- .as_ref()
- .map(|pm_data| {
+ payment_method_data: self.payment_attempt.payment_method_data.as_ref().and_then(
+ |pm_data| {
pm_data
.clone()
.parse_value::<api_models::payments::AdditionalPaymentData>(
"AdditionalPaymentData",
)
- })
- .transpose()
- .unwrap_or_default(),
- email: customer_details
- .as_ref()
- .and_then(|customer_data| customer_data.email.clone()),
+ .inspect_err(|err| {
+ router_env::logger::warn!(
+ ?err,
+ "Failed to parse AdditionalPaymentData for FRM checkout flow"
+ )
+ })
+ .ok()
+ },
+ ),
gateway: self.payment_attempt.connector.clone(),
- }, // self.order_details
+ client_ip,
+ customer_id,
+ email,
+ phone,
+ phone_country_code,
+ },
response: Ok(FraudCheckResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId("".to_string()),
connector_metadata: None,
diff --git a/crates/router/src/core/fraud_check/flows/sale_flow.rs b/crates/router/src/core/fraud_check/flows/sale_flow.rs
index 506fe09102..8d99712c9b 100644
--- a/crates/router/src/core/fraud_check/flows/sale_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs
@@ -16,7 +16,7 @@ use crate::{
domain,
fraud_check::{FraudCheckResponseData, FraudCheckSaleData, FrmSaleRouterData},
storage::enums as storage_enums,
- ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData,
+ BrowserInformation, ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData,
},
SessionState,
};
@@ -77,10 +77,46 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp
.attach_printable("Failed to parse customer data from payment intent")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
+ let client_ip = self
+ .payment_attempt
+ .browser_info
+ .clone()
+ .and_then(|browser_info_value| {
+ browser_info_value
+ .parse_value::<BrowserInformation>("BrowserInformation")
+ .ok()
+ })
+ .and_then(|browser_info| browser_info.ip_address);
+
+ let payment_method_data =
+ self.payment_attempt
+ .payment_method_data
+ .as_ref()
+ .and_then(|pm_data| {
+ pm_data
+ .clone()
+ .parse_value::<api_models::payments::AdditionalPaymentData>(
+ "AdditionalPaymentData",
+ )
+ .inspect_err(|err| {
+ router_env::logger::warn!(
+ ?err,
+ "Failed to parse AdditionalPaymentData for FRM sale flow"
+ )
+ })
+ .ok()
+ });
+
+ let email = customer_details.as_ref().and_then(|c| c.email.clone());
+ let phone = customer_details.as_ref().and_then(|c| c.phone.clone());
+ let phone_country_code = customer_details
+ .as_ref()
+ .and_then(|c| c.phone_country_code.clone());
+
let router_data = RouterData {
flow: std::marker::PhantomData,
merchant_id: processor.get_account().get_id().clone(),
- customer_id,
+ customer_id: customer_id.clone(),
connector: connector_id.to_string(),
payment_id: self.payment_intent.payment_id.get_string_repr().to_owned(),
attempt_id: self.payment_attempt.attempt_id.clone(),
@@ -100,16 +136,16 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp
amount_captured: None,
minor_amount_captured: None,
request: FraudCheckSaleData {
- amount: self
- .payment_attempt
- .net_amount
- .get_total_amount()
- .get_amount_as_i64(),
+ amount: self.payment_attempt.net_amount.get_total_amount(),
order_details: self.order_details.clone(),
currency: self.payment_attempt.currency,
- email: customer_details
- .as_ref()
- .and_then(|customer_data| customer_data.email.clone()),
+ gateway: self.payment_attempt.connector.clone(),
+ client_ip,
+ customer_id,
+ email,
+ phone,
+ phone_country_code,
+ payment_method_data,
},
response: Ok(FraudCheckResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId("".to_string()),
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 58cf3f4d28..b9aa39a7ba 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
@@ -206,7 +206,13 @@ where
amount: router_data.request.amount,
order_details: router_data.request.order_details,
currency: router_data.request.currency,
+ gateway: router_data.request.gateway,
+ client_ip: router_data.request.client_ip,
+ customer_id: router_data.request.customer_id,
email: router_data.request.email,
+ phone: router_data.request.phone,
+ phone_country_code: router_data.request.phone_country_code,
+ payment_method_data: router_data.request.payment_method_data,
}),
response: FrmResponse::Sale(router_data.response),
}))
@@ -366,7 +372,13 @@ where
amount: router_data.request.amount,
order_details: router_data.request.order_details,
currency: router_data.request.currency,
+ gateway: router_data.request.gateway,
+ client_ip: router_data.request.client_ip,
+ customer_id: router_data.request.customer_id,
email: router_data.request.email,
+ phone: router_data.request.phone,
+ phone_country_code: router_data.request.phone_country_code,
+ payment_method_data: router_data.request.payment_method_data,
}),
response: FrmResponse::Sale(router_data.response),
})
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 b96d1a6f85..7ecda8437f 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
@@ -253,8 +253,12 @@ where
currency: router_data.request.currency,
browser_info: router_data.request.browser_info,
payment_method_data: router_data.request.payment_method_data,
- email: router_data.request.email,
gateway: router_data.request.gateway,
+ client_ip: router_data.request.client_ip,
+ customer_id: router_data.request.customer_id,
+ email: router_data.request.email,
+ phone: router_data.request.phone,
+ phone_country_code: router_data.request.phone_country_code,
})),
response: FrmResponse::Checkout(router_data.response),
})
diff --git a/crates/router/src/types/api/feature_matrix.rs b/crates/router/src/types/api/feature_matrix.rs
index b2756b1d55..fe86f32ede 100644
--- a/crates/router/src/types/api/feature_matrix.rs
+++ b/crates/router/src/types/api/feature_matrix.rs
@@ -424,7 +424,7 @@ impl FeatureMatrixConnectorData {
Ok(ConnectorEnum::Old(Box::new(connector::Plaid::new())))
}
enums::Connector::Signifyd => {
- Ok(ConnectorEnum::Old(Box::new(&connector::Signifyd)))
+ Ok(ConnectorEnum::Old(Box::new(connector::Signifyd::new())))
}
enums::Connector::Silverflow => {
Ok(ConnectorEnum::Old(Box::new(connector::Silverflow::new())))
diff --git a/crates/router/src/types/api/fraud_check.rs b/crates/router/src/types/api/fraud_check.rs
index a644a5baad..67e2141d04 100644
--- a/crates/router/src/types/api/fraud_check.rs
+++ b/crates/router/src/types/api/fraud_check.rs
@@ -60,7 +60,7 @@ impl FraudCheckConnectorData {
) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> {
match connector_name {
enums::FrmConnectors::Signifyd => {
- Ok(ConnectorEnum::Old(Box::new(&connector::Signifyd)))
+ Ok(ConnectorEnum::Old(Box::new(connector::Signifyd::new())))
}
enums::FrmConnectors::Riskified => {
Ok(ConnectorEnum::Old(Box::new(connector::Riskified::new())))