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

chore: move RouterData Request types to hyperswitch_domain_models crate (#4723)

Hrithikeshae77373b4cac
diff --git a/Cargo.lock b/Cargo.lock
index 89a0d9d507..9411c009ae 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3667,18 +3667,25 @@ dependencies = [
name = "hyperswitch_domain_models"
version = "0.1.0"
dependencies = [
+ "actix-web",
"api_models",
"async-trait",
+ "cards",
"common_enums",
"common_utils",
"diesel_models",
"error-stack",
"http 0.2.12",
"masking",
+ "mime",
+ "router_derive",
"serde",
"serde_json",
+ "serde_with",
"thiserror",
"time",
+ "url",
+ "utoipa",
]
[[package]]
@@ -6051,6 +6058,7 @@ dependencies = [
"error-stack",
"external_services",
"futures 0.3.30",
+ "hyperswitch_domain_models",
"masking",
"num_cpus",
"once_cell",
diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml
index dd3335cb2c..c1db2a4fb9 100644
--- a/crates/hyperswitch_domain_models/Cargo.toml
+++ b/crates/hyperswitch_domain_models/Cargo.toml
@@ -14,17 +14,25 @@ payouts = ["api_models/payouts"]
[dependencies]
# First party deps
-api_models = { version = "0.1.0", path = "../api_models" }
+api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] }
common_enums = { version = "0.1.0", path = "../common_enums" }
common_utils = { version = "0.1.0", path = "../common_utils" }
masking = { version = "0.1.0", path = "../masking" }
diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] }
+cards = {version = "0.1.0", path = "../cards"}
+router_derive = {version = "0.1.0", path = "../router_derive"}
# Third party deps
+actix-web = "4.5.1"
async-trait = "0.1.79"
error-stack = "0.4.1"
http = "0.2.12"
+mime = "0.3.17"
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
+serde_with = "3.7.0"
thiserror = "1.0.58"
time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] }
+url = { version = "2.5.0", features = ["serde"] }
+utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order", "time"] }
+
diff --git a/crates/hyperswitch_domain_models/src/errors.rs b/crates/hyperswitch_domain_models/src/errors.rs
index bed1ab9ccb..bd05e1a377 100644
--- a/crates/hyperswitch_domain_models/src/errors.rs
+++ b/crates/hyperswitch_domain_models/src/errors.rs
@@ -1,3 +1,4 @@
+pub mod api_error_response;
use diesel_models::errors::DatabaseError;
pub type StorageResult<T> = error_stack::Result<T, StorageError>;
diff --git a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
new file mode 100644
index 0000000000..26a6f1618f
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
@@ -0,0 +1,634 @@
+use api_models::errors::types::Extra;
+use common_utils::errors::ErrorSwitch;
+use http::StatusCode;
+
+use crate::router_data;
+
+#[derive(Clone, Debug, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ErrorType {
+ InvalidRequestError,
+ ObjectNotFound,
+ RouterError,
+ ProcessingError,
+ BadGateway,
+ ServerNotAvailable,
+ DuplicateRequest,
+ ValidationError,
+ ConnectorError,
+ LockTimeout,
+}
+
+#[derive(Debug, Clone, router_derive::ApiError)]
+#[error(error_type_enum = ErrorType)]
+pub enum ApiErrorResponse {
+ #[error(error_type = ErrorType::ServerNotAvailable, code = "IR_00", message = "{message:?}")]
+ NotImplemented { message: NotImplementedMessage },
+ #[error(
+ error_type = ErrorType::InvalidRequestError, code = "IR_01",
+ message = "API key not provided or invalid API key used"
+ )]
+ Unauthorized,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_02", message = "Unrecognized request URL")]
+ InvalidRequestUrl,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_03", message = "The HTTP method is not applicable for this API")]
+ InvalidHttpMethod,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_04", message = "Missing required param: {field_name}")]
+ MissingRequiredField { field_name: &'static str },
+ #[error(
+ error_type = ErrorType::InvalidRequestError, code = "IR_05",
+ message = "{field_name} contains invalid data. Expected format is {expected_format}"
+ )]
+ InvalidDataFormat {
+ field_name: String,
+ expected_format: String,
+ },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_06", message = "{message}")]
+ InvalidRequestData { message: String },
+ /// Typically used when a field has invalid value, or deserialization of the value contained in a field fails.
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_07", message = "Invalid value provided: {field_name}")]
+ InvalidDataValue { field_name: &'static str },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Client secret was not provided")]
+ ClientSecretNotGiven,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Client secret has expired")]
+ ClientSecretExpired,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_09", message = "The client_secret provided does not match the client_secret associated with the Payment")]
+ ClientSecretInvalid,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_10", message = "Customer has active mandate/subsciption")]
+ MandateActive,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_11", message = "Customer has already been redacted")]
+ CustomerRedacted,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_12", message = "Reached maximum refund attempts")]
+ MaximumRefundCount,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_13", message = "The refund amount exceeds the amount captured")]
+ RefundAmountExceedsPaymentAmount,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_14", message = "This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}")]
+ PaymentUnexpectedState {
+ current_flow: String,
+ field_name: String,
+ current_value: String,
+ states: String,
+ },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_15", message = "Invalid Ephemeral Key for the customer")]
+ InvalidEphemeralKey,
+ /// Typically used when information involving multiple fields or previously provided information doesn't satisfy a condition.
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_16", message = "{message}")]
+ PreconditionFailed { message: String },
+ #[error(
+ error_type = ErrorType::InvalidRequestError, code = "IR_17",
+ message = "Access forbidden, invalid JWT token was used"
+ )]
+ InvalidJwtToken,
+ #[error(
+ error_type = ErrorType::InvalidRequestError, code = "IR_18",
+ message = "{message}",
+ )]
+ GenericUnauthorized { message: String },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_19", message = "{message}")]
+ NotSupported { message: String },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_20", message = "{flow} flow not supported by the {connector} connector")]
+ FlowNotSupported { flow: String, connector: String },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_21", message = "Missing required params")]
+ MissingRequiredFields { field_names: Vec<&'static str> },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_22", message = "Access forbidden. Not authorized to access this resource {resource}")]
+ AccessForbidden { resource: String },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_23", message = "{message}")]
+ FileProviderNotSupported { message: String },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_23", message = "{message}")]
+ UnprocessableEntity { message: String },
+ #[error(
+ error_type = ErrorType::ProcessingError, code = "IR_24",
+ message = "Invalid {wallet_name} wallet token"
+ )]
+ InvalidWalletToken { wallet_name: String },
+ #[error(error_type = ErrorType::ConnectorError, code = "CE_00", message = "{code}: {message}", ignore = "status_code")]
+ ExternalConnectorError {
+ code: String,
+ message: String,
+ connector: String,
+ status_code: u16,
+ reason: Option<String>,
+ },
+ #[error(error_type = ErrorType::ProcessingError, code = "CE_01", message = "Payment failed during authorization with connector. Retry payment")]
+ PaymentAuthorizationFailed { data: Option<serde_json::Value> },
+ #[error(error_type = ErrorType::ProcessingError, code = "CE_02", message = "Payment failed during authentication with connector. Retry payment")]
+ PaymentAuthenticationFailed { data: Option<serde_json::Value> },
+ #[error(error_type = ErrorType::ProcessingError, code = "CE_03", message = "Capture attempt failed while processing with connector")]
+ PaymentCaptureFailed { data: Option<serde_json::Value> },
+ #[error(error_type = ErrorType::ProcessingError, code = "CE_04", message = "The card data is invalid")]
+ InvalidCardData { data: Option<serde_json::Value> },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "CE_04", message = "Payout validation failed")]
+ PayoutFailed { data: Option<serde_json::Value> },
+ #[error(error_type = ErrorType::ProcessingError, code = "CE_05", message = "The card has expired")]
+ CardExpired { data: Option<serde_json::Value> },
+ #[error(error_type = ErrorType::ProcessingError, code = "CE_06", message = "Refund failed while processing with connector. Retry refund")]
+ RefundFailed { data: Option<serde_json::Value> },
+ #[error(error_type = ErrorType::ProcessingError, code = "CE_07", message = "Verification failed while processing with connector. Retry operation")]
+ VerificationFailed { data: Option<serde_json::Value> },
+ #[error(error_type = ErrorType::ProcessingError, code = "CE_08", message = "Dispute operation failed while processing with connector. Retry operation")]
+ DisputeFailed { data: Option<serde_json::Value> },
+ #[error(error_type = ErrorType::ServerNotAvailable, code = "HE_00", message = "Something went wrong")]
+ InternalServerError,
+ #[error(error_type = ErrorType::LockTimeout, code = "HE_00", message = "Resource is busy. Please try again later.")]
+ ResourceBusy,
+ #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "Duplicate refund request. Refund already attempted with the refund ID")]
+ DuplicateRefundRequest,
+ #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "Duplicate mandate request. Mandate already attempted with the Mandate ID")]
+ DuplicateMandate,
+ #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The merchant account with the specified details already exists in our records")]
+ DuplicateMerchantAccount,
+ #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_label}' already exists in our records")]
+ DuplicateMerchantConnectorAccount {
+ profile_id: String,
+ connector_label: String,
+ },
+ #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment method with the specified details already exists in our records")]
+ DuplicatePaymentMethod,
+ #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment with the specified payment_id already exists in our records")]
+ DuplicatePayment { payment_id: String },
+ #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payout with the specified payout_id '{payout_id}' already exists in our records")]
+ DuplicatePayout { payout_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")]
+ RefundNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Customer does not exist in our records")]
+ CustomerNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "RE_02", message = "Config key does not exist in our records.")]
+ 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 = "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")]
+ MerchantAccountNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Merchant connector account does not exist in our records")]
+ MerchantConnectorAccountNotFound { id: String },
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Business profile with the given id '{id}' does not exist in our records")]
+ BusinessProfileNotFound { id: String },
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Poll with the given id '{id}' does not exist in our records")]
+ PollNotFound { id: String },
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Resource ID does not exist in our records")]
+ ResourceIdNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Mandate does not exist in our records")]
+ MandateNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Authentication does not exist in our records")]
+ AuthenticationNotFound { id: String },
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Failed to update mandate")]
+ MandateUpdateFailed,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "API Key does not exist in our records")]
+ ApiKeyNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payout does not exist in our records")]
+ PayoutNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Event does not exist in our records")]
+ EventNotFound,
+ #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Invalid mandate id passed from connector")]
+ MandateSerializationFailed,
+ #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Unable to parse the mandate identifier passed from connector")]
+ MandateDeserializationFailed,
+ #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Return URL is not configured and not passed in payments request")]
+ ReturnUrlUnavailable,
+ #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard")]
+ RefundNotPossible { connector: String },
+ #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Mandate Validation Failed" )]
+ MandateValidationFailed { reason: String },
+ #[error(error_type= ErrorType::ValidationError, code = "HE_03", message = "The payment has not succeeded yet. Please pass a successful payment to initiate refund")]
+ PaymentNotSucceeded,
+ #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "The specified merchant connector account is disabled")]
+ MerchantConnectorAccountDisabled,
+ #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "{code}: {message}")]
+ PaymentBlockedError {
+ code: u16,
+ message: String,
+ status: String,
+ reason: String,
+ },
+ #[error(error_type= ErrorType::ObjectNotFound, code = "HE_04", message = "Successful payment not found for the given payment id")]
+ SuccessfulPaymentNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "The connector provided in the request is incorrect or not available")]
+ IncorrectConnectorNameGiven,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "Address does not exist in our records")]
+ AddressNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "Dispute does not exist in our records")]
+ DisputeNotFound { dispute_id: String },
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "File does not exist in our records")]
+ FileNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "File not available")]
+ FileNotAvailable,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "Dispute status validation failed")]
+ DisputeStatusValidationFailed { reason: String },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "Card with the provided iin does not exist")]
+ InvalidCardIin,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "The provided card IIN length is invalid, please provide an iin with 6 or 8 digits")]
+ InvalidCardIinLength,
+ #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "File validation failed")]
+ FileValidationFailed { reason: String },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "File not found / valid in the request")]
+ MissingFile,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "Dispute id not found in the request")]
+ MissingDisputeId,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "File purpose not found in the request or is invalid")]
+ MissingFilePurpose,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "File content type not found / valid")]
+ MissingFileContentType,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "HE_05", message = "{message}")]
+ GenericNotFoundError { message: String },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "HE_01", message = "{message}")]
+ GenericDuplicateError { message: String },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "WE_01", message = "Failed to authenticate the webhook")]
+ WebhookAuthenticationFailed,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "WE_04", message = "Webhook resource not found")]
+ WebhookResourceNotFound,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "WE_02", message = "Bad request received in webhook")]
+ WebhookBadRequest,
+ #[error(error_type = ErrorType::RouterError, code = "WE_03", message = "There was some issue processing the webhook")]
+ WebhookProcessingFailure,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "required payment method is not configured or configured incorrectly for all configured connectors")]
+ IncorrectPaymentMethodConfiguration,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "WE_05", message = "Unable to process the webhook body")]
+ WebhookUnprocessableEntity,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment Link does not exist in our records")]
+ PaymentLinkNotFound,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "WE_05", message = "Merchant Secret set my merchant for webhook source verification is invalid")]
+ WebhookInvalidMerchantSecret,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_19", message = "{message}")]
+ CurrencyNotSupported { message: String },
+ #[error(error_type = ErrorType::ServerNotAvailable, code= "HE_00", message = "{component} health check is failing with error: {message}")]
+ HealthCheckError {
+ component: &'static str,
+ message: String,
+ },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_24", message = "Merchant connector account is configured with invalid {config}")]
+ InvalidConnectorConfiguration { config: String },
+ #[error(error_type = ErrorType::ValidationError, code = "HE_01", message = "Failed to convert currency to minor unit")]
+ CurrencyConversionFailed,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")]
+ PaymentMethodDeleteFailed,
+ #[error(
+ error_type = ErrorType::InvalidRequestError, code = "IR_26",
+ message = "Invalid Cookie"
+ )]
+ InvalidCookie,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_27", message = "Extended card info does not exist")]
+ ExtendedCardInfoNotFound,
+}
+
+#[derive(Clone)]
+pub enum NotImplementedMessage {
+ Reason(String),
+ Default,
+}
+
+impl std::fmt::Debug for NotImplementedMessage {
+ fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Reason(message) => write!(fmt, "{message} is not implemented"),
+ Self::Default => {
+ write!(
+ fmt,
+ "This API is under development and will be made available soon."
+ )
+ }
+ }
+ }
+}
+
+impl ::core::fmt::Display for ApiErrorResponse {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ r#"{{"error":{}}}"#,
+ serde_json::to_string(self).unwrap_or_else(|_| "API error response".to_string())
+ )
+ }
+}
+
+impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorResponse {
+ fn switch(&self) -> api_models::errors::types::ApiErrorResponse {
+ use api_models::errors::types::{ApiError, ApiErrorResponse as AER};
+
+ match self {
+ Self::NotImplemented { message } => {
+ AER::NotImplemented(ApiError::new("IR", 0, format!("{message:?}"), None))
+ }
+ Self::Unauthorized => AER::Unauthorized(ApiError::new(
+ "IR",
+ 1,
+ "API key not provided or invalid API key used", None
+ )),
+ Self::InvalidRequestUrl => {
+ AER::NotFound(ApiError::new("IR", 2, "Unrecognized request URL", None))
+ }
+ Self::InvalidHttpMethod => AER::MethodNotAllowed(ApiError::new(
+ "IR",
+ 3,
+ "The HTTP method is not applicable for this API", None
+ )),
+ Self::MissingRequiredField { field_name } => AER::BadRequest(
+ ApiError::new("IR", 4, format!("Missing required param: {field_name}"), None),
+ ),
+ Self::InvalidDataFormat {
+ field_name,
+ expected_format,
+ } => AER::Unprocessable(ApiError::new(
+ "IR",
+ 5,
+ format!(
+ "{field_name} contains invalid data. Expected format is {expected_format}"
+ ), None
+ )),
+ Self::InvalidRequestData { message } => {
+ AER::Unprocessable(ApiError::new("IR", 6, message.to_string(), None))
+ }
+ Self::InvalidDataValue { field_name } => AER::BadRequest(ApiError::new(
+ "IR",
+ 7,
+ format!("Invalid value provided: {field_name}"), None
+ )),
+ Self::ClientSecretNotGiven => AER::BadRequest(ApiError::new(
+ "IR",
+ 8,
+ "client_secret was not provided", None
+ )),
+ Self::ClientSecretInvalid => {
+ AER::BadRequest(ApiError::new("IR", 9, "The client_secret provided does not match the client_secret associated with the Payment", None))
+ }
+ Self::CurrencyNotSupported { message } => {
+ AER::BadRequest(ApiError::new("IR", 9, message, None))
+ }
+ Self::MandateActive => {
+ AER::BadRequest(ApiError::new("IR", 10, "Customer has active mandate/subsciption", None))
+ }
+ Self::CustomerRedacted => {
+ AER::BadRequest(ApiError::new("IR", 11, "Customer has already been redacted", None))
+ }
+ Self::MaximumRefundCount => AER::BadRequest(ApiError::new("IR", 12, "Reached maximum refund attempts", None)),
+ Self::RefundAmountExceedsPaymentAmount => {
+ AER::BadRequest(ApiError::new("IR", 13, "The refund amount exceeds the amount captured", None))
+ }
+ Self::PaymentUnexpectedState {
+ current_flow,
+ field_name,
+ current_value,
+ states,
+ } => AER::BadRequest(ApiError::new("IR", 14, format!("This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}"), None)),
+ Self::InvalidEphemeralKey => AER::Unauthorized(ApiError::new("IR", 15, "Invalid Ephemeral Key for the customer", None)),
+ Self::PreconditionFailed { message } => {
+ AER::BadRequest(ApiError::new("IR", 16, message.to_string(), None))
+ }
+ Self::InvalidJwtToken => AER::Unauthorized(ApiError::new("IR", 17, "Access forbidden, invalid JWT token was used", None)),
+ Self::GenericUnauthorized { message } => {
+ AER::Unauthorized(ApiError::new("IR", 18, message.to_string(), None))
+ },
+ Self::ClientSecretExpired => AER::BadRequest(ApiError::new(
+ "IR",
+ 19,
+ "The provided client_secret has expired", None
+ )),
+ Self::MissingRequiredFields { field_names } => AER::BadRequest(
+ ApiError::new("IR", 21, "Missing required params".to_string(), Some(Extra {data: Some(serde_json::json!(field_names)), ..Default::default() })),
+ ),
+ Self::AccessForbidden {resource} => {
+ AER::ForbiddenCommonResource(ApiError::new("IR", 22, format!("Access forbidden. Not authorized to access this resource {resource}"), None))
+ },
+ Self::FileProviderNotSupported { message } => {
+ AER::BadRequest(ApiError::new("IR", 23, message.to_string(), None))
+ },
+ Self::UnprocessableEntity {message} => AER::Unprocessable(ApiError::new("IR", 23, message.to_string(), None)),
+ Self::InvalidWalletToken { wallet_name} => AER::Unprocessable(ApiError::new(
+ "IR",
+ 24,
+ format!("Invalid {wallet_name} wallet token"), None
+ )),
+ Self::ExternalConnectorError {
+ code,
+ message,
+ connector,
+ reason,
+ status_code,
+ } => AER::ConnectorError(ApiError::new("CE", 0, format!("{code}: {message}"), Some(Extra {connector: Some(connector.clone()), reason: reason.to_owned().map(Into::into), ..Default::default()})), StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)),
+ Self::PaymentAuthorizationFailed { data } => {
+ AER::BadRequest(ApiError::new("CE", 1, "Payment failed during authorization with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()})))
+ }
+ Self::PaymentAuthenticationFailed { data } => {
+ AER::BadRequest(ApiError::new("CE", 2, "Payment failed during authentication with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()})))
+ }
+ Self::PaymentCaptureFailed { data } => {
+ AER::BadRequest(ApiError::new("CE", 3, "Capture attempt failed while processing with connector", Some(Extra { data: data.clone(), ..Default::default()})))
+ }
+ Self::DisputeFailed { data } => {
+ AER::BadRequest(ApiError::new("CE", 1, "Dispute operation failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()})))
+ }
+ Self::InvalidCardData { data } => AER::BadRequest(ApiError::new("CE", 4, "The card data is invalid", Some(Extra { data: data.clone(), ..Default::default()}))),
+ Self::CardExpired { data } => AER::BadRequest(ApiError::new("CE", 5, "The card has expired", Some(Extra { data: data.clone(), ..Default::default()}))),
+ Self::RefundFailed { data } => AER::BadRequest(ApiError::new("CE", 6, "Refund failed while processing with connector. Retry refund", Some(Extra { data: data.clone(), ..Default::default()}))),
+ Self::VerificationFailed { data } => {
+ AER::BadRequest(ApiError::new("CE", 7, "Verification failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()})))
+ },
+ Self::MandateUpdateFailed | Self::MandateSerializationFailed | Self::MandateDeserializationFailed | Self::InternalServerError => {
+ AER::InternalServerError(ApiError::new("HE", 0, "Something went wrong", None))
+ },
+ Self::HealthCheckError { message,component } => {
+ AER::InternalServerError(ApiError::new("HE",0,format!("{} health check failed with error: {}",component,message),None))
+ },
+ Self::PayoutFailed { data } => {
+ AER::BadRequest(ApiError::new("CE", 4, "Payout failed while processing with connector.", Some(Extra { data: data.clone(), ..Default::default()})))
+ },
+ Self::DuplicateRefundRequest => AER::BadRequest(ApiError::new("HE", 1, "Duplicate refund request. Refund already attempted with the refund ID", None)),
+ Self::DuplicateMandate => AER::BadRequest(ApiError::new("HE", 1, "Duplicate mandate request. Mandate already attempted with the Mandate ID", None)),
+ Self::DuplicateMerchantAccount => AER::BadRequest(ApiError::new("HE", 1, "The merchant account with the specified details already exists in our records", None)),
+ Self::DuplicateMerchantConnectorAccount { profile_id, connector_label: connector_name } => {
+ AER::BadRequest(ApiError::new("HE", 1, format!("The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_name}' already exists in our records"), None))
+ }
+ Self::DuplicatePaymentMethod => AER::BadRequest(ApiError::new("HE", 1, "The payment method with the specified details already exists in our records", None)),
+ Self::DuplicatePayment { payment_id } => {
+ AER::BadRequest(ApiError::new("HE", 1, "The payment with the specified payment_id already exists in our records", Some(Extra {reason: Some(format!("{payment_id} already exists")), ..Default::default()})))
+ }
+ 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::GenericDuplicateError { message } => {
+ AER::BadRequest(ApiError::new("HE", 1, message, None))
+ }
+ Self::RefundNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Refund does not exist in our records.", None))
+ }
+ Self::CustomerNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Customer does not exist in our records", None))
+ }
+ Self::ConfigNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Config key does not exist in our records.", None))
+ },
+ Self::DuplicateConfig => {
+ AER::BadRequest(ApiError::new("HE", 1, "The config with the specified key already exists in our records", None))
+ }
+ Self::PaymentNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Payment does not exist in our records", None))
+ }
+ Self::PaymentMethodNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Payment method does not exist in our records", None))
+ }
+ Self::MerchantAccountNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Merchant account does not exist in our records", None))
+ }
+ Self::MerchantConnectorAccountNotFound {id } => {
+ AER::NotFound(ApiError::new("HE", 2, "Merchant connector account does not exist in our records", Some(Extra {reason: Some(format!("{id} does not exist")), ..Default::default()})))
+ }
+ Self::MerchantConnectorAccountDisabled => {
+ AER::BadRequest(ApiError::new("HE", 3, "The selected merchant connector account is disabled", None))
+ }
+ Self::ResourceIdNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Resource ID does not exist in our records", None))
+ }
+ Self::MandateNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Mandate does not exist in our records", None))
+ }
+ Self::PayoutNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Payout does not exist in our records", None))
+ }
+ Self::EventNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Event does not exist in our records", None))
+ }
+ Self::ReturnUrlUnavailable => AER::NotFound(ApiError::new("HE", 3, "Return URL is not configured and not passed in payments request", None)),
+ Self::RefundNotPossible { connector } => {
+ AER::BadRequest(ApiError::new("HE", 3, format!("This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard"), None))
+ }
+ Self::MandateValidationFailed { reason } => {
+ AER::BadRequest(ApiError::new("HE", 3, "Mandate Validation Failed", Some(Extra { reason: Some(reason.to_owned()), ..Default::default() })))
+ }
+ Self::PaymentNotSucceeded => AER::BadRequest(ApiError::new("HE", 3, "The payment has not succeeded yet. Please pass a successful payment to initiate refund", None)),
+ Self::PaymentBlockedError {
+ message,
+ reason,
+ ..
+ } => AER::DomainError(ApiError::new("HE", 3, message, Some(Extra { reason: Some(reason.clone()), ..Default::default() }))),
+ Self::SuccessfulPaymentNotFound => {
+ AER::NotFound(ApiError::new("HE", 4, "Successful payment not found for the given payment id", None))
+ }
+ Self::IncorrectConnectorNameGiven => {
+ AER::NotFound(ApiError::new("HE", 4, "The connector provided in the request is incorrect or not available", None))
+ }
+ Self::AddressNotFound => {
+ AER::NotFound(ApiError::new("HE", 4, "Address does not exist in our records", None))
+ },
+ Self::GenericNotFoundError { message } => {
+ AER::NotFound(ApiError::new("HE", 5, message, None))
+ },
+ Self::ApiKeyNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "API Key does not exist in our records", None))
+ }
+ Self::NotSupported { message } => {
+ AER::BadRequest(ApiError::new("HE", 3, "Payment method type not supported", Some(Extra {reason: Some(message.to_owned()), ..Default::default()})))
+ },
+ Self::InvalidCardIin => AER::BadRequest(ApiError::new("HE", 3, "The provided card IIN does not exist", None)),
+ Self::InvalidCardIinLength => AER::BadRequest(ApiError::new("HE", 3, "The provided card IIN length is invalid, please provide an IIN with 6 digits", None)),
+ Self::FlowNotSupported { flow, connector } => {
+ AER::BadRequest(ApiError::new("IR", 20, format!("{flow} flow not supported"), Some(Extra {connector: Some(connector.to_owned()), ..Default::default()}))) //FIXME: error message
+ }
+ Self::DisputeNotFound { .. } => {
+ AER::NotFound(ApiError::new("HE", 2, "Dispute does not exist in our records", None))
+ },
+ Self::AuthenticationNotFound { .. } => {
+ AER::NotFound(ApiError::new("HE", 2, "Authentication does not exist in our records", None))
+ },
+ Self::BusinessProfileNotFound { id } => {
+ AER::NotFound(ApiError::new("HE", 2, format!("Business profile with the given id {id} does not exist"), None))
+ }
+ Self::FileNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "File does not exist in our records", None))
+ }
+ Self::PollNotFound { .. } => {
+ AER::NotFound(ApiError::new("HE", 2, "Poll does not exist in our records", None))
+ },
+ Self::FileNotAvailable => {
+ AER::NotFound(ApiError::new("HE", 2, "File not available", None))
+ }
+ Self::DisputeStatusValidationFailed { .. } => {
+ AER::BadRequest(ApiError::new("HE", 2, "Dispute status validation failed", None))
+ }
+ Self::FileValidationFailed { reason } => {
+ AER::BadRequest(ApiError::new("HE", 2, format!("File validation failed {reason}"), None))
+ }
+ Self::MissingFile => {
+ AER::BadRequest(ApiError::new("HE", 2, "File not found in the request", None))
+ }
+ Self::MissingFilePurpose => {
+ AER::BadRequest(ApiError::new("HE", 2, "File purpose not found in the request or is invalid", None))
+ }
+ Self::MissingFileContentType => {
+ AER::BadRequest(ApiError::new("HE", 2, "File content type not found", None))
+ }
+ Self::MissingDisputeId => {
+ AER::BadRequest(ApiError::new("HE", 2, "Dispute id not found in the request", None))
+ }
+ Self::WebhookAuthenticationFailed => {
+ AER::Unauthorized(ApiError::new("WE", 1, "Webhook authentication failed", None))
+ }
+ Self::WebhookResourceNotFound => {
+ AER::NotFound(ApiError::new("WE", 4, "Webhook resource was not found", None))
+ }
+ Self::WebhookBadRequest => {
+ AER::BadRequest(ApiError::new("WE", 2, "Bad request body received", None))
+ }
+ Self::WebhookProcessingFailure => {
+ AER::InternalServerError(ApiError::new("WE", 3, "There was an issue processing the webhook", None))
+ },
+ Self::WebhookInvalidMerchantSecret => {
+ AER::BadRequest(ApiError::new("WE", 2, "Merchant Secret set for webhook source verificartion is invalid", None))
+ }
+ Self::IncorrectPaymentMethodConfiguration => {
+ AER::BadRequest(ApiError::new("HE", 4, "No eligible connector was found for the current payment method configuration", None))
+ }
+ Self::WebhookUnprocessableEntity => {
+ AER::Unprocessable(ApiError::new("WE", 5, "There was an issue processing the webhook body", None))
+ },
+ Self::ResourceBusy => {
+ AER::Unprocessable(ApiError::new("WE", 5, "There was an issue processing the webhook body", None))
+ }
+ Self::PaymentLinkNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Payment Link does not exist in our records", None))
+ }
+ Self::InvalidConnectorConfiguration {config} => {
+ AER::BadRequest(ApiError::new("IR", 24, format!("Merchant connector account is configured with invalid {config}"), None))
+ }
+ Self::CurrencyConversionFailed => {
+ AER::Unprocessable(ApiError::new("HE", 2, "Failed to convert currency to minor unit", None))
+ }
+ Self::PaymentMethodDeleteFailed => {
+ AER::BadRequest(ApiError::new("IR", 25, "Cannot delete the default payment method", None))
+ }
+ Self::InvalidCookie => {
+ AER::BadRequest(ApiError::new("IR", 26, "Invalid Cookie", None))
+ }
+ Self::ExtendedCardInfoNotFound => {
+ AER::NotFound(ApiError::new("IR", 27, "Extended card info does not exist", None))
+ }
+ }
+ }
+}
+
+impl actix_web::ResponseError for ApiErrorResponse {
+ fn status_code(&self) -> StatusCode {
+ ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(self).status_code()
+ }
+
+ fn error_response(&self) -> actix_web::HttpResponse {
+ ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(self).error_response()
+ }
+}
+
+impl From<ApiErrorResponse> for router_data::ErrorResponse {
+ fn from(error: ApiErrorResponse) -> Self {
+ Self {
+ code: error.error_code(),
+ message: error.error_message(),
+ reason: None,
+ status_code: match error {
+ ApiErrorResponse::ExternalConnectorError { status_code, .. } => status_code,
+ _ => 500,
+ },
+ attempt_status: None,
+ connector_transaction_id: None,
+ }
+ }
+}
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index b470b538d7..ba6ccdf839 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -1,10 +1,12 @@
pub mod errors;
pub mod mandates;
pub mod payment_address;
+pub mod payment_method_data;
pub mod payments;
#[cfg(feature = "payouts")]
pub mod payouts;
pub mod router_data;
+pub mod router_request_types;
#[cfg(not(feature = "payouts"))]
pub trait PayoutAttemptInterface {}
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
new file mode 100644
index 0000000000..9dc85c103e
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -0,0 +1,837 @@
+use common_utils::pii::{self, Email};
+use masking::Secret;
+use serde::{Deserialize, Serialize};
+
+// We need to derive Serialize and Deserialize because some parts of payment method data are being
+// stored in the database as serde_json::Value
+#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
+pub enum PaymentMethodData {
+ Card(Card),
+ CardRedirect(CardRedirectData),
+ Wallet(WalletData),
+ PayLater(PayLaterData),
+ BankRedirect(BankRedirectData),
+ BankDebit(BankDebitData),
+ BankTransfer(Box<BankTransferData>),
+ Crypto(CryptoData),
+ MandatePayment,
+ Reward,
+ Upi(UpiData),
+ Voucher(VoucherData),
+ GiftCard(Box<GiftCardData>),
+ CardToken(CardToken),
+}
+
+impl PaymentMethodData {
+ pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> {
+ match self {
+ Self::Card(_) => Some(common_enums::PaymentMethod::Card),
+ Self::CardRedirect(_) => Some(common_enums::PaymentMethod::CardRedirect),
+ Self::Wallet(_) => Some(common_enums::PaymentMethod::Wallet),
+ Self::PayLater(_) => Some(common_enums::PaymentMethod::PayLater),
+ Self::BankRedirect(_) => Some(common_enums::PaymentMethod::BankRedirect),
+ Self::BankDebit(_) => Some(common_enums::PaymentMethod::BankDebit),
+ Self::BankTransfer(_) => Some(common_enums::PaymentMethod::BankTransfer),
+ Self::Crypto(_) => Some(common_enums::PaymentMethod::Crypto),
+ Self::Reward => Some(common_enums::PaymentMethod::Reward),
+ Self::Upi(_) => Some(common_enums::PaymentMethod::Upi),
+ Self::Voucher(_) => Some(common_enums::PaymentMethod::Voucher),
+ Self::GiftCard(_) => Some(common_enums::PaymentMethod::GiftCard),
+ Self::CardToken(_) | Self::MandatePayment => None,
+ }
+ }
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
+pub struct Card {
+ pub card_number: cards::CardNumber,
+ pub card_exp_month: Secret<String>,
+ pub card_exp_year: Secret<String>,
+ pub card_cvc: Secret<String>,
+ pub card_issuer: Option<String>,
+ pub card_network: Option<common_enums::CardNetwork>,
+ pub card_type: Option<String>,
+ pub card_issuing_country: Option<String>,
+ pub bank_code: Option<String>,
+ pub nick_name: Option<Secret<String>>,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
+pub enum CardRedirectData {
+ Knet {},
+ Benefit {},
+ MomoAtm {},
+ CardRedirect {},
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub enum PayLaterData {
+ KlarnaRedirect {},
+ KlarnaSdk { token: String },
+ AffirmRedirect {},
+ AfterpayClearpayRedirect {},
+ PayBrightRedirect {},
+ WalleyRedirect {},
+ AlmaRedirect {},
+ AtomeRedirect {},
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+
+pub enum WalletData {
+ AliPayQr(Box<AliPayQr>),
+ AliPayRedirect(AliPayRedirection),
+ AliPayHkRedirect(AliPayHkRedirection),
+ MomoRedirect(MomoRedirection),
+ KakaoPayRedirect(KakaoPayRedirection),
+ GoPayRedirect(GoPayRedirection),
+ GcashRedirect(GcashRedirection),
+ ApplePay(ApplePayWalletData),
+ ApplePayRedirect(Box<ApplePayRedirectData>),
+ ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>),
+ DanaRedirect {},
+ GooglePay(GooglePayWalletData),
+ GooglePayRedirect(Box<GooglePayRedirectData>),
+ GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>),
+ MbWayRedirect(Box<MbWayRedirection>),
+ MobilePayRedirect(Box<MobilePayRedirection>),
+ PaypalRedirect(PaypalRedirection),
+ PaypalSdk(PayPalWalletData),
+ SamsungPay(Box<SamsungPayWalletData>),
+ TwintRedirect {},
+ VippsRedirect {},
+ TouchNGoRedirect(Box<TouchNGoRedirection>),
+ WeChatPayRedirect(Box<WeChatPayRedirection>),
+ WeChatPayQr(Box<WeChatPayQr>),
+ CashappQr(Box<CashappQr>),
+ SwishQr(SwishQrData),
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+
+pub struct SamsungPayWalletData {
+ /// The encrypted payment token from Samsung
+ pub token: Secret<String>,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+
+pub struct GooglePayWalletData {
+ /// The type of payment method
+ pub pm_type: String,
+ /// User-facing message to describe the payment method that funds this transaction.
+ pub description: String,
+ /// The information of the payment method
+ pub info: GooglePayPaymentMethodInfo,
+ /// The tokenization data of Google pay
+ pub tokenization_data: GpayTokenizationData,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct ApplePayRedirectData {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct GooglePayRedirectData {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct GooglePayThirdPartySdkData {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct ApplePayThirdPartySdkData {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct WeChatPayRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct WeChatPay {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct WeChatPayQr {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct CashappQr {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct PaypalRedirection {
+ /// paypal's email address
+ pub email: Option<Email>,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct AliPayQr {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct AliPayRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct AliPayHkRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct MomoRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct KakaoPayRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct GoPayRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct GcashRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct MobilePayRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct MbWayRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+
+pub struct GooglePayPaymentMethodInfo {
+ /// The name of the card network
+ pub card_network: String,
+ /// The details of the card
+ pub card_details: String,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct PayPalWalletData {
+ /// Token generated for the Apple pay
+ pub token: String,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct TouchNGoRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct SwishQrData {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct GpayTokenizationData {
+ /// The type of the token
+ pub token_type: String,
+ /// Token generated for the wallet
+ pub token: String,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct ApplePayWalletData {
+ /// The payment data of Apple pay
+ pub payment_data: String,
+ /// The payment method of Apple pay
+ pub payment_method: ApplepayPaymentMethod,
+ /// The unique identifier for the transaction
+ pub transaction_identifier: String,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct ApplepayPaymentMethod {
+ pub display_name: String,
+ pub network: String,
+ pub pm_type: String,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
+
+pub enum BankRedirectData {
+ BancontactCard {
+ card_number: Option<cards::CardNumber>,
+ card_exp_month: Option<Secret<String>>,
+ card_exp_year: Option<Secret<String>>,
+ },
+ Bizum {},
+ Blik {
+ blik_code: Option<String>,
+ },
+ Eps {
+ bank_name: Option<common_enums::BankNames>,
+ },
+ Giropay {
+ bank_account_bic: Option<Secret<String>>,
+ bank_account_iban: Option<Secret<String>>,
+ },
+ Ideal {
+ bank_name: Option<common_enums::BankNames>,
+ },
+ Interac {},
+ OnlineBankingCzechRepublic {
+ issuer: common_enums::BankNames,
+ },
+ OnlineBankingFinland {},
+ OnlineBankingPoland {
+ issuer: common_enums::BankNames,
+ },
+ OnlineBankingSlovakia {
+ issuer: common_enums::BankNames,
+ },
+ OpenBankingUk {
+ issuer: Option<common_enums::BankNames>,
+ },
+ Przelewy24 {
+ bank_name: Option<common_enums::BankNames>,
+ },
+ Sofort {
+ preferred_language: Option<String>,
+ },
+ Trustly {},
+ OnlineBankingFpx {
+ issuer: common_enums::BankNames,
+ },
+ OnlineBankingThailand {
+ issuer: common_enums::BankNames,
+ },
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub struct CryptoData {
+ pub pay_currency: Option<String>,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub struct UpiData {
+ pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum VoucherData {
+ Boleto(Box<BoletoVoucherData>),
+ Efecty,
+ PagoEfectivo,
+ RedCompra,
+ RedPagos,
+ Alfamart(Box<AlfamartVoucherData>),
+ Indomaret(Box<IndomaretVoucherData>),
+ Oxxo,
+ SevenEleven(Box<JCSVoucherData>),
+ Lawson(Box<JCSVoucherData>),
+ MiniStop(Box<JCSVoucherData>),
+ FamilyMart(Box<JCSVoucherData>),
+ Seicomart(Box<JCSVoucherData>),
+ PayEasy(Box<JCSVoucherData>),
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
+pub struct BoletoVoucherData {
+ /// The shopper's social security number
+ pub social_security_number: Option<Secret<String>>,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
+pub struct AlfamartVoucherData {}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
+pub struct IndomaretVoucherData {}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
+pub struct JCSVoucherData {}
+
+#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub enum GiftCardData {
+ Givex(GiftCardDetails),
+ PaySafeCard {},
+}
+
+#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub struct GiftCardDetails {
+ /// The gift card number
+ pub number: Secret<String>,
+ /// The card verification code.
+ pub cvc: Secret<String>,
+}
+
+#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, Default)]
+#[serde(rename_all = "snake_case")]
+pub struct CardToken {
+ /// The card holder's name
+ pub card_holder_name: Option<Secret<String>>,
+
+ /// The CVC number for the card
+ pub card_cvc: Option<Secret<String>>,
+}
+
+#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub enum BankDebitData {
+ AchBankDebit {
+ account_number: Secret<String>,
+ routing_number: Secret<String>,
+ bank_name: Option<common_enums::BankNames>,
+ bank_type: Option<common_enums::BankType>,
+ bank_holder_type: Option<common_enums::BankHolderType>,
+ },
+ SepaBankDebit {
+ iban: Secret<String>,
+ },
+ BecsBankDebit {
+ account_number: Secret<String>,
+ bsb_number: Secret<String>,
+ },
+ BacsBankDebit {
+ account_number: Secret<String>,
+ sort_code: Secret<String>,
+ },
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum BankTransferData {
+ AchBankTransfer {},
+ SepaBankTransfer {},
+ BacsBankTransfer {},
+ MultibancoBankTransfer {},
+ PermataBankTransfer {},
+ BcaBankTransfer {},
+ BniVaBankTransfer {},
+ BriVaBankTransfer {},
+ CimbVaBankTransfer {},
+ DanamonVaBankTransfer {},
+ MandiriVaBankTransfer {},
+ Pix {},
+ Pse {},
+ LocalBankTransfer { bank_code: Option<String> },
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
+pub struct SepaAndBacsBillingDetails {
+ /// The Email ID for SEPA and BACS billing
+ pub email: Email,
+ /// The billing name for SEPA and BACS billing
+ pub name: Secret<String>,
+}
+
+impl From<api_models::payments::PaymentMethodData> for PaymentMethodData {
+ fn from(api_model_payment_method_data: api_models::payments::PaymentMethodData) -> Self {
+ match api_model_payment_method_data {
+ api_models::payments::PaymentMethodData::Card(card_data) => {
+ Self::Card(Card::from(card_data))
+ }
+ api_models::payments::PaymentMethodData::CardRedirect(card_redirect) => {
+ Self::CardRedirect(From::from(card_redirect))
+ }
+ api_models::payments::PaymentMethodData::Wallet(wallet_data) => {
+ Self::Wallet(From::from(wallet_data))
+ }
+ api_models::payments::PaymentMethodData::PayLater(pay_later_data) => {
+ Self::PayLater(From::from(pay_later_data))
+ }
+ api_models::payments::PaymentMethodData::BankRedirect(bank_redirect_data) => {
+ Self::BankRedirect(From::from(bank_redirect_data))
+ }
+ api_models::payments::PaymentMethodData::BankDebit(bank_debit_data) => {
+ Self::BankDebit(From::from(bank_debit_data))
+ }
+ api_models::payments::PaymentMethodData::BankTransfer(bank_transfer_data) => {
+ Self::BankTransfer(Box::new(From::from(*bank_transfer_data)))
+ }
+ api_models::payments::PaymentMethodData::Crypto(crypto_data) => {
+ Self::Crypto(From::from(crypto_data))
+ }
+ api_models::payments::PaymentMethodData::MandatePayment => Self::MandatePayment,
+ api_models::payments::PaymentMethodData::Reward => Self::Reward,
+ api_models::payments::PaymentMethodData::Upi(upi_data) => {
+ Self::Upi(From::from(upi_data))
+ }
+ api_models::payments::PaymentMethodData::Voucher(voucher_data) => {
+ Self::Voucher(From::from(voucher_data))
+ }
+ api_models::payments::PaymentMethodData::GiftCard(gift_card) => {
+ Self::GiftCard(Box::new(From::from(*gift_card)))
+ }
+ api_models::payments::PaymentMethodData::CardToken(card_token) => {
+ Self::CardToken(From::from(card_token))
+ }
+ }
+ }
+}
+
+impl From<api_models::payments::Card> for Card {
+ fn from(value: api_models::payments::Card) -> Self {
+ let api_models::payments::Card {
+ card_number,
+ card_exp_month,
+ card_exp_year,
+ card_holder_name: _,
+ card_cvc,
+ card_issuer,
+ card_network,
+ card_type,
+ card_issuing_country,
+ bank_code,
+ nick_name,
+ } = value;
+
+ Self {
+ card_number,
+ card_exp_month,
+ card_exp_year,
+ card_cvc,
+ card_issuer,
+ card_network,
+ card_type,
+ card_issuing_country,
+ bank_code,
+ nick_name,
+ }
+ }
+}
+
+impl From<api_models::payments::CardRedirectData> for CardRedirectData {
+ fn from(value: api_models::payments::CardRedirectData) -> Self {
+ match value {
+ api_models::payments::CardRedirectData::Knet {} => Self::Knet {},
+ api_models::payments::CardRedirectData::Benefit {} => Self::Benefit {},
+ api_models::payments::CardRedirectData::MomoAtm {} => Self::MomoAtm {},
+ api_models::payments::CardRedirectData::CardRedirect {} => Self::CardRedirect {},
+ }
+ }
+}
+
+impl From<api_models::payments::WalletData> for WalletData {
+ fn from(value: api_models::payments::WalletData) -> Self {
+ match value {
+ api_models::payments::WalletData::AliPayQr(_) => Self::AliPayQr(Box::new(AliPayQr {})),
+ api_models::payments::WalletData::AliPayRedirect(_) => {
+ Self::AliPayRedirect(AliPayRedirection {})
+ }
+ api_models::payments::WalletData::AliPayHkRedirect(_) => {
+ Self::AliPayHkRedirect(AliPayHkRedirection {})
+ }
+ api_models::payments::WalletData::MomoRedirect(_) => {
+ Self::MomoRedirect(MomoRedirection {})
+ }
+ api_models::payments::WalletData::KakaoPayRedirect(_) => {
+ Self::KakaoPayRedirect(KakaoPayRedirection {})
+ }
+ api_models::payments::WalletData::GoPayRedirect(_) => {
+ Self::GoPayRedirect(GoPayRedirection {})
+ }
+ api_models::payments::WalletData::GcashRedirect(_) => {
+ Self::GcashRedirect(GcashRedirection {})
+ }
+ api_models::payments::WalletData::ApplePay(apple_pay_data) => {
+ Self::ApplePay(ApplePayWalletData::from(apple_pay_data))
+ }
+ api_models::payments::WalletData::ApplePayRedirect(_) => {
+ Self::ApplePayRedirect(Box::new(ApplePayRedirectData {}))
+ }
+ api_models::payments::WalletData::ApplePayThirdPartySdk(_) => {
+ Self::ApplePayThirdPartySdk(Box::new(ApplePayThirdPartySdkData {}))
+ }
+ api_models::payments::WalletData::DanaRedirect {} => Self::DanaRedirect {},
+ api_models::payments::WalletData::GooglePay(google_pay_data) => {
+ Self::GooglePay(GooglePayWalletData::from(google_pay_data))
+ }
+ api_models::payments::WalletData::GooglePayRedirect(_) => {
+ Self::GooglePayRedirect(Box::new(GooglePayRedirectData {}))
+ }
+ api_models::payments::WalletData::GooglePayThirdPartySdk(_) => {
+ Self::GooglePayThirdPartySdk(Box::new(GooglePayThirdPartySdkData {}))
+ }
+ api_models::payments::WalletData::MbWayRedirect(..) => {
+ Self::MbWayRedirect(Box::new(MbWayRedirection {}))
+ }
+ api_models::payments::WalletData::MobilePayRedirect(_) => {
+ Self::MobilePayRedirect(Box::new(MobilePayRedirection {}))
+ }
+ api_models::payments::WalletData::PaypalRedirect(paypal_redirect_data) => {
+ Self::PaypalRedirect(PaypalRedirection {
+ email: paypal_redirect_data.email,
+ })
+ }
+ api_models::payments::WalletData::PaypalSdk(paypal_sdk_data) => {
+ Self::PaypalSdk(PayPalWalletData {
+ token: paypal_sdk_data.token,
+ })
+ }
+ api_models::payments::WalletData::SamsungPay(samsung_pay_data) => {
+ Self::SamsungPay(Box::new(SamsungPayWalletData {
+ token: samsung_pay_data.token,
+ }))
+ }
+ api_models::payments::WalletData::TwintRedirect {} => Self::TwintRedirect {},
+ api_models::payments::WalletData::VippsRedirect {} => Self::VippsRedirect {},
+ api_models::payments::WalletData::TouchNGoRedirect(_) => {
+ Self::TouchNGoRedirect(Box::new(TouchNGoRedirection {}))
+ }
+ api_models::payments::WalletData::WeChatPayRedirect(_) => {
+ Self::WeChatPayRedirect(Box::new(WeChatPayRedirection {}))
+ }
+ api_models::payments::WalletData::WeChatPayQr(_) => {
+ Self::WeChatPayQr(Box::new(WeChatPayQr {}))
+ }
+ api_models::payments::WalletData::CashappQr(_) => {
+ Self::CashappQr(Box::new(CashappQr {}))
+ }
+ api_models::payments::WalletData::SwishQr(_) => Self::SwishQr(SwishQrData {}),
+ }
+ }
+}
+
+impl From<api_models::payments::GooglePayWalletData> for GooglePayWalletData {
+ fn from(value: api_models::payments::GooglePayWalletData) -> Self {
+ Self {
+ pm_type: value.pm_type,
+ description: value.description,
+ info: GooglePayPaymentMethodInfo {
+ card_network: value.info.card_network,
+ card_details: value.info.card_details,
+ },
+ tokenization_data: GpayTokenizationData {
+ token_type: value.tokenization_data.token_type,
+ token: value.tokenization_data.token,
+ },
+ }
+ }
+}
+
+impl From<api_models::payments::ApplePayWalletData> for ApplePayWalletData {
+ fn from(value: api_models::payments::ApplePayWalletData) -> Self {
+ Self {
+ payment_data: value.payment_data,
+ payment_method: ApplepayPaymentMethod {
+ display_name: value.payment_method.display_name,
+ network: value.payment_method.network,
+ pm_type: value.payment_method.pm_type,
+ },
+ transaction_identifier: value.transaction_identifier,
+ }
+ }
+}
+
+impl From<api_models::payments::PayLaterData> for PayLaterData {
+ fn from(value: api_models::payments::PayLaterData) -> Self {
+ match value {
+ api_models::payments::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect {},
+ api_models::payments::PayLaterData::KlarnaSdk { token } => Self::KlarnaSdk { token },
+ api_models::payments::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect {},
+ api_models::payments::PayLaterData::AfterpayClearpayRedirect { .. } => {
+ Self::AfterpayClearpayRedirect {}
+ }
+ api_models::payments::PayLaterData::PayBrightRedirect {} => Self::PayBrightRedirect {},
+ api_models::payments::PayLaterData::WalleyRedirect {} => Self::WalleyRedirect {},
+ api_models::payments::PayLaterData::AlmaRedirect {} => Self::AlmaRedirect {},
+ api_models::payments::PayLaterData::AtomeRedirect {} => Self::AtomeRedirect {},
+ }
+ }
+}
+
+impl From<api_models::payments::BankRedirectData> for BankRedirectData {
+ fn from(value: api_models::payments::BankRedirectData) -> Self {
+ match value {
+ api_models::payments::BankRedirectData::BancontactCard {
+ card_number,
+ card_exp_month,
+ card_exp_year,
+ ..
+ } => Self::BancontactCard {
+ card_number,
+ card_exp_month,
+ card_exp_year,
+ },
+ api_models::payments::BankRedirectData::Bizum {} => Self::Bizum {},
+ api_models::payments::BankRedirectData::Blik { blik_code } => Self::Blik { blik_code },
+ api_models::payments::BankRedirectData::Eps { bank_name, .. } => {
+ Self::Eps { bank_name }
+ }
+ api_models::payments::BankRedirectData::Giropay {
+ bank_account_bic,
+ bank_account_iban,
+ ..
+ } => Self::Giropay {
+ bank_account_bic,
+ bank_account_iban,
+ },
+ api_models::payments::BankRedirectData::Ideal { bank_name, .. } => {
+ Self::Ideal { bank_name }
+ }
+ api_models::payments::BankRedirectData::Interac { .. } => Self::Interac {},
+ api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { issuer } => {
+ Self::OnlineBankingCzechRepublic { issuer }
+ }
+ api_models::payments::BankRedirectData::OnlineBankingFinland { .. } => {
+ Self::OnlineBankingFinland {}
+ }
+ api_models::payments::BankRedirectData::OnlineBankingPoland { issuer } => {
+ Self::OnlineBankingPoland { issuer }
+ }
+ api_models::payments::BankRedirectData::OnlineBankingSlovakia { issuer } => {
+ Self::OnlineBankingSlovakia { issuer }
+ }
+ api_models::payments::BankRedirectData::OpenBankingUk { issuer, .. } => {
+ Self::OpenBankingUk { issuer }
+ }
+ api_models::payments::BankRedirectData::Przelewy24 { bank_name, .. } => {
+ Self::Przelewy24 { bank_name }
+ }
+ api_models::payments::BankRedirectData::Sofort {
+ preferred_language, ..
+ } => Self::Sofort { preferred_language },
+ api_models::payments::BankRedirectData::Trustly { .. } => Self::Trustly {},
+ api_models::payments::BankRedirectData::OnlineBankingFpx { issuer } => {
+ Self::OnlineBankingFpx { issuer }
+ }
+ api_models::payments::BankRedirectData::OnlineBankingThailand { issuer } => {
+ Self::OnlineBankingThailand { issuer }
+ }
+ }
+ }
+}
+
+impl From<api_models::payments::CryptoData> for CryptoData {
+ fn from(value: api_models::payments::CryptoData) -> Self {
+ let api_models::payments::CryptoData { pay_currency } = value;
+ Self { pay_currency }
+ }
+}
+
+impl From<api_models::payments::UpiData> for UpiData {
+ fn from(value: api_models::payments::UpiData) -> Self {
+ let api_models::payments::UpiData { vpa_id } = value;
+ Self { vpa_id }
+ }
+}
+
+impl From<api_models::payments::VoucherData> for VoucherData {
+ fn from(value: api_models::payments::VoucherData) -> Self {
+ match value {
+ api_models::payments::VoucherData::Boleto(boleto_data) => {
+ Self::Boleto(Box::new(BoletoVoucherData {
+ social_security_number: boleto_data.social_security_number,
+ }))
+ }
+ api_models::payments::VoucherData::Alfamart(_) => {
+ Self::Alfamart(Box::new(AlfamartVoucherData {}))
+ }
+ api_models::payments::VoucherData::Indomaret(_) => {
+ Self::Indomaret(Box::new(IndomaretVoucherData {}))
+ }
+ api_models::payments::VoucherData::SevenEleven(_)
+ | api_models::payments::VoucherData::Lawson(_)
+ | api_models::payments::VoucherData::MiniStop(_)
+ | api_models::payments::VoucherData::FamilyMart(_)
+ | api_models::payments::VoucherData::Seicomart(_)
+ | api_models::payments::VoucherData::PayEasy(_) => {
+ Self::SevenEleven(Box::new(JCSVoucherData {}))
+ }
+ api_models::payments::VoucherData::Efecty => Self::Efecty,
+ api_models::payments::VoucherData::PagoEfectivo => Self::PagoEfectivo,
+ api_models::payments::VoucherData::RedCompra => Self::RedCompra,
+ api_models::payments::VoucherData::RedPagos => Self::RedPagos,
+ api_models::payments::VoucherData::Oxxo => Self::Oxxo,
+ }
+ }
+}
+
+impl From<api_models::payments::GiftCardData> for GiftCardData {
+ fn from(value: api_models::payments::GiftCardData) -> Self {
+ match value {
+ api_models::payments::GiftCardData::Givex(details) => Self::Givex(GiftCardDetails {
+ number: details.number,
+ cvc: details.cvc,
+ }),
+ api_models::payments::GiftCardData::PaySafeCard {} => Self::PaySafeCard {},
+ }
+ }
+}
+
+impl From<api_models::payments::CardToken> for CardToken {
+ fn from(value: api_models::payments::CardToken) -> Self {
+ let api_models::payments::CardToken {
+ card_holder_name,
+ card_cvc,
+ } = value;
+ Self {
+ card_holder_name,
+ card_cvc,
+ }
+ }
+}
+
+impl From<api_models::payments::BankDebitData> for BankDebitData {
+ fn from(value: api_models::payments::BankDebitData) -> Self {
+ match value {
+ api_models::payments::BankDebitData::AchBankDebit {
+ account_number,
+ routing_number,
+ bank_name,
+ bank_type,
+ bank_holder_type,
+ ..
+ } => Self::AchBankDebit {
+ account_number,
+ routing_number,
+ bank_name,
+ bank_type,
+ bank_holder_type,
+ },
+ api_models::payments::BankDebitData::SepaBankDebit { iban, .. } => {
+ Self::SepaBankDebit { iban }
+ }
+ api_models::payments::BankDebitData::BecsBankDebit {
+ account_number,
+ bsb_number,
+ ..
+ } => Self::BecsBankDebit {
+ account_number,
+ bsb_number,
+ },
+ api_models::payments::BankDebitData::BacsBankDebit {
+ account_number,
+ sort_code,
+ ..
+ } => Self::BacsBankDebit {
+ account_number,
+ sort_code,
+ },
+ }
+ }
+}
+
+impl From<api_models::payments::BankTransferData> for BankTransferData {
+ fn from(value: api_models::payments::BankTransferData) -> Self {
+ match value {
+ api_models::payments::BankTransferData::AchBankTransfer { .. } => {
+ Self::AchBankTransfer {}
+ }
+ api_models::payments::BankTransferData::SepaBankTransfer { .. } => {
+ Self::SepaBankTransfer {}
+ }
+ api_models::payments::BankTransferData::BacsBankTransfer { .. } => {
+ Self::BacsBankTransfer {}
+ }
+ api_models::payments::BankTransferData::MultibancoBankTransfer { .. } => {
+ Self::MultibancoBankTransfer {}
+ }
+ api_models::payments::BankTransferData::PermataBankTransfer { .. } => {
+ Self::PermataBankTransfer {}
+ }
+ api_models::payments::BankTransferData::BcaBankTransfer { .. } => {
+ Self::BcaBankTransfer {}
+ }
+ api_models::payments::BankTransferData::BniVaBankTransfer { .. } => {
+ Self::BniVaBankTransfer {}
+ }
+ api_models::payments::BankTransferData::BriVaBankTransfer { .. } => {
+ Self::BriVaBankTransfer {}
+ }
+ api_models::payments::BankTransferData::CimbVaBankTransfer { .. } => {
+ Self::CimbVaBankTransfer {}
+ }
+ api_models::payments::BankTransferData::DanamonVaBankTransfer { .. } => {
+ Self::DanamonVaBankTransfer {}
+ }
+ api_models::payments::BankTransferData::MandiriVaBankTransfer { .. } => {
+ Self::MandiriVaBankTransfer {}
+ }
+ api_models::payments::BankTransferData::Pix {} => Self::Pix {},
+ api_models::payments::BankTransferData::Pse {} => Self::Pse {},
+ api_models::payments::BankTransferData::LocalBankTransfer { bank_code } => {
+ Self::LocalBankTransfer { bank_code }
+ }
+ }
+ }
+}
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
new file mode 100644
index 0000000000..e95f6efd37
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -0,0 +1,453 @@
+pub mod authentication;
+pub mod fraud_check;
+use api_models::payments::RequestSurchargeDetails;
+use common_utils::{consts, errors, pii};
+use diesel_models::enums as storage_enums;
+use error_stack::ResultExt;
+use masking::Secret;
+use serde::Serialize;
+use serde_with::serde_as;
+
+use super::payment_method_data::PaymentMethodData;
+use crate::{errors::api_error_response, mandates, payments, router_data};
+#[derive(Debug, Clone)]
+pub struct PaymentsAuthorizeData {
+ pub payment_method_data: PaymentMethodData,
+ /// total amount (original_amount + surcharge_amount + tax_on_surcharge_amount)
+ /// If connector supports separate field for surcharge amount, consider using below functions defined on `PaymentsAuthorizeData` to fetch original amount and surcharge amount separately
+ /// ```
+ /// get_original_amount()
+ /// get_surcharge_amount()
+ /// get_tax_on_surcharge_amount()
+ /// get_total_surcharge_amount() // returns surcharge_amount + tax_on_surcharge_amount
+ /// ```
+ pub amount: i64,
+ pub email: Option<pii::Email>,
+ pub customer_name: Option<Secret<String>>,
+ pub currency: storage_enums::Currency,
+ pub confirm: bool,
+ pub statement_descriptor_suffix: Option<String>,
+ pub statement_descriptor: Option<String>,
+ pub capture_method: Option<storage_enums::CaptureMethod>,
+ pub router_return_url: Option<String>,
+ pub webhook_url: Option<String>,
+ pub complete_authorize_url: Option<String>,
+ // Mandates
+ pub setup_future_usage: Option<storage_enums::FutureUsage>,
+ pub mandate_id: Option<api_models::payments::MandateIds>,
+ pub off_session: Option<bool>,
+ pub customer_acceptance: Option<mandates::CustomerAcceptance>,
+ pub setup_mandate_details: Option<mandates::MandateData>,
+ pub browser_info: Option<BrowserInformation>,
+ pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
+ pub order_category: Option<String>,
+ pub session_token: Option<String>,
+ pub enrolled_for_3ds: bool,
+ pub related_transaction_id: Option<String>,
+ pub payment_experience: Option<storage_enums::PaymentExperience>,
+ pub payment_method_type: Option<storage_enums::PaymentMethodType>,
+ pub surcharge_details: Option<SurchargeDetails>,
+ pub customer_id: Option<String>,
+ pub request_incremental_authorization: bool,
+ pub metadata: Option<pii::SecretSerdeValue>,
+ pub authentication_data: Option<AuthenticationData>,
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct PaymentsCaptureData {
+ pub amount_to_capture: i64,
+ pub currency: storage_enums::Currency,
+ pub connector_transaction_id: String,
+ pub payment_amount: i64,
+ pub multiple_capture_data: Option<MultipleCaptureRequestData>,
+ pub connector_meta: Option<serde_json::Value>,
+ pub browser_info: Option<BrowserInformation>,
+ pub metadata: Option<pii::SecretSerdeValue>,
+ // This metadata is used to store the metadata shared during the payment intent request.
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct PaymentsIncrementalAuthorizationData {
+ pub total_amount: i64,
+ pub additional_amount: i64,
+ pub currency: storage_enums::Currency,
+ pub reason: Option<String>,
+ pub connector_transaction_id: String,
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct MultipleCaptureRequestData {
+ pub capture_sequence: i16,
+ pub capture_reference: String,
+}
+
+#[derive(Debug, Clone)]
+pub struct AuthorizeSessionTokenData {
+ pub amount_to_capture: Option<i64>,
+ pub currency: storage_enums::Currency,
+ pub connector_transaction_id: String,
+ pub amount: Option<i64>,
+}
+
+#[derive(Debug, Clone)]
+pub struct ConnectorCustomerData {
+ pub description: Option<String>,
+ pub email: Option<pii::Email>,
+ pub phone: Option<Secret<String>>,
+ pub name: Option<Secret<String>>,
+ pub preprocessing_id: Option<String>,
+ pub payment_method_data: PaymentMethodData,
+}
+
+#[derive(Debug, Clone)]
+pub struct PaymentMethodTokenizationData {
+ pub payment_method_data: PaymentMethodData,
+ pub browser_info: Option<BrowserInformation>,
+ pub currency: storage_enums::Currency,
+ pub amount: Option<i64>,
+}
+
+#[derive(Debug, Clone)]
+pub struct PaymentsPreProcessingData {
+ pub payment_method_data: Option<PaymentMethodData>,
+ pub amount: Option<i64>,
+ pub email: Option<pii::Email>,
+ pub currency: Option<storage_enums::Currency>,
+ pub payment_method_type: Option<storage_enums::PaymentMethodType>,
+ pub setup_mandate_details: Option<mandates::MandateData>,
+ pub capture_method: Option<storage_enums::CaptureMethod>,
+ pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
+ pub router_return_url: Option<String>,
+ pub webhook_url: Option<String>,
+ pub complete_authorize_url: Option<String>,
+ pub surcharge_details: Option<SurchargeDetails>,
+ pub browser_info: Option<BrowserInformation>,
+ pub connector_transaction_id: Option<String>,
+ pub redirect_response: Option<CompleteAuthorizeRedirectResponse>,
+}
+
+#[derive(Debug, Clone)]
+pub struct CompleteAuthorizeData {
+ pub payment_method_data: Option<PaymentMethodData>,
+ pub amount: i64,
+ pub email: Option<pii::Email>,
+ pub currency: storage_enums::Currency,
+ pub confirm: bool,
+ pub statement_descriptor_suffix: Option<String>,
+ pub capture_method: Option<storage_enums::CaptureMethod>,
+ // Mandates
+ pub setup_future_usage: Option<storage_enums::FutureUsage>,
+ pub mandate_id: Option<api_models::payments::MandateIds>,
+ pub off_session: Option<bool>,
+ pub setup_mandate_details: Option<mandates::MandateData>,
+ pub redirect_response: Option<CompleteAuthorizeRedirectResponse>,
+ pub browser_info: Option<BrowserInformation>,
+ pub connector_transaction_id: Option<String>,
+ pub connector_meta: Option<serde_json::Value>,
+ pub complete_authorize_url: Option<String>,
+ pub metadata: Option<pii::SecretSerdeValue>,
+}
+
+#[derive(Debug, Clone)]
+pub struct CompleteAuthorizeRedirectResponse {
+ pub params: Option<Secret<String>>,
+ pub payload: Option<pii::SecretSerdeValue>,
+}
+
+#[derive(Debug, Default, Clone)]
+pub struct PaymentsSyncData {
+ //TODO : add fields based on the connector requirements
+ pub connector_transaction_id: ResponseId,
+ pub encoded_data: Option<String>,
+ pub capture_method: Option<storage_enums::CaptureMethod>,
+ pub connector_meta: Option<serde_json::Value>,
+ pub sync_type: SyncRequestType,
+ pub mandate_id: Option<api_models::payments::MandateIds>,
+ pub payment_method_type: Option<storage_enums::PaymentMethodType>,
+ pub currency: storage_enums::Currency,
+}
+
+#[derive(Debug, Default, Clone)]
+pub enum SyncRequestType {
+ MultipleCaptureSync(Vec<String>),
+ #[default]
+ SinglePaymentSync,
+}
+
+#[derive(Debug, Default, Clone)]
+pub struct PaymentsCancelData {
+ pub amount: Option<i64>,
+ pub currency: Option<storage_enums::Currency>,
+ pub connector_transaction_id: String,
+ pub cancellation_reason: Option<String>,
+ pub connector_meta: Option<serde_json::Value>,
+ pub browser_info: Option<BrowserInformation>,
+ pub metadata: Option<pii::SecretSerdeValue>,
+ // This metadata is used to store the metadata shared during the payment intent request.
+}
+
+#[derive(Debug, Default, Clone)]
+pub struct PaymentsRejectData {
+ pub amount: Option<i64>,
+ pub currency: Option<storage_enums::Currency>,
+}
+
+#[derive(Debug, Default, Clone)]
+pub struct PaymentsApproveData {
+ pub amount: Option<i64>,
+ pub currency: Option<storage_enums::Currency>,
+}
+
+#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
+pub struct BrowserInformation {
+ pub color_depth: Option<u8>,
+ pub java_enabled: Option<bool>,
+ pub java_script_enabled: Option<bool>,
+ pub language: Option<String>,
+ pub screen_height: Option<u32>,
+ pub screen_width: Option<u32>,
+ pub time_zone: Option<i32>,
+ pub ip_address: Option<std::net::IpAddr>,
+ pub accept_header: Option<String>,
+ pub user_agent: Option<String>,
+}
+
+#[derive(Debug, Clone, Default, Serialize)]
+pub enum ResponseId {
+ ConnectorTransactionId(String),
+ EncodedData(String),
+ #[default]
+ NoResponseId,
+}
+impl ResponseId {
+ pub fn get_connector_transaction_id(
+ &self,
+ ) -> errors::CustomResult<String, errors::ValidationError> {
+ match self {
+ Self::ConnectorTransactionId(txn_id) => Ok(txn_id.to_string()),
+ _ => Err(errors::ValidationError::IncorrectValueProvided {
+ field_name: "connector_transaction_id",
+ })
+ .attach_printable("Expected connector transaction ID not found"),
+ }
+ }
+}
+
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct SurchargeDetails {
+ /// original_amount
+ pub original_amount: common_utils::types::MinorUnit,
+ /// surcharge value
+ pub surcharge: common_utils::types::Surcharge,
+ /// tax on surcharge value
+ pub tax_on_surcharge:
+ Option<common_utils::types::Percentage<{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH }>>,
+ /// surcharge amount for this payment
+ pub surcharge_amount: common_utils::types::MinorUnit,
+ /// tax on surcharge amount for this payment
+ pub tax_on_surcharge_amount: common_utils::types::MinorUnit,
+ /// sum of original amount,
+ pub final_amount: common_utils::types::MinorUnit,
+}
+
+impl SurchargeDetails {
+ pub fn is_request_surcharge_matching(
+ &self,
+ request_surcharge_details: RequestSurchargeDetails,
+ ) -> bool {
+ request_surcharge_details.surcharge_amount == self.surcharge_amount
+ && request_surcharge_details.tax_amount.unwrap_or_default()
+ == self.tax_on_surcharge_amount
+ }
+ pub fn get_total_surcharge_amount(&self) -> common_utils::types::MinorUnit {
+ self.surcharge_amount + self.tax_on_surcharge_amount
+ }
+}
+
+impl
+ From<(
+ &RequestSurchargeDetails,
+ &payments::payment_attempt::PaymentAttempt,
+ )> for SurchargeDetails
+{
+ fn from(
+ (request_surcharge_details, payment_attempt): (
+ &RequestSurchargeDetails,
+ &payments::payment_attempt::PaymentAttempt,
+ ),
+ ) -> Self {
+ let surcharge_amount = request_surcharge_details.surcharge_amount;
+ let tax_on_surcharge_amount = request_surcharge_details.tax_amount.unwrap_or_default();
+ Self {
+ original_amount: payment_attempt.amount,
+ surcharge: common_utils::types::Surcharge::Fixed(
+ request_surcharge_details.surcharge_amount,
+ ),
+ tax_on_surcharge: None,
+ surcharge_amount,
+ tax_on_surcharge_amount,
+ final_amount: payment_attempt.amount + surcharge_amount + tax_on_surcharge_amount,
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct AuthenticationData {
+ pub eci: Option<String>,
+ pub cavv: String,
+ pub threeds_server_transaction_id: String,
+ pub message_version: String,
+}
+
+#[derive(Debug, Clone)]
+pub struct RefundsData {
+ pub refund_id: String,
+ pub connector_transaction_id: String,
+
+ pub connector_refund_id: Option<String>,
+ pub currency: storage_enums::Currency,
+ /// Amount for the payment against which this refund is issued
+ pub payment_amount: i64,
+ pub reason: Option<String>,
+ pub webhook_url: Option<String>,
+ /// Amount to be refunded
+ pub refund_amount: i64,
+ /// Arbitrary metadata required for refund
+ pub connector_metadata: Option<serde_json::Value>,
+ pub browser_info: Option<BrowserInformation>,
+}
+
+#[derive(Debug, Clone)]
+pub struct AccessTokenRequestData {
+ pub app_id: Secret<String>,
+ pub id: Option<Secret<String>>,
+ // Add more keys if required
+}
+
+impl TryFrom<router_data::ConnectorAuthType> for AccessTokenRequestData {
+ type Error = api_error_response::ApiErrorResponse;
+ fn try_from(connector_auth: router_data::ConnectorAuthType) -> Result<Self, Self::Error> {
+ match connector_auth {
+ router_data::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
+ app_id: api_key,
+ id: None,
+ }),
+ router_data::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
+ app_id: api_key,
+ id: Some(key1),
+ }),
+ router_data::ConnectorAuthType::SignatureKey { api_key, key1, .. } => Ok(Self {
+ app_id: api_key,
+ id: Some(key1),
+ }),
+ router_data::ConnectorAuthType::MultiAuthKey { api_key, key1, .. } => Ok(Self {
+ app_id: api_key,
+ id: Some(key1),
+ }),
+
+ _ => Err(api_error_response::ApiErrorResponse::InvalidDataValue {
+ field_name: "connector_account_details",
+ }),
+ }
+ }
+}
+
+#[derive(Default, Debug, Clone)]
+pub struct AcceptDisputeRequestData {
+ pub dispute_id: String,
+ pub connector_dispute_id: String,
+}
+
+#[derive(Default, Debug, Clone)]
+pub struct DefendDisputeRequestData {
+ pub dispute_id: String,
+ pub connector_dispute_id: String,
+}
+
+#[derive(Default, Debug, Clone)]
+pub struct SubmitEvidenceRequestData {
+ pub dispute_id: String,
+ pub connector_dispute_id: String,
+ pub access_activity_log: Option<String>,
+ pub billing_address: Option<String>,
+ pub cancellation_policy: Option<Vec<u8>>,
+ pub cancellation_policy_provider_file_id: Option<String>,
+ pub cancellation_policy_disclosure: Option<String>,
+ pub cancellation_rebuttal: Option<String>,
+ pub customer_communication: Option<Vec<u8>>,
+ pub customer_communication_provider_file_id: Option<String>,
+ pub customer_email_address: Option<String>,
+ pub customer_name: Option<String>,
+ pub customer_purchase_ip: Option<String>,
+ pub customer_signature: Option<Vec<u8>>,
+ pub customer_signature_provider_file_id: Option<String>,
+ pub product_description: Option<String>,
+ pub receipt: Option<Vec<u8>>,
+ pub receipt_provider_file_id: Option<String>,
+ pub refund_policy: Option<Vec<u8>>,
+ pub refund_policy_provider_file_id: Option<String>,
+ pub refund_policy_disclosure: Option<String>,
+ pub refund_refusal_explanation: Option<String>,
+ pub service_date: Option<String>,
+ pub service_documentation: Option<Vec<u8>>,
+ pub service_documentation_provider_file_id: Option<String>,
+ pub shipping_address: Option<String>,
+ pub shipping_carrier: Option<String>,
+ pub shipping_date: Option<String>,
+ pub shipping_documentation: Option<Vec<u8>>,
+ pub shipping_documentation_provider_file_id: Option<String>,
+ pub shipping_tracking_number: Option<String>,
+ pub invoice_showing_distinct_transactions: Option<Vec<u8>>,
+ pub invoice_showing_distinct_transactions_provider_file_id: Option<String>,
+ pub recurring_transaction_agreement: Option<Vec<u8>>,
+ pub recurring_transaction_agreement_provider_file_id: Option<String>,
+ pub uncategorized_file: Option<Vec<u8>>,
+ pub uncategorized_file_provider_file_id: Option<String>,
+ pub uncategorized_text: Option<String>,
+}
+
+#[derive(Clone, Debug)]
+pub struct RetrieveFileRequestData {
+ pub provider_file_id: String,
+}
+
+#[serde_as]
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct UploadFileRequestData {
+ pub file_key: String,
+ #[serde(skip)]
+ pub file: Vec<u8>,
+ #[serde_as(as = "serde_with::DisplayFromStr")]
+ pub file_type: mime::Mime,
+ pub file_size: i32,
+}
+
+#[cfg(feature = "payouts")]
+#[derive(Debug, Clone)]
+pub struct PayoutsData {
+ pub payout_id: String,
+ pub amount: i64,
+ pub connector_payout_id: Option<String>,
+ pub destination_currency: storage_enums::Currency,
+ pub source_currency: storage_enums::Currency,
+ pub payout_type: storage_enums::PayoutType,
+ pub entity_type: storage_enums::PayoutEntityType,
+ pub customer_details: Option<CustomerDetails>,
+ pub vendor_details: Option<api_models::payouts::PayoutVendorAccountDetails>,
+}
+
+#[derive(Debug, Default, Clone)]
+pub struct CustomerDetails {
+ pub customer_id: Option<String>,
+ pub name: Option<Secret<String, masking::WithType>>,
+ pub email: Option<pii::Email>,
+ pub phone: Option<Secret<String, masking::WithType>>,
+ pub phone_country_code: Option<String>,
+}
+
+#[derive(Debug, Clone)]
+pub struct VerifyWebhookSourceRequestData {
+ pub webhook_headers: actix_web::http::header::HeaderMap,
+ pub webhook_body: Vec<u8>,
+ pub merchant_secret: api_models::webhooks::ConnectorWebhookSecrets,
+}
diff --git a/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs b/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs
new file mode 100644
index 0000000000..1a554e8054
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs
@@ -0,0 +1,182 @@
+use cards::CardNumber;
+use common_utils::{ext_traits::OptionExt, pii::Email};
+use error_stack::{Report, ResultExt};
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ errors::api_error_response::ApiErrorResponse, payment_method_data::PaymentMethodData,
+ router_request_types::BrowserInformation,
+};
+
+#[derive(Debug, Clone)]
+pub enum AuthenticationResponseData {
+ PreAuthNResponse {
+ threeds_server_transaction_id: String,
+ maximum_supported_3ds_version: common_utils::types::SemanticVersion,
+ connector_authentication_id: String,
+ three_ds_method_data: Option<String>,
+ three_ds_method_url: Option<String>,
+ message_version: common_utils::types::SemanticVersion,
+ connector_metadata: Option<serde_json::Value>,
+ },
+ AuthNResponse {
+ authn_flow_type: AuthNFlowType,
+ authentication_value: Option<String>,
+ trans_status: common_enums::TransactionStatus,
+ },
+ PostAuthNResponse {
+ trans_status: common_enums::TransactionStatus,
+ authentication_value: Option<String>,
+ eci: Option<String>,
+ },
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct ChallengeParams {
+ pub acs_url: Option<url::Url>,
+ pub challenge_request: Option<String>,
+ pub acs_reference_number: Option<String>,
+ pub acs_trans_id: Option<String>,
+ pub three_dsserver_trans_id: Option<String>,
+ pub acs_signed_content: Option<String>,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub enum AuthNFlowType {
+ Challenge(Box<ChallengeParams>),
+ Frictionless,
+}
+
+impl AuthNFlowType {
+ pub fn get_acs_url(&self) -> Option<String> {
+ if let Self::Challenge(challenge_params) = self {
+ challenge_params.acs_url.as_ref().map(ToString::to_string)
+ } else {
+ None
+ }
+ }
+ pub fn get_challenge_request(&self) -> Option<String> {
+ if let Self::Challenge(challenge_params) = self {
+ challenge_params.challenge_request.clone()
+ } else {
+ None
+ }
+ }
+ pub fn get_acs_reference_number(&self) -> Option<String> {
+ if let Self::Challenge(challenge_params) = self {
+ challenge_params.acs_reference_number.clone()
+ } else {
+ None
+ }
+ }
+ pub fn get_acs_trans_id(&self) -> Option<String> {
+ if let Self::Challenge(challenge_params) = self {
+ challenge_params.acs_trans_id.clone()
+ } else {
+ None
+ }
+ }
+ pub fn get_acs_signed_content(&self) -> Option<String> {
+ if let Self::Challenge(challenge_params) = self {
+ challenge_params.acs_signed_content.clone()
+ } else {
+ None
+ }
+ }
+ pub fn get_decoupled_authentication_type(&self) -> common_enums::DecoupledAuthenticationType {
+ match self {
+ Self::Challenge(_) => common_enums::DecoupledAuthenticationType::Challenge,
+ Self::Frictionless => common_enums::DecoupledAuthenticationType::Frictionless,
+ }
+ }
+}
+
+#[derive(Clone, Default, Debug)]
+pub struct PreAuthNRequestData {
+ // card number
+ #[allow(dead_code)]
+ pub(crate) card_holder_account_number: CardNumber,
+}
+
+#[derive(Clone, Debug)]
+pub struct ConnectorAuthenticationRequestData {
+ pub payment_method_data: PaymentMethodData,
+ pub billing_address: api_models::payments::Address,
+ pub shipping_address: Option<api_models::payments::Address>,
+ pub browser_details: Option<BrowserInformation>,
+ pub amount: Option<i64>,
+ pub currency: Option<common_enums::Currency>,
+ pub message_category: MessageCategory,
+ pub device_channel: api_models::payments::DeviceChannel,
+ pub pre_authentication_data: PreAuthenticationData,
+ pub return_url: Option<String>,
+ pub sdk_information: Option<api_models::payments::SdkInformation>,
+ pub email: Option<Email>,
+ pub threeds_method_comp_ind: api_models::payments::ThreeDsCompletionIndicator,
+ pub three_ds_requestor_url: String,
+ pub webhook_url: String,
+}
+
+#[derive(Clone, serde::Deserialize, Debug, serde::Serialize, PartialEq, Eq)]
+pub enum MessageCategory {
+ Payment,
+ NonPayment,
+}
+
+#[derive(Clone, Debug)]
+pub struct ConnectorPostAuthenticationRequestData {
+ pub threeds_server_transaction_id: String,
+}
+
+#[derive(Clone, Debug)]
+pub struct PreAuthenticationData {
+ pub threeds_server_transaction_id: String,
+ pub message_version: common_utils::types::SemanticVersion,
+ pub acquirer_bin: Option<String>,
+ pub acquirer_merchant_id: Option<String>,
+ pub connector_metadata: Option<serde_json::Value>,
+}
+
+impl TryFrom<&diesel_models::authentication::Authentication> for PreAuthenticationData {
+ type Error = Report<ApiErrorResponse>;
+
+ fn try_from(
+ authentication: &diesel_models::authentication::Authentication,
+ ) -> Result<Self, Self::Error> {
+ let error_message = ApiErrorResponse::UnprocessableEntity { message: "Pre Authentication must be completed successfully before Authentication can be performed".to_string() };
+ let threeds_server_transaction_id = authentication
+ .threeds_server_transaction_id
+ .clone()
+ .get_required_value("threeds_server_transaction_id")
+ .change_context(error_message.clone())?;
+ let message_version = authentication
+ .message_version
+ .clone()
+ .get_required_value("message_version")
+ .change_context(error_message)?;
+ Ok(Self {
+ threeds_server_transaction_id,
+ message_version,
+ acquirer_bin: authentication.acquirer_bin.clone(),
+ acquirer_merchant_id: authentication.acquirer_merchant_id.clone(),
+ connector_metadata: authentication.connector_metadata.clone(),
+ })
+ }
+}
+
+#[derive(Clone, Default, Debug, Serialize, Deserialize)]
+pub struct ThreeDsMethodData {
+ pub three_ds_method_data_submission: bool,
+ pub three_ds_method_data: String,
+ pub three_ds_method_url: Option<String>,
+}
+#[derive(Clone, Default, Debug, Serialize, Deserialize)]
+pub struct AcquirerDetails {
+ pub acquirer_bin: String,
+ pub acquirer_merchant_id: String,
+}
+
+#[derive(Clone, Debug, Deserialize)]
+pub struct ExternalThreeDSConnectorMetadata {
+ pub pull_mechanism_for_external_3ds_enabled: Option<bool>,
+}
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
new file mode 100644
index 0000000000..441d3a70b4
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs
@@ -0,0 +1,164 @@
+use api_models;
+use common_enums;
+use common_utils::{
+ events::{ApiEventMetric, ApiEventsType},
+ pii::Email,
+};
+use masking::Secret;
+use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
+
+use crate::router_request_types;
+#[derive(Debug, Clone)]
+pub struct FraudCheckSaleData {
+ pub amount: i64,
+ pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
+ pub currency: Option<common_enums::Currency>,
+ pub email: Option<Email>,
+}
+
+#[derive(Debug, Clone)]
+pub struct FraudCheckCheckoutData {
+ pub amount: i64,
+ pub order_details: Option<Vec<api_models::payments::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>,
+}
+
+#[derive(Debug, Clone)]
+pub struct FraudCheckTransactionData {
+ pub amount: i64,
+ pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
+ pub currency: Option<common_enums::Currency>,
+ pub payment_method: Option<common_enums::PaymentMethod>,
+ pub error_code: Option<String>,
+ pub error_message: Option<String>,
+ pub connector_transaction_id: Option<String>,
+ //The name of the payment gateway or financial institution that processed the transaction.
+ pub connector: Option<String>,
+}
+
+#[derive(Debug, Clone)]
+pub struct FraudCheckRecordReturnData {
+ pub amount: i64,
+ pub currency: Option<common_enums::Currency>,
+ pub refund_method: RefundMethod,
+ pub refund_transaction_id: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
+#[serde_with::skip_serializing_none]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum RefundMethod {
+ StoreCredit,
+ OriginalPaymentInstrument,
+ NewPaymentInstrument,
+}
+
+#[derive(Debug, Clone)]
+pub struct FraudCheckFulfillmentData {
+ pub amount: i64,
+ pub order_details: Option<Vec<Secret<serde_json::Value>>>,
+ pub fulfillment_req: FrmFulfillmentRequest,
+}
+
+#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+#[serde_with::skip_serializing_none]
+#[serde(rename_all = "snake_case")]
+pub struct FrmFulfillmentRequest {
+ ///unique payment_id for the transaction
+ #[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")]
+ pub payment_id: String,
+ ///unique order_id for the order_details in the transaction
+ #[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")]
+ pub order_id: String,
+ ///denotes the status of the fulfillment... can be one of PARTIAL, COMPLETE, REPLACEMENT, CANCELED
+ #[schema(value_type = Option<FulfillmentStatus>, example = "COMPLETE")]
+ pub fulfillment_status: Option<FulfillmentStatus>,
+ ///contains details of the fulfillment
+ #[schema(value_type = Vec<Fulfillments>)]
+ pub fulfillments: Vec<Fulfillments>,
+ //name of the tracking Company
+ #[schema(max_length = 255, example = "fedex")]
+ pub tracking_company: Option<String>,
+ //tracking ID of the product
+ #[schema(example = r#"["track_8327446667", "track_8327446668"]"#)]
+ pub tracking_numbers: Option<Vec<String>>,
+ //tracking_url for tracking the product
+ pub tracking_urls: Option<Vec<String>>,
+ // The name of the Shipper.
+ pub carrier: Option<String>,
+ // Fulfillment method for the shipment.
+ pub fulfillment_method: Option<String>,
+ // Statuses to indicate shipment state.
+ pub shipment_status: Option<String>,
+ // The date and time items are ready to be shipped.
+ pub shipped_at: Option<String>,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
+#[serde_with::skip_serializing_none]
+#[serde(rename_all = "snake_case")]
+pub struct Fulfillments {
+ ///shipment_id of the shipped items
+ #[schema(max_length = 255, example = "ship_101")]
+ pub shipment_id: String,
+ ///products sent in the shipment
+ #[schema(value_type = Option<Vec<Product>>)]
+ pub products: Option<Vec<Product>>,
+ ///destination address of the shipment
+ #[schema(value_type = Destination)]
+ pub destination: Destination,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
+#[serde(untagged)]
+#[serde_with::skip_serializing_none]
+#[serde(rename_all = "snake_case")]
+pub enum FulfillmentStatus {
+ PARTIAL,
+ COMPLETE,
+ REPLACEMENT,
+ CANCELED,
+}
+
+#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
+#[serde_with::skip_serializing_none]
+#[serde(rename_all = "snake_case")]
+pub struct Product {
+ pub item_name: String,
+ pub item_quantity: i64,
+ pub item_id: String,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
+#[serde_with::skip_serializing_none]
+#[serde(rename_all = "snake_case")]
+pub struct Destination {
+ pub full_name: Secret<String>,
+ pub organization: Option<String>,
+ pub email: Option<Email>,
+ pub address: Address,
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
+#[serde_with::skip_serializing_none]
+#[serde(rename_all = "snake_case")]
+pub struct Address {
+ pub street_address: Secret<String>,
+ pub unit: Option<Secret<String>>,
+ pub postal_code: Secret<String>,
+ pub city: String,
+ pub province_code: Secret<String>,
+ pub country_code: common_enums::CountryAlpha2,
+}
+
+impl ApiEventMetric for FrmFulfillmentRequest {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::FraudCheck)
+ }
+}
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs
index bca1cbb64b..528381061c 100644
--- a/crates/router/src/compatibility/stripe/errors.rs
+++ b/crates/router/src/compatibility/stripe/errors.rs
@@ -1,7 +1,7 @@
-#![allow(unused_variables)]
use common_utils::errors::ErrorSwitch;
+use hyperswitch_domain_models::errors::api_error_response as errors;
-use crate::core::errors::{self, CustomersErrorResponse};
+use crate::core::errors::CustomersErrorResponse;
#[derive(Debug, router_derive::ApiError, Clone)]
#[error(error_type_enum = StripeErrorType)]
@@ -481,11 +481,11 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {
Self::PaymentIntentPaymentAttemptFailed { data }
}
errors::ApiErrorResponse::DisputeFailed { data } => Self::DisputeFailed { data },
- errors::ApiErrorResponse::InvalidCardData { data } => Self::InvalidCardType, // Maybe it is better to de generalize this router error
- errors::ApiErrorResponse::CardExpired { data } => Self::ExpiredCard,
- errors::ApiErrorResponse::RefundNotPossible { connector } => Self::RefundFailed,
- errors::ApiErrorResponse::RefundFailed { data } => Self::RefundFailed, // Nothing at stripe to map
- errors::ApiErrorResponse::PayoutFailed { data } => Self::PayoutFailed,
+ errors::ApiErrorResponse::InvalidCardData { data: _ } => Self::InvalidCardType, // Maybe it is better to de generalize this router error
+ errors::ApiErrorResponse::CardExpired { data: _ } => Self::ExpiredCard,
+ errors::ApiErrorResponse::RefundNotPossible { connector: _ } => Self::RefundFailed,
+ errors::ApiErrorResponse::RefundFailed { data: _ } => Self::RefundFailed, // Nothing at stripe to map
+ errors::ApiErrorResponse::PayoutFailed { data: _ } => Self::PayoutFailed,
errors::ApiErrorResponse::MandateUpdateFailed
| errors::ApiErrorResponse::MandateSerializationFailed
@@ -605,7 +605,7 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {
object: "poll".to_owned(),
id,
},
- errors::ApiErrorResponse::DisputeStatusValidationFailed { reason } => {
+ errors::ApiErrorResponse::DisputeStatusValidationFailed { reason: _ } => {
Self::InternalServerError
}
errors::ApiErrorResponse::FileValidationFailed { .. } => Self::FileValidationFailed,
diff --git a/crates/router/src/connector/signifyd/transformers/api.rs b/crates/router/src/connector/signifyd/transformers/api.rs
index 8c487f904f..9ffae8a02d 100644
--- a/crates/router/src/connector/signifyd/transformers/api.rs
+++ b/crates/router/src/connector/signifyd/transformers/api.rs
@@ -1,6 +1,7 @@
use bigdecimal::ToPrimitive;
use common_utils::{ext_traits::ValueExt, pii::Email};
use error_stack::{self, ResultExt};
+pub use hyperswitch_domain_models::router_request_types::fraud_check::RefundMethod;
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -14,7 +15,7 @@ use crate::{
core::{errors, fraud_check::types as core_types},
types::{
self, api, api::Fulfillment, fraud_check as frm_types, storage::enums as storage_enums,
- ResponseId, ResponseRouterData,
+ transformers::ForeignFrom, ResponseId, ResponseRouterData,
},
};
@@ -509,7 +510,7 @@ impl TryFrom<&frm_types::FrmFulfillmentRouterData> for FrmFulfillmentSignifydReq
.fulfillment_status
.as_ref()
.map(|fulfillment_status| FulfillmentStatus::from(&fulfillment_status.clone())),
- fulfillments: Vec::<Fulfillments>::from(&item.request.fulfillment_req),
+ fulfillments: Vec::<Fulfillments>::foreign_from(&item.request.fulfillment_req),
})
}
}
@@ -525,8 +526,8 @@ impl From<&core_types::FulfillmentStatus> for FulfillmentStatus {
}
}
-impl From<&core_types::FrmFulfillmentRequest> for Vec<Fulfillments> {
- fn from(fulfillment_req: &core_types::FrmFulfillmentRequest) -> Self {
+impl ForeignFrom<&core_types::FrmFulfillmentRequest> for Vec<Fulfillments> {
+ fn foreign_from(fulfillment_req: &core_types::FrmFulfillmentRequest) -> Self {
fulfillment_req
.fulfillments
.iter()
@@ -643,15 +644,6 @@ pub struct SignifydPaymentsRecordReturnRequest {
refund: SignifydRefund,
}
-#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
-#[serde_with::skip_serializing_none]
-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
-pub enum RefundMethod {
- StoreCredit,
- OriginalPaymentInstrument,
- NewPaymentInstrument,
-}
-
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs
index 495d176ab9..af1a0787d9 100644
--- a/crates/router/src/connector/worldpay.rs
+++ b/crates/router/src/connector/worldpay.rs
@@ -24,6 +24,7 @@ use crate::{
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
+ transformers::ForeignTryFrom,
ErrorResponse, Response,
},
utils::BytesExt,
@@ -225,7 +226,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
Ok(types::PaymentsCancelRouterData {
status: enums::AttemptStatus::Voided,
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::try_from(response.links)?,
+ resource_id: types::ResponseId::foreign_try_from(response.links)?,
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -392,7 +393,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
Ok(types::PaymentsCaptureRouterData {
status: enums::AttemptStatus::Charged,
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::try_from(response.links)?,
+ resource_id: types::ResponseId::foreign_try_from(response.links)?,
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
diff --git a/crates/router/src/connector/worldpay/response.rs b/crates/router/src/connector/worldpay/response.rs
index 0a50885d28..14ccbc1fac 100644
--- a/crates/router/src/connector/worldpay/response.rs
+++ b/crates/router/src/connector/worldpay/response.rs
@@ -1,7 +1,7 @@
use masking::Secret;
use serde::{Deserialize, Serialize};
-use crate::{core::errors, types};
+use crate::{core::errors, types, types::transformers::ForeignTryFrom};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorldpayPaymentsResponse {
@@ -109,9 +109,9 @@ impl TryFrom<Option<PaymentLinks>> for ResponseIdStr {
}
}
-impl TryFrom<Option<PaymentLinks>> for types::ResponseId {
+impl ForeignTryFrom<Option<PaymentLinks>> for types::ResponseId {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(links: Option<PaymentLinks>) -> Result<Self, Self::Error> {
+ fn foreign_try_from(links: Option<PaymentLinks>) -> Result<Self, Self::Error> {
get_resource_id(links, Self::ConnectorTransactionId)
}
}
diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs
index 9c908cf749..5f0fd9f332 100644
--- a/crates/router/src/connector/worldpay/transformers.rs
+++ b/crates/router/src/connector/worldpay/transformers.rs
@@ -9,7 +9,9 @@ use crate::{
connector::utils,
consts,
core::errors,
- types::{self, domain, PaymentsAuthorizeData, PaymentsResponseData},
+ types::{
+ self, domain, transformers::ForeignTryFrom, PaymentsAuthorizeData, PaymentsResponseData,
+ },
};
#[derive(Debug, Serialize)]
@@ -245,7 +247,7 @@ impl TryFrom<types::PaymentsResponseRouterData<WorldpayPaymentsResponse>>
},
description: item.response.description,
response: Ok(PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::try_from(item.response.links)?,
+ resource_id: types::ResponseId::foreign_try_from(item.response.links)?,
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index a70a97e7bf..3a8cab8c51 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -1,4 +1,3 @@
-pub mod api_error_response;
pub mod customers_error_response;
pub mod error_handlers;
pub mod transformers;
@@ -11,7 +10,10 @@ use std::fmt::Display;
use actix_web::{body::BoxBody, ResponseError};
pub use common_utils::errors::{CustomResult, ParsingError, ValidationError};
use diesel_models::errors as storage_errors;
-pub use hyperswitch_domain_models::errors::StorageError as DataStorageError;
+pub use hyperswitch_domain_models::errors::{
+ api_error_response::{ApiErrorResponse, ErrorType, NotImplementedMessage},
+ StorageError as DataStorageError,
+};
pub use redis_interface::errors::RedisError;
use scheduler::errors as sch_errors;
use storage_impl::errors as storage_impl_errors;
@@ -19,7 +21,6 @@ use storage_impl::errors as storage_impl_errors;
pub use user::*;
pub use self::{
- api_error_response::{ApiErrorResponse, NotImplementedMessage},
customers_error_response::CustomersErrorResponse,
sch_errors::*,
storage_errors::*,
diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs
deleted file mode 100644
index 0c492f0f08..0000000000
--- a/crates/router/src/core/errors/api_error_response.rs
+++ /dev/null
@@ -1,328 +0,0 @@
-#![allow(dead_code, unused_variables)]
-
-use http::StatusCode;
-use scheduler::errors::{PTError, ProcessTrackerError};
-
-#[derive(Clone, Debug, serde::Serialize)]
-#[serde(rename_all = "snake_case")]
-pub enum ErrorType {
- InvalidRequestError,
- ObjectNotFound,
- RouterError,
- ProcessingError,
- BadGateway,
- ServerNotAvailable,
- DuplicateRequest,
- ValidationError,
- ConnectorError,
- LockTimeout,
-}
-
-#[allow(dead_code)]
-#[derive(Debug, Clone, router_derive::ApiError)]
-#[error(error_type_enum = ErrorType)]
-pub enum ApiErrorResponse {
- #[error(error_type = ErrorType::ServerNotAvailable, code = "IR_00", message = "{message:?}")]
- NotImplemented { message: NotImplementedMessage },
- #[error(
- error_type = ErrorType::InvalidRequestError, code = "IR_01",
- message = "API key not provided or invalid API key used"
- )]
- Unauthorized,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_02", message = "Unrecognized request URL")]
- InvalidRequestUrl,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_03", message = "The HTTP method is not applicable for this API")]
- InvalidHttpMethod,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_04", message = "Missing required param: {field_name}")]
- MissingRequiredField { field_name: &'static str },
- #[error(
- error_type = ErrorType::InvalidRequestError, code = "IR_05",
- message = "{field_name} contains invalid data. Expected format is {expected_format}"
- )]
- InvalidDataFormat {
- field_name: String,
- expected_format: String,
- },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_06", message = "{message}")]
- InvalidRequestData { message: String },
- /// Typically used when a field has invalid value, or deserialization of the value contained in a field fails.
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_07", message = "Invalid value provided: {field_name}")]
- InvalidDataValue { field_name: &'static str },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Client secret was not provided")]
- ClientSecretNotGiven,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Client secret has expired")]
- ClientSecretExpired,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_09", message = "The client_secret provided does not match the client_secret associated with the Payment")]
- ClientSecretInvalid,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_10", message = "Customer has active mandate/subsciption")]
- MandateActive,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_11", message = "Customer has already been redacted")]
- CustomerRedacted,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_12", message = "Reached maximum refund attempts")]
- MaximumRefundCount,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_13", message = "The refund amount exceeds the amount captured")]
- RefundAmountExceedsPaymentAmount,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_14", message = "This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}")]
- PaymentUnexpectedState {
- current_flow: String,
- field_name: String,
- current_value: String,
- states: String,
- },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_15", message = "Invalid Ephemeral Key for the customer")]
- InvalidEphemeralKey,
- /// Typically used when information involving multiple fields or previously provided information doesn't satisfy a condition.
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_16", message = "{message}")]
- PreconditionFailed { message: String },
- #[error(
- error_type = ErrorType::InvalidRequestError, code = "IR_17",
- message = "Access forbidden, invalid JWT token was used"
- )]
- InvalidJwtToken,
- #[error(
- error_type = ErrorType::InvalidRequestError, code = "IR_18",
- message = "{message}",
- )]
- GenericUnauthorized { message: String },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_19", message = "{message}")]
- NotSupported { message: String },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_20", message = "{flow} flow not supported by the {connector} connector")]
- FlowNotSupported { flow: String, connector: String },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_21", message = "Missing required params")]
- MissingRequiredFields { field_names: Vec<&'static str> },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_22", message = "Access forbidden. Not authorized to access this resource {resource}")]
- AccessForbidden { resource: String },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_23", message = "{message}")]
- FileProviderNotSupported { message: String },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_23", message = "{message}")]
- UnprocessableEntity { message: String },
- #[error(
- error_type = ErrorType::ProcessingError, code = "IR_24",
- message = "Invalid {wallet_name} wallet token"
- )]
- InvalidWalletToken { wallet_name: String },
- #[error(error_type = ErrorType::ConnectorError, code = "CE_00", message = "{code}: {message}", ignore = "status_code")]
- ExternalConnectorError {
- code: String,
- message: String,
- connector: String,
- status_code: u16,
- reason: Option<String>,
- },
- #[error(error_type = ErrorType::ProcessingError, code = "CE_01", message = "Payment failed during authorization with connector. Retry payment")]
- PaymentAuthorizationFailed { data: Option<serde_json::Value> },
- #[error(error_type = ErrorType::ProcessingError, code = "CE_02", message = "Payment failed during authentication with connector. Retry payment")]
- PaymentAuthenticationFailed { data: Option<serde_json::Value> },
- #[error(error_type = ErrorType::ProcessingError, code = "CE_03", message = "Capture attempt failed while processing with connector")]
- PaymentCaptureFailed { data: Option<serde_json::Value> },
- #[error(error_type = ErrorType::ProcessingError, code = "CE_04", message = "The card data is invalid")]
- InvalidCardData { data: Option<serde_json::Value> },
- #[error(error_type = ErrorType::InvalidRequestError, code = "CE_04", message = "Payout validation failed")]
- PayoutFailed { data: Option<serde_json::Value> },
- #[error(error_type = ErrorType::ProcessingError, code = "CE_05", message = "The card has expired")]
- CardExpired { data: Option<serde_json::Value> },
- #[error(error_type = ErrorType::ProcessingError, code = "CE_06", message = "Refund failed while processing with connector. Retry refund")]
- RefundFailed { data: Option<serde_json::Value> },
- #[error(error_type = ErrorType::ProcessingError, code = "CE_07", message = "Verification failed while processing with connector. Retry operation")]
- VerificationFailed { data: Option<serde_json::Value> },
- #[error(error_type = ErrorType::ProcessingError, code = "CE_08", message = "Dispute operation failed while processing with connector. Retry operation")]
- DisputeFailed { data: Option<serde_json::Value> },
- #[error(error_type = ErrorType::ServerNotAvailable, code = "HE_00", message = "Something went wrong")]
- InternalServerError,
- #[error(error_type = ErrorType::LockTimeout, code = "HE_00", message = "Resource is busy. Please try again later.")]
- ResourceBusy,
- #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "Duplicate refund request. Refund already attempted with the refund ID")]
- DuplicateRefundRequest,
- #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "Duplicate mandate request. Mandate already attempted with the Mandate ID")]
- DuplicateMandate,
- #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The merchant account with the specified details already exists in our records")]
- DuplicateMerchantAccount,
- #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_label}' already exists in our records")]
- DuplicateMerchantConnectorAccount {
- profile_id: String,
- connector_label: String,
- },
- #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment method with the specified details already exists in our records")]
- DuplicatePaymentMethod,
- #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment with the specified payment_id already exists in our records")]
- DuplicatePayment { payment_id: String },
- #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payout with the specified payout_id '{payout_id}' already exists in our records")]
- DuplicatePayout { payout_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")]
- RefundNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Customer does not exist in our records")]
- CustomerNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "RE_02", message = "Config key does not exist in our records.")]
- 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 = "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")]
- MerchantAccountNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Merchant connector account does not exist in our records")]
- MerchantConnectorAccountNotFound { id: String },
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Business profile with the given id '{id}' does not exist in our records")]
- BusinessProfileNotFound { id: String },
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Poll with the given id '{id}' does not exist in our records")]
- PollNotFound { id: String },
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Resource ID does not exist in our records")]
- ResourceIdNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Mandate does not exist in our records")]
- MandateNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Authentication does not exist in our records")]
- AuthenticationNotFound { id: String },
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Failed to update mandate")]
- MandateUpdateFailed,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "API Key does not exist in our records")]
- ApiKeyNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payout does not exist in our records")]
- PayoutNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Event does not exist in our records")]
- EventNotFound,
- #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Invalid mandate id passed from connector")]
- MandateSerializationFailed,
- #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Unable to parse the mandate identifier passed from connector")]
- MandateDeserializationFailed,
- #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Return URL is not configured and not passed in payments request")]
- ReturnUrlUnavailable,
- #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard")]
- RefundNotPossible { connector: String },
- #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Mandate Validation Failed" )]
- MandateValidationFailed { reason: String },
- #[error(error_type= ErrorType::ValidationError, code = "HE_03", message = "The payment has not succeeded yet. Please pass a successful payment to initiate refund")]
- PaymentNotSucceeded,
- #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "The specified merchant connector account is disabled")]
- MerchantConnectorAccountDisabled,
- #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "{code}: {message}")]
- PaymentBlockedError {
- code: u16,
- message: String,
- status: String,
- reason: String,
- },
- #[error(error_type= ErrorType::ObjectNotFound, code = "HE_04", message = "Successful payment not found for the given payment id")]
- SuccessfulPaymentNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "The connector provided in the request is incorrect or not available")]
- IncorrectConnectorNameGiven,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "Address does not exist in our records")]
- AddressNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "Dispute does not exist in our records")]
- DisputeNotFound { dispute_id: String },
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "File does not exist in our records")]
- FileNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "File not available")]
- FileNotAvailable,
- #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "Dispute status validation failed")]
- DisputeStatusValidationFailed { reason: String },
- #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "Card with the provided iin does not exist")]
- InvalidCardIin,
- #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "The provided card IIN length is invalid, please provide an iin with 6 or 8 digits")]
- InvalidCardIinLength,
- #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "File validation failed")]
- FileValidationFailed { reason: String },
- #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "File not found / valid in the request")]
- MissingFile,
- #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "Dispute id not found in the request")]
- MissingDisputeId,
- #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "File purpose not found in the request or is invalid")]
- MissingFilePurpose,
- #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "File content type not found / valid")]
- MissingFileContentType,
- #[error(error_type = ErrorType::InvalidRequestError, code = "HE_05", message = "{message}")]
- GenericNotFoundError { message: String },
- #[error(error_type = ErrorType::InvalidRequestError, code = "HE_01", message = "{message}")]
- GenericDuplicateError { message: String },
- #[error(error_type = ErrorType::InvalidRequestError, code = "WE_01", message = "Failed to authenticate the webhook")]
- WebhookAuthenticationFailed,
- #[error(error_type = ErrorType::ObjectNotFound, code = "WE_04", message = "Webhook resource not found")]
- WebhookResourceNotFound,
- #[error(error_type = ErrorType::InvalidRequestError, code = "WE_02", message = "Bad request received in webhook")]
- WebhookBadRequest,
- #[error(error_type = ErrorType::RouterError, code = "WE_03", message = "There was some issue processing the webhook")]
- WebhookProcessingFailure,
- #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "required payment method is not configured or configured incorrectly for all configured connectors")]
- IncorrectPaymentMethodConfiguration,
- #[error(error_type = ErrorType::InvalidRequestError, code = "WE_05", message = "Unable to process the webhook body")]
- WebhookUnprocessableEntity,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment Link does not exist in our records")]
- PaymentLinkNotFound,
- #[error(error_type = ErrorType::InvalidRequestError, code = "WE_05", message = "Merchant Secret set my merchant for webhook source verification is invalid")]
- WebhookInvalidMerchantSecret,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_19", message = "{message}")]
- CurrencyNotSupported { message: String },
- #[error(error_type = ErrorType::ServerNotAvailable, code= "HE_00", message = "{component} health check is failing with error: {message}")]
- HealthCheckError {
- component: &'static str,
- message: String,
- },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_24", message = "Merchant connector account is configured with invalid {config}")]
- InvalidConnectorConfiguration { config: String },
- #[error(error_type = ErrorType::ValidationError, code = "HE_01", message = "Failed to convert currency to minor unit")]
- CurrencyConversionFailed,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")]
- PaymentMethodDeleteFailed,
- #[error(
- error_type = ErrorType::InvalidRequestError, code = "IR_26",
- message = "Invalid Cookie"
- )]
- InvalidCookie,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_27", message = "Extended card info does not exist")]
- ExtendedCardInfoNotFound,
-}
-
-impl PTError for ApiErrorResponse {
- fn to_pt_error(&self) -> ProcessTrackerError {
- ProcessTrackerError::EApiErrorResponse
- }
-}
-
-#[derive(Clone)]
-pub enum NotImplementedMessage {
- Reason(String),
- Default,
-}
-
-impl std::fmt::Debug for NotImplementedMessage {
- fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- match self {
- Self::Reason(message) => write!(fmt, "{message} is not implemented"),
- Self::Default => {
- write!(
- fmt,
- "This API is under development and will be made available soon."
- )
- }
- }
- }
-}
-
-impl ::core::fmt::Display for ApiErrorResponse {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- r#"{{"error":{}}}"#,
- serde_json::to_string(self).unwrap_or_else(|_| "API error response".to_string())
- )
- }
-}
-
-impl actix_web::ResponseError for ApiErrorResponse {
- fn status_code(&self) -> StatusCode {
- common_utils::errors::ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(
- self,
- )
- .status_code()
- }
-
- fn error_response(&self) -> actix_web::HttpResponse {
- common_utils::errors::ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(
- self,
- )
- .error_response()
- }
-}
-
-impl crate::services::EmbedError for error_stack::Report<ApiErrorResponse> {}
diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rs
index 880c0d7b20..df529f8180 100644
--- a/crates/router/src/core/errors/transformers.rs
+++ b/crates/router/src/core/errors/transformers.rs
@@ -1,312 +1,7 @@
-use api_models::errors::types::Extra;
use common_utils::errors::ErrorSwitch;
-use http::StatusCode;
+use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
-use super::{ApiErrorResponse, ConnectorError, CustomersErrorResponse, StorageError};
-
-impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorResponse {
- fn switch(&self) -> api_models::errors::types::ApiErrorResponse {
- use api_models::errors::types::{ApiError, ApiErrorResponse as AER};
-
- match self {
- Self::NotImplemented { message } => {
- AER::NotImplemented(ApiError::new("IR", 0, format!("{message:?}"), None))
- }
- Self::Unauthorized => AER::Unauthorized(ApiError::new(
- "IR",
- 1,
- "API key not provided or invalid API key used", None
- )),
- Self::InvalidRequestUrl => {
- AER::NotFound(ApiError::new("IR", 2, "Unrecognized request URL", None))
- }
- Self::InvalidHttpMethod => AER::MethodNotAllowed(ApiError::new(
- "IR",
- 3,
- "The HTTP method is not applicable for this API", None
- )),
- Self::MissingRequiredField { field_name } => AER::BadRequest(
- ApiError::new("IR", 4, format!("Missing required param: {field_name}"), None),
- ),
- Self::InvalidDataFormat {
- field_name,
- expected_format,
- } => AER::Unprocessable(ApiError::new(
- "IR",
- 5,
- format!(
- "{field_name} contains invalid data. Expected format is {expected_format}"
- ), None
- )),
- Self::InvalidRequestData { message } => {
- AER::Unprocessable(ApiError::new("IR", 6, message.to_string(), None))
- }
- Self::InvalidDataValue { field_name } => AER::BadRequest(ApiError::new(
- "IR",
- 7,
- format!("Invalid value provided: {field_name}"), None
- )),
- Self::ClientSecretNotGiven => AER::BadRequest(ApiError::new(
- "IR",
- 8,
- "client_secret was not provided", None
- )),
- Self::ClientSecretInvalid => {
- AER::BadRequest(ApiError::new("IR", 9, "The client_secret provided does not match the client_secret associated with the Payment", None))
- }
- Self::CurrencyNotSupported { message } => {
- AER::BadRequest(ApiError::new("IR", 9, message, None))
- }
- Self::MandateActive => {
- AER::BadRequest(ApiError::new("IR", 10, "Customer has active mandate/subsciption", None))
- }
- Self::CustomerRedacted => {
- AER::BadRequest(ApiError::new("IR", 11, "Customer has already been redacted", None))
- }
- Self::MaximumRefundCount => AER::BadRequest(ApiError::new("IR", 12, "Reached maximum refund attempts", None)),
- Self::RefundAmountExceedsPaymentAmount => {
- AER::BadRequest(ApiError::new("IR", 13, "The refund amount exceeds the amount captured", None))
- }
- Self::PaymentUnexpectedState {
- current_flow,
- field_name,
- current_value,
- states,
- } => AER::BadRequest(ApiError::new("IR", 14, format!("This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}"), None)),
- Self::InvalidEphemeralKey => AER::Unauthorized(ApiError::new("IR", 15, "Invalid Ephemeral Key for the customer", None)),
- Self::PreconditionFailed { message } => {
- AER::BadRequest(ApiError::new("IR", 16, message.to_string(), None))
- }
- Self::InvalidJwtToken => AER::Unauthorized(ApiError::new("IR", 17, "Access forbidden, invalid JWT token was used", None)),
- Self::GenericUnauthorized { message } => {
- AER::Unauthorized(ApiError::new("IR", 18, message.to_string(), None))
- },
- Self::ClientSecretExpired => AER::BadRequest(ApiError::new(
- "IR",
- 19,
- "The provided client_secret has expired", None
- )),
- Self::MissingRequiredFields { field_names } => AER::BadRequest(
- ApiError::new("IR", 21, "Missing required params".to_string(), Some(Extra {data: Some(serde_json::json!(field_names)), ..Default::default() })),
- ),
- Self::AccessForbidden {resource} => {
- AER::ForbiddenCommonResource(ApiError::new("IR", 22, format!("Access forbidden. Not authorized to access this resource {resource}"), None))
- },
- Self::FileProviderNotSupported { message } => {
- AER::BadRequest(ApiError::new("IR", 23, message.to_string(), None))
- },
- Self::UnprocessableEntity {message} => AER::Unprocessable(ApiError::new("IR", 23, message.to_string(), None)),
- Self::InvalidWalletToken { wallet_name} => AER::Unprocessable(ApiError::new(
- "IR",
- 24,
- format!("Invalid {wallet_name} wallet token"), None
- )),
- Self::ExternalConnectorError {
- code,
- message,
- connector,
- reason,
- status_code,
- } => AER::ConnectorError(ApiError::new("CE", 0, format!("{code}: {message}"), Some(Extra {connector: Some(connector.clone()), reason: reason.to_owned().map(Into::into), ..Default::default()})), StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)),
- Self::PaymentAuthorizationFailed { data } => {
- AER::BadRequest(ApiError::new("CE", 1, "Payment failed during authorization with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()})))
- }
- Self::PaymentAuthenticationFailed { data } => {
- AER::BadRequest(ApiError::new("CE", 2, "Payment failed during authentication with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()})))
- }
- Self::PaymentCaptureFailed { data } => {
- AER::BadRequest(ApiError::new("CE", 3, "Capture attempt failed while processing with connector", Some(Extra { data: data.clone(), ..Default::default()})))
- }
- Self::DisputeFailed { data } => {
- AER::BadRequest(ApiError::new("CE", 1, "Dispute operation failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()})))
- }
- Self::InvalidCardData { data } => AER::BadRequest(ApiError::new("CE", 4, "The card data is invalid", Some(Extra { data: data.clone(), ..Default::default()}))),
- Self::CardExpired { data } => AER::BadRequest(ApiError::new("CE", 5, "The card has expired", Some(Extra { data: data.clone(), ..Default::default()}))),
- Self::RefundFailed { data } => AER::BadRequest(ApiError::new("CE", 6, "Refund failed while processing with connector. Retry refund", Some(Extra { data: data.clone(), ..Default::default()}))),
- Self::VerificationFailed { data } => {
- AER::BadRequest(ApiError::new("CE", 7, "Verification failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()})))
- },
- Self::MandateUpdateFailed | Self::MandateSerializationFailed | Self::MandateDeserializationFailed | Self::InternalServerError => {
- AER::InternalServerError(ApiError::new("HE", 0, "Something went wrong", None))
- },
- Self::HealthCheckError { message,component } => {
- AER::InternalServerError(ApiError::new("HE",0,format!("{} health check failed with error: {}",component,message),None))
- },
- Self::PayoutFailed { data } => {
- AER::BadRequest(ApiError::new("CE", 4, "Payout failed while processing with connector.", Some(Extra { data: data.clone(), ..Default::default()})))
- },
- Self::DuplicateRefundRequest => AER::BadRequest(ApiError::new("HE", 1, "Duplicate refund request. Refund already attempted with the refund ID", None)),
- Self::DuplicateMandate => AER::BadRequest(ApiError::new("HE", 1, "Duplicate mandate request. Mandate already attempted with the Mandate ID", None)),
- Self::DuplicateMerchantAccount => AER::BadRequest(ApiError::new("HE", 1, "The merchant account with the specified details already exists in our records", None)),
- Self::DuplicateMerchantConnectorAccount { profile_id, connector_label: connector_name } => {
- AER::BadRequest(ApiError::new("HE", 1, format!("The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_name}' already exists in our records"), None))
- }
- Self::DuplicatePaymentMethod => AER::BadRequest(ApiError::new("HE", 1, "The payment method with the specified details already exists in our records", None)),
- Self::DuplicatePayment { payment_id } => {
- AER::BadRequest(ApiError::new("HE", 1, "The payment with the specified payment_id already exists in our records", Some(Extra {reason: Some(format!("{payment_id} already exists")), ..Default::default()})))
- }
- 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::GenericDuplicateError { message } => {
- AER::BadRequest(ApiError::new("HE", 1, message, None))
- }
- Self::RefundNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Refund does not exist in our records.", None))
- }
- Self::CustomerNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Customer does not exist in our records", None))
- }
- Self::ConfigNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Config key does not exist in our records.", None))
- },
- Self::DuplicateConfig => {
- AER::BadRequest(ApiError::new("HE", 1, "The config with the specified key already exists in our records", None))
- }
- Self::PaymentNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Payment does not exist in our records", None))
- }
- Self::PaymentMethodNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Payment method does not exist in our records", None))
- }
- Self::MerchantAccountNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Merchant account does not exist in our records", None))
- }
- Self::MerchantConnectorAccountNotFound {id } => {
- AER::NotFound(ApiError::new("HE", 2, "Merchant connector account does not exist in our records", Some(Extra {reason: Some(format!("{id} does not exist")), ..Default::default()})))
- }
- Self::MerchantConnectorAccountDisabled => {
- AER::BadRequest(ApiError::new("HE", 3, "The selected merchant connector account is disabled", None))
- }
- Self::ResourceIdNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Resource ID does not exist in our records", None))
- }
- Self::MandateNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Mandate does not exist in our records", None))
- }
- Self::PayoutNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Payout does not exist in our records", None))
- }
- Self::EventNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Event does not exist in our records", None))
- }
- Self::ReturnUrlUnavailable => AER::NotFound(ApiError::new("HE", 3, "Return URL is not configured and not passed in payments request", None)),
- Self::RefundNotPossible { connector } => {
- AER::BadRequest(ApiError::new("HE", 3, format!("This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard"), None))
- }
- Self::MandateValidationFailed { reason } => {
- AER::BadRequest(ApiError::new("HE", 3, "Mandate Validation Failed", Some(Extra { reason: Some(reason.to_owned()), ..Default::default() })))
- }
- Self::PaymentNotSucceeded => AER::BadRequest(ApiError::new("HE", 3, "The payment has not succeeded yet. Please pass a successful payment to initiate refund", None)),
- Self::PaymentBlockedError {
- message,
- reason,
- ..
- } => AER::DomainError(ApiError::new("HE", 3, message, Some(Extra { reason: Some(reason.clone()), ..Default::default() }))),
- Self::SuccessfulPaymentNotFound => {
- AER::NotFound(ApiError::new("HE", 4, "Successful payment not found for the given payment id", None))
- }
- Self::IncorrectConnectorNameGiven => {
- AER::NotFound(ApiError::new("HE", 4, "The connector provided in the request is incorrect or not available", None))
- }
- Self::AddressNotFound => {
- AER::NotFound(ApiError::new("HE", 4, "Address does not exist in our records", None))
- },
- Self::GenericNotFoundError { message } => {
- AER::NotFound(ApiError::new("HE", 5, message, None))
- },
- Self::ApiKeyNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "API Key does not exist in our records", None))
- }
- Self::NotSupported { message } => {
- AER::BadRequest(ApiError::new("HE", 3, "Payment method type not supported", Some(Extra {reason: Some(message.to_owned()), ..Default::default()})))
- },
- Self::InvalidCardIin => AER::BadRequest(ApiError::new("HE", 3, "The provided card IIN does not exist", None)),
- Self::InvalidCardIinLength => AER::BadRequest(ApiError::new("HE", 3, "The provided card IIN length is invalid, please provide an IIN with 6 digits", None)),
- Self::FlowNotSupported { flow, connector } => {
- AER::BadRequest(ApiError::new("IR", 20, format!("{flow} flow not supported"), Some(Extra {connector: Some(connector.to_owned()), ..Default::default()}))) //FIXME: error message
- }
- Self::DisputeNotFound { .. } => {
- AER::NotFound(ApiError::new("HE", 2, "Dispute does not exist in our records", None))
- },
- Self::AuthenticationNotFound { .. } => {
- AER::NotFound(ApiError::new("HE", 2, "Authentication does not exist in our records", None))
- },
- Self::BusinessProfileNotFound { id } => {
- AER::NotFound(ApiError::new("HE", 2, format!("Business profile with the given id {id} does not exist"), None))
- }
- Self::FileNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "File does not exist in our records", None))
- }
- Self::PollNotFound { .. } => {
- AER::NotFound(ApiError::new("HE", 2, "Poll does not exist in our records", None))
- },
- Self::FileNotAvailable => {
- AER::NotFound(ApiError::new("HE", 2, "File not available", None))
- }
- Self::DisputeStatusValidationFailed { .. } => {
- AER::BadRequest(ApiError::new("HE", 2, "Dispute status validation failed", None))
- }
- Self::FileValidationFailed { reason } => {
- AER::BadRequest(ApiError::new("HE", 2, format!("File validation failed {reason}"), None))
- }
- Self::MissingFile => {
- AER::BadRequest(ApiError::new("HE", 2, "File not found in the request", None))
- }
- Self::MissingFilePurpose => {
- AER::BadRequest(ApiError::new("HE", 2, "File purpose not found in the request or is invalid", None))
- }
- Self::MissingFileContentType => {
- AER::BadRequest(ApiError::new("HE", 2, "File content type not found", None))
- }
- Self::MissingDisputeId => {
- AER::BadRequest(ApiError::new("HE", 2, "Dispute id not found in the request", None))
- }
- Self::WebhookAuthenticationFailed => {
- AER::Unauthorized(ApiError::new("WE", 1, "Webhook authentication failed", None))
- }
- Self::WebhookResourceNotFound => {
- AER::NotFound(ApiError::new("WE", 4, "Webhook resource was not found", None))
- }
- Self::WebhookBadRequest => {
- AER::BadRequest(ApiError::new("WE", 2, "Bad request body received", None))
- }
- Self::WebhookProcessingFailure => {
- AER::InternalServerError(ApiError::new("WE", 3, "There was an issue processing the webhook", None))
- },
- Self::WebhookInvalidMerchantSecret => {
- AER::BadRequest(ApiError::new("WE", 2, "Merchant Secret set for webhook source verificartion is invalid", None))
- }
- Self::IncorrectPaymentMethodConfiguration => {
- AER::BadRequest(ApiError::new("HE", 4, "No eligible connector was found for the current payment method configuration", None))
- }
- Self::WebhookUnprocessableEntity => {
- AER::Unprocessable(ApiError::new("WE", 5, "There was an issue processing the webhook body", None))
- },
- Self::ResourceBusy => {
- AER::Unprocessable(ApiError::new("WE", 5, "There was an issue processing the webhook body", None))
- }
- Self::PaymentLinkNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Payment Link does not exist in our records", None))
- }
- Self::InvalidConnectorConfiguration {config} => {
- AER::BadRequest(ApiError::new("IR", 24, format!("Merchant connector account is configured with invalid {config}"), None))
- }
- Self::CurrencyConversionFailed => {
- AER::Unprocessable(ApiError::new("HE", 2, "Failed to convert currency to minor unit", None))
- }
- Self::PaymentMethodDeleteFailed => {
- AER::BadRequest(ApiError::new("IR", 25, "Cannot delete the default payment method", None))
- }
- Self::InvalidCookie => {
- AER::BadRequest(ApiError::new("IR", 26, "Invalid Cookie", None))
- }
- Self::ExtendedCardInfoNotFound => {
- AER::NotFound(ApiError::new("IR", 27, "Extended card info does not exist", None))
- }
- }
- }
-}
+use super::{ConnectorError, CustomersErrorResponse, StorageError};
impl ErrorSwitch<ApiErrorResponse> for ConnectorError {
fn switch(&self) -> ApiErrorResponse {
diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs
index 678a351a4c..1e2f5a2c30 100644
--- a/crates/router/src/core/errors/utils.rs
+++ b/crates/router/src/core/errors/utils.rs
@@ -158,9 +158,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError>
}
errors::ConnectorError::NotImplemented(reason) => {
errors::ApiErrorResponse::NotImplemented {
- message: errors::api_error_response::NotImplementedMessage::Reason(
- reason.to_string(),
- ),
+ message: errors::NotImplementedMessage::Reason(reason.to_string()),
}
.into()
}
@@ -249,7 +247,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError>
}
errors::ConnectorError::NotImplemented(reason) => {
errors::ApiErrorResponse::NotImplemented {
- message: errors::api_error_response::NotImplementedMessage::Reason(
+ message: errors::NotImplementedMessage::Reason(
reason.to_string(),
),
}
@@ -476,9 +474,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError>
}
errors::ConnectorError::NotImplemented(reason) => {
errors::ApiErrorResponse::NotImplemented {
- message: errors::api_error_response::NotImplementedMessage::Reason(
- reason.to_string(),
- ),
+ message: errors::NotImplementedMessage::Reason(reason.to_string()),
}
}
_ => errors::ApiErrorResponse::InternalServerError,
diff --git a/crates/router/src/core/fraud_check/types.rs b/crates/router/src/core/fraud_check/types.rs
index d2a9b92045..bc30ad83b1 100644
--- a/crates/router/src/core/fraud_check/types.rs
+++ b/crates/router/src/core/fraud_check/types.rs
@@ -5,20 +5,20 @@ use api_models::{
refunds::RefundResponse,
};
use common_enums::FrmSuggestion;
-use common_utils::pii::{Email, SecretSerdeValue};
+use common_utils::pii::SecretSerdeValue;
use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
+pub use hyperswitch_domain_models::router_request_types::fraud_check::{
+ Address, Destination, FrmFulfillmentRequest, FulfillmentStatus, Fulfillments, Product,
+};
use masking::Serialize;
use serde::Deserialize;
use utoipa::ToSchema;
use super::operation::BoxedFraudCheckOperation;
-use crate::{
- pii::Secret,
- types::{
- domain::MerchantAccount,
- storage::{enums as storage_enums, fraud_check::FraudCheck},
- PaymentAddress,
- },
+use crate::types::{
+ domain::MerchantAccount,
+ storage::{enums as storage_enums, fraud_check::FraudCheck},
+ PaymentAddress,
};
#[derive(Clone, Default, Debug)]
@@ -106,98 +106,6 @@ pub struct FrmFulfillmentSignifydApiRequest {
pub fulfillments: Vec<Fulfillments>,
}
-#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]
-#[serde(deny_unknown_fields)]
-#[serde_with::skip_serializing_none]
-#[serde(rename_all = "snake_case")]
-pub struct FrmFulfillmentRequest {
- ///unique payment_id for the transaction
- #[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")]
- pub payment_id: String,
- ///unique order_id for the order_details in the transaction
- #[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")]
- pub order_id: String,
- ///denotes the status of the fulfillment... can be one of PARTIAL, COMPLETE, REPLACEMENT, CANCELED
- #[schema(value_type = Option<FulfillmentStatus>, example = "COMPLETE")]
- pub fulfillment_status: Option<FulfillmentStatus>,
- ///contains details of the fulfillment
- #[schema(value_type = Vec<Fulfillments>)]
- pub fulfillments: Vec<Fulfillments>,
- //name of the tracking Company
- #[schema(max_length = 255, example = "fedex")]
- pub tracking_company: Option<String>,
- //tracking ID of the product
- #[schema(example = r#"["track_8327446667", "track_8327446668"]"#)]
- pub tracking_numbers: Option<Vec<String>>,
- //tracking_url for tracking the product
- pub tracking_urls: Option<Vec<String>>,
- // The name of the Shipper.
- pub carrier: Option<String>,
- // Fulfillment method for the shipment.
- pub fulfillment_method: Option<String>,
- // Statuses to indicate shipment state.
- pub shipment_status: Option<String>,
- // The date and time items are ready to be shipped.
- pub shipped_at: Option<String>,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
-#[serde_with::skip_serializing_none]
-#[serde(rename_all = "snake_case")]
-pub struct Fulfillments {
- ///shipment_id of the shipped items
- #[schema(max_length = 255, example = "ship_101")]
- pub shipment_id: String,
- ///products sent in the shipment
- #[schema(value_type = Option<Vec<Product>>)]
- pub products: Option<Vec<Product>>,
- ///destination address of the shipment
- #[schema(value_type = Destination)]
- pub destination: Destination,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
-#[serde(untagged)]
-#[serde_with::skip_serializing_none]
-#[serde(rename_all = "snake_case")]
-pub enum FulfillmentStatus {
- PARTIAL,
- COMPLETE,
- REPLACEMENT,
- CANCELED,
-}
-
-#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
-#[serde_with::skip_serializing_none]
-#[serde(rename_all = "snake_case")]
-pub struct Product {
- pub item_name: String,
- pub item_quantity: i64,
- pub item_id: String,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
-#[serde_with::skip_serializing_none]
-#[serde(rename_all = "snake_case")]
-pub struct Destination {
- pub full_name: Secret<String>,
- pub organization: Option<String>,
- pub email: Option<Email>,
- pub address: Address,
-}
-
-#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
-#[serde_with::skip_serializing_none]
-#[serde(rename_all = "snake_case")]
-pub struct Address {
- pub street_address: Secret<String>,
- pub unit: Option<Secret<String>>,
- pub postal_code: Secret<String>,
- pub city: String,
- pub province_code: Secret<String>,
- pub country_code: common_enums::CountryAlpha2,
-}
-
#[derive(Debug, ToSchema, Clone, Serialize)]
pub struct FrmFulfillmentResponse {
///unique order_id for the transaction
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 9b2082cf31..a6befa5269 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -34,10 +34,11 @@ use error_stack::{report, ResultExt};
use events::EventInfo;
use futures::future::join_all;
use helpers::ApplePayData;
-use hyperswitch_domain_models::{
+pub use hyperswitch_domain_models::{
mandates::{CustomerAcceptance, MandateData},
payment_address::PaymentAddress,
router_data::RouterData,
+ router_request_types::CustomerDetails,
};
use masking::{ExposeInterface, Secret};
use redis_interface::errors::RedisError;
@@ -2488,15 +2489,6 @@ pub struct IncrementalAuthorizationDetails {
pub authorization_id: Option<String>,
}
-#[derive(Debug, Default, Clone)]
-pub struct CustomerDetails {
- pub customer_id: Option<String>,
- pub name: Option<Secret<String, masking::WithType>>,
- pub email: Option<pii::Email>,
- pub phone: Option<Secret<String, masking::WithType>>,
- pub phone_country_code: Option<String>,
-}
-
pub trait CustomerDetailsExt {
type Error;
fn get_name(&self) -> Result<Secret<String, masking::WithType>, Self::Error>;
diff --git a/crates/router/src/core/payments/flows/approve_flow.rs b/crates/router/src/core/payments/flows/approve_flow.rs
index 92f815f6b5..95ca0c3e31 100644
--- a/crates/router/src/core/payments/flows/approve_flow.rs
+++ b/crates/router/src/core/payments/flows/approve_flow.rs
@@ -3,7 +3,7 @@ use async_trait::async_trait;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
- errors::{api_error_response::NotImplementedMessage, ApiErrorResponse, RouterResult},
+ errors::{ApiErrorResponse, NotImplementedMessage, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
routes::AppState,
diff --git a/crates/router/src/core/payments/flows/reject_flow.rs b/crates/router/src/core/payments/flows/reject_flow.rs
index 726993aa7f..638efa054e 100644
--- a/crates/router/src/core/payments/flows/reject_flow.rs
+++ b/crates/router/src/core/payments/flows/reject_flow.rs
@@ -3,7 +3,7 @@ use async_trait::async_trait;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
- errors::{api_error_response::NotImplementedMessage, ApiErrorResponse, RouterResult},
+ errors::{ApiErrorResponse, NotImplementedMessage, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
routes::AppState,
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
index f74ec42075..7c6c6336fc 100644
--- a/crates/router/src/core/payments/retry.rs
+++ b/crates/router/src/core/payments/retry.rs
@@ -150,7 +150,7 @@ where
}
api_models::gsm::GsmDecision::Requeue => {
Err(report!(errors::ApiErrorResponse::NotImplemented {
- message: errors::api_error_response::NotImplementedMessage::Reason(
+ message: errors::NotImplementedMessage::Reason(
"Requeue not implemented".to_string(),
),
}))?
diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rs
index 71b7d84b9f..e3a1daf39a 100644
--- a/crates/router/src/core/payments/types.rs
+++ b/crates/router/src/core/payments/types.rs
@@ -1,8 +1,7 @@
use std::{collections::HashMap, num::TryFromIntError};
-use api_models::{payment_methods::SurchargeDetailsResponse, payments::RequestSurchargeDetails};
+use api_models::payment_methods::SurchargeDetailsResponse;
use common_utils::{
- consts,
errors::CustomResult,
ext_traits::{Encode, OptionExt},
types as common_types,
@@ -10,6 +9,7 @@ use common_utils::{
use diesel_models::business_profile::BusinessProfile;
use error_stack::ResultExt;
use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt;
+pub use hyperswitch_domain_models::router_request_types::{AuthenticationData, SurchargeDetails};
use redis_interface::errors::RedisError;
use router_env::{instrument, tracing};
@@ -186,40 +186,6 @@ impl MultipleCaptureData {
}
}
-#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct SurchargeDetails {
- /// original_amount
- pub original_amount: common_types::MinorUnit,
- /// surcharge value
- pub surcharge: common_types::Surcharge,
- /// tax on surcharge value
- pub tax_on_surcharge:
- Option<common_types::Percentage<{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH }>>,
- /// surcharge amount for this payment
- pub surcharge_amount: common_types::MinorUnit,
- /// tax on surcharge amount for this payment
- pub tax_on_surcharge_amount: common_types::MinorUnit,
- /// sum of original amount,
- pub final_amount: common_types::MinorUnit,
-}
-
-impl From<(&RequestSurchargeDetails, &PaymentAttempt)> for SurchargeDetails {
- fn from(
- (request_surcharge_details, payment_attempt): (&RequestSurchargeDetails, &PaymentAttempt),
- ) -> Self {
- let surcharge_amount = request_surcharge_details.surcharge_amount;
- let tax_on_surcharge_amount = request_surcharge_details.tax_amount.unwrap_or_default();
- Self {
- original_amount: payment_attempt.amount,
- surcharge: common_types::Surcharge::Fixed(request_surcharge_details.surcharge_amount), // need to check this
- tax_on_surcharge: None,
- surcharge_amount,
- tax_on_surcharge_amount,
- final_amount: payment_attempt.amount + surcharge_amount + tax_on_surcharge_amount,
- }
- }
-}
-
impl ForeignTryFrom<(&SurchargeDetails, &PaymentAttempt)> for SurchargeDetailsResponse {
type Error = TryFromIntError;
fn foreign_try_from(
@@ -250,20 +216,6 @@ impl ForeignTryFrom<(&SurchargeDetails, &PaymentAttempt)> for SurchargeDetailsRe
}
}
-impl SurchargeDetails {
- pub fn is_request_surcharge_matching(
- &self,
- request_surcharge_details: RequestSurchargeDetails,
- ) -> bool {
- request_surcharge_details.surcharge_amount == self.surcharge_amount
- && request_surcharge_details.tax_amount.unwrap_or_default()
- == self.tax_on_surcharge_amount
- }
- pub fn get_total_surcharge_amount(&self) -> common_types::MinorUnit {
- self.surcharge_amount + self.tax_on_surcharge_amount
- }
-}
-
#[derive(Eq, Hash, PartialEq, Clone, Debug, strum::Display)]
pub enum SurchargeKey {
Token(String),
@@ -387,14 +339,6 @@ impl SurchargeMetadata {
}
}
-#[derive(Debug, Clone)]
-pub struct AuthenticationData {
- pub eci: Option<String>,
- pub cavv: String,
- pub threeds_server_transaction_id: String,
- pub message_version: String,
-}
-
impl ForeignTryFrom<&storage::Authentication> for AuthenticationData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(authentication: &storage::Authentication) -> Result<Self, Self::Error> {
diff --git a/crates/router/src/core/payouts/retry.rs b/crates/router/src/core/payouts/retry.rs
index a7dcfa864a..7cb929db94 100644
--- a/crates/router/src/core/payouts/retry.rs
+++ b/crates/router/src/core/payouts/retry.rs
@@ -81,7 +81,7 @@ pub async fn do_gsm_multiple_connector_actions(
}
api_models::gsm::GsmDecision::Requeue => {
Err(report!(errors::ApiErrorResponse::NotImplemented {
- message: errors::api_error_response::NotImplementedMessage::Reason(
+ message: errors::NotImplementedMessage::Reason(
"Requeue not implemented".to_string(),
),
}))?
@@ -145,7 +145,7 @@ pub async fn do_gsm_single_connector_actions(
}
api_models::gsm::GsmDecision::Requeue => {
Err(report!(errors::ApiErrorResponse::NotImplemented {
- message: errors::api_error_response::NotImplementedMessage::Reason(
+ message: errors::NotImplementedMessage::Reason(
"Requeue not implemented".to_string(),
),
}))?
diff --git a/crates/router/src/core/verification.rs b/crates/router/src/core/verification.rs
index fe3d752497..802a4ec3c6 100644
--- a/crates/router/src/core/verification.rs
+++ b/crates/router/src/core/verification.rs
@@ -4,7 +4,7 @@ use common_utils::{errors::CustomResult, request::RequestContent};
use error_stack::ResultExt;
use masking::ExposeInterface;
-use crate::{core::errors::api_error_response, headers, logger, routes::AppState, services};
+use crate::{core::errors, headers, logger, routes::AppState, services};
const APPLEPAY_INTERNAL_MERCHANT_NAME: &str = "Applepay_merchant";
@@ -12,10 +12,8 @@ pub async fn verify_merchant_creds_for_applepay(
state: AppState,
body: verifications::ApplepayMerchantVerificationRequest,
merchant_id: String,
-) -> CustomResult<
- services::ApplicationResponse<ApplepayMerchantResponse>,
- api_error_response::ApiErrorResponse,
-> {
+) -> CustomResult<services::ApplicationResponse<ApplepayMerchantResponse>, errors::ApiErrorResponse>
+{
let applepay_merchant_configs = state.conf.applepay_merchant_configs.get_inner();
let applepay_internal_merchant_identifier = applepay_merchant_configs
@@ -55,7 +53,7 @@ pub async fn verify_merchant_creds_for_applepay(
utils::log_applepay_verification_response_if_error(&response);
let applepay_response =
- response.change_context(api_error_response::ApiErrorResponse::InternalServerError)?;
+ response.change_context(errors::ApiErrorResponse::InternalServerError)?;
// Error is already logged
match applepay_response {
@@ -67,7 +65,7 @@ pub async fn verify_merchant_creds_for_applepay(
body.domain_names.clone(),
)
.await
- .change_context(api_error_response::ApiErrorResponse::InternalServerError)?;
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
Ok(services::api::ApplicationResponse::Json(
ApplepayMerchantResponse {
status_message: "Applepay verification Completed".to_string(),
@@ -76,7 +74,7 @@ pub async fn verify_merchant_creds_for_applepay(
}
Err(error) => {
logger::error!(?error);
- Err(api_error_response::ApiErrorResponse::InvalidRequestData {
+ Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Applepay verification Failed".to_string(),
}
.into())
@@ -90,13 +88,13 @@ pub async fn get_verified_apple_domains_with_mid_mca_id(
merchant_connector_id: String,
) -> CustomResult<
services::ApplicationResponse<verifications::ApplepayVerifiedDomainsResponse>,
- api_error_response::ApiErrorResponse,
+ errors::ApiErrorResponse,
> {
let db = state.store.as_ref();
let key_store = db
.get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into())
.await
- .change_context(api_error_response::ApiErrorResponse::MerchantAccountNotFound)?;
+ .change_context(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let verified_domains = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
@@ -105,7 +103,7 @@ pub async fn get_verified_apple_domains_with_mid_mca_id(
&key_store,
)
.await
- .change_context(api_error_response::ApiErrorResponse::ResourceIdNotFound)?
+ .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?
.applepay_verified_domains
.unwrap_or_default();
diff --git a/crates/router/src/routes/fraud_check.rs b/crates/router/src/routes/fraud_check.rs
index f0b73015f3..70bd55b710 100644
--- a/crates/router/src/routes/fraud_check.rs
+++ b/crates/router/src/routes/fraud_check.rs
@@ -34,9 +34,3 @@ impl ApiEventMetric for FraudCheckResponseData {
Some(ApiEventsType::FraudCheck)
}
}
-
-impl ApiEventMetric for frm_core::types::FrmFulfillmentRequest {
- fn get_api_event_type(&self) -> Option<ApiEventsType> {
- Some(ApiEventsType::FraudCheck)
- }
-}
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 71c74099de..287f98cdb7 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -1328,6 +1328,11 @@ impl EmbedError for Report<api_models::errors::types::ApiErrorResponse> {
}
}
+impl EmbedError
+ for Report<hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse>
+{
+}
+
pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpResponse {
HttpResponse::Ok()
.content_type(mime::APPLICATION_JSON)
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 0afef76051..7f2f0764b5 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -22,10 +22,11 @@ pub use api_models::{enums::Connector, mandates};
#[cfg(feature = "payouts")]
pub use api_models::{enums::PayoutConnectors, payouts as payout_types};
use common_enums::MandateStatus;
-use common_utils::{pii, pii::Email};
-pub use common_utils::{request::RequestContent, types::MinorUnit};
-use error_stack::ResultExt;
+pub use common_utils::request::RequestContent;
+use common_utils::{pii, pii::Email, types::MinorUnit};
use hyperswitch_domain_models::mandates::{CustomerAcceptance, MandateData};
+#[cfg(feature = "payouts")]
+pub use hyperswitch_domain_models::router_request_types::PayoutsData;
pub use hyperswitch_domain_models::{
payment_address::PaymentAddress,
router_data::{
@@ -33,9 +34,13 @@ pub use hyperswitch_domain_models::{
ApplePayPredecryptData, ConnectorAuthType, ConnectorResponseData, ErrorResponse,
PaymentMethodBalance, PaymentMethodToken, RecurringMandatePaymentData, RouterData,
},
+ router_request_types::{
+ AcceptDisputeRequestData, AccessTokenRequestData, BrowserInformation,
+ DefendDisputeRequestData, RefundsData, ResponseId, RetrieveFileRequestData,
+ SubmitEvidenceRequestData, UploadFileRequestData, VerifyWebhookSourceRequestData,
+ },
};
use masking::Secret;
-use serde::Serialize;
use self::storage::enums as storage_enums;
pub use crate::core::payments::CustomerDetails;
@@ -51,7 +56,10 @@ use crate::{
payments::{types, PaymentData},
},
services,
- types::{transformers::ForeignFrom, types::AuthenticationData},
+ types::{
+ transformers::{ForeignFrom, ForeignTryFrom},
+ types::AuthenticationData,
+ },
};
pub type PaymentsAuthorizeRouterData =
RouterData<api::Authorize, PaymentsAuthorizeData, PaymentsResponseData>;
@@ -275,20 +283,6 @@ pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>;
pub type PayoutsResponseRouterData<F, R> =
ResponseRouterData<F, R, PayoutsData, PayoutsResponseData>;
-#[cfg(feature = "payouts")]
-#[derive(Debug, Clone)]
-pub struct PayoutsData {
- pub payout_id: String,
- pub amount: i64,
- pub connector_payout_id: Option<String>,
- pub destination_currency: storage_enums::Currency,
- pub source_currency: storage_enums::Currency,
- pub payout_type: storage_enums::PayoutType,
- pub entity_type: storage_enums::PayoutEntityType,
- pub customer_details: Option<CustomerDetails>,
- pub vendor_details: Option<api_models::payouts::PayoutVendorAccountDetails>,
-}
-
#[cfg(feature = "payouts")]
pub trait PayoutIndividualDetailsExt {
type Error;
@@ -534,13 +528,6 @@ pub struct SetupMandateRequestData {
pub metadata: Option<pii::SecretSerdeValue>,
}
-#[derive(Debug, Clone)]
-pub struct AccessTokenRequestData {
- pub app_id: Secret<String>,
- pub id: Option<Secret<String>>,
- // Add more keys if required
-}
-
pub trait Capturable {
fn get_captured_amount<F>(&self, _payment_data: &PaymentData<F>) -> Option<i64>
where
@@ -868,60 +855,6 @@ pub enum PreprocessingResponseId {
ConnectorTransactionId(String),
}
-#[derive(Debug, Clone, Default, Serialize)]
-pub enum ResponseId {
- ConnectorTransactionId(String),
- EncodedData(String),
- #[default]
- NoResponseId,
-}
-
-impl ResponseId {
- pub fn get_connector_transaction_id(
- &self,
- ) -> errors::CustomResult<String, errors::ValidationError> {
- match self {
- Self::ConnectorTransactionId(txn_id) => Ok(txn_id.to_string()),
- _ => Err(errors::ValidationError::IncorrectValueProvided {
- field_name: "connector_transaction_id",
- })
- .attach_printable("Expected connector transaction ID not found"),
- }
- }
-}
-
-#[derive(Debug, Clone)]
-pub struct RefundsData {
- pub refund_id: String,
- pub connector_transaction_id: String,
-
- pub connector_refund_id: Option<String>,
- pub currency: storage_enums::Currency,
- /// Amount for the payment against which this refund is issued
- pub payment_amount: i64,
- pub reason: Option<String>,
- pub webhook_url: Option<String>,
- /// Amount to be refunded
- pub refund_amount: i64,
- /// Arbitrary metadata required for refund
- pub connector_metadata: Option<serde_json::Value>,
- pub browser_info: Option<BrowserInformation>,
-}
-
-#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
-pub struct BrowserInformation {
- pub color_depth: Option<u8>,
- pub java_enabled: Option<bool>,
- pub java_script_enabled: Option<bool>,
- pub language: Option<String>,
- pub screen_height: Option<u32>,
- pub screen_width: Option<u32>,
- pub time_zone: Option<i32>,
- pub ip_address: Option<std::net::IpAddr>,
- pub accept_header: Option<String>,
- pub user_agent: Option<String>,
-}
-
#[derive(Debug, Clone)]
pub struct RefundsResponseData {
pub connector_refund_id: String,
@@ -935,13 +868,6 @@ pub enum Redirection {
NoRedirect,
}
-#[derive(Debug, Clone)]
-pub struct VerifyWebhookSourceRequestData {
- pub webhook_headers: actix_web::http::header::HeaderMap,
- pub webhook_body: Vec<u8>,
- pub merchant_secret: api_models::webhooks::ConnectorWebhookSecrets,
-}
-
#[derive(Debug, Clone)]
pub struct VerifyWebhookSourceResponseData {
pub verify_webhook_status: VerifyWebhookStatus,
@@ -953,98 +879,28 @@ pub enum VerifyWebhookStatus {
SourceNotVerified,
}
-#[derive(Default, Debug, Clone)]
-pub struct AcceptDisputeRequestData {
- pub dispute_id: String,
- pub connector_dispute_id: String,
-}
-
#[derive(Default, Clone, Debug)]
pub struct AcceptDisputeResponse {
pub dispute_status: api_models::enums::DisputeStatus,
pub connector_status: Option<String>,
}
-#[derive(Default, Debug, Clone)]
-pub struct SubmitEvidenceRequestData {
- pub dispute_id: String,
- pub connector_dispute_id: String,
- pub access_activity_log: Option<String>,
- pub billing_address: Option<String>,
- pub cancellation_policy: Option<Vec<u8>>,
- pub cancellation_policy_provider_file_id: Option<String>,
- pub cancellation_policy_disclosure: Option<String>,
- pub cancellation_rebuttal: Option<String>,
- pub customer_communication: Option<Vec<u8>>,
- pub customer_communication_provider_file_id: Option<String>,
- pub customer_email_address: Option<String>,
- pub customer_name: Option<String>,
- pub customer_purchase_ip: Option<String>,
- pub customer_signature: Option<Vec<u8>>,
- pub customer_signature_provider_file_id: Option<String>,
- pub product_description: Option<String>,
- pub receipt: Option<Vec<u8>>,
- pub receipt_provider_file_id: Option<String>,
- pub refund_policy: Option<Vec<u8>>,
- pub refund_policy_provider_file_id: Option<String>,
- pub refund_policy_disclosure: Option<String>,
- pub refund_refusal_explanation: Option<String>,
- pub service_date: Option<String>,
- pub service_documentation: Option<Vec<u8>>,
- pub service_documentation_provider_file_id: Option<String>,
- pub shipping_address: Option<String>,
- pub shipping_carrier: Option<String>,
- pub shipping_date: Option<String>,
- pub shipping_documentation: Option<Vec<u8>>,
- pub shipping_documentation_provider_file_id: Option<String>,
- pub shipping_tracking_number: Option<String>,
- pub invoice_showing_distinct_transactions: Option<Vec<u8>>,
- pub invoice_showing_distinct_transactions_provider_file_id: Option<String>,
- pub recurring_transaction_agreement: Option<Vec<u8>>,
- pub recurring_transaction_agreement_provider_file_id: Option<String>,
- pub uncategorized_file: Option<Vec<u8>>,
- pub uncategorized_file_provider_file_id: Option<String>,
- pub uncategorized_text: Option<String>,
-}
-
#[derive(Default, Clone, Debug)]
pub struct SubmitEvidenceResponse {
pub dispute_status: api_models::enums::DisputeStatus,
pub connector_status: Option<String>,
}
-#[derive(Default, Debug, Clone)]
-pub struct DefendDisputeRequestData {
- pub dispute_id: String,
- pub connector_dispute_id: String,
-}
-
#[derive(Default, Debug, Clone)]
pub struct DefendDisputeResponse {
pub dispute_status: api_models::enums::DisputeStatus,
pub connector_status: Option<String>,
}
-#[derive(Clone, Debug, serde::Serialize)]
-pub struct UploadFileRequestData {
- pub file_key: String,
- #[serde(skip)]
- pub file: Vec<u8>,
- #[serde(serialize_with = "crate::utils::custom_serde::display_serialize")]
- pub file_type: mime::Mime,
- pub file_size: i32,
-}
-
#[derive(Default, Clone, Debug)]
pub struct UploadFileResponse {
pub provider_file_id: String,
}
-
-#[derive(Clone, Debug)]
-pub struct RetrieveFileRequestData {
- pub provider_file_id: String,
-}
-
#[derive(Clone, Debug)]
pub struct RetrieveFileResponse {
pub file_data: Vec<u8>,
@@ -1210,9 +1066,9 @@ pub struct Response {
pub status_code: u16,
}
-impl TryFrom<ConnectorAuthType> for AccessTokenRequestData {
+impl ForeignTryFrom<ConnectorAuthType> for AccessTokenRequestData {
type Error = errors::ApiErrorResponse;
- fn try_from(connector_auth: ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn foreign_try_from(connector_auth: ConnectorAuthType) -> Result<Self, Self::Error> {
match connector_auth {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
app_id: api_key,
@@ -1238,22 +1094,6 @@ impl TryFrom<ConnectorAuthType> for AccessTokenRequestData {
}
}
-impl From<errors::ApiErrorResponse> for ErrorResponse {
- fn from(error: errors::ApiErrorResponse) -> Self {
- Self {
- code: error.error_code(),
- message: error.error_message(),
- reason: None,
- status_code: match error {
- errors::ApiErrorResponse::ExternalConnectorError { status_code, .. } => status_code,
- _ => 500,
- },
- attempt_status: None,
- connector_transaction_id: None,
- }
- }
-}
-
impl From<&&mut PaymentsAuthorizeRouterData> for AuthorizeSessionTokenData {
fn from(data: &&mut PaymentsAuthorizeRouterData) -> Self {
Self {
diff --git a/crates/router/src/types/api/authentication.rs b/crates/router/src/types/api/authentication.rs
index 0f86f46216..9837059dc0 100644
--- a/crates/router/src/types/api/authentication.rs
+++ b/crates/router/src/types/api/authentication.rs
@@ -3,6 +3,7 @@ use std::str::FromStr;
use api_models::enums;
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
+pub use hyperswitch_domain_models::router_request_types::authentication::MessageCategory;
use super::BoxedConnector;
use crate::core::errors;
@@ -66,12 +67,6 @@ pub struct PostAuthenticationResponse {
pub eci: Option<String>,
}
-#[derive(Clone, serde::Deserialize, Debug, serde::Serialize, PartialEq, Eq)]
-pub enum MessageCategory {
- Payment,
- NonPayment,
-}
-
#[derive(Clone, serde::Deserialize, Debug, serde::Serialize, PartialEq, Eq)]
pub struct ExternalAuthenticationPayload {
pub trans_status: common_enums::TransactionStatus,
diff --git a/crates/router/src/types/api/files.rs b/crates/router/src/types/api/files.rs
index 873516ee71..688962bd83 100644
--- a/crates/router/src/types/api/files.rs
+++ b/crates/router/src/types/api/files.rs
@@ -1,5 +1,6 @@
use api_models::enums::FileUploadProvider;
use masking::{Deserialize, Serialize};
+use serde_with::serde_as;
use super::ConnectorCommon;
use crate::{
@@ -47,12 +48,13 @@ impl ForeignTryFrom<&types::Connector> for FileUploadProvider {
}
}
+#[serde_as]
#[derive(Debug, Clone, serde::Serialize)]
pub struct CreateFileRequest {
pub file: Vec<u8>,
pub file_name: Option<String>,
pub file_size: i32,
- #[serde(serialize_with = "crate::utils::custom_serde::display_serialize")]
+ #[serde_as(as = "serde_with::DisplayFromStr")]
pub file_type: mime::Mime,
pub purpose: FilePurpose,
pub dispute_id: Option<String>,
diff --git a/crates/router/src/types/domain/payments.rs b/crates/router/src/types/domain/payments.rs
index 9dc85c103e..7b1f336549 100644
--- a/crates/router/src/types/domain/payments.rs
+++ b/crates/router/src/types/domain/payments.rs
@@ -1,837 +1,10 @@
-use common_utils::pii::{self, Email};
-use masking::Secret;
-use serde::{Deserialize, Serialize};
-
-// We need to derive Serialize and Deserialize because some parts of payment method data are being
-// stored in the database as serde_json::Value
-#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
-pub enum PaymentMethodData {
- Card(Card),
- CardRedirect(CardRedirectData),
- Wallet(WalletData),
- PayLater(PayLaterData),
- BankRedirect(BankRedirectData),
- BankDebit(BankDebitData),
- BankTransfer(Box<BankTransferData>),
- Crypto(CryptoData),
- MandatePayment,
- Reward,
- Upi(UpiData),
- Voucher(VoucherData),
- GiftCard(Box<GiftCardData>),
- CardToken(CardToken),
-}
-
-impl PaymentMethodData {
- pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> {
- match self {
- Self::Card(_) => Some(common_enums::PaymentMethod::Card),
- Self::CardRedirect(_) => Some(common_enums::PaymentMethod::CardRedirect),
- Self::Wallet(_) => Some(common_enums::PaymentMethod::Wallet),
- Self::PayLater(_) => Some(common_enums::PaymentMethod::PayLater),
- Self::BankRedirect(_) => Some(common_enums::PaymentMethod::BankRedirect),
- Self::BankDebit(_) => Some(common_enums::PaymentMethod::BankDebit),
- Self::BankTransfer(_) => Some(common_enums::PaymentMethod::BankTransfer),
- Self::Crypto(_) => Some(common_enums::PaymentMethod::Crypto),
- Self::Reward => Some(common_enums::PaymentMethod::Reward),
- Self::Upi(_) => Some(common_enums::PaymentMethod::Upi),
- Self::Voucher(_) => Some(common_enums::PaymentMethod::Voucher),
- Self::GiftCard(_) => Some(common_enums::PaymentMethod::GiftCard),
- Self::CardToken(_) | Self::MandatePayment => None,
- }
- }
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
-pub struct Card {
- pub card_number: cards::CardNumber,
- pub card_exp_month: Secret<String>,
- pub card_exp_year: Secret<String>,
- pub card_cvc: Secret<String>,
- pub card_issuer: Option<String>,
- pub card_network: Option<common_enums::CardNetwork>,
- pub card_type: Option<String>,
- pub card_issuing_country: Option<String>,
- pub bank_code: Option<String>,
- pub nick_name: Option<Secret<String>>,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
-pub enum CardRedirectData {
- Knet {},
- Benefit {},
- MomoAtm {},
- CardRedirect {},
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub enum PayLaterData {
- KlarnaRedirect {},
- KlarnaSdk { token: String },
- AffirmRedirect {},
- AfterpayClearpayRedirect {},
- PayBrightRedirect {},
- WalleyRedirect {},
- AlmaRedirect {},
- AtomeRedirect {},
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-
-pub enum WalletData {
- AliPayQr(Box<AliPayQr>),
- AliPayRedirect(AliPayRedirection),
- AliPayHkRedirect(AliPayHkRedirection),
- MomoRedirect(MomoRedirection),
- KakaoPayRedirect(KakaoPayRedirection),
- GoPayRedirect(GoPayRedirection),
- GcashRedirect(GcashRedirection),
- ApplePay(ApplePayWalletData),
- ApplePayRedirect(Box<ApplePayRedirectData>),
- ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>),
- DanaRedirect {},
- GooglePay(GooglePayWalletData),
- GooglePayRedirect(Box<GooglePayRedirectData>),
- GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>),
- MbWayRedirect(Box<MbWayRedirection>),
- MobilePayRedirect(Box<MobilePayRedirection>),
- PaypalRedirect(PaypalRedirection),
- PaypalSdk(PayPalWalletData),
- SamsungPay(Box<SamsungPayWalletData>),
- TwintRedirect {},
- VippsRedirect {},
- TouchNGoRedirect(Box<TouchNGoRedirection>),
- WeChatPayRedirect(Box<WeChatPayRedirection>),
- WeChatPayQr(Box<WeChatPayQr>),
- CashappQr(Box<CashappQr>),
- SwishQr(SwishQrData),
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-
-pub struct SamsungPayWalletData {
- /// The encrypted payment token from Samsung
- pub token: Secret<String>,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-
-pub struct GooglePayWalletData {
- /// The type of payment method
- pub pm_type: String,
- /// User-facing message to describe the payment method that funds this transaction.
- pub description: String,
- /// The information of the payment method
- pub info: GooglePayPaymentMethodInfo,
- /// The tokenization data of Google pay
- pub tokenization_data: GpayTokenizationData,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct ApplePayRedirectData {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct GooglePayRedirectData {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct GooglePayThirdPartySdkData {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct ApplePayThirdPartySdkData {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct WeChatPayRedirection {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct WeChatPay {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct WeChatPayQr {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct CashappQr {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct PaypalRedirection {
- /// paypal's email address
- pub email: Option<Email>,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct AliPayQr {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct AliPayRedirection {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct AliPayHkRedirection {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct MomoRedirection {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct KakaoPayRedirection {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct GoPayRedirection {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct GcashRedirection {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct MobilePayRedirection {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct MbWayRedirection {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-
-pub struct GooglePayPaymentMethodInfo {
- /// The name of the card network
- pub card_network: String,
- /// The details of the card
- pub card_details: String,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct PayPalWalletData {
- /// Token generated for the Apple pay
- pub token: String,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct TouchNGoRedirection {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct SwishQrData {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct GpayTokenizationData {
- /// The type of the token
- pub token_type: String,
- /// Token generated for the wallet
- pub token: String,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct ApplePayWalletData {
- /// The payment data of Apple pay
- pub payment_data: String,
- /// The payment method of Apple pay
- pub payment_method: ApplepayPaymentMethod,
- /// The unique identifier for the transaction
- pub transaction_identifier: String,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct ApplepayPaymentMethod {
- pub display_name: String,
- pub network: String,
- pub pm_type: String,
-}
-
-#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
-
-pub enum BankRedirectData {
- BancontactCard {
- card_number: Option<cards::CardNumber>,
- card_exp_month: Option<Secret<String>>,
- card_exp_year: Option<Secret<String>>,
- },
- Bizum {},
- Blik {
- blik_code: Option<String>,
- },
- Eps {
- bank_name: Option<common_enums::BankNames>,
- },
- Giropay {
- bank_account_bic: Option<Secret<String>>,
- bank_account_iban: Option<Secret<String>>,
- },
- Ideal {
- bank_name: Option<common_enums::BankNames>,
- },
- Interac {},
- OnlineBankingCzechRepublic {
- issuer: common_enums::BankNames,
- },
- OnlineBankingFinland {},
- OnlineBankingPoland {
- issuer: common_enums::BankNames,
- },
- OnlineBankingSlovakia {
- issuer: common_enums::BankNames,
- },
- OpenBankingUk {
- issuer: Option<common_enums::BankNames>,
- },
- Przelewy24 {
- bank_name: Option<common_enums::BankNames>,
- },
- Sofort {
- preferred_language: Option<String>,
- },
- Trustly {},
- OnlineBankingFpx {
- issuer: common_enums::BankNames,
- },
- OnlineBankingThailand {
- issuer: common_enums::BankNames,
- },
-}
-
-#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
-#[serde(rename_all = "snake_case")]
-pub struct CryptoData {
- pub pay_currency: Option<String>,
-}
-
-#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
-#[serde(rename_all = "snake_case")]
-pub struct UpiData {
- pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>,
-}
-
-#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum VoucherData {
- Boleto(Box<BoletoVoucherData>),
- Efecty,
- PagoEfectivo,
- RedCompra,
- RedPagos,
- Alfamart(Box<AlfamartVoucherData>),
- Indomaret(Box<IndomaretVoucherData>),
- Oxxo,
- SevenEleven(Box<JCSVoucherData>),
- Lawson(Box<JCSVoucherData>),
- MiniStop(Box<JCSVoucherData>),
- FamilyMart(Box<JCSVoucherData>),
- Seicomart(Box<JCSVoucherData>),
- PayEasy(Box<JCSVoucherData>),
-}
-
-#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
-pub struct BoletoVoucherData {
- /// The shopper's social security number
- pub social_security_number: Option<Secret<String>>,
-}
-
-#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
-pub struct AlfamartVoucherData {}
-
-#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
-pub struct IndomaretVoucherData {}
-
-#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
-pub struct JCSVoucherData {}
-
-#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
-#[serde(rename_all = "snake_case")]
-pub enum GiftCardData {
- Givex(GiftCardDetails),
- PaySafeCard {},
-}
-
-#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
-#[serde(rename_all = "snake_case")]
-pub struct GiftCardDetails {
- /// The gift card number
- pub number: Secret<String>,
- /// The card verification code.
- pub cvc: Secret<String>,
-}
-
-#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, Default)]
-#[serde(rename_all = "snake_case")]
-pub struct CardToken {
- /// The card holder's name
- pub card_holder_name: Option<Secret<String>>,
-
- /// The CVC number for the card
- pub card_cvc: Option<Secret<String>>,
-}
-
-#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
-#[serde(rename_all = "snake_case")]
-pub enum BankDebitData {
- AchBankDebit {
- account_number: Secret<String>,
- routing_number: Secret<String>,
- bank_name: Option<common_enums::BankNames>,
- bank_type: Option<common_enums::BankType>,
- bank_holder_type: Option<common_enums::BankHolderType>,
- },
- SepaBankDebit {
- iban: Secret<String>,
- },
- BecsBankDebit {
- account_number: Secret<String>,
- bsb_number: Secret<String>,
- },
- BacsBankDebit {
- account_number: Secret<String>,
- sort_code: Secret<String>,
- },
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-#[serde(rename_all = "snake_case")]
-pub enum BankTransferData {
- AchBankTransfer {},
- SepaBankTransfer {},
- BacsBankTransfer {},
- MultibancoBankTransfer {},
- PermataBankTransfer {},
- BcaBankTransfer {},
- BniVaBankTransfer {},
- BriVaBankTransfer {},
- CimbVaBankTransfer {},
- DanamonVaBankTransfer {},
- MandiriVaBankTransfer {},
- Pix {},
- Pse {},
- LocalBankTransfer { bank_code: Option<String> },
-}
-
-#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
-pub struct SepaAndBacsBillingDetails {
- /// The Email ID for SEPA and BACS billing
- pub email: Email,
- /// The billing name for SEPA and BACS billing
- pub name: Secret<String>,
-}
-
-impl From<api_models::payments::PaymentMethodData> for PaymentMethodData {
- fn from(api_model_payment_method_data: api_models::payments::PaymentMethodData) -> Self {
- match api_model_payment_method_data {
- api_models::payments::PaymentMethodData::Card(card_data) => {
- Self::Card(Card::from(card_data))
- }
- api_models::payments::PaymentMethodData::CardRedirect(card_redirect) => {
- Self::CardRedirect(From::from(card_redirect))
- }
- api_models::payments::PaymentMethodData::Wallet(wallet_data) => {
- Self::Wallet(From::from(wallet_data))
- }
- api_models::payments::PaymentMethodData::PayLater(pay_later_data) => {
- Self::PayLater(From::from(pay_later_data))
- }
- api_models::payments::PaymentMethodData::BankRedirect(bank_redirect_data) => {
- Self::BankRedirect(From::from(bank_redirect_data))
- }
- api_models::payments::PaymentMethodData::BankDebit(bank_debit_data) => {
- Self::BankDebit(From::from(bank_debit_data))
- }
- api_models::payments::PaymentMethodData::BankTransfer(bank_transfer_data) => {
- Self::BankTransfer(Box::new(From::from(*bank_transfer_data)))
- }
- api_models::payments::PaymentMethodData::Crypto(crypto_data) => {
- Self::Crypto(From::from(crypto_data))
- }
- api_models::payments::PaymentMethodData::MandatePayment => Self::MandatePayment,
- api_models::payments::PaymentMethodData::Reward => Self::Reward,
- api_models::payments::PaymentMethodData::Upi(upi_data) => {
- Self::Upi(From::from(upi_data))
- }
- api_models::payments::PaymentMethodData::Voucher(voucher_data) => {
- Self::Voucher(From::from(voucher_data))
- }
- api_models::payments::PaymentMethodData::GiftCard(gift_card) => {
- Self::GiftCard(Box::new(From::from(*gift_card)))
- }
- api_models::payments::PaymentMethodData::CardToken(card_token) => {
- Self::CardToken(From::from(card_token))
- }
- }
- }
-}
-
-impl From<api_models::payments::Card> for Card {
- fn from(value: api_models::payments::Card) -> Self {
- let api_models::payments::Card {
- card_number,
- card_exp_month,
- card_exp_year,
- card_holder_name: _,
- card_cvc,
- card_issuer,
- card_network,
- card_type,
- card_issuing_country,
- bank_code,
- nick_name,
- } = value;
-
- Self {
- card_number,
- card_exp_month,
- card_exp_year,
- card_cvc,
- card_issuer,
- card_network,
- card_type,
- card_issuing_country,
- bank_code,
- nick_name,
- }
- }
-}
-
-impl From<api_models::payments::CardRedirectData> for CardRedirectData {
- fn from(value: api_models::payments::CardRedirectData) -> Self {
- match value {
- api_models::payments::CardRedirectData::Knet {} => Self::Knet {},
- api_models::payments::CardRedirectData::Benefit {} => Self::Benefit {},
- api_models::payments::CardRedirectData::MomoAtm {} => Self::MomoAtm {},
- api_models::payments::CardRedirectData::CardRedirect {} => Self::CardRedirect {},
- }
- }
-}
-
-impl From<api_models::payments::WalletData> for WalletData {
- fn from(value: api_models::payments::WalletData) -> Self {
- match value {
- api_models::payments::WalletData::AliPayQr(_) => Self::AliPayQr(Box::new(AliPayQr {})),
- api_models::payments::WalletData::AliPayRedirect(_) => {
- Self::AliPayRedirect(AliPayRedirection {})
- }
- api_models::payments::WalletData::AliPayHkRedirect(_) => {
- Self::AliPayHkRedirect(AliPayHkRedirection {})
- }
- api_models::payments::WalletData::MomoRedirect(_) => {
- Self::MomoRedirect(MomoRedirection {})
- }
- api_models::payments::WalletData::KakaoPayRedirect(_) => {
- Self::KakaoPayRedirect(KakaoPayRedirection {})
- }
- api_models::payments::WalletData::GoPayRedirect(_) => {
- Self::GoPayRedirect(GoPayRedirection {})
- }
- api_models::payments::WalletData::GcashRedirect(_) => {
- Self::GcashRedirect(GcashRedirection {})
- }
- api_models::payments::WalletData::ApplePay(apple_pay_data) => {
- Self::ApplePay(ApplePayWalletData::from(apple_pay_data))
- }
- api_models::payments::WalletData::ApplePayRedirect(_) => {
- Self::ApplePayRedirect(Box::new(ApplePayRedirectData {}))
- }
- api_models::payments::WalletData::ApplePayThirdPartySdk(_) => {
- Self::ApplePayThirdPartySdk(Box::new(ApplePayThirdPartySdkData {}))
- }
- api_models::payments::WalletData::DanaRedirect {} => Self::DanaRedirect {},
- api_models::payments::WalletData::GooglePay(google_pay_data) => {
- Self::GooglePay(GooglePayWalletData::from(google_pay_data))
- }
- api_models::payments::WalletData::GooglePayRedirect(_) => {
- Self::GooglePayRedirect(Box::new(GooglePayRedirectData {}))
- }
- api_models::payments::WalletData::GooglePayThirdPartySdk(_) => {
- Self::GooglePayThirdPartySdk(Box::new(GooglePayThirdPartySdkData {}))
- }
- api_models::payments::WalletData::MbWayRedirect(..) => {
- Self::MbWayRedirect(Box::new(MbWayRedirection {}))
- }
- api_models::payments::WalletData::MobilePayRedirect(_) => {
- Self::MobilePayRedirect(Box::new(MobilePayRedirection {}))
- }
- api_models::payments::WalletData::PaypalRedirect(paypal_redirect_data) => {
- Self::PaypalRedirect(PaypalRedirection {
- email: paypal_redirect_data.email,
- })
- }
- api_models::payments::WalletData::PaypalSdk(paypal_sdk_data) => {
- Self::PaypalSdk(PayPalWalletData {
- token: paypal_sdk_data.token,
- })
- }
- api_models::payments::WalletData::SamsungPay(samsung_pay_data) => {
- Self::SamsungPay(Box::new(SamsungPayWalletData {
- token: samsung_pay_data.token,
- }))
- }
- api_models::payments::WalletData::TwintRedirect {} => Self::TwintRedirect {},
- api_models::payments::WalletData::VippsRedirect {} => Self::VippsRedirect {},
- api_models::payments::WalletData::TouchNGoRedirect(_) => {
- Self::TouchNGoRedirect(Box::new(TouchNGoRedirection {}))
- }
- api_models::payments::WalletData::WeChatPayRedirect(_) => {
- Self::WeChatPayRedirect(Box::new(WeChatPayRedirection {}))
- }
- api_models::payments::WalletData::WeChatPayQr(_) => {
- Self::WeChatPayQr(Box::new(WeChatPayQr {}))
- }
- api_models::payments::WalletData::CashappQr(_) => {
- Self::CashappQr(Box::new(CashappQr {}))
- }
- api_models::payments::WalletData::SwishQr(_) => Self::SwishQr(SwishQrData {}),
- }
- }
-}
-
-impl From<api_models::payments::GooglePayWalletData> for GooglePayWalletData {
- fn from(value: api_models::payments::GooglePayWalletData) -> Self {
- Self {
- pm_type: value.pm_type,
- description: value.description,
- info: GooglePayPaymentMethodInfo {
- card_network: value.info.card_network,
- card_details: value.info.card_details,
- },
- tokenization_data: GpayTokenizationData {
- token_type: value.tokenization_data.token_type,
- token: value.tokenization_data.token,
- },
- }
- }
-}
-
-impl From<api_models::payments::ApplePayWalletData> for ApplePayWalletData {
- fn from(value: api_models::payments::ApplePayWalletData) -> Self {
- Self {
- payment_data: value.payment_data,
- payment_method: ApplepayPaymentMethod {
- display_name: value.payment_method.display_name,
- network: value.payment_method.network,
- pm_type: value.payment_method.pm_type,
- },
- transaction_identifier: value.transaction_identifier,
- }
- }
-}
-
-impl From<api_models::payments::PayLaterData> for PayLaterData {
- fn from(value: api_models::payments::PayLaterData) -> Self {
- match value {
- api_models::payments::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect {},
- api_models::payments::PayLaterData::KlarnaSdk { token } => Self::KlarnaSdk { token },
- api_models::payments::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect {},
- api_models::payments::PayLaterData::AfterpayClearpayRedirect { .. } => {
- Self::AfterpayClearpayRedirect {}
- }
- api_models::payments::PayLaterData::PayBrightRedirect {} => Self::PayBrightRedirect {},
- api_models::payments::PayLaterData::WalleyRedirect {} => Self::WalleyRedirect {},
- api_models::payments::PayLaterData::AlmaRedirect {} => Self::AlmaRedirect {},
- api_models::payments::PayLaterData::AtomeRedirect {} => Self::AtomeRedirect {},
- }
- }
-}
-
-impl From<api_models::payments::BankRedirectData> for BankRedirectData {
- fn from(value: api_models::payments::BankRedirectData) -> Self {
- match value {
- api_models::payments::BankRedirectData::BancontactCard {
- card_number,
- card_exp_month,
- card_exp_year,
- ..
- } => Self::BancontactCard {
- card_number,
- card_exp_month,
- card_exp_year,
- },
- api_models::payments::BankRedirectData::Bizum {} => Self::Bizum {},
- api_models::payments::BankRedirectData::Blik { blik_code } => Self::Blik { blik_code },
- api_models::payments::BankRedirectData::Eps { bank_name, .. } => {
- Self::Eps { bank_name }
- }
- api_models::payments::BankRedirectData::Giropay {
- bank_account_bic,
- bank_account_iban,
- ..
- } => Self::Giropay {
- bank_account_bic,
- bank_account_iban,
- },
- api_models::payments::BankRedirectData::Ideal { bank_name, .. } => {
- Self::Ideal { bank_name }
- }
- api_models::payments::BankRedirectData::Interac { .. } => Self::Interac {},
- api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { issuer } => {
- Self::OnlineBankingCzechRepublic { issuer }
- }
- api_models::payments::BankRedirectData::OnlineBankingFinland { .. } => {
- Self::OnlineBankingFinland {}
- }
- api_models::payments::BankRedirectData::OnlineBankingPoland { issuer } => {
- Self::OnlineBankingPoland { issuer }
- }
- api_models::payments::BankRedirectData::OnlineBankingSlovakia { issuer } => {
- Self::OnlineBankingSlovakia { issuer }
- }
- api_models::payments::BankRedirectData::OpenBankingUk { issuer, .. } => {
- Self::OpenBankingUk { issuer }
- }
- api_models::payments::BankRedirectData::Przelewy24 { bank_name, .. } => {
- Self::Przelewy24 { bank_name }
- }
- api_models::payments::BankRedirectData::Sofort {
- preferred_language, ..
- } => Self::Sofort { preferred_language },
- api_models::payments::BankRedirectData::Trustly { .. } => Self::Trustly {},
- api_models::payments::BankRedirectData::OnlineBankingFpx { issuer } => {
- Self::OnlineBankingFpx { issuer }
- }
- api_models::payments::BankRedirectData::OnlineBankingThailand { issuer } => {
- Self::OnlineBankingThailand { issuer }
- }
- }
- }
-}
-
-impl From<api_models::payments::CryptoData> for CryptoData {
- fn from(value: api_models::payments::CryptoData) -> Self {
- let api_models::payments::CryptoData { pay_currency } = value;
- Self { pay_currency }
- }
-}
-
-impl From<api_models::payments::UpiData> for UpiData {
- fn from(value: api_models::payments::UpiData) -> Self {
- let api_models::payments::UpiData { vpa_id } = value;
- Self { vpa_id }
- }
-}
-
-impl From<api_models::payments::VoucherData> for VoucherData {
- fn from(value: api_models::payments::VoucherData) -> Self {
- match value {
- api_models::payments::VoucherData::Boleto(boleto_data) => {
- Self::Boleto(Box::new(BoletoVoucherData {
- social_security_number: boleto_data.social_security_number,
- }))
- }
- api_models::payments::VoucherData::Alfamart(_) => {
- Self::Alfamart(Box::new(AlfamartVoucherData {}))
- }
- api_models::payments::VoucherData::Indomaret(_) => {
- Self::Indomaret(Box::new(IndomaretVoucherData {}))
- }
- api_models::payments::VoucherData::SevenEleven(_)
- | api_models::payments::VoucherData::Lawson(_)
- | api_models::payments::VoucherData::MiniStop(_)
- | api_models::payments::VoucherData::FamilyMart(_)
- | api_models::payments::VoucherData::Seicomart(_)
- | api_models::payments::VoucherData::PayEasy(_) => {
- Self::SevenEleven(Box::new(JCSVoucherData {}))
- }
- api_models::payments::VoucherData::Efecty => Self::Efecty,
- api_models::payments::VoucherData::PagoEfectivo => Self::PagoEfectivo,
- api_models::payments::VoucherData::RedCompra => Self::RedCompra,
- api_models::payments::VoucherData::RedPagos => Self::RedPagos,
- api_models::payments::VoucherData::Oxxo => Self::Oxxo,
- }
- }
-}
-
-impl From<api_models::payments::GiftCardData> for GiftCardData {
- fn from(value: api_models::payments::GiftCardData) -> Self {
- match value {
- api_models::payments::GiftCardData::Givex(details) => Self::Givex(GiftCardDetails {
- number: details.number,
- cvc: details.cvc,
- }),
- api_models::payments::GiftCardData::PaySafeCard {} => Self::PaySafeCard {},
- }
- }
-}
-
-impl From<api_models::payments::CardToken> for CardToken {
- fn from(value: api_models::payments::CardToken) -> Self {
- let api_models::payments::CardToken {
- card_holder_name,
- card_cvc,
- } = value;
- Self {
- card_holder_name,
- card_cvc,
- }
- }
-}
-
-impl From<api_models::payments::BankDebitData> for BankDebitData {
- fn from(value: api_models::payments::BankDebitData) -> Self {
- match value {
- api_models::payments::BankDebitData::AchBankDebit {
- account_number,
- routing_number,
- bank_name,
- bank_type,
- bank_holder_type,
- ..
- } => Self::AchBankDebit {
- account_number,
- routing_number,
- bank_name,
- bank_type,
- bank_holder_type,
- },
- api_models::payments::BankDebitData::SepaBankDebit { iban, .. } => {
- Self::SepaBankDebit { iban }
- }
- api_models::payments::BankDebitData::BecsBankDebit {
- account_number,
- bsb_number,
- ..
- } => Self::BecsBankDebit {
- account_number,
- bsb_number,
- },
- api_models::payments::BankDebitData::BacsBankDebit {
- account_number,
- sort_code,
- ..
- } => Self::BacsBankDebit {
- account_number,
- sort_code,
- },
- }
- }
-}
-
-impl From<api_models::payments::BankTransferData> for BankTransferData {
- fn from(value: api_models::payments::BankTransferData) -> Self {
- match value {
- api_models::payments::BankTransferData::AchBankTransfer { .. } => {
- Self::AchBankTransfer {}
- }
- api_models::payments::BankTransferData::SepaBankTransfer { .. } => {
- Self::SepaBankTransfer {}
- }
- api_models::payments::BankTransferData::BacsBankTransfer { .. } => {
- Self::BacsBankTransfer {}
- }
- api_models::payments::BankTransferData::MultibancoBankTransfer { .. } => {
- Self::MultibancoBankTransfer {}
- }
- api_models::payments::BankTransferData::PermataBankTransfer { .. } => {
- Self::PermataBankTransfer {}
- }
- api_models::payments::BankTransferData::BcaBankTransfer { .. } => {
- Self::BcaBankTransfer {}
- }
- api_models::payments::BankTransferData::BniVaBankTransfer { .. } => {
- Self::BniVaBankTransfer {}
- }
- api_models::payments::BankTransferData::BriVaBankTransfer { .. } => {
- Self::BriVaBankTransfer {}
- }
- api_models::payments::BankTransferData::CimbVaBankTransfer { .. } => {
- Self::CimbVaBankTransfer {}
- }
- api_models::payments::BankTransferData::DanamonVaBankTransfer { .. } => {
- Self::DanamonVaBankTransfer {}
- }
- api_models::payments::BankTransferData::MandiriVaBankTransfer { .. } => {
- Self::MandiriVaBankTransfer {}
- }
- api_models::payments::BankTransferData::Pix {} => Self::Pix {},
- api_models::payments::BankTransferData::Pse {} => Self::Pse {},
- api_models::payments::BankTransferData::LocalBankTransfer { bank_code } => {
- Self::LocalBankTransfer { bank_code }
- }
- }
- }
-}
+pub use hyperswitch_domain_models::payment_method_data::{
+ AliPayQr, ApplePayThirdPartySdkData, ApplePayWalletData, ApplepayPaymentMethod, BankDebitData,
+ BankRedirectData, BankTransferData, BoletoVoucherData, Card, CardRedirectData, CardToken,
+ CashappQr, CryptoData, GcashRedirection, GiftCardData, GiftCardDetails, GoPayRedirection,
+ GooglePayPaymentMethodInfo, GooglePayRedirectData, GooglePayThirdPartySdkData,
+ GooglePayWalletData, GpayTokenizationData, IndomaretVoucherData, KakaoPayRedirection,
+ MbWayRedirection, PayLaterData, PaymentMethodData, SamsungPayWalletData,
+ SepaAndBacsBillingDetails, SwishQrData, TouchNGoRedirection, VoucherData, WalletData,
+ WeChatPayQr,
+};
diff --git a/crates/router/src/types/fraud_check.rs b/crates/router/src/types/fraud_check.rs
index 12ab7e4a06..59be546b1c 100644
--- a/crates/router/src/types/fraud_check.rs
+++ b/crates/router/src/types/fraud_check.rs
@@ -1,11 +1,12 @@
-use common_utils::pii::Email;
+pub use hyperswitch_domain_models::router_request_types::fraud_check::{
+ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData,
+ FraudCheckSaleData, FraudCheckTransactionData, RefundMethod,
+};
use crate::{
- connector::signifyd::transformers::RefundMethod,
- core::fraud_check::types::FrmFulfillmentRequest,
pii::Serialize,
services,
- types::{self, api, storage_enums, ErrorResponse, ResponseId, RouterData},
+ types::{api, storage_enums, ErrorResponse, ResponseId, RouterData},
};
pub type FrmSaleRouterData = RouterData<api::Sale, FraudCheckSaleData, FraudCheckResponseData>;
@@ -13,13 +14,6 @@ pub type FrmSaleRouterData = RouterData<api::Sale, FraudCheckSaleData, FraudChec
pub type FrmSaleType =
dyn services::ConnectorIntegration<api::Sale, FraudCheckSaleData, FraudCheckResponseData>;
-#[derive(Debug, Clone)]
-pub struct FraudCheckSaleData {
- pub amount: i64,
- pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
- pub currency: Option<common_enums::Currency>,
- pub email: Option<Email>,
-}
#[derive(Debug, Clone)]
pub struct FrmRouterData {
pub merchant_id: String,
@@ -76,17 +70,6 @@ pub type FrmCheckoutType = dyn services::ConnectorIntegration<
FraudCheckResponseData,
>;
-#[derive(Debug, Clone)]
-pub struct FraudCheckCheckoutData {
- pub amount: i64,
- pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
- pub currency: Option<common_enums::Currency>,
- pub browser_info: Option<types::BrowserInformation>,
- pub payment_method_data: Option<api_models::payments::AdditionalPaymentData>,
- pub email: Option<Email>,
- pub gateway: Option<String>,
-}
-
pub type FrmTransactionRouterData =
RouterData<api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>;
@@ -96,19 +79,6 @@ pub type FrmTransactionType = dyn services::ConnectorIntegration<
FraudCheckResponseData,
>;
-#[derive(Debug, Clone)]
-pub struct FraudCheckTransactionData {
- pub amount: i64,
- pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
- pub currency: Option<storage_enums::Currency>,
- pub payment_method: Option<storage_enums::PaymentMethod>,
- pub error_code: Option<String>,
- pub error_message: Option<String>,
- pub connector_transaction_id: Option<String>,
- //The name of the payment gateway or financial institution that processed the transaction.
- pub connector: Option<String>,
-}
-
pub type FrmFulfillmentRouterData =
RouterData<api::Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>;
@@ -125,18 +95,3 @@ pub type FrmRecordReturnType = dyn services::ConnectorIntegration<
FraudCheckRecordReturnData,
FraudCheckResponseData,
>;
-
-#[derive(Debug, Clone)]
-pub struct FraudCheckFulfillmentData {
- pub amount: i64,
- pub order_details: Option<Vec<masking::Secret<serde_json::Value>>>,
- pub fulfillment_req: FrmFulfillmentRequest,
-}
-
-#[derive(Debug, Clone)]
-pub struct FraudCheckRecordReturnData {
- pub amount: i64,
- pub currency: Option<storage_enums::Currency>,
- pub refund_method: RefundMethod,
- pub refund_transaction_id: Option<String>,
-}
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index 059278a1b1..62c260de71 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -1,7 +1,6 @@
#[cfg(feature = "olap")]
pub mod connector_onboarding;
pub mod currency;
-pub mod custom_serde;
pub mod db_utils;
pub mod ext_traits;
#[cfg(feature = "kv_store")]
diff --git a/crates/router/src/utils/connector_onboarding.rs b/crates/router/src/utils/connector_onboarding.rs
index 03735e61cc..aeea146df2 100644
--- a/crates/router/src/utils/connector_onboarding.rs
+++ b/crates/router/src/utils/connector_onboarding.rs
@@ -4,7 +4,7 @@ use error_stack::ResultExt;
use super::errors::StorageErrorExt;
use crate::{
consts,
- core::errors::{api_error_response::NotImplementedMessage, ApiErrorResponse, RouterResult},
+ core::errors::{ApiErrorResponse, NotImplementedMessage, RouterResult},
routes::{app::settings, AppState},
types::{self, api::enums},
};
diff --git a/crates/router/src/utils/custom_serde.rs b/crates/router/src/utils/custom_serde.rs
deleted file mode 100644
index dcdad3092b..0000000000
--- a/crates/router/src/utils/custom_serde.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-pub fn display_serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
-where
- T: std::fmt::Display,
- S: serde::ser::Serializer,
-{
- serializer.serialize_str(&format!("{}", value))
-}
diff --git a/crates/scheduler/Cargo.toml b/crates/scheduler/Cargo.toml
index b98f212d67..73832a1ad6 100644
--- a/crates/scheduler/Cargo.toml
+++ b/crates/scheduler/Cargo.toml
@@ -7,7 +7,7 @@ license.workspace = true
[features]
default = ["kv_store", "olap"]
-olap = ["storage_impl/olap"]
+olap = ["storage_impl/olap", "hyperswitch_domain_models/olap"]
kv_store = []
email = ["external_services/email"]
@@ -35,6 +35,7 @@ masking = { version = "0.1.0", path = "../masking" }
redis_interface = { version = "0.1.0", path = "../redis_interface" }
router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }
storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false }
+hyperswitch_domain_models = {version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }
# [[bin]]
# name = "scheduler"
diff --git a/crates/scheduler/src/errors.rs b/crates/scheduler/src/errors.rs
index e4fd56ba8d..e630287c31 100644
--- a/crates/scheduler/src/errors.rs
+++ b/crates/scheduler/src/errors.rs
@@ -1,6 +1,7 @@
pub use common_utils::errors::{ParsingError, ValidationError};
#[cfg(feature = "email")]
use external_services::email::EmailError;
+use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
pub use redis_interface::errors::RedisError;
pub use storage_impl::errors::ApplicationError;
use storage_impl::errors::StorageError;
@@ -88,6 +89,12 @@ impl<T: PTError> From<T> for ProcessTrackerError {
}
}
+impl PTError for ApiErrorResponse {
+ fn to_pt_error(&self) -> ProcessTrackerError {
+ ProcessTrackerError::EApiErrorResponse
+ }
+}
+
impl<T: PTError + std::fmt::Debug + std::fmt::Display> From<error_stack::Report<T>>
for ProcessTrackerError
{