repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
#[cfg(all(feature = "v1", feature = "olap"))] use api_models::enums::Connector; use common_enums as storage_enums; #[cfg(feature = "v2")] use common_types::payments as common_payments_types; #[cfg(feature = "v1")] use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, OvercaptureEnabledBool, RequestExtendedAuthorizationBool, }; #[cfg(feature = "v2")] use common_utils::ext_traits::Encode; use common_utils::{ crypto::Encryptable, encryption::Encryption, errors::{CustomResult, ValidationError}, ext_traits::{OptionExt, ValueExt}, id_type, pii, types::{ keymanager::{self, KeyManagerState, ToEncryptable}, ConnectorTransactionId, ConnectorTransactionIdTrait, CreatedBy, MinorUnit, }, }; #[cfg(feature = "v1")] use diesel_models::{ ConnectorMandateReferenceId, NetworkDetails, PaymentAttemptUpdate as DieselPaymentAttemptUpdate, }; use diesel_models::{ PaymentAttempt as DieselPaymentAttempt, PaymentAttemptNew as DieselPaymentAttemptNew, }; #[cfg(feature = "v2")] use diesel_models::{ PaymentAttemptFeatureMetadata as DieselPaymentAttemptFeatureMetadata, PaymentAttemptRecoveryData as DieselPassiveChurnRecoveryData, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; #[cfg(feature = "v1")] use router_env::logger; use rustc_hash::FxHashMap; #[cfg(feature = "v1")] use serde::Deserialize; use serde::Serialize; use serde_json::Value; use time::PrimitiveDateTime; use url::Url; #[cfg(all(feature = "v1", feature = "olap"))] use super::PaymentIntent; #[cfg(feature = "v2")] use crate::{address::Address, consts, router_response_types}; use crate::{ behaviour, errors, merchant_key_store::MerchantKeyStore, type_encryption::{crypto_operation, CryptoOperation}, ForeignIDRef, }; #[cfg(feature = "v1")] use crate::{ mandates::{MandateDataType, MandateDetails}, router_request_types, }; #[async_trait::async_trait] pub trait PaymentAttemptInterface { type Error; #[cfg(feature = "v1")] async fn insert_payment_attempt( &self, payment_attempt: PaymentAttempt, storage_scheme: storage_enums::MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v2")] async fn insert_payment_attempt( &self, merchant_key_store: &MerchantKeyStore, payment_attempt: PaymentAttempt, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v1")] async fn update_payment_attempt_with_attempt_id( &self, this: PaymentAttempt, payment_attempt: PaymentAttemptUpdate, storage_scheme: storage_enums::MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v2")] async fn update_payment_attempt( &self, merchant_key_store: &MerchantKeyStore, this: PaymentAttempt, payment_attempt: PaymentAttemptUpdate, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v1")] async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, connector_transaction_id: &ConnectorTransactionId, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: storage_enums::MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v1")] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: storage_enums::MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v1")] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: storage_enums::MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v2")] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( &self, merchant_key_store: &MerchantKeyStore, payment_id: &id_type::GlobalPaymentId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v1")] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, merchant_id: &id_type::MerchantId, connector_txn_id: &str, storage_scheme: storage_enums::MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v2")] async fn find_payment_attempt_by_profile_id_connector_transaction_id( &self, merchant_key_store: &MerchantKeyStore, profile_id: &id_type::ProfileId, connector_transaction_id: &str, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, Self::Error>; #[cfg(feature = "v1")] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, attempt_id: &str, storage_scheme: storage_enums::MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v1")] async fn find_payment_attempt_by_attempt_id_merchant_id( &self, attempt_id: &str, merchant_id: &id_type::MerchantId, storage_scheme: storage_enums::MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v2")] async fn find_payment_attempt_by_id( &self, merchant_key_store: &MerchantKeyStore, attempt_id: &id_type::GlobalAttemptId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v2")] async fn find_payment_attempts_by_payment_intent_id( &self, payment_id: &id_type::GlobalPaymentId, merchant_key_store: &MerchantKeyStore, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentAttempt>, Self::Error>; #[cfg(feature = "v1")] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, preprocessing_id: &str, merchant_id: &id_type::MerchantId, storage_scheme: storage_enums::MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v1")] async fn find_attempts_by_merchant_id_payment_id( &self, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, storage_scheme: storage_enums::MerchantStorageScheme, merchant_key_store: &MerchantKeyStore, ) -> error_stack::Result<Vec<PaymentAttempt>, Self::Error>; #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filters_for_payments( &self, pi: &[PaymentIntent], merchant_id: &id_type::MerchantId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentListFilters, Self::Error>; #[cfg(all(feature = "v1", feature = "olap"))] #[allow(clippy::too_many_arguments)] async fn get_total_count_of_filtered_payment_attempts( &self, merchant_id: &id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<Connector>>, payment_method: Option<Vec<storage_enums::PaymentMethod>>, payment_method_type: Option<Vec<storage_enums::PaymentMethodType>>, authentication_type: Option<Vec<storage_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<storage_enums::CardNetwork>>, card_discovery: Option<Vec<storage_enums::CardDiscovery>>, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<i64, Self::Error>; #[cfg(all(feature = "v2", feature = "olap"))] #[allow(clippy::too_many_arguments)] async fn get_total_count_of_filtered_payment_attempts( &self, merchant_id: &id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<api_models::enums::Connector>>, payment_method_type: Option<Vec<storage_enums::PaymentMethod>>, payment_method_subtype: Option<Vec<storage_enums::PaymentMethodType>>, authentication_type: Option<Vec<storage_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<storage_enums::CardNetwork>>, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<i64, Self::Error>; } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AttemptAmountDetails { /// The total amount for this payment attempt. This includes all the surcharge and tax amounts. net_amount: MinorUnit, /// The amount that has to be captured, amount_to_capture: Option<MinorUnit>, /// Surcharge amount for the payment attempt. /// This is either derived by surcharge rules, or sent by the merchant surcharge_amount: Option<MinorUnit>, /// Tax amount for the payment attempt /// This is either derived by surcharge rules, or sent by the merchant tax_on_surcharge: Option<MinorUnit>, /// The total amount that can be captured for this payment attempt. amount_capturable: MinorUnit, /// Shipping cost for the payment attempt. shipping_cost: Option<MinorUnit>, /// Tax amount for the order. /// This is either derived by calling an external tax processor, or sent by the merchant order_tax_amount: Option<MinorUnit>, /// Amount captured for this payment attempt amount_captured: Option<MinorUnit>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AttemptAmountDetailsSetter { /// The total amount for this payment attempt. This includes all the surcharge and tax amounts. pub net_amount: MinorUnit, /// The amount that has to be captured, pub amount_to_capture: Option<MinorUnit>, /// Surcharge amount for the payment attempt. /// This is either derived by surcharge rules, or sent by the merchant pub surcharge_amount: Option<MinorUnit>, /// Tax amount for the payment attempt /// This is either derived by surcharge rules, or sent by the merchant pub tax_on_surcharge: Option<MinorUnit>, /// The total amount that can be captured for this payment attempt. pub amount_capturable: MinorUnit, /// Shipping cost for the payment attempt. pub shipping_cost: Option<MinorUnit>, /// Tax amount for the order. /// This is either derived by calling an external tax processor, or sent by the merchant pub order_tax_amount: Option<MinorUnit>, /// Amount captured for this payment attempt pub amount_captured: Option<MinorUnit>, } /// Set the fields of amount details, since the fields are not public impl From<AttemptAmountDetailsSetter> for AttemptAmountDetails { fn from(setter: AttemptAmountDetailsSetter) -> Self { Self { net_amount: setter.net_amount, amount_to_capture: setter.amount_to_capture, surcharge_amount: setter.surcharge_amount, tax_on_surcharge: setter.tax_on_surcharge, amount_capturable: setter.amount_capturable, shipping_cost: setter.shipping_cost, order_tax_amount: setter.order_tax_amount, amount_captured: setter.amount_captured, } } } impl AttemptAmountDetails { pub fn get_net_amount(&self) -> MinorUnit { self.net_amount } pub fn get_amount_to_capture(&self) -> Option<MinorUnit> { self.amount_to_capture } pub fn get_surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn get_tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } pub fn get_amount_capturable(&self) -> MinorUnit { self.amount_capturable } pub fn get_amount_captured(&self) -> Option<MinorUnit> { self.amount_captured } pub fn get_shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn get_order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn set_amount_to_capture(&mut self, amount_to_capture: MinorUnit) { self.amount_to_capture = Some(amount_to_capture); } /// Validate the amount to capture that is sent in the request pub fn validate_amount_to_capture( &self, request_amount_to_capture: MinorUnit, ) -> Result<(), ValidationError> { common_utils::fp_utils::when(request_amount_to_capture > self.get_net_amount(), || { Err(ValidationError::IncorrectValueProvided { field_name: "amount_to_capture", }) }) } } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct ErrorDetails { /// The error code that was returned by the connector. /// This is a mandatory field. This is used to lookup the global status map record for unified code and retries pub code: String, /// The error message that was returned by the connector. /// This is a mandatory field. This is used to lookup the global status map record for unified message and retries pub message: String, /// The detailed error reason that was returned by the connector. pub reason: Option<String>, /// The unified code that is generated by the application based on the global status map record. /// This can be relied upon for common error code across all connectors pub unified_code: Option<String>, /// The unified message that is generated by the application based on the global status map record. /// This can be relied upon for common error code across all connectors /// If there is translation available, message will be translated to the requested language pub unified_message: Option<String>, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, } #[cfg(feature = "v2")] impl From<ErrorDetails> for api_models::payments::RecordAttemptErrorDetails { fn from(error_details: ErrorDetails) -> Self { Self { code: error_details.code, message: error_details.message, network_decline_code: error_details.network_decline_code, network_advice_code: error_details.network_advice_code, network_error_message: error_details.network_error_message, } } } /// Domain model for the payment attempt. /// Few fields which are related are grouped together for better readability and understandability. /// These fields will be flattened and stored in the database in individual columns #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, router_derive::ToEncryption)] pub struct PaymentAttempt { /// Payment id for the payment attempt pub payment_id: id_type::GlobalPaymentId, /// Merchant id for the payment attempt pub merchant_id: id_type::MerchantId, /// Group id for the payment attempt pub attempts_group_id: Option<id_type::GlobalAttemptGroupId>, /// Amount details for the payment attempt pub amount_details: AttemptAmountDetails, /// Status of the payment attempt. This is the status that is updated by the connector. /// The intent status is updated by the AttemptStatus. pub status: storage_enums::AttemptStatus, /// Name of the connector that was used for the payment attempt. The connector is either decided by /// either running the routing algorithm or by straight through processing request. /// This will be updated before calling the connector // TODO: use connector enum, this should be done in v1 as well as a part of moving to domain types wherever possible pub connector: Option<String>, /// Error details in case the payment attempt failed pub error: Option<ErrorDetails>, /// The authentication type that was requested for the payment attempt. /// This authentication type maybe decided by step up 3ds or by running the decision engine. pub authentication_type: storage_enums::AuthenticationType, /// The time at which the payment attempt was created pub created_at: PrimitiveDateTime, /// The time at which the payment attempt was last modified pub modified_at: PrimitiveDateTime, pub last_synced: Option<PrimitiveDateTime>, /// The reason for the cancellation of the payment attempt. Some connectors will have strict rules regarding the values this can have /// Cancellation reason will be validated at the connector level when building the request pub cancellation_reason: Option<String>, /// Browser information required for 3DS authentication pub browser_info: Option<common_utils::types::BrowserInformation>, /// Payment token is the token used for temporary use in case the payment method is stored in vault pub payment_token: Option<String>, /// Metadata that is returned by the connector. pub connector_metadata: Option<pii::SecretSerdeValue>, pub payment_experience: Option<storage_enums::PaymentExperience>, /// The insensitive data of the payment method data is stored here pub payment_method_data: Option<pii::SecretSerdeValue>, /// The result of the routing algorithm. /// This will store the list of connectors and other related information that was used to route the payment. // TODO: change this to type instead of serde_json::Value pub routing_result: Option<Value>, pub preprocessing_step_id: Option<String>, /// Number of captures that have happened for the payment attempt pub multiple_capture_count: Option<i16>, /// A reference to the payment at connector side. This is returned by the connector pub connector_response_reference_id: Option<String>, /// Whether the payment was updated by postgres or redis pub updated_by: String, /// The authentication data which is used for external authentication pub redirection_data: Option<router_response_types::RedirectForm>, pub encoded_data: Option<Secret<String>>, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Whether external 3DS authentication was attempted for this payment. /// This is based on the configuration of the merchant in the business profile pub external_three_ds_authentication_attempted: Option<bool>, /// The connector that was used for external authentication pub authentication_connector: Option<String>, /// The foreign key reference to the authentication details pub authentication_id: Option<id_type::AuthenticationId>, pub fingerprint_id: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, pub customer_acceptance: Option<Secret<common_payments_types::CustomerAcceptance>>, /// The profile id for the payment attempt. This will be derived from payment intent. pub profile_id: id_type::ProfileId, /// The organization id for the payment attempt. This will be derived from payment intent. pub organization_id: id_type::OrganizationId, /// Payment method type for the payment attempt pub payment_method_type: storage_enums::PaymentMethod, /// Foreig key reference of Payment method id in case the payment instrument was stored pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// The reference to the payment at the connector side pub connector_payment_id: Option<String>, /// The payment method subtype for the payment attempt. pub payment_method_subtype: storage_enums::PaymentMethodType, /// The authentication type that was applied for the payment attempt. pub authentication_applied: Option<common_enums::AuthenticationType>, /// A reference to the payment at connector side. This is returned by the connector pub external_reference_id: Option<String>, /// The billing address for the payment method #[encrypt(ty = Value)] pub payment_method_billing_address: Option<Encryptable<Address>>, /// The global identifier for the payment attempt pub id: id_type::GlobalAttemptId, /// Connector token information that can be used to make payments directly by the merchant. pub connector_token_details: Option<diesel_models::ConnectorTokenDetails>, /// Indicates the method by which a card is discovered during a payment pub card_discovery: Option<common_enums::CardDiscovery>, /// Split payment data pub charges: Option<common_types::payments::ConnectorChargeResponseData>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// merchant who owns the credentials of the processor, i.e. processor owner pub processor_merchant_id: id_type::MerchantId, /// merchant or user who invoked the resource-based API (identifier) and the source (Api, Jwt(Dashboard)) pub created_by: Option<CreatedBy>, pub connector_request_reference_id: Option<String>, pub network_transaction_id: Option<String>, /// stores the authorized amount in case of partial authorization pub authorized_amount: Option<MinorUnit>, } impl PaymentAttempt { #[cfg(feature = "v1")] pub fn get_payment_method(&self) -> Option<storage_enums::PaymentMethod> { self.payment_method } #[cfg(feature = "v2")] pub fn get_payment_method(&self) -> Option<storage_enums::PaymentMethod> { // TODO: check if we can fix this Some(self.payment_method_type) } #[cfg(feature = "v1")] pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethodType> { self.payment_method_type } #[cfg(feature = "v2")] pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethodType> { // TODO: check if we can fix this Some(self.payment_method_subtype) } #[cfg(feature = "v1")] pub fn get_id(&self) -> &str { &self.attempt_id } #[cfg(feature = "v2")] pub fn get_id(&self) -> &id_type::GlobalAttemptId { &self.id } #[cfg(feature = "v1")] pub fn get_connector_payment_id(&self) -> Option<&str> { self.connector_transaction_id.as_deref() } #[cfg(feature = "v2")] pub fn get_connector_payment_id(&self) -> Option<&str> { self.connector_payment_id.as_deref() } /// Construct the domain model from the ConfirmIntentRequest and PaymentIntent #[cfg(feature = "v2")] pub async fn create_domain_model( payment_intent: &super::PaymentIntent, cell_id: id_type::CellId, storage_scheme: storage_enums::MerchantStorageScheme, request: &api_models::payments::PaymentsConfirmIntentRequest, encrypted_data: DecryptedPaymentAttempt, ) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> { let id = id_type::GlobalAttemptId::generate(&cell_id); let intent_amount_details = payment_intent.amount_details.clone(); let attempt_amount_details = intent_amount_details.create_attempt_amount_details(request); let now = common_utils::date_time::now(); let payment_method_billing_address = encrypted_data .payment_method_billing_address .as_ref() .map(|data| { data.clone() .deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Unable to decode billing address")?; let connector_token = Some(diesel_models::ConnectorTokenDetails { connector_mandate_id: None, connector_token_request_reference_id: Some(common_utils::generate_id_with_len( consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH, )), }); let authentication_type = payment_intent.authentication_type.unwrap_or_default(); Ok(Self { payment_id: payment_intent.id.clone(), merchant_id: payment_intent.merchant_id.clone(), attempts_group_id: None, amount_details: attempt_amount_details, status: common_enums::AttemptStatus::Started, // This will be decided by the routing algorithm and updated in update trackers // right before calling the connector connector: None, authentication_type, created_at: now, modified_at: now, last_synced: None, cancellation_reason: None, browser_info: request.browser_info.clone(), payment_token: request.payment_token.clone(), connector_metadata: None, payment_experience: None, payment_method_data: None, routing_result: None, preprocessing_step_id: None, multiple_capture_count: None, connector_response_reference_id: None, updated_by: storage_scheme.to_string(), redirection_data: None, encoded_data: None, merchant_connector_id: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, charges: None, client_source: None, client_version: None, customer_acceptance: request.customer_acceptance.clone().map(Secret::new), profile_id: payment_intent.profile_id.clone(), organization_id: payment_intent.organization_id.clone(), payment_method_type: request.payment_method_type, payment_method_id: request.payment_method_id.clone(), connector_payment_id: None, payment_method_subtype: request.payment_method_subtype, authentication_applied: None, external_reference_id: None, payment_method_billing_address, error: None, connector_token_details: connector_token, id, card_discovery: None, feature_metadata: None, processor_merchant_id: payment_intent.merchant_id.clone(), created_by: None, connector_request_reference_id: None, network_transaction_id: None, authorized_amount: None, }) } #[cfg(feature = "v2")] pub async fn proxy_create_domain_model( payment_intent: &super::PaymentIntent, cell_id: id_type::CellId, storage_scheme: storage_enums::MerchantStorageScheme, request: &api_models::payments::ProxyPaymentsRequest, encrypted_data: DecryptedPaymentAttempt, ) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> { let id = id_type::GlobalAttemptId::generate(&cell_id); let intent_amount_details = payment_intent.amount_details.clone(); let attempt_amount_details = intent_amount_details.proxy_create_attempt_amount_details(request); let now = common_utils::date_time::now(); let payment_method_billing_address = encrypted_data .payment_method_billing_address .as_ref() .map(|data| { data.clone() .deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Unable to decode billing address")?; let connector_token = Some(diesel_models::ConnectorTokenDetails { connector_mandate_id: None, connector_token_request_reference_id: Some(common_utils::generate_id_with_len( consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH, )), }); let payment_method_type_data = payment_intent.get_payment_method_type(); let payment_method_subtype_data = payment_intent.get_payment_method_sub_type(); let authentication_type = payment_intent.authentication_type.unwrap_or_default(); Ok(Self { payment_id: payment_intent.id.clone(), merchant_id: payment_intent.merchant_id.clone(), attempts_group_id: None, amount_details: attempt_amount_details, status: common_enums::AttemptStatus::Started, connector: Some(request.connector.clone()), authentication_type, created_at: now, modified_at: now, last_synced: None, cancellation_reason: None, browser_info: request.browser_info.clone(), payment_token: None, connector_metadata: None, payment_experience: None, payment_method_data: None, routing_result: None, preprocessing_step_id: None, multiple_capture_count: None, connector_response_reference_id: None, updated_by: storage_scheme.to_string(), redirection_data: None, encoded_data: None, merchant_connector_id: Some(request.merchant_connector_id.clone()), external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, charges: None, client_source: None, client_version: None, customer_acceptance: None, profile_id: payment_intent.profile_id.clone(), organization_id: payment_intent.organization_id.clone(), payment_method_type: payment_method_type_data .unwrap_or(common_enums::PaymentMethod::Card), payment_method_id: None, connector_payment_id: None, payment_method_subtype: payment_method_subtype_data .unwrap_or(common_enums::PaymentMethodType::Credit), authentication_applied: None, external_reference_id: None, payment_method_billing_address, error: None, connector_token_details: connector_token, feature_metadata: None, id, card_discovery: None, processor_merchant_id: payment_intent.merchant_id.clone(), created_by: None, connector_request_reference_id: None, network_transaction_id: None, authorized_amount: None, }) } #[cfg(feature = "v2")] pub async fn external_vault_proxy_create_domain_model( payment_intent: &super::PaymentIntent, cell_id: id_type::CellId, storage_scheme: storage_enums::MerchantStorageScheme, request: &api_models::payments::ExternalVaultProxyPaymentsRequest, encrypted_data: DecryptedPaymentAttempt, ) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> { let id = id_type::GlobalAttemptId::generate(&cell_id);
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
crates/hyperswitch_domain_models/src/payments/payment_intent.rs
use common_types::primitive_wrappers; #[cfg(feature = "v1")] use common_utils::consts::PAYMENTS_LIST_MAX_LIMIT_V2; #[cfg(feature = "v2")] use common_utils::errors::ParsingError; #[cfg(feature = "v2")] use common_utils::ext_traits::{Encode, ValueExt}; use common_utils::{ consts::PAYMENTS_LIST_MAX_LIMIT_V1, crypto::Encryptable, encryption::Encryption, errors::{CustomResult, ValidationError}, id_type, pii::{self, Email}, type_name, types::{ keymanager::{self, KeyManagerState, ToEncryptable}, CreatedBy, MinorUnit, }, }; use diesel_models::{ PaymentIntent as DieselPaymentIntent, PaymentIntentNew as DieselPaymentIntentNew, }; use error_stack::ResultExt; #[cfg(feature = "v2")] use masking::ExposeInterface; use masking::{Deserialize, PeekInterface, Secret}; use serde::Serialize; use time::PrimitiveDateTime; #[cfg(all(feature = "v1", feature = "olap"))] use super::payment_attempt::PaymentAttempt; use super::PaymentIntent; #[cfg(feature = "v2")] use crate::address::Address; #[cfg(feature = "v2")] use crate::routing; use crate::{ behaviour, merchant_key_store::MerchantKeyStore, type_encryption::{crypto_operation, CryptoOperation}, }; #[cfg(feature = "v1")] use crate::{errors, RemoteStorageObject}; #[async_trait::async_trait] pub trait PaymentIntentInterface { type Error; async fn update_payment_intent( &self, this: PaymentIntent, payment_intent: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, Self::Error>; async fn insert_payment_intent( &self, new: PaymentIntent, merchant_key_store: &MerchantKeyStore, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, Self::Error>; #[cfg(feature = "v1")] async fn find_payment_intent_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, merchant_key_store: &MerchantKeyStore, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, Self::Error>; #[cfg(feature = "v2")] async fn find_payment_intent_by_merchant_reference_id_profile_id( &self, merchant_reference_id: &id_type::PaymentReferenceId, profile_id: &id_type::ProfileId, merchant_key_store: &MerchantKeyStore, storage_scheme: &common_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, Self::Error>; #[cfg(feature = "v2")] async fn find_payment_intent_by_id( &self, id: &id_type::GlobalPaymentId, merchant_key_store: &MerchantKeyStore, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, Self::Error>; #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_payment_intent_by_constraints( &self, merchant_id: &id_type::MerchantId, filters: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, Self::Error>; #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_payment_intents_by_time_range_constraints( &self, merchant_id: &id_type::MerchantId, time_range: &common_utils::types::TimeRange, merchant_key_store: &MerchantKeyStore, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, Self::Error>; #[cfg(feature = "olap")] async fn get_intent_status_with_count( &self, merchant_id: &id_type::MerchantId, profile_id_list: Option<Vec<id_type::ProfileId>>, constraints: &common_utils::types::TimeRange, ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, Self::Error>; #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filtered_payment_intents_attempt( &self, merchant_id: &id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, Self::Error>; #[cfg(all(feature = "v2", feature = "olap"))] async fn get_filtered_payment_intents_attempt( &self, merchant_id: &id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result< Vec<( PaymentIntent, Option<super::payment_attempt::PaymentAttempt>, )>, Self::Error, >; #[cfg(all(feature = "v2", feature = "olap"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<Option<String>>, Self::Error>; #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<String>, Self::Error>; } #[derive(Clone, Debug, PartialEq, router_derive::DebugAsDisplay, Serialize, Deserialize)] pub struct CustomerData { pub name: Option<Secret<String>>, pub email: Option<Email>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, pub tax_registration_id: Option<Secret<String>>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize)] pub struct PaymentIntentUpdateFields { pub amount: Option<MinorUnit>, pub currency: Option<common_enums::Currency>, pub shipping_cost: Option<MinorUnit>, pub tax_details: Option<diesel_models::TaxDetails>, pub skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, pub skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, pub routing_algorithm_id: Option<id_type::RoutingId>, pub capture_method: Option<common_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub billing_address: Option<Encryptable<Address>>, pub shipping_address: Option<Encryptable<Address>>, pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, pub description: Option<common_utils::types::Description>, pub return_url: Option<common_utils::types::Url>, pub setup_future_usage: Option<common_enums::FutureUsage>, pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, pub order_details: Option<Vec<Secret<diesel_models::types::OrderDetailsWithAmount>>>, pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub feature_metadata: Option<diesel_models::types::FeatureMetadata>, pub payment_link_config: Option<diesel_models::PaymentLinkConfigRequestForPayments>, pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, pub session_expiry: Option<PrimitiveDateTime>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, pub active_attempt_id: Option<Option<id_type::GlobalAttemptId>>, // updated_by is set internally, field not present in request pub updated_by: String, pub force_3ds_challenge: Option<bool>, pub is_iframe_redirection_enabled: Option<bool>, pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, pub active_attempt_id_type: Option<common_enums::ActiveAttemptIDType>, pub active_attempts_group_id: Option<id_type::GlobalAttemptGroupId>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize)] pub struct PaymentIntentUpdateFields { pub amount: MinorUnit, pub currency: common_enums::Currency, pub setup_future_usage: Option<common_enums::FutureUsage>, pub status: common_enums::IntentStatus, pub customer_id: Option<id_type::CustomerId>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, pub return_url: Option<String>, pub business_country: Option<common_enums::CountryAlpha2>, pub business_label: Option<String>, pub description: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub metadata: Option<serde_json::Value>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub payment_confirm_source: Option<common_enums::PaymentSource>, pub updated_by: String, pub fingerprint_id: Option<String>, pub session_expiry: Option<PrimitiveDateTime>, pub request_external_three_ds_authentication: Option<bool>, pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>, pub billing_details: Option<Encryptable<Secret<serde_json::Value>>>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryptable<Secret<serde_json::Value>>>, pub is_payment_processor_token_flow: Option<bool>, pub tax_details: Option<diesel_models::TaxDetails>, pub force_3ds_challenge: Option<bool>, pub is_iframe_redirection_enabled: Option<bool>, pub tax_status: Option<common_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, pub shipping_amount_tax: Option<MinorUnit>, pub duty_amount: Option<MinorUnit>, pub is_confirm_operation: bool, pub payment_channel: Option<common_enums::PaymentChannel>, pub feature_metadata: Option<Secret<serde_json::Value>>, pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, pub enable_overcapture: Option<primitive_wrappers::EnableOvercaptureBool>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize)] pub enum PaymentIntentUpdate { ResponseUpdate { status: common_enums::IntentStatus, amount_captured: Option<MinorUnit>, updated_by: String, fingerprint_id: Option<String>, incremental_authorization_allowed: Option<bool>, feature_metadata: Option<Secret<serde_json::Value>>, }, MetadataUpdate { metadata: serde_json::Value, updated_by: String, }, Update(Box<PaymentIntentUpdateFields>), PaymentCreateUpdate { return_url: Option<String>, status: Option<common_enums::IntentStatus>, customer_id: Option<id_type::CustomerId>, shipping_address_id: Option<String>, billing_address_id: Option<String>, customer_details: Option<Encryptable<Secret<serde_json::Value>>>, updated_by: String, }, MerchantStatusUpdate { status: common_enums::IntentStatus, shipping_address_id: Option<String>, billing_address_id: Option<String>, updated_by: String, }, PGStatusUpdate { status: common_enums::IntentStatus, incremental_authorization_allowed: Option<bool>, updated_by: String, feature_metadata: Option<Secret<serde_json::Value>>, }, PaymentAttemptAndAttemptCountUpdate { active_attempt_id: String, attempt_count: i16, updated_by: String, }, StatusAndAttemptUpdate { status: common_enums::IntentStatus, active_attempt_id: String, attempt_count: i16, updated_by: String, }, ApproveUpdate { status: common_enums::IntentStatus, merchant_decision: Option<String>, updated_by: String, }, RejectUpdate { status: common_enums::IntentStatus, merchant_decision: Option<String>, updated_by: String, }, SurchargeApplicableUpdate { surcharge_applicable: bool, updated_by: String, }, IncrementalAuthorizationAmountUpdate { amount: MinorUnit, }, AuthorizationCountUpdate { authorization_count: i32, }, CompleteAuthorizeUpdate { shipping_address_id: Option<String>, }, ManualUpdate { status: Option<common_enums::IntentStatus>, updated_by: String, }, SessionResponseUpdate { tax_details: diesel_models::TaxDetails, shipping_address_id: Option<String>, updated_by: String, shipping_details: Option<Encryptable<Secret<serde_json::Value>>>, }, } #[cfg(feature = "v1")] impl PaymentIntentUpdate { pub fn is_confirm_operation(&self) -> bool { match self { Self::Update(value) => value.is_confirm_operation, _ => false, } } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize)] pub enum PaymentIntentUpdate { /// PreUpdate tracker of ConfirmIntent ConfirmIntent { status: common_enums::IntentStatus, active_attempt_id: Option<id_type::GlobalAttemptId>, updated_by: String, }, /// PostUpdate tracker of ConfirmIntent ConfirmIntentPostUpdate { status: common_enums::IntentStatus, amount_captured: Option<MinorUnit>, updated_by: String, feature_metadata: Option<Box<diesel_models::types::FeatureMetadata>>, }, /// SyncUpdate of ConfirmIntent in PostUpdateTrackers SyncUpdate { status: common_enums::IntentStatus, amount_captured: Option<MinorUnit>, updated_by: String, }, CaptureUpdate { status: common_enums::IntentStatus, amount_captured: Option<MinorUnit>, updated_by: String, }, /// Update the payment intent details on payment sdk session call, before calling the connector. SessionIntentUpdate { prerouting_algorithm: routing::PaymentRoutingInfo, updated_by: String, }, RecordUpdate { status: common_enums::IntentStatus, feature_metadata: Box<Option<diesel_models::types::FeatureMetadata>>, updated_by: String, active_attempt_id: Option<id_type::GlobalAttemptId>, active_attempts_group_id: Option<id_type::GlobalAttemptGroupId>, }, /// UpdateIntent UpdateIntent(Box<PaymentIntentUpdateFields>), /// VoidUpdate for payment cancellation VoidUpdate { status: common_enums::IntentStatus, updated_by: String, }, AttemptGroupUpdate { active_attempts_group_id: id_type::GlobalAttemptGroupId, active_attempt_id_type: common_enums::ActiveAttemptIDType, updated_by: String, }, SplitPaymentStatusUpdate { status: common_enums::IntentStatus, updated_by: String, }, } #[cfg(feature = "v2")] impl PaymentIntentUpdate { pub fn is_confirm_operation(&self) -> bool { matches!(self, Self::ConfirmIntent { .. }) } } #[cfg(feature = "v1")] #[derive(Clone, Debug, Default)] pub struct PaymentIntentUpdateInternal { pub amount: Option<MinorUnit>, pub currency: Option<common_enums::Currency>, pub status: Option<common_enums::IntentStatus>, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<id_type::CustomerId>, pub return_url: Option<String>, pub setup_future_usage: Option<common_enums::FutureUsage>, pub off_session: Option<bool>, pub metadata: Option<serde_json::Value>, pub billing_address_id: Option<String>, pub shipping_address_id: Option<String>, pub modified_at: Option<PrimitiveDateTime>, pub active_attempt_id: Option<String>, pub business_country: Option<common_enums::CountryAlpha2>, pub business_label: Option<String>, pub description: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub attempt_count: Option<i16>, // Denotes the action(approve or reject) taken by merchant in case of manual review. // Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, pub payment_confirm_source: Option<common_enums::PaymentSource>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, pub fingerprint_id: Option<String>, pub session_expiry: Option<PrimitiveDateTime>, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>, pub billing_details: Option<Encryptable<Secret<serde_json::Value>>>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryptable<Secret<serde_json::Value>>>, pub is_payment_processor_token_flow: Option<bool>, pub tax_details: Option<diesel_models::TaxDetails>, pub force_3ds_challenge: Option<bool>, pub is_iframe_redirection_enabled: Option<bool>, pub payment_channel: Option<common_enums::PaymentChannel>, pub feature_metadata: Option<Secret<serde_json::Value>>, pub tax_status: Option<common_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, pub shipping_amount_tax: Option<MinorUnit>, pub duty_amount: Option<MinorUnit>, pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, pub enable_overcapture: Option<primitive_wrappers::EnableOvercaptureBool>, } // This conversion is used in the `update_payment_intent` function #[cfg(feature = "v2")] impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal { type Error = error_stack::Report<ParsingError>; fn try_from(payment_intent_update: PaymentIntentUpdate) -> Result<Self, Self::Error> { match payment_intent_update { PaymentIntentUpdate::ConfirmIntent { status, active_attempt_id, updated_by, } => Ok(Self { status: Some(status), active_attempt_id: Some(active_attempt_id), active_attempt_id_type: None, active_attempts_group_id: None, prerouting_algorithm: None, modified_at: common_utils::date_time::now(), amount: None, amount_captured: None, currency: None, shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, surcharge_applicable: None, surcharge_amount: None, tax_on_surcharge: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing_address: None, shipping_address: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, feature_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, updated_by, force_3ds_challenge: None, is_iframe_redirection_enabled: None, enable_partial_authorization: None, }), PaymentIntentUpdate::ConfirmIntentPostUpdate { status, updated_by, amount_captured, feature_metadata, } => Ok(Self { status: Some(status), active_attempt_id: None, active_attempt_id_type: None, active_attempts_group_id: None, prerouting_algorithm: None, modified_at: common_utils::date_time::now(), amount_captured, amount: None, currency: None, shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, surcharge_applicable: None, surcharge_amount: None, tax_on_surcharge: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing_address: None, shipping_address: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, feature_metadata: feature_metadata.map(|val| *val), payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, updated_by, force_3ds_challenge: None, is_iframe_redirection_enabled: None, enable_partial_authorization: None, }), PaymentIntentUpdate::SyncUpdate { status, amount_captured, updated_by, } => Ok(Self { status: Some(status), active_attempt_id: None, active_attempt_id_type: None, active_attempts_group_id: None, prerouting_algorithm: None, modified_at: common_utils::date_time::now(), amount: None, currency: None, amount_captured, shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, surcharge_applicable: None, surcharge_amount: None, tax_on_surcharge: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing_address: None, shipping_address: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, feature_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, updated_by, force_3ds_challenge: None, is_iframe_redirection_enabled: None, enable_partial_authorization: None, }), PaymentIntentUpdate::CaptureUpdate { status, amount_captured, updated_by, } => Ok(Self { status: Some(status), amount_captured, active_attempt_id: None, active_attempt_id_type: None, active_attempts_group_id: None, prerouting_algorithm: None, modified_at: common_utils::date_time::now(), amount: None, currency: None, shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, surcharge_applicable: None, surcharge_amount: None, tax_on_surcharge: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing_address: None, shipping_address: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, feature_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, updated_by, force_3ds_challenge: None, is_iframe_redirection_enabled: None, enable_partial_authorization: None, }), PaymentIntentUpdate::SessionIntentUpdate { prerouting_algorithm, updated_by, } => Ok(Self { status: None, active_attempt_id: None, active_attempt_id_type: None, active_attempts_group_id: None, modified_at: common_utils::date_time::now(), amount_captured: None, prerouting_algorithm: Some( prerouting_algorithm .encode_to_value() .attach_printable("Failed to Serialize prerouting_algorithm")?, ), amount: None, currency: None, shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, surcharge_applicable: None, surcharge_amount: None, tax_on_surcharge: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing_address: None, shipping_address: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, feature_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, updated_by, force_3ds_challenge: None, is_iframe_redirection_enabled: None, enable_partial_authorization: None, }), PaymentIntentUpdate::UpdateIntent(boxed_intent) => { let PaymentIntentUpdateFields { amount, currency, shipping_cost, tax_details, skip_external_tax_calculation, skip_surcharge_calculation, surcharge_amount, tax_on_surcharge, routing_algorithm_id, capture_method, authentication_type, billing_address, shipping_address, customer_present, description, return_url, setup_future_usage, apply_mit_exemption, statement_descriptor, order_details, allowed_payment_method_types, metadata, connector_metadata, feature_metadata, payment_link_config, request_incremental_authorization, session_expiry, frm_metadata, request_external_three_ds_authentication, active_attempt_id, updated_by, force_3ds_challenge, is_iframe_redirection_enabled, enable_partial_authorization, active_attempt_id_type, active_attempts_group_id, } = *boxed_intent; Ok(Self { status: None, active_attempt_id, active_attempt_id_type, active_attempts_group_id, prerouting_algorithm: None, modified_at: common_utils::date_time::now(), amount_captured: None, amount, currency, shipping_cost, tax_details, skip_external_tax_calculation: skip_external_tax_calculation .map(|val| val.as_bool()), surcharge_applicable: skip_surcharge_calculation.map(|val| val.as_bool()), surcharge_amount, tax_on_surcharge, routing_algorithm_id, capture_method, authentication_type, billing_address: billing_address.map(Encryption::from), shipping_address: shipping_address.map(Encryption::from), customer_present: customer_present.map(|val| val.as_bool()), description, return_url, setup_future_usage, apply_mit_exemption: apply_mit_exemption.map(|val| val.as_bool()), statement_descriptor, order_details, allowed_payment_method_types: allowed_payment_method_types .map(|allowed_payment_method_types| { allowed_payment_method_types.encode_to_value() }) .and_then(|r| r.ok().map(Secret::new)), metadata, connector_metadata, feature_metadata, payment_link_config, request_incremental_authorization, session_expiry, frm_metadata, request_external_three_ds_authentication: request_external_three_ds_authentication.map(|val| val.as_bool()), updated_by, force_3ds_challenge, is_iframe_redirection_enabled, enable_partial_authorization, }) } PaymentIntentUpdate::RecordUpdate { status, feature_metadata, updated_by, active_attempt_id, active_attempts_group_id, } => Ok(Self { status: Some(status), amount_captured: None, active_attempt_id: Some(active_attempt_id), active_attempt_id_type: None, active_attempts_group_id, modified_at: common_utils::date_time::now(), amount: None, currency: None,
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/payments/split_payments.rs
crates/hyperswitch_domain_models/src/payments/split_payments.rs
use api_models::payments::PaymentMethodData; use common_utils::types::MinorUnit; #[derive(Clone, Debug)] pub struct PaymentMethodDetails { pub payment_method_data: PaymentMethodData, pub payment_method_type: common_enums::PaymentMethod, pub payment_method_subtype: common_enums::PaymentMethodType, } /// There can be multiple gift-cards, but at most one non-gift card PM pub struct PaymentMethodAmountSplit { pub balance_pm_split: Vec<PaymentMethodDetailsWithSplitAmount>, pub non_balance_pm_split: Option<PaymentMethodDetailsWithSplitAmount>, } #[derive(Clone, Debug)] pub struct PaymentMethodDetailsWithSplitAmount { pub payment_method_details: PaymentMethodDetails, pub split_amount: MinorUnit, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
use api_models::enums::PayoutConnectors; use common_enums as storage_enums; use common_utils::{ id_type, payout_method_utils, pii, types::{UnifiedCode, UnifiedMessage}, }; use serde::{Deserialize, Serialize}; use storage_enums::MerchantStorageScheme; use time::PrimitiveDateTime; use super::payouts::Payouts; #[async_trait::async_trait] pub trait PayoutAttemptInterface { type Error; async fn insert_payout_attempt( &self, _payout_attempt: PayoutAttemptNew, _payouts: &Payouts, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, Self::Error>; async fn update_payout_attempt( &self, _this: &PayoutAttempt, _payout_attempt_update: PayoutAttemptUpdate, _payouts: &Payouts, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, Self::Error>; async fn find_payout_attempt_by_merchant_id_payout_attempt_id( &self, _merchant_id: &id_type::MerchantId, _payout_attempt_id: &str, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, Self::Error>; async fn find_payout_attempt_by_merchant_id_connector_payout_id( &self, _merchant_id: &id_type::MerchantId, _connector_payout_id: &str, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, Self::Error>; async fn find_payout_attempt_by_merchant_id_merchant_order_reference_id( &self, _merchant_id: &id_type::MerchantId, _merchant_order_reference_id: &str, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, Self::Error>; async fn get_filters_for_payouts( &self, _payout: &[Payouts], _merchant_id: &id_type::MerchantId, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutListFilters, Self::Error>; } #[derive(Clone, Debug, Eq, PartialEq)] pub struct PayoutListFilters { pub connector: Vec<PayoutConnectors>, pub currency: Vec<storage_enums::Currency>, pub status: Vec<storage_enums::PayoutStatus>, pub payout_method: Vec<storage_enums::PayoutType>, } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct PayoutAttempt { pub payout_attempt_id: String, pub payout_id: id_type::PayoutId, pub customer_id: Option<id_type::CustomerId>, pub merchant_id: id_type::MerchantId, pub address_id: Option<String>, pub connector: Option<String>, pub connector_payout_id: Option<String>, pub payout_token: Option<String>, pub status: storage_enums::PayoutStatus, pub is_eligible: Option<bool>, pub error_message: Option<String>, pub error_code: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub last_modified_at: PrimitiveDateTime, pub profile_id: id_type::ProfileId, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub routing_info: Option<serde_json::Value>, pub unified_code: Option<UnifiedCode>, pub unified_message: Option<UnifiedMessage>, pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>, pub merchant_order_reference_id: Option<String>, pub payout_connector_metadata: Option<pii::SecretSerdeValue>, } #[derive(Clone, Debug, PartialEq)] pub struct PayoutAttemptNew { pub payout_attempt_id: String, pub payout_id: id_type::PayoutId, pub customer_id: Option<id_type::CustomerId>, pub merchant_id: id_type::MerchantId, pub address_id: Option<String>, pub connector: Option<String>, pub connector_payout_id: Option<String>, pub payout_token: Option<String>, pub status: storage_enums::PayoutStatus, pub is_eligible: Option<bool>, pub error_message: Option<String>, pub error_code: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub profile_id: id_type::ProfileId, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub routing_info: Option<serde_json::Value>, pub unified_code: Option<UnifiedCode>, pub unified_message: Option<UnifiedMessage>, pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>, pub merchant_order_reference_id: Option<String>, pub payout_connector_metadata: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub enum PayoutAttemptUpdate { StatusUpdate { connector_payout_id: Option<String>, status: storage_enums::PayoutStatus, error_message: Option<String>, error_code: Option<String>, is_eligible: Option<bool>, unified_code: Option<UnifiedCode>, unified_message: Option<UnifiedMessage>, payout_connector_metadata: Option<pii::SecretSerdeValue>, }, PayoutTokenUpdate { payout_token: String, }, BusinessUpdate { business_country: Option<storage_enums::CountryAlpha2>, business_label: Option<String>, address_id: Option<String>, customer_id: Option<id_type::CustomerId>, }, UpdateRouting { connector: String, routing_info: Option<serde_json::Value>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, }, AdditionalPayoutMethodDataUpdate { additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>, }, ManualUpdate { status: Option<storage_enums::PayoutStatus>, error_code: Option<String>, error_message: Option<String>, unified_code: Option<UnifiedCode>, unified_message: Option<UnifiedMessage>, connector_payout_id: Option<String>, }, } #[derive(Clone, Debug, Default)] pub struct PayoutAttemptUpdateInternal { pub payout_token: Option<String>, pub connector_payout_id: Option<String>, pub status: Option<storage_enums::PayoutStatus>, pub error_message: Option<String>, pub error_code: Option<String>, pub is_eligible: Option<bool>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub connector: Option<String>, pub routing_info: Option<serde_json::Value>, pub address_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub unified_code: Option<UnifiedCode>, pub unified_message: Option<UnifiedMessage>, pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>, pub payout_connector_metadata: Option<pii::SecretSerdeValue>, } impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal { fn from(payout_update: PayoutAttemptUpdate) -> Self { match payout_update { PayoutAttemptUpdate::PayoutTokenUpdate { payout_token } => Self { payout_token: Some(payout_token), ..Default::default() }, PayoutAttemptUpdate::StatusUpdate { connector_payout_id, status, error_message, error_code, is_eligible, unified_code, unified_message, payout_connector_metadata, } => Self { connector_payout_id, status: Some(status), error_message, error_code, is_eligible, unified_code, unified_message, payout_connector_metadata, ..Default::default() }, PayoutAttemptUpdate::BusinessUpdate { business_country, business_label, address_id, customer_id, } => Self { business_country, business_label, address_id, customer_id, ..Default::default() }, PayoutAttemptUpdate::UpdateRouting { connector, routing_info, merchant_connector_id, } => Self { connector: Some(connector), routing_info, merchant_connector_id, ..Default::default() }, PayoutAttemptUpdate::AdditionalPayoutMethodDataUpdate { additional_payout_method_data, } => Self { additional_payout_method_data, ..Default::default() }, PayoutAttemptUpdate::ManualUpdate { status, error_code, error_message, unified_code, unified_message, connector_payout_id, } => Self { status, error_code, error_message, unified_code, unified_message, connector_payout_id, ..Default::default() }, } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/payouts/payouts.rs
crates/hyperswitch_domain_models/src/payouts/payouts.rs
use common_enums as storage_enums; use common_utils::{id_type, pii, types::MinorUnit}; use serde::{Deserialize, Serialize}; use storage_enums::MerchantStorageScheme; use time::PrimitiveDateTime; use super::payout_attempt::PayoutAttempt; #[cfg(feature = "olap")] use super::PayoutFetchConstraints; #[async_trait::async_trait] pub trait PayoutsInterface { type Error; async fn insert_payout( &self, _payout: PayoutsNew, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, Self::Error>; async fn find_payout_by_merchant_id_payout_id( &self, _merchant_id: &id_type::MerchantId, _payout_id: &id_type::PayoutId, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, Self::Error>; async fn update_payout( &self, _this: &Payouts, _payout: PayoutsUpdate, _payout_attempt: &PayoutAttempt, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, Self::Error>; async fn find_optional_payout_by_merchant_id_payout_id( &self, _merchant_id: &id_type::MerchantId, _payout_id: &id_type::PayoutId, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Option<Payouts>, Self::Error>; #[cfg(feature = "olap")] async fn filter_payouts_by_constraints( &self, _merchant_id: &id_type::MerchantId, _filters: &PayoutFetchConstraints, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Payouts>, Self::Error>; #[cfg(feature = "olap")] async fn filter_payouts_and_attempts( &self, _merchant_id: &id_type::MerchantId, _filters: &PayoutFetchConstraints, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result< Vec<( Payouts, PayoutAttempt, Option<diesel_models::Customer>, Option<diesel_models::Address>, )>, Self::Error, >; #[cfg(feature = "olap")] async fn filter_payouts_by_time_range_constraints( &self, _merchant_id: &id_type::MerchantId, _time_range: &common_utils::types::TimeRange, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Payouts>, Self::Error>; #[cfg(feature = "olap")] #[allow(clippy::too_many_arguments)] async fn get_total_count_of_filtered_payouts( &self, _merchant_id: &id_type::MerchantId, _active_payout_ids: &[id_type::PayoutId], _connector: Option<Vec<api_models::enums::PayoutConnectors>>, _currency: Option<Vec<storage_enums::Currency>>, _status: Option<Vec<storage_enums::PayoutStatus>>, _payout_method: Option<Vec<storage_enums::PayoutType>>, ) -> error_stack::Result<i64, Self::Error>; #[cfg(feature = "olap")] async fn filter_active_payout_ids_by_constraints( &self, _merchant_id: &id_type::MerchantId, _constraints: &PayoutFetchConstraints, ) -> error_stack::Result<Vec<id_type::PayoutId>, Self::Error>; #[cfg(feature = "olap")] async fn get_payout_intent_status_with_count( &self, merchant_id: &id_type::MerchantId, profile_id_list: Option<Vec<id_type::ProfileId>>, constraints: &common_utils::types::TimeRange, ) -> error_stack::Result<Vec<(common_enums::PayoutStatus, i64)>, Self::Error>; } #[derive(Clone, Debug, Eq, PartialEq)] pub struct Payouts { pub payout_id: id_type::PayoutId, pub merchant_id: id_type::MerchantId, pub customer_id: Option<id_type::CustomerId>, pub address_id: Option<String>, pub payout_type: Option<storage_enums::PayoutType>, pub payout_method_id: Option<String>, pub amount: MinorUnit, pub destination_currency: storage_enums::Currency, pub source_currency: storage_enums::Currency, pub description: Option<String>, pub recurring: bool, pub auto_fulfill: bool, pub return_url: Option<String>, pub entity_type: storage_enums::PayoutEntityType, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub attempt_count: i16, pub profile_id: id_type::ProfileId, pub status: storage_enums::PayoutStatus, pub confirm: Option<bool>, pub payout_link_id: Option<String>, pub client_secret: Option<String>, pub priority: Option<storage_enums::PayoutSendPriority>, pub organization_id: Option<id_type::OrganizationId>, } #[derive(Clone, Debug, Eq, PartialEq)] pub struct PayoutsNew { pub payout_id: id_type::PayoutId, pub merchant_id: id_type::MerchantId, pub customer_id: Option<id_type::CustomerId>, pub address_id: Option<String>, pub payout_type: Option<storage_enums::PayoutType>, pub payout_method_id: Option<String>, pub amount: MinorUnit, pub destination_currency: storage_enums::Currency, pub source_currency: storage_enums::Currency, pub description: Option<String>, pub recurring: bool, pub auto_fulfill: bool, pub return_url: Option<String>, pub entity_type: storage_enums::PayoutEntityType, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub attempt_count: i16, pub profile_id: id_type::ProfileId, pub status: storage_enums::PayoutStatus, pub confirm: Option<bool>, pub payout_link_id: Option<String>, pub client_secret: Option<String>, pub priority: Option<storage_enums::PayoutSendPriority>, pub organization_id: Option<id_type::OrganizationId>, } #[derive(Debug, Serialize, Deserialize)] pub enum PayoutsUpdate { Update { amount: MinorUnit, destination_currency: storage_enums::Currency, source_currency: storage_enums::Currency, description: Option<String>, recurring: bool, auto_fulfill: bool, return_url: Option<String>, entity_type: storage_enums::PayoutEntityType, metadata: Option<pii::SecretSerdeValue>, profile_id: Option<id_type::ProfileId>, status: Option<storage_enums::PayoutStatus>, confirm: Option<bool>, payout_type: Option<storage_enums::PayoutType>, address_id: Option<String>, customer_id: Option<id_type::CustomerId>, }, PayoutMethodIdUpdate { payout_method_id: String, }, RecurringUpdate { recurring: bool, }, AttemptCountUpdate { attempt_count: i16, }, StatusUpdate { status: storage_enums::PayoutStatus, }, ManualUpdate { status: Option<storage_enums::PayoutStatus>, }, } #[derive(Clone, Debug, Default)] pub struct PayoutsUpdateInternal { pub amount: Option<MinorUnit>, pub destination_currency: Option<storage_enums::Currency>, pub source_currency: Option<storage_enums::Currency>, pub description: Option<String>, pub recurring: Option<bool>, pub auto_fulfill: Option<bool>, pub return_url: Option<String>, pub entity_type: Option<storage_enums::PayoutEntityType>, pub metadata: Option<pii::SecretSerdeValue>, pub payout_method_id: Option<String>, pub profile_id: Option<id_type::ProfileId>, pub status: Option<storage_enums::PayoutStatus>, pub attempt_count: Option<i16>, pub confirm: Option<bool>, pub payout_type: Option<common_enums::PayoutType>, pub address_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, } impl From<PayoutsUpdate> for PayoutsUpdateInternal { fn from(payout_update: PayoutsUpdate) -> Self { match payout_update { PayoutsUpdate::Update { amount, destination_currency, source_currency, description, recurring, auto_fulfill, return_url, entity_type, metadata, profile_id, status, confirm, payout_type, address_id, customer_id, } => Self { amount: Some(amount), destination_currency: Some(destination_currency), source_currency: Some(source_currency), description, recurring: Some(recurring), auto_fulfill: Some(auto_fulfill), return_url, entity_type: Some(entity_type), metadata, profile_id, status, confirm, payout_type, address_id, customer_id, ..Default::default() }, PayoutsUpdate::PayoutMethodIdUpdate { payout_method_id } => Self { payout_method_id: Some(payout_method_id), ..Default::default() }, PayoutsUpdate::RecurringUpdate { recurring } => Self { recurring: Some(recurring), ..Default::default() }, PayoutsUpdate::AttemptCountUpdate { attempt_count } => Self { attempt_count: Some(attempt_count), ..Default::default() }, PayoutsUpdate::StatusUpdate { status } => Self { status: Some(status), ..Default::default() }, PayoutsUpdate::ManualUpdate { status } => Self { status, ..Default::default() }, } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_response_types/fraud_check.rs
crates/hyperswitch_domain_models/src/router_response_types/fraud_check.rs
use serde::Serialize; use crate::router_response_types::ResponseId; #[derive(Debug, Clone, Serialize)] #[serde(untagged)] pub enum FraudCheckResponseData { TransactionResponse { resource_id: ResponseId, status: diesel_models::enums::FraudCheckStatus, connector_metadata: Option<serde_json::Value>, reason: Option<serde_json::Value>, score: Option<i32>, }, FulfillmentResponse { order_id: String, shipment_ids: Vec<String>, }, RecordReturnResponse { resource_id: ResponseId, connector_metadata: Option<serde_json::Value>, return_id: Option<String>, }, } impl common_utils::events::ApiEventMetric for FraudCheckResponseData { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::FraudCheck) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_response_types/disputes.rs
crates/hyperswitch_domain_models/src/router_response_types/disputes.rs
#[derive(Default, Clone, Debug)] pub struct AcceptDisputeResponse { pub dispute_status: api_models::enums::DisputeStatus, pub connector_status: 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 DefendDisputeResponse { pub dispute_status: api_models::enums::DisputeStatus, pub connector_status: Option<String>, } pub struct FileInfo { pub file_data: Option<Vec<u8>>, pub provider_file_id: Option<String>, pub file_type: Option<String>, } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub struct DisputeSyncResponse { pub object_reference_id: api_models::webhooks::ObjectReferenceId, pub amount: common_utils::types::StringMinorUnit, pub currency: common_enums::enums::Currency, pub dispute_stage: common_enums::enums::DisputeStage, pub dispute_status: api_models::enums::DisputeStatus, pub connector_status: String, pub connector_dispute_id: String, pub connector_reason: Option<String>, pub connector_reason_code: Option<String>, pub challenge_required_by: Option<time::PrimitiveDateTime>, pub created_at: Option<time::PrimitiveDateTime>, pub updated_at: Option<time::PrimitiveDateTime>, } pub type FetchDisputesResponse = Vec<DisputeSyncResponse>;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs
crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs
use common_utils::types::MinorUnit; use time::PrimitiveDateTime; #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct BillingConnectorPaymentsSyncResponse { /// transaction amount against invoice, accepted in minor unit. pub amount: MinorUnit, /// currency of the transaction pub currency: common_enums::enums::Currency, /// merchant reference id at billing connector. ex: invoice_id pub merchant_reference_id: common_utils::id_type::PaymentReferenceId, /// transaction id reference at payment connector pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, /// error code sent by billing connector. pub error_code: Option<String>, /// error message sent by billing connector. pub error_message: Option<String>, /// mandate token at payment processor end. pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. pub connector_customer_id: String, /// Payment gateway identifier id at billing processor. pub connector_account_reference_id: String, /// timestamp at which transaction has been created at billing connector pub transaction_created_at: Option<PrimitiveDateTime>, /// transaction status at billing connector equivalent to payment attempt status. pub status: common_enums::enums::AttemptStatus, /// payment method of payment attempt. pub payment_method_type: common_enums::enums::PaymentMethod, /// payment method sub type of the payment attempt. pub payment_method_sub_type: common_enums::enums::PaymentMethodType, /// stripe specific id used to validate duplicate attempts. pub charge_id: Option<String>, /// card information pub card_info: api_models::payments::AdditionalCardInfo, } #[derive(Debug, Clone)] pub struct InvoiceRecordBackResponse { pub merchant_reference_id: common_utils::id_type::PaymentReferenceId, } #[derive(Debug, Clone)] pub struct BillingConnectorInvoiceSyncResponse { /// transaction amount against invoice, accepted in minor unit. pub amount: MinorUnit, /// currency of the transaction pub currency: common_enums::enums::Currency, /// merchant reference id at billing connector. ex: invoice_id pub merchant_reference_id: common_utils::id_type::PaymentReferenceId, /// No of attempts made against an invoice pub retry_count: Option<u16>, /// Billing Address of the customer for Invoice pub billing_address: Option<api_models::payments::Address>, /// creation time of the invoice pub created_at: Option<PrimitiveDateTime>, /// Ending time of Invoice pub ends_at: Option<PrimitiveDateTime>, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs
crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs
use common_enums::Currency; use common_utils::{id_type, types::MinorUnit}; use time::PrimitiveDateTime; #[derive(Debug, Clone)] pub struct SubscriptionCreateResponse { pub subscription_id: id_type::SubscriptionId, pub status: SubscriptionStatus, pub customer_id: id_type::CustomerId, pub currency_code: Currency, pub total_amount: MinorUnit, pub next_billing_at: Option<PrimitiveDateTime>, pub created_at: Option<PrimitiveDateTime>, pub invoice_details: Option<SubscriptionInvoiceData>, } #[derive(Debug, Clone, serde::Serialize)] pub struct SubscriptionInvoiceData { pub id: id_type::InvoiceId, pub total: MinorUnit, pub currency_code: Currency, pub status: Option<common_enums::connector_enums::InvoiceStatus>, pub billing_address: Option<api_models::payments::Address>, } #[derive(Debug, Clone, PartialEq, Eq, Copy)] pub enum SubscriptionStatus { Pending, Trial, Active, Paused, Unpaid, Onetime, Cancelled, Failed, Created, } impl From<SubscriptionStatus> for common_enums::SubscriptionStatus { fn from(status: SubscriptionStatus) -> Self { match status { SubscriptionStatus::Pending => Self::Pending, SubscriptionStatus::Trial => Self::Trial, SubscriptionStatus::Active => Self::Active, SubscriptionStatus::Paused => Self::Paused, SubscriptionStatus::Unpaid => Self::Unpaid, SubscriptionStatus::Onetime => Self::Onetime, SubscriptionStatus::Cancelled => Self::Cancelled, SubscriptionStatus::Failed => Self::Failed, SubscriptionStatus::Created => Self::Created, } } } #[derive(Debug, Clone)] pub struct GetSubscriptionItemsResponse { pub list: Vec<SubscriptionItems>, } #[derive(Debug, Clone)] pub struct SubscriptionItems { pub subscription_provider_item_id: String, pub name: String, pub description: Option<String>, } #[derive(Debug, Clone)] pub struct GetSubscriptionItemPricesResponse { pub list: Vec<SubscriptionItemPrices>, } #[derive(Debug, Clone)] pub struct SubscriptionPauseResponse { pub subscription_id: id_type::SubscriptionId, pub status: SubscriptionStatus, pub paused_at: Option<PrimitiveDateTime>, } #[derive(Debug, Clone)] pub struct SubscriptionResumeResponse { pub subscription_id: id_type::SubscriptionId, pub status: SubscriptionStatus, pub next_billing_at: Option<PrimitiveDateTime>, } #[derive(Debug, Clone)] pub struct SubscriptionCancelResponse { pub subscription_id: id_type::SubscriptionId, pub status: SubscriptionStatus, pub cancelled_at: Option<PrimitiveDateTime>, } #[derive(Debug, Clone)] pub struct SubscriptionItemPrices { pub price_id: String, pub item_id: Option<String>, pub amount: MinorUnit, pub currency: Currency, pub interval: PeriodUnit, pub interval_count: i64, pub trial_period: Option<i64>, pub trial_period_unit: Option<PeriodUnit>, } impl From<SubscriptionItemPrices> for api_models::subscription::SubscriptionItemPrices { fn from(item: SubscriptionItemPrices) -> Self { Self { price_id: item.price_id, item_id: item.item_id, amount: item.amount, currency: item.currency, interval: item.interval.into(), interval_count: item.interval_count, trial_period: item.trial_period, trial_period_unit: item.trial_period_unit.map(Into::into), } } } #[derive(Debug, Clone)] pub enum PeriodUnit { Day, Week, Month, Year, } impl From<PeriodUnit> for api_models::subscription::PeriodUnit { fn from(unit: PeriodUnit) -> Self { match unit { PeriodUnit::Day => Self::Day, PeriodUnit::Week => Self::Week, PeriodUnit::Month => Self::Month, PeriodUnit::Year => Self::Year, } } } #[derive(Debug, Clone)] pub struct GetSubscriptionEstimateResponse { pub sub_total: MinorUnit, pub total: MinorUnit, pub credits_applied: Option<MinorUnit>, pub amount_paid: Option<MinorUnit>, pub amount_due: Option<MinorUnit>, pub currency: Currency, pub next_billing_at: Option<PrimitiveDateTime>, pub line_items: Vec<SubscriptionLineItem>, pub customer_id: Option<id_type::CustomerId>, } impl From<GetSubscriptionEstimateResponse> for api_models::subscription::EstimateSubscriptionResponse { fn from(value: GetSubscriptionEstimateResponse) -> Self { Self { amount: value.total, currency: value.currency, plan_id: None, item_price_id: None, coupon_code: None, customer_id: value.customer_id, line_items: value .line_items .into_iter() .map(api_models::subscription::SubscriptionLineItem::from) .collect(), } } } #[derive(Debug, Clone)] pub struct SubscriptionLineItem { pub item_id: String, pub item_type: String, pub description: String, pub amount: MinorUnit, pub currency: Currency, pub unit_amount: Option<MinorUnit>, pub quantity: i64, pub pricing_model: Option<String>, } impl From<SubscriptionLineItem> for api_models::subscription::SubscriptionLineItem { fn from(value: SubscriptionLineItem) -> Self { Self { item_id: value.item_id, description: value.description, item_type: value.item_type, amount: value.amount, currency: value.currency, quantity: value.quantity, } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
crates/hyperswitch_domain_models/src/errors/api_error_response.rs
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, } // CE Connector Error Errors originating from connector's end // HE Hyperswitch Error Errors originating from Hyperswitch's end // IR Invalid Request Error Error caused due to invalid fields and values in API request // WE Webhook Error Errors related to Webhooks #[derive(Debug, Clone, router_derive::ApiError)] #[error(error_type_enum = ErrorType)] pub enum ApiErrorResponse { #[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::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::LockTimeout, code = "HE_00", message = "Resource is busy. Please try again later.")] ResourceBusy, #[error(error_type = ErrorType::ServerNotAvailable, code = "HE_00", message = "Something went wrong")] InternalServerError, #[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::ValidationError, code = "HE_00", message = "Failed to convert currency to minor unit")] CurrencyConversionFailed, #[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: common_utils::id_type::PaymentId, }, #[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: common_utils::id_type::PayoutId, }, #[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 = "Payment Link does not exist in our records")] PaymentLinkNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Customer does not exist in our records")] CustomerNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_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")] ProfileNotFound { id: String }, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Profile acquirer with id '{profile_acquirer_id}' not found for profile '{profile_id}'.")] ProfileAcquirerNotFound { profile_acquirer_id: String, profile_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::ValidationError, code = "HE_03", message = "File validation failed")] FileValidationFailed { reason: String }, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Dispute status validation failed")] DisputeStatusValidationFailed { 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::ProcessingError, code = "HE_05", message = "Missing tenant id")] MissingTenantId, #[error(error_type = ErrorType::ProcessingError, code = "HE_05", message = "Invalid tenant id: {tenant_id}")] InvalidTenant { tenant_id: String }, #[error(error_type = ErrorType::ValidationError, code = "HE_06", message = "Failed to convert amount to {amount_type} type")] AmountConversionFailed { amount_type: &'static str }, #[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::ProcessingError, code = "IR_24", message = "Invalid {wallet_name} wallet token" )] InvalidWalletToken { wallet_name: String }, #[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, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_28", message = "{message}")] CurrencyNotSupported { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_29", message = "{message}")] UnprocessableEntity { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_30", message = "Merchant connector account is configured with invalid {config}")] InvalidConnectorConfiguration { config: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_31", message = "Card with the provided iin does not exist")] InvalidCardIin, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_32", message = "The provided card IIN length is invalid, please provide an iin with 6 or 8 digits")] InvalidCardIinLength, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_33", message = "File not found / valid in the request")] MissingFile, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_34", message = "Dispute id not found in the request")] MissingDisputeId, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_35", message = "File purpose not found in the request or is invalid")] MissingFilePurpose, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_36", message = "File content type not found / valid")] MissingFileContentType, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_37", message = "{message}")] GenericNotFoundError { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_38", message = "{message}")] GenericDuplicateError { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_39", message = "required payment method is not configured or configured incorrectly for all configured connectors")] IncorrectPaymentMethodConfiguration, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_40", message = "{message}")] LinkConfigurationError { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_41", message = "Payout validation failed")] PayoutFailed { data: Option<serde_json::Value> }, #[error( error_type = ErrorType::InvalidRequestError, code = "IR_42", message = "Cookies are not found in the request" )] CookieNotFound, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_43", message = "API does not support platform account operation")] PlatformAccountAuthNotSupported, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_44", message = "Invalid platform account operation")] InvalidPlatformOperation, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_45", message = "External vault failed during processing with connector")] ExternalVaultFailed, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_46", message = "Field {fields} doesn't match with the ones used during mandate creation")] MandatePaymentDataMismatch { fields: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_47", message = "Connector '{connector}' rejected field '{field_name}': length {received_length} exceeds maximum of {max_length}")] MaxFieldLengthViolated { connector: String, field_name: String, max_length: usize, received_length: usize, }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_48", message = "The Status token for connector costumer id {resource} is locked by different PaymentIntent ID")] InvalidPaymentIdProvided { resource: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_49", message = "API does not support connected account operation")] ConnectedAccountAuthNotSupported, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_50", message = "Invalid connected account operation")] InvalidConnectedOperation, #[error( error_type = ErrorType::InvalidRequestError, code = "IR_51", message = "Access forbidden, invalid Basic authentication credentials" )] InvalidBasicAuth, #[error(error_type = ErrorType::InvalidRequestError, code = "WE_01", message = "Failed to authenticate the webhook")] WebhookAuthenticationFailed, #[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::ObjectNotFound, code = "WE_04", message = "Webhook resource not found")] WebhookResourceNotFound, #[error(error_type = ErrorType::InvalidRequestError, code = "WE_05", message = "Unable to process the webhook body")] WebhookUnprocessableEntity, #[error(error_type = ErrorType::InvalidRequestError, code = "WE_06", message = "Merchant Secret set my merchant for webhook source verification is invalid")] WebhookInvalidMerchantSecret, #[error(error_type = ErrorType::ServerNotAvailable, code = "IE", message = "{reason} as data mismatched for {field_names}")] IntegrityCheckFailed { reason: String, field_names: String, connector_transaction_id: Option<String>, }, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Tokenization record not found for the given token_id {id}")] TokenizationRecordNotFound { id: String }, #[error(error_type = ErrorType::ConnectorError, code = "CE_00", message = "Subscription operation: {operation} failed with connector")] SubscriptionError { operation: String }, } #[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::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(), ..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::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::DisputeFailed { data } => { AER::BadRequest(ApiError::new("CE", 8, "Dispute operation failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()}))) } Self::ResourceBusy => { AER::Unprocessable(ApiError::new("HE", 0, "There was an issue processing the webhook body", None)) } Self::CurrencyConversionFailed => { AER::Unprocessable(ApiError::new("HE", 0, "Failed to convert currency to minor unit", None)) } Self::InternalServerError => { AER::InternalServerError(ApiError::new("HE", 0, "Something went wrong", None)) }, Self::HealthCheckError { message,component } => { AER::InternalServerError(ApiError::new("HE",0,format!("{component} health check failed with error: {message}"),None)) }, 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::DuplicateConfig => { AER::BadRequest(ApiError::new("HE", 1, "The config with the specified key already exists in our records", None)) } Self::RefundNotFound => { AER::NotFound(ApiError::new("HE", 2, "Refund does not exist in our records.", None)) } Self::PaymentLinkNotFound => { AER::NotFound(ApiError::new("HE", 2, "Payment Link 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::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::ProfileNotFound { id } => { AER::NotFound(ApiError::new("HE", 2, format!("Business profile with the given id {id} does not exist"), None)) } Self::ProfileAcquirerNotFound { profile_acquirer_id, profile_id } => { AER::NotFound(ApiError::new("HE", 2, format!("Profile acquirer with id '{profile_acquirer_id}' not found for profile '{profile_id}'."), None)) } Self::PollNotFound { .. } => { AER::NotFound(ApiError::new("HE", 2, "Poll does not exist in our records", 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::AuthenticationNotFound { .. } => { AER::NotFound(ApiError::new("HE", 2, "Authentication does not exist in our records", None)) }, Self::MandateUpdateFailed => { AER::InternalServerError(ApiError::new("HE", 2, "Mandate update failed", None)) }, Self::ApiKeyNotFound => { AER::NotFound(ApiError::new("HE", 2, "API Key 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::MandateSerializationFailed | Self::MandateDeserializationFailed => { AER::InternalServerError(ApiError::new("HE", 3, "Something went wrong", 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::MerchantConnectorAccountDisabled => { AER::BadRequest(ApiError::new("HE", 3, "The selected merchant connector account is disabled", None)) } Self::PaymentBlockedError { message, reason, .. } => AER::DomainError(ApiError::new("HE", 3, message, Some(Extra { reason: Some(reason.clone()), ..Default::default() }))), Self::FileValidationFailed { reason } => { AER::BadRequest(ApiError::new("HE", 3, format!("File validation failed {reason}"), None)) } Self::DisputeStatusValidationFailed { .. } => { AER::BadRequest(ApiError::new("HE", 3, "Dispute status validation failed", None)) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs
crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs
use common_utils::{ events::{ApiEventMetric, ApiEventsType}, pii::Email, }; use diesel_models::types::OrderDetailsWithAmount; 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<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<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<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: common_utils::id_type::PaymentId, ///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) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_request_types/revenue_recovery.rs
crates/hyperswitch_domain_models/src/router_request_types/revenue_recovery.rs
use common_enums::enums; use crate::connector_endpoints; #[derive(Debug, Clone)] pub struct BillingConnectorPaymentsSyncRequest { /// unique id for making billing connector psync call pub billing_connector_psync_id: String, /// connector params of the connector pub connector_params: connector_endpoints::ConnectorParams, } #[derive(Debug, Clone)] pub struct InvoiceRecordBackRequest { pub merchant_reference_id: common_utils::id_type::PaymentReferenceId, pub amount: common_utils::types::MinorUnit, pub currency: enums::Currency, pub payment_method_type: Option<common_enums::PaymentMethodType>, pub attempt_status: common_enums::AttemptStatus, pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, pub connector_params: connector_endpoints::ConnectorParams, } #[derive(Debug, Clone)] pub struct BillingConnectorInvoiceSyncRequest { /// Invoice id pub billing_connector_invoice_id: String, /// connector params of the connector pub connector_params: connector_endpoints::ConnectorParams, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs
crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs
use api_models::payments::DeviceChannel; use common_enums::MerchantCategoryCode; use common_types::payments::MerchantCountryCode; use common_utils::types::MinorUnit; use masking::Secret; use crate::address::Address; #[derive(Clone, Debug)] pub struct UasPreAuthenticationRequestData { pub service_details: Option<CtpServiceDetails>, pub transaction_details: Option<TransactionDetails>, pub payment_details: Option<PaymentDetails>, pub authentication_info: Option<AuthenticationInfo>, pub merchant_details: Option<MerchantDetails>, pub billing_address: Option<Address>, pub acquirer_bin: Option<String>, pub acquirer_merchant_id: Option<String>, } #[derive(Debug, Clone)] pub struct MerchantDetails { pub merchant_id: Option<String>, pub merchant_name: Option<String>, pub merchant_category_code: Option<MerchantCategoryCode>, pub merchant_country_code: Option<MerchantCountryCode>, pub endpoint_prefix: Option<String>, pub three_ds_requestor_url: Option<String>, pub three_ds_requestor_id: Option<String>, pub three_ds_requestor_name: Option<String>, pub notification_url: Option<url::Url>, } #[derive(Clone, Debug, PartialEq, serde::Serialize)] pub struct AuthenticationInfo { pub authentication_type: Option<String>, pub authentication_reasons: Option<Vec<String>>, pub consent_received: bool, pub is_authenticated: bool, pub locale: Option<String>, pub supported_card_brands: Option<String>, pub encrypted_payload: Option<Secret<String>>, } #[derive(Clone, Debug)] pub struct UasAuthenticationRequestData { pub browser_details: Option<super::BrowserInformation>, pub transaction_details: TransactionDetails, pub pre_authentication_data: super::authentication::PreAuthenticationData, pub return_url: Option<String>, pub sdk_information: Option<api_models::payments::SdkInformation>, pub email: Option<common_utils::pii::Email>, pub threeds_method_comp_ind: api_models::payments::ThreeDsCompletionIndicator, pub webhook_url: String, } #[derive(Clone, Debug, serde::Serialize)] pub struct CtpServiceDetails { pub service_session_ids: Option<ServiceSessionIds>, pub payment_details: Option<PaymentDetails>, } #[derive(Debug, Clone, serde::Serialize)] pub struct PaymentDetails { pub pan: cards::CardNumber, pub digital_card_id: Option<String>, pub payment_data_type: Option<common_enums::PaymentMethodType>, pub encrypted_src_card_details: Option<String>, pub card_expiry_month: Secret<String>, pub card_expiry_year: Secret<String>, pub cardholder_name: Option<Secret<String>>, pub card_token_number: Option<Secret<String>>, pub account_type: Option<common_enums::PaymentMethodType>, pub card_cvc: Option<Secret<String>>, } #[derive(Clone, serde::Deserialize, Debug, serde::Serialize)] pub struct ServiceSessionIds { pub correlation_id: Option<String>, pub merchant_transaction_id: Option<String>, pub x_src_flow_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone)] pub struct TransactionDetails { pub amount: Option<MinorUnit>, pub currency: Option<common_enums::Currency>, pub device_channel: Option<DeviceChannel>, pub message_category: Option<super::authentication::MessageCategory>, pub force_3ds_challenge: Option<bool>, pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, } #[derive(Clone, Debug)] pub struct UasPostAuthenticationRequestData { pub threeds_server_transaction_id: Option<String>, } #[derive(Debug, Clone)] pub enum UasAuthenticationResponseData { PreAuthentication { authentication_details: PreAuthenticationDetails, }, Authentication { authentication_details: AuthenticationDetails, }, PostAuthentication { authentication_details: PostAuthenticationDetails, }, Confirmation {}, } #[derive(Debug, Clone, serde::Serialize)] pub struct PreAuthenticationDetails { pub threeds_server_transaction_id: Option<String>, pub maximum_supported_3ds_version: Option<common_utils::types::SemanticVersion>, pub connector_authentication_id: Option<String>, pub three_ds_method_data: Option<String>, pub three_ds_method_url: Option<String>, pub message_version: Option<common_utils::types::SemanticVersion>, pub connector_metadata: Option<serde_json::Value>, pub directory_server_id: Option<String>, pub scheme_id: Option<String>, } #[derive(Debug, Clone)] pub struct AuthenticationDetails { pub authn_flow_type: super::authentication::AuthNFlowType, pub authentication_value: Option<Secret<String>>, pub trans_status: common_enums::TransactionStatus, pub connector_metadata: Option<serde_json::Value>, pub ds_trans_id: Option<String>, pub eci: Option<String>, pub challenge_code: Option<String>, pub challenge_cancel: Option<String>, pub challenge_code_reason: Option<String>, pub message_extension: Option<common_utils::pii::SecretSerdeValue>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] pub struct PostAuthenticationDetails { pub eci: Option<String>, pub token_details: Option<TokenDetails>, pub dynamic_data_details: Option<DynamicData>, pub trans_status: Option<common_enums::TransactionStatus>, pub challenge_cancel: Option<String>, pub challenge_code_reason: Option<String>, pub raw_card_details: Option<RawCardDetails>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] pub struct RawCardDetails { pub pan: cards::CardNumber, pub expiration_month: Secret<String>, pub expiration_year: Secret<String>, pub card_security_code: Option<Secret<String>>, pub payment_account_reference: Option<String>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] pub struct TokenDetails { pub payment_token: cards::NetworkToken, pub payment_account_reference: String, pub token_expiration_month: Secret<String>, pub token_expiration_year: Secret<String>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] pub struct DynamicData { pub dynamic_data_value: Option<Secret<String>>, pub dynamic_data_type: Option<String>, pub ds_trans_id: Option<String>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] pub struct UasConfirmationRequestData { pub x_src_flow_id: Option<String>, pub transaction_amount: MinorUnit, pub transaction_currency: common_enums::Currency, // Type of event associated with the checkout. Valid values are: - 01 - Authorise - 02 - Capture - 03 - Refund - 04 - Cancel - 05 - Fraud - 06 - Chargeback - 07 - Other pub checkout_event_type: Option<String>, pub checkout_event_status: Option<String>, pub confirmation_status: Option<String>, pub confirmation_reason: Option<String>, pub confirmation_timestamp: Option<String>, // Authorisation code associated with an approved transaction. pub network_authorization_code: Option<String>, // The unique authorisation related tracing value assigned by a Payment Network and provided in an authorisation response. Required only when checkoutEventType=01. If checkoutEventType=01 and the value of networkTransactionIdentifier is unknown, please pass UNAVLB pub network_transaction_identifier: Option<String>, pub correlation_id: Option<String>, pub merchant_transaction_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ThreeDsMetaData { pub merchant_category_code: Option<MerchantCategoryCode>, pub merchant_country_code: Option<MerchantCountryCode>, pub merchant_name: Option<String>, pub endpoint_prefix: Option<String>, pub three_ds_requestor_name: Option<String>, pub three_ds_requestor_id: Option<String>, pub merchant_configuration_id: Option<String>, } #[cfg(feature = "v1")] impl From<PostAuthenticationDetails> for Option<api_models::authentication::AuthenticationPaymentMethodDataResponse> { fn from(item: PostAuthenticationDetails) -> Self { match (item.raw_card_details, item.token_details) { (Some(card_data), _) => Some( api_models::authentication::AuthenticationPaymentMethodDataResponse::CardData { card_expiry_year: Some(card_data.expiration_year), card_expiry_month: Some(card_data.expiration_month), }, ), (None, Some(network_token_data)) => { Some( api_models::authentication::AuthenticationPaymentMethodDataResponse::NetworkTokenData { network_token_expiry_year: Some(network_token_data.token_expiration_year), network_token_expiry_month: Some(network_token_data.token_expiration_month), }, ) } (None, None) => None, } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs
crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs
use api_models::{payments::Address, subscription}; use common_utils::id_type; use crate::connector_endpoints; #[derive(Debug, Clone)] pub struct SubscriptionItem { pub item_price_id: String, pub quantity: Option<u32>, } #[derive(Debug, Clone)] pub struct SubscriptionCreateRequest { pub customer_id: id_type::CustomerId, pub subscription_id: id_type::SubscriptionId, pub subscription_items: Vec<SubscriptionItem>, pub billing_address: Address, pub auto_collection: SubscriptionAutoCollection, pub connector_params: connector_endpoints::ConnectorParams, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum SubscriptionAutoCollection { On, Off, } #[derive(Debug, Clone)] pub struct GetSubscriptionItemsRequest { pub limit: Option<u32>, pub offset: Option<u32>, pub item_type: subscription::SubscriptionItemType, } impl GetSubscriptionItemsRequest { pub fn new( limit: Option<u32>, offset: Option<u32>, item_type: subscription::SubscriptionItemType, ) -> Self { Self { limit, offset, item_type, } } } impl Default for GetSubscriptionItemsRequest { fn default() -> Self { Self { limit: Some(10), offset: Some(0), item_type: subscription::SubscriptionItemType::Plan, } } } #[derive(Debug, Clone)] pub struct GetSubscriptionItemPricesRequest { pub item_price_id: String, } #[derive(Debug, Clone)] pub struct SubscriptionPauseRequest { pub subscription_id: id_type::SubscriptionId, pub pause_option: Option<subscription::PauseOption>, pub pause_date: Option<time::PrimitiveDateTime>, } #[derive(Debug, Clone)] pub struct SubscriptionResumeRequest { pub subscription_id: id_type::SubscriptionId, pub resume_option: Option<subscription::ResumeOption>, pub resume_date: Option<time::PrimitiveDateTime>, pub charges_handling: Option<subscription::ChargesHandling>, pub unpaid_invoices_handling: Option<subscription::UnpaidInvoicesHandling>, } #[derive(Debug, Clone)] pub struct SubscriptionCancelRequest { pub subscription_id: id_type::SubscriptionId, pub cancel_option: Option<subscription::CancelOption>, pub cancel_date: Option<time::PrimitiveDateTime>, pub unbilled_charges_option: Option<subscription::UnbilledChargesOption>, pub credit_option_for_current_term_charges: Option<subscription::CreditOption>, pub account_receivables_handling: Option<subscription::AccountReceivablesHandling>, pub refundable_credits_handling: Option<subscription::RefundableCreditsHandling>, pub cancel_reason_code: Option<String>, } #[derive(Debug, Clone)] pub struct GetSubscriptionEstimateRequest { pub price_id: String, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs
crates/hyperswitch_domain_models/src/router_request_types/authentication.rs
use common_utils::{ext_traits::OptionExt, pii::Email}; use error_stack::{Report, ResultExt}; use serde::{Deserialize, Serialize}; use crate::{ address, authentication, errors::api_error_response::ApiErrorResponse, payment_method_data::{Card, PaymentMethodData}, router_request_types::BrowserInformation, }; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ChallengeParams { pub acs_url: Option<url::Url>, pub challenge_request: Option<String>, pub challenge_request_key: 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_challenge_request_key(&self) -> Option<String> { if let Self::Challenge(challenge_params) = self { challenge_params.challenge_request_key.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(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct MessageExtensionAttribute { pub id: String, pub name: String, pub criticality_indicator: bool, pub data: serde_json::Value, } #[derive(Clone, Default, Debug)] pub struct PreAuthNRequestData { // card data pub card: Card, } #[derive(Clone, Debug)] pub struct ConnectorAuthenticationRequestData { pub payment_method_data: PaymentMethodData, pub billing_address: address::Address, pub shipping_address: Option<address::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, pub force_3ds_challenge: bool, } #[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 acquirer_country_code: 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(), acquirer_country_code: authentication.acquirer_country_code.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, pub acquirer_country_code: Option<String>, } #[derive(Clone, Debug, Deserialize)] pub struct ExternalThreeDSConnectorMetadata { pub pull_mechanism_for_external_3ds_enabled: Option<bool>, } #[derive(Clone, Debug)] pub struct AuthenticationStore { pub cavv: Option<masking::Secret<String>>, pub authentication: authentication::Authentication, } #[derive(Clone, Debug)] pub struct AuthenticationInfo { pub billing_address: Option<address::Address>, pub shipping_address: Option<address::Address>, pub browser_info: Option<BrowserInformation>, pub email: Option<Email>, pub device_details: Option<api_models::payments::DeviceDetails>, pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_enums::CountryAlpha2>, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
use common_utils::{pii, types::MinorUnit}; use crate::{ payment_address::PaymentAddress, payment_method_data::ApplePayFlow, router_data::{ AccessToken, ConnectorResponseData, PaymentMethodBalance, PaymentMethodToken, RecurringMandatePaymentData, }, }; #[derive(Debug, Clone)] pub struct PaymentFlowData { pub merchant_id: common_utils::id_type::MerchantId, pub customer_id: Option<common_utils::id_type::CustomerId>, pub connector_customer: Option<String>, pub connector: String, pub payment_id: String, pub attempt_id: String, pub status: common_enums::AttemptStatus, pub payment_method: common_enums::PaymentMethod, pub description: Option<String>, pub address: PaymentAddress, pub auth_type: common_enums::AuthenticationType, pub connector_meta_data: Option<pii::SecretSerdeValue>, pub amount_captured: Option<i64>, // minor amount for amount framework pub minor_amount_captured: Option<MinorUnit>, pub access_token: Option<AccessToken>, pub session_token: Option<String>, pub reference_id: Option<String>, pub payment_method_token: Option<PaymentMethodToken>, pub recurring_mandate_payment_data: Option<RecurringMandatePaymentData>, pub preprocessing_id: Option<String>, /// This is the balance amount for gift cards or voucher pub payment_method_balance: Option<PaymentMethodBalance>, ///for switching between two different versions of the same connector pub connector_api_version: Option<String>, /// Contains a reference ID that should be sent in the connector request pub connector_request_reference_id: String, pub test_mode: Option<bool>, pub connector_http_status_code: Option<u16>, pub external_latency: Option<u128>, /// Contains apple pay flow type simplified or manual pub apple_pay_flow: Option<ApplePayFlow>, /// This field is used to store various data regarding the response from connector pub connector_response: Option<ConnectorResponseData>, pub payment_method_status: Option<common_enums::PaymentMethodStatus>, } #[derive(Debug, Clone)] pub struct RefundFlowData { pub merchant_id: common_utils::id_type::MerchantId, pub customer_id: Option<common_utils::id_type::CustomerId>, pub payment_id: String, pub attempt_id: String, pub status: common_enums::AttemptStatus, pub payment_method: common_enums::PaymentMethod, pub connector_meta_data: Option<pii::SecretSerdeValue>, pub amount_captured: Option<i64>, // minor amount for amount framework pub minor_amount_captured: Option<MinorUnit>, /// Contains a reference ID that should be sent in the connector request pub connector_request_reference_id: String, pub refund_id: String, } #[cfg(feature = "payouts")] #[derive(Debug, Clone)] pub struct PayoutFlowData { pub merchant_id: common_utils::id_type::MerchantId, pub customer_id: Option<common_utils::id_type::CustomerId>, pub connector_customer: Option<String>, pub address: PaymentAddress, pub connector_meta_data: Option<pii::SecretSerdeValue>, pub connector_wallets_details: Option<pii::SecretSerdeValue>, /// Contains a reference ID that should be sent in the connector request pub connector_request_reference_id: String, pub payout_method_data: Option<api_models::payouts::PayoutMethodData>, pub quote_id: Option<String>, } #[cfg(feature = "frm")] #[derive(Debug, Clone)] pub struct FrmFlowData { pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: String, pub attempt_id: String, pub payment_method: common_enums::enums::PaymentMethod, pub connector_request_reference_id: String, pub auth_type: common_enums::enums::AuthenticationType, pub connector_wallets_details: Option<pii::SecretSerdeValue>, pub connector_meta_data: Option<pii::SecretSerdeValue>, pub amount_captured: Option<i64>, // minor amount for amount framework pub minor_amount_captured: Option<MinorUnit>, } #[derive(Debug, Clone)] pub struct ExternalAuthenticationFlowData { pub merchant_id: common_utils::id_type::MerchantId, pub connector_meta_data: Option<pii::SecretSerdeValue>, pub address: PaymentAddress, } #[derive(Debug, Clone)] pub struct DisputesFlowData { pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: String, pub attempt_id: String, pub payment_method: common_enums::enums::PaymentMethod, pub connector_meta_data: Option<pii::SecretSerdeValue>, pub amount_captured: Option<i64>, // minor amount for amount framework pub minor_amount_captured: Option<MinorUnit>, /// Contains a reference ID that should be sent in the connector request pub connector_request_reference_id: String, pub dispute_id: String, } #[derive(Debug, Clone)] pub struct MandateRevokeFlowData { pub merchant_id: common_utils::id_type::MerchantId, pub customer_id: common_utils::id_type::CustomerId, pub payment_id: Option<String>, } #[derive(Debug, Clone)] pub struct WebhookSourceVerifyData { pub merchant_id: common_utils::id_type::MerchantId, } #[derive(Debug, Clone)] pub struct AuthenticationTokenFlowData {} #[derive(Debug, Clone)] pub struct AccessTokenFlowData {} #[derive(Debug, Clone)] pub struct FilesFlowData { pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: String, pub attempt_id: String, pub connector_meta_data: Option<pii::SecretSerdeValue>, pub connector_request_reference_id: String, } #[derive(Debug, Clone)] pub struct InvoiceRecordBackData { pub connector_meta_data: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub struct SubscriptionCustomerData { pub connector_meta_data: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub struct SubscriptionCreateData { pub connector_meta_data: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub struct GetSubscriptionItemsData { pub connector_meta_data: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub struct GetSubscriptionItemPricesData { pub connector_meta_data: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub struct GetSubscriptionEstimateData { pub connector_meta_data: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub struct SubscriptionPauseData { pub connector_meta_data: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub struct SubscriptionResumeData { pub connector_meta_data: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub struct SubscriptionCancelData { pub connector_meta_data: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub struct UasFlowData { pub authenticate_by: String, pub source_authentication_id: common_utils::id_type::AuthenticationId, } #[derive(Debug, Clone)] pub struct BillingConnectorPaymentsSyncFlowData; #[derive(Debug, Clone)] pub struct BillingConnectorInvoiceSyncFlowData; #[derive(Debug, Clone)] pub struct VaultConnectorFlowData { pub merchant_id: common_utils::id_type::MerchantId, } #[derive(Debug, Clone)] pub struct GiftCardBalanceCheckFlowData; #[derive(Debug, Clone)] pub struct ExternalVaultProxyFlowData { pub merchant_id: common_utils::id_type::MerchantId, pub customer_id: Option<common_utils::id_type::CustomerId>, pub connector_customer: Option<String>, pub payment_id: String, pub attempt_id: String, pub status: common_enums::AttemptStatus, pub payment_method: common_enums::PaymentMethod, pub description: Option<String>, pub address: PaymentAddress, pub auth_type: common_enums::AuthenticationType, pub connector_meta_data: Option<pii::SecretSerdeValue>, pub amount_captured: Option<i64>, // minor amount for amount framework pub minor_amount_captured: Option<MinorUnit>, pub access_token: Option<AccessToken>, pub session_token: Option<String>, pub reference_id: Option<String>, pub payment_method_token: Option<PaymentMethodToken>, pub recurring_mandate_payment_data: Option<RecurringMandatePaymentData>, pub preprocessing_id: Option<String>, /// This is the balance amount for gift cards or voucher pub payment_method_balance: Option<PaymentMethodBalance>, ///for switching between two different versions of the same connector pub connector_api_version: Option<String>, /// Contains a reference ID that should be sent in the connector request pub connector_request_reference_id: String, pub test_mode: Option<bool>, pub connector_http_status_code: Option<u16>, pub external_latency: Option<u128>, /// Contains apple pay flow type simplified or manual pub apple_pay_flow: Option<ApplePayFlow>, /// This field is used to store various data regarding the response from connector pub connector_response: Option<ConnectorResponseData>, pub payment_method_status: Option<common_enums::PaymentMethodStatus>, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_flow_types/vault.rs
crates/hyperswitch_domain_models/src/router_flow_types/vault.rs
#[derive(Debug, Clone)] pub struct ExternalVaultInsertFlow; #[derive(Debug, Clone)] pub struct ExternalVaultRetrieveFlow; #[derive(Debug, Clone)] pub struct ExternalVaultDeleteFlow; #[derive(Debug, Clone)] pub struct ExternalVaultCreateFlow;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_flow_types/fraud_check.rs
crates/hyperswitch_domain_models/src/router_flow_types/fraud_check.rs
#[derive(Debug, Clone)] pub struct Sale; #[derive(Debug, Clone)] pub struct Checkout; #[derive(Debug, Clone)] pub struct Transaction; #[derive(Debug, Clone)] pub struct Fulfillment; #[derive(Debug, Clone)] pub struct RecordReturn;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_flow_types/refunds.rs
crates/hyperswitch_domain_models/src/router_flow_types/refunds.rs
#[derive(Debug, Clone)] pub struct Execute; #[derive(Debug, Clone)] pub struct RSync;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_flow_types/access_token_auth.rs
crates/hyperswitch_domain_models/src/router_flow_types/access_token_auth.rs
use serde; #[derive(Clone, Debug)] pub struct AccessTokenAuthentication; #[derive(Clone, Debug, serde::Serialize)] pub struct AccessTokenAuth;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_flow_types/revenue_recovery.rs
crates/hyperswitch_domain_models/src/router_flow_types/revenue_recovery.rs
#[derive(Debug, Clone)] pub struct BillingConnectorPaymentsSync; #[derive(Debug, Clone)] pub struct InvoiceRecordBack; #[derive(Debug, Clone)] pub struct BillingConnectorInvoiceSync;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_flow_types/dispute.rs
crates/hyperswitch_domain_models/src/router_flow_types/dispute.rs
#[derive(Debug, Clone)] pub struct Accept; #[derive(Debug, Clone)] pub struct Evidence; #[derive(Debug, Clone)] pub struct Defend; #[derive(Debug, Clone)] pub struct Fetch; #[derive(Debug, Clone)] pub struct Dsync;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_flow_types/unified_authentication_service.rs
crates/hyperswitch_domain_models/src/router_flow_types/unified_authentication_service.rs
#[derive(Debug, Clone)] pub struct PreAuthenticate; #[derive(Debug, Clone)] pub struct PostAuthenticate; #[derive(Debug, Clone)] pub struct AuthenticationConfirmation; #[derive(Debug, Clone)] pub struct Authenticate;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_flow_types/webhooks.rs
crates/hyperswitch_domain_models/src/router_flow_types/webhooks.rs
use serde::Serialize; #[derive(Clone, Debug)] pub struct VerifyWebhookSource; #[derive(Debug, Clone, Serialize)] pub struct ConnectorMandateDetails { pub connector_mandate_id: masking::Secret<String>, } #[derive(Debug, Clone, Serialize)] pub struct ConnectorNetworkTxnId(masking::Secret<String>); impl ConnectorNetworkTxnId { pub fn new(txn_id: masking::Secret<String>) -> Self { Self(txn_id) } pub fn get_id(&self) -> &masking::Secret<String> { &self.0 } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_flow_types/payouts.rs
crates/hyperswitch_domain_models/src/router_flow_types/payouts.rs
#[derive(Debug, Clone)] pub struct PoCancel; #[derive(Debug, Clone)] pub struct PoCreate; #[derive(Debug, Clone)] pub struct PoEligibility; #[derive(Debug, Clone)] pub struct PoFulfill; #[derive(Debug, Clone)] pub struct PoQuote; #[derive(Debug, Clone)] pub struct PoRecipient; #[derive(Debug, Clone)] pub struct PoRecipientAccount; #[derive(Debug, Clone)] pub struct PoSync;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_flow_types/mandate_revoke.rs
crates/hyperswitch_domain_models/src/router_flow_types/mandate_revoke.rs
#[derive(Clone, Debug)] pub struct MandateRevoke;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs
crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs
use common_enums::connector_enums::InvoiceStatus; #[derive(Debug, Clone)] pub struct SubscriptionCreate; #[derive(Debug, Clone)] pub struct SubscriptionPause; #[derive(Debug, Clone)] pub struct SubscriptionResume; #[derive(Debug, Clone)] pub struct SubscriptionCancel; #[derive(Debug, Clone)] pub struct GetSubscriptionItems; #[derive(Debug, Clone)] pub struct GetSubscriptionItemPrices; #[derive(Debug, Clone)] pub struct GetSubscriptionEstimate; /// Generic structure for subscription MIT (Merchant Initiated Transaction) payment data #[derive(Debug, Clone)] pub struct SubscriptionMitPaymentData { pub invoice_id: common_utils::id_type::InvoiceId, pub amount_due: common_utils::types::MinorUnit, pub currency_code: common_enums::enums::Currency, pub status: Option<InvoiceStatus>, pub customer_id: common_utils::id_type::CustomerId, pub subscription_id: common_utils::id_type::SubscriptionId, pub first_invoice: bool, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_flow_types/authentication.rs
crates/hyperswitch_domain_models/src/router_flow_types/authentication.rs
#[derive(Debug, Clone)] pub struct PreAuthentication; #[derive(Debug, Clone)] pub struct PreAuthenticationVersionCall; #[derive(Debug, Clone)] pub struct Authentication; #[derive(Debug, Clone)] pub struct PostAuthentication;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_flow_types/files.rs
crates/hyperswitch_domain_models/src/router_flow_types/files.rs
#[derive(Debug, Clone)] pub struct Retrieve; #[derive(Debug, Clone)] pub struct Upload;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
// Core related api layer. #[derive(Debug, Clone)] pub struct Authorize; #[derive(Debug, Clone)] pub struct AuthorizeSessionToken; #[derive(Debug, Clone)] pub struct CompleteAuthorize; #[derive(Debug, Clone)] pub struct Approve; // Used in gift cards balance check #[derive(Debug, Clone)] pub struct Balance; #[derive(Debug, Clone)] pub struct InitPayment; #[derive(Debug, Clone)] pub struct Capture; #[derive(Debug, Clone)] pub struct PSync; #[derive(Debug, Clone)] pub struct Void; #[derive(Debug, Clone)] pub struct PostCaptureVoid; #[derive(Debug, Clone)] pub struct Reject; #[derive(Debug, Clone)] pub struct Session; #[derive(Debug, Clone)] pub struct PaymentMethodToken; #[derive(Debug, Clone)] pub struct CreateConnectorCustomer; #[derive(Debug, Clone)] pub struct SetupMandate; #[derive(Debug, Clone)] pub struct PreProcessing; #[derive(Debug, Clone)] pub struct IncrementalAuthorization; #[derive(Debug, Clone)] pub struct ExtendAuthorization; #[derive(Debug, Clone)] pub struct PostProcessing; #[derive(Debug, Clone)] pub struct CalculateTax; #[derive(Debug, Clone)] pub struct SdkSessionUpdate; #[derive(Debug, Clone)] pub struct PaymentCreateIntent; #[derive(Debug, Clone)] pub struct PaymentGetIntent; #[derive(Debug, Clone)] pub struct PaymentUpdateIntent; #[derive(Debug, Clone)] pub struct PostSessionTokens; #[derive(Debug, Clone)] pub struct RecordAttempt; #[derive(Debug, Clone)] pub struct UpdateMetadata; #[derive(Debug, Clone)] pub struct CreateOrder; #[derive(Debug, Clone)] pub struct PaymentGetListAttempts; #[derive(Debug, Clone)] pub struct ExternalVaultProxy; #[derive(Debug, Clone)] pub struct GiftCardBalanceCheck;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/cards/src/lib.rs
crates/cards/src/lib.rs
pub mod validate; use std::ops::Deref; use common_utils::{date_time, errors}; use error_stack::report; use masking::{PeekInterface, StrongSecret}; use serde::{de, Deserialize, Serialize}; use time::{Date, Duration, PrimitiveDateTime, Time}; pub use crate::validate::{CardNumber, CardNumberStrategy, CardNumberValidationErr, NetworkToken}; #[derive(Serialize)] pub struct CardSecurityCode(StrongSecret<u16>); impl TryFrom<u16> for CardSecurityCode { type Error = error_stack::Report<errors::ValidationError>; fn try_from(csc: u16) -> Result<Self, Self::Error> { if (0..=9999).contains(&csc) { Ok(Self(StrongSecret::new(csc))) } else { Err(report!(errors::ValidationError::InvalidValue { message: "invalid card security code".to_string() })) } } } impl<'de> Deserialize<'de> for CardSecurityCode { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let csc = u16::deserialize(deserializer)?; csc.try_into().map_err(de::Error::custom) } } #[derive(Clone, Debug, Serialize)] pub struct CardExpirationMonth(StrongSecret<u8>); impl CardExpirationMonth { pub fn two_digits(&self) -> String { format!("{:02}", self.peek()) } } impl TryFrom<u8> for CardExpirationMonth { type Error = error_stack::Report<errors::ValidationError>; fn try_from(month: u8) -> Result<Self, Self::Error> { if (1..=12).contains(&month) { Ok(Self(StrongSecret::new(month))) } else { Err(report!(errors::ValidationError::InvalidValue { message: "invalid card expiration month".to_string() })) } } } impl<'de> Deserialize<'de> for CardExpirationMonth { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let month = u8::deserialize(deserializer)?; month.try_into().map_err(de::Error::custom) } } #[derive(Clone, Debug, Serialize)] pub struct CardExpirationYear(StrongSecret<u16>); impl CardExpirationYear { pub fn four_digits(&self) -> String { self.peek().to_string() } pub fn two_digits(&self) -> String { let year = self.peek() % 100; year.to_string() } } impl TryFrom<u16> for CardExpirationYear { type Error = error_stack::Report<errors::ValidationError>; fn try_from(year: u16) -> Result<Self, Self::Error> { let curr_year = u16::try_from(date_time::now().year()).map_err(|_| { report!(errors::ValidationError::InvalidValue { message: "invalid year".to_string() }) })?; if year >= curr_year { Ok(Self(StrongSecret::<u16>::new(year))) } else { Err(report!(errors::ValidationError::InvalidValue { message: "invalid card expiration year".to_string() })) } } } impl<'de> Deserialize<'de> for CardExpirationYear { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let year = u16::deserialize(deserializer)?; year.try_into().map_err(de::Error::custom) } } #[derive(Serialize, Deserialize)] pub struct CardExpiration { pub month: CardExpirationMonth, pub year: CardExpirationYear, } impl CardExpiration { pub fn is_expired(&self) -> Result<bool, error_stack::Report<errors::ValidationError>> { let current_datetime_utc = date_time::now(); let expiration_month = time::Month::try_from(*self.month.peek()).map_err(|_| { report!(errors::ValidationError::InvalidValue { message: "invalid month".to_string() }) })?; let expiration_year = *self.year.peek(); let expiration_day = expiration_month.length(i32::from(expiration_year)); let expiration_date = Date::from_calendar_date(i32::from(expiration_year), expiration_month, expiration_day) .map_err(|_| { report!(errors::ValidationError::InvalidValue { message: "error while constructing calendar date".to_string() }) })?; let expiration_time = Time::MIDNIGHT; // actual expiry date specified on card w.r.t. local timezone // max diff b/w utc and other timezones is 14 hours let mut expiration_datetime_utc = PrimitiveDateTime::new(expiration_date, expiration_time); // compensating time difference b/w local and utc timezone by adding a day expiration_datetime_utc = expiration_datetime_utc.saturating_add(Duration::days(1)); Ok(current_datetime_utc > expiration_datetime_utc) } pub fn get_month(&self) -> &CardExpirationMonth { &self.month } pub fn get_year(&self) -> &CardExpirationYear { &self.year } } impl TryFrom<(u8, u16)> for CardExpiration { type Error = error_stack::Report<errors::ValidationError>; fn try_from(items: (u8, u16)) -> errors::CustomResult<Self, errors::ValidationError> { let month = CardExpirationMonth::try_from(items.0)?; let year = CardExpirationYear::try_from(items.1)?; Ok(Self { month, year }) } } impl Deref for CardSecurityCode { type Target = StrongSecret<u16>; fn deref(&self) -> &Self::Target { &self.0 } } impl Deref for CardExpirationMonth { type Target = StrongSecret<u8>; fn deref(&self) -> &Self::Target { &self.0 } } impl Deref for CardExpirationYear { type Target = StrongSecret<u16>; fn deref(&self) -> &Self::Target { &self.0 } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/cards/src/validate.rs
crates/cards/src/validate.rs
use std::{collections::HashMap, fmt, ops::Deref, str::FromStr, sync::LazyLock}; use common_utils::errors::ValidationError; use error_stack::report; use masking::{PeekInterface, Strategy, StrongSecret, WithType}; use regex::Regex; #[cfg(not(target_arch = "wasm32"))] use router_env::{logger, which as router_env_which, Env}; use serde::{Deserialize, Deserializer, Serialize}; use thiserror::Error; /// Minimum limit of a card number will not be less than 8 by ISO standards pub const MIN_CARD_NUMBER_LENGTH: usize = 8; /// Maximum limit of a card number will not exceed 19 by ISO standards pub const MAX_CARD_NUMBER_LENGTH: usize = 19; #[derive(Debug, Deserialize, Serialize, Error)] #[error("{0}")] pub struct CardNumberValidationErr(&'static str); /// Card number #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)] pub struct CardNumber(StrongSecret<String, CardNumberStrategy>); //Network Token #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)] pub struct NetworkToken(StrongSecret<String, CardNumberStrategy>); impl CardNumber { pub fn get_card_isin(&self) -> String { self.0.peek().chars().take(6).collect::<String>() } pub fn get_extended_card_bin(&self) -> String { self.0.peek().chars().take(8).collect::<String>() } pub fn get_card_no(&self) -> String { self.0.peek().chars().collect::<String>() } pub fn get_last4(&self) -> String { self.0 .peek() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>() } pub fn is_cobadged_card(&self) -> Result<bool, error_stack::Report<ValidationError>> { /// Regex to identify card networks static CARD_NETWORK_REGEX: LazyLock<HashMap<&str, Result<Regex, regex::Error>>> = LazyLock::new(|| { let mut map = HashMap::new(); map.insert( "Mastercard", Regex::new(r"^(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[0-1][0-9]|2720|5[1-5])"), ); map.insert("American Express", Regex::new(r"^3[47]")); map.insert("Visa", Regex::new(r"^4")); map.insert( "Discover", Regex::new( r"^(6011|64[4-9]|65|622126|622[1-9][0-9][0-9]|6229[0-1][0-9]|622925)", ), ); map.insert( "Maestro", Regex::new(r"^(5018|5081|5044|504681|504993|5020|502260|5038|5893|603845|603123|6304|6759|676[1-3]|6220|504834|504817|504645|504775|600206|627741)"), ); map.insert( "RuPay", Regex::new(r"^(508227|508[5-9]|603741|60698[5-9]|60699|607[0-8]|6079[0-7]|60798[0-4]|60800[1-9]|6080[1-9]|608[1-4]|608500|6521[5-9]|652[2-9]|6530|6531[0-4]|817290|817368|817378|353800|82)"), ); map.insert("Diners Club", Regex::new(r"^(36|38|39|30[0-5])")); map.insert("JCB", Regex::new(r"^35(2[89]|[3-8][0-9])")); map.insert("CarteBlanche", Regex::new(r"^389[0-9]{11}$")); map.insert("Sodex", Regex::new(r"^(637513)")); map.insert("BAJAJ", Regex::new(r"^(203040)")); map.insert("CartesBancaires", Regex::new(r"^(401(005|006|581)|4021(01|02)|403550|405936|406572|41(3849|4819|50(56|59|62|71|74)|6286|65(37|79)|71[7])|420110|423460|43(47(21|22)|50(48|49|50|51|52)|7875|95(09|11|15|39|98)|96(03|18|19|20|22|72))|4424(48|49|50|51|52|57)|448412|4505(19|60)|45(33|56[6-8]|61|62[^3]|6955|7452|7717|93[02379])|46(099|54(76|77)|6258|6575|98[023])|47(4107|71(73|74|86)|72(65|93)|9619)|48(1091|3622|6519)|49(7|83[5-9]|90(0[1-6]|1[0-6]|2[0-3]|3[0-3]|4[0-3]|5[0-2]|68|9[256789]))|5075(89|90|93|94|97)|51(0726|3([0-7]|8[56]|9(00|38))|5214|62(07|36)|72(22|43)|73(65|66)|7502|7647|8101|9920)|52(0993|1662|3718|7429|9227|93(13|14|31)|94(14|21|30|40|47|55|56|[6-9])|9542)|53(0901|10(28|30)|1195|23(4[4-7])|2459|25(09|34|54|56)|3801|41(02|05|11)|50(29|66)|5324|61(07|15)|71(06|12)|8011)|54(2848|5157|9538|98(5[89]))|55(39(79|93)|42(05|60)|4965|7008|88(67|82)|89(29|4[23])|9618|98(09|10))|56(0408|12(0[2-6]|4[134]|5[04678]))|58(17(0[0-7]|15|2[14]|3[16789]|4[0-9]|5[016]|6[269]|7[3789]|8[0-7]|9[017])|55(0[2-5]|7[7-9]|8[0-2])))")); map }); let mut no_of_supported_card_networks = 0; let card_number_str = self.get_card_no(); for (_, regex) in CARD_NETWORK_REGEX.iter() { let card_regex = match regex.as_ref() { Ok(regex) => Ok(regex), Err(_) => Err(report!(ValidationError::InvalidValue { message: "Invalid regex expression".into(), })), }?; if card_regex.is_match(&card_number_str) { no_of_supported_card_networks += 1; if no_of_supported_card_networks > 1 { break; } } } Ok(no_of_supported_card_networks > 1) } pub fn to_network_token(&self) -> NetworkToken { NetworkToken(self.0.clone()) } } impl NetworkToken { pub fn get_card_isin(&self) -> String { self.0.peek().chars().take(6).collect::<String>() } pub fn get_extended_card_bin(&self) -> String { self.0.peek().chars().take(8).collect::<String>() } pub fn get_card_no(&self) -> String { self.0.peek().chars().collect::<String>() } pub fn get_last4(&self) -> String { self.0 .peek() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>() } } impl FromStr for CardNumber { type Err = CardNumberValidationErr; fn from_str(card_number: &str) -> Result<Self, Self::Err> { // Valid test cards for threedsecureio let valid_test_cards = vec![ "4000100511112003", "6000100611111203", "3000100811111072", "9000100111111111", ]; #[cfg(not(target_arch = "wasm32"))] let valid_test_cards = match router_env_which() { Env::Development | Env::Sandbox | Env::Integ => valid_test_cards, Env::Production => vec![], }; let card_number = card_number.split_whitespace().collect::<String>(); let is_card_valid = sanitize_card_number(&card_number)?; if valid_test_cards.contains(&card_number.as_str()) || is_card_valid { Ok(Self(StrongSecret::new(card_number))) } else { Err(CardNumberValidationErr("card number invalid")) } } } impl FromStr for NetworkToken { type Err = CardNumberValidationErr; fn from_str(network_token: &str) -> Result<Self, Self::Err> { // Valid test cards for threedsecureio let valid_test_network_tokens = vec![ "4000100511112003", "6000100611111203", "3000100811111072", "9000100111111111", ]; #[cfg(not(target_arch = "wasm32"))] let valid_test_network_tokens = match router_env_which() { Env::Development | Env::Sandbox | Env::Integ => valid_test_network_tokens, Env::Production => vec![], }; let network_token = network_token.split_whitespace().collect::<String>(); let is_network_token_valid = sanitize_card_number(&network_token)?; if valid_test_network_tokens.contains(&network_token.as_str()) || is_network_token_valid { Ok(Self(StrongSecret::new(network_token))) } else { Err(CardNumberValidationErr("network token invalid")) } } } pub fn sanitize_card_number(card_number: &str) -> Result<bool, CardNumberValidationErr> { let is_card_number_valid = Ok(card_number) .and_then(validate_card_number_chars) .and_then(validate_card_number_length) .map(|number| luhn(&number))?; Ok(is_card_number_valid) } /// # Panics /// /// Never, as a single decimal digit will never be greater than 10, or `u8` pub fn validate_card_number_chars(number: &str) -> Result<Vec<u8>, CardNumberValidationErr> { let data = number.chars().try_fold( Vec::with_capacity(MAX_CARD_NUMBER_LENGTH), |mut data, character| { data.push( #[allow(clippy::expect_used)] character .to_digit(10) .ok_or(CardNumberValidationErr( "invalid character found in card number", ))? .try_into() .expect("error while converting a single decimal digit to u8"), // safety, a single decimal digit will never be greater `u8` ); Ok::<Vec<u8>, CardNumberValidationErr>(data) }, )?; Ok(data) } pub fn validate_card_number_length(number: Vec<u8>) -> Result<Vec<u8>, CardNumberValidationErr> { if number.len() >= MIN_CARD_NUMBER_LENGTH && number.len() <= MAX_CARD_NUMBER_LENGTH { Ok(number) } else { Err(CardNumberValidationErr("invalid card number length")) } } #[allow(clippy::as_conversions)] pub fn luhn(number: &[u8]) -> bool { number .iter() .rev() .enumerate() .map(|(idx, element)| { ((*element * 2) / 10 + (*element * 2) % 10) * ((idx as u8) % 2) + (*element) * (((idx + 1) as u8) % 2) }) .sum::<u8>() % 10 == 0 } impl TryFrom<String> for CardNumber { type Error = CardNumberValidationErr; fn try_from(value: String) -> Result<Self, Self::Error> { Self::from_str(&value) } } impl TryFrom<String> for NetworkToken { type Error = CardNumberValidationErr; fn try_from(value: String) -> Result<Self, Self::Error> { Self::from_str(&value) } } impl Deref for CardNumber { type Target = StrongSecret<String, CardNumberStrategy>; fn deref(&self) -> &StrongSecret<String, CardNumberStrategy> { &self.0 } } impl Deref for NetworkToken { type Target = StrongSecret<String, CardNumberStrategy>; fn deref(&self) -> &StrongSecret<String, CardNumberStrategy> { &self.0 } } impl From<NetworkToken> for CardNumber { fn from(network_token: NetworkToken) -> Self { Self(network_token.0) } } impl From<CardNumber> for NetworkToken { fn from(card_number: CardNumber) -> Self { Self(card_number.0) } } impl<'de> Deserialize<'de> for CardNumber { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { let s = String::deserialize(d)?; Self::from_str(&s).map_err(serde::de::Error::custom) } } impl<'de> Deserialize<'de> for NetworkToken { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { let s = String::deserialize(d)?; Self::from_str(&s).map_err(serde::de::Error::custom) } } pub enum CardNumberStrategy {} impl<T> Strategy<T> for CardNumberStrategy where T: AsRef<str>, { fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { let val_str: &str = val.as_ref(); if val_str.len() < 15 || val_str.len() > 19 { return WithType::fmt(val, f); } if let Some(value) = val_str.get(..6) { write!(f, "{}{}", value, "*".repeat(val_str.len() - 6)) } else { #[cfg(not(target_arch = "wasm32"))] logger::error!("Invalid card number {val_str}"); WithType::fmt(val, f) } } } #[cfg(test)] mod tests { use masking::Secret; use super::*; #[test] fn valid_card_number() { let s = "371449635398431"; assert_eq!( CardNumber::from_str(s).unwrap(), CardNumber(StrongSecret::from_str(s).unwrap()) ); } #[test] fn invalid_card_number_length() { let s = "371446"; assert_eq!( CardNumber::from_str(s).unwrap_err().to_string(), "invalid card number length".to_string() ); } #[test] fn card_number_with_non_digit_character() { let s = "371446431 A"; assert_eq!( CardNumber::from_str(s).unwrap_err().to_string(), "invalid character found in card number".to_string() ); } #[test] fn invalid_card_number() { let s = "371446431"; assert_eq!( CardNumber::from_str(s).unwrap_err().to_string(), "card number invalid".to_string() ); } #[test] fn card_number_no_whitespace() { let s = "3714 4963 5398 431"; assert_eq!( CardNumber::from_str(s).unwrap().to_string(), "371449*********" ); } #[test] fn test_valid_card_number_masking() { let secret: Secret<String, CardNumberStrategy> = Secret::new("1234567890987654".to_string()); assert_eq!("123456**********", format!("{secret:?}")); } #[test] fn test_invalid_card_number_masking() { let secret: Secret<String, CardNumberStrategy> = Secret::new("9123456789".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); } #[test] fn test_valid_card_number_strong_secret_masking() { let card_number = CardNumber::from_str("3714 4963 5398 431").unwrap(); let secret = &(*card_number); assert_eq!("371449*********", format!("{secret:?}")); } #[test] fn test_valid_card_number_deserialization() { let card_number = serde_json::from_str::<CardNumber>(r#""3714 4963 5398 431""#).unwrap(); let secret = card_number.to_string(); assert_eq!(r#""371449*********""#, format!("{secret:?}")); } #[test] fn test_invalid_card_number_deserialization() { let card_number = serde_json::from_str::<CardNumber>(r#""1234 5678""#); let error_msg = card_number.unwrap_err().to_string(); assert_eq!(error_msg, "card number invalid".to_string()); } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/cards/tests/basic.rs
crates/cards/tests/basic.rs
#![allow(clippy::unwrap_used, clippy::expect_used)] use cards::{CardExpiration, CardExpirationMonth, CardExpirationYear, CardSecurityCode}; use common_utils::date_time; use masking::PeekInterface; #[test] fn test_card_security_code() { // no panic let valid_card_security_code = CardSecurityCode::try_from(1234).unwrap(); assert_eq!(*valid_card_security_code.peek(), 1234); let serialized = serde_json::to_string(&valid_card_security_code).unwrap(); assert_eq!(serialized, "1234"); let derialized = serde_json::from_str::<CardSecurityCode>(&serialized).unwrap(); assert_eq!(*derialized.peek(), 1234); let invalid_deserialization = serde_json::from_str::<CardSecurityCode>("00"); assert!(invalid_deserialization.is_err()); } #[test] fn test_card_expiration_month() { // no panic let card_exp_month = CardExpirationMonth::try_from(12).unwrap(); // will panic on unwrap let invalid_card_exp_month = CardExpirationMonth::try_from(13); assert_eq!(*card_exp_month.peek(), 12); assert!(invalid_card_exp_month.is_err()); let serialized = serde_json::to_string(&card_exp_month).unwrap(); assert_eq!(serialized, "12"); let derialized = serde_json::from_str::<CardExpirationMonth>(&serialized).unwrap(); assert_eq!(*derialized.peek(), 12); let invalid_deserialization = serde_json::from_str::<CardExpirationMonth>("13"); assert!(invalid_deserialization.is_err()); } #[test] fn test_card_expiration_year() { let curr_date = date_time::now(); let curr_year = u16::try_from(curr_date.year()).expect("valid year"); // no panic let card_exp_year = CardExpirationYear::try_from(curr_year).unwrap(); // will panic on unwrap let invalid_card_exp_year = CardExpirationYear::try_from(curr_year - 1); assert_eq!(*card_exp_year.peek(), curr_year); assert!(invalid_card_exp_year.is_err()); let serialized = serde_json::to_string(&card_exp_year).unwrap(); assert_eq!(serialized, curr_year.to_string()); let derialized = serde_json::from_str::<CardExpirationYear>(&serialized).unwrap(); assert_eq!(*derialized.peek(), curr_year); let invalid_deserialization = serde_json::from_str::<CardExpirationYear>("123"); assert!(invalid_deserialization.is_err()); } #[test] fn test_card_expiration() { let curr_date = date_time::now(); let curr_year = u16::try_from(curr_date.year()).expect("valid year"); let curr_month = u8::from(curr_date.month()); // no panic let card_exp = CardExpiration::try_from((curr_month, curr_year)).unwrap(); // will panic on unwrap let invalid_card_exp = CardExpiration::try_from((13, curr_year)); assert_eq!(*card_exp.get_month().peek(), curr_month); assert_eq!(*card_exp.get_year().peek(), curr_year); assert!(!card_exp.is_expired().unwrap()); assert!(invalid_card_exp.is_err()); let serialized = serde_json::to_string(&card_exp).unwrap(); let expected_string = format!(r#"{{"month":{},"year":{}}}"#, 3, curr_year); assert_eq!(serialized, expected_string); let derialized = serde_json::from_str::<CardExpiration>(&serialized).unwrap(); assert_eq!(*derialized.get_month().peek(), 3); assert_eq!(*derialized.get_year().peek(), curr_year); let invalid_serialized_string = r#"{"month":13,"year":123}"#; let invalid_deserialization = serde_json::from_str::<CardExpiration>(invalid_serialized_string); assert!(invalid_deserialization.is_err()); }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/errors.rs
crates/hyperswitch_interfaces/src/errors.rs
//! Errors interface use common_enums::ApiClientError; use common_utils::errors::ErrorSwitch; use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse; /// Connector Errors #[allow(missing_docs, missing_debug_implementations)] #[derive(Debug, thiserror::Error, PartialEq)] pub enum ConnectorError { #[error("Error while obtaining URL for the integration")] FailedToObtainIntegrationUrl, #[error("Failed to encode connector request")] RequestEncodingFailed, #[error("Request encoding failed : {0}")] RequestEncodingFailedWithReason(String), #[error("Parsing failed")] ParsingFailed, #[error("Failed to deserialize connector response")] ResponseDeserializationFailed, #[error("Failed to execute a processing step: {0:?}")] ProcessingStepFailed(Option<bytes::Bytes>), #[error("The connector returned an unexpected response: {0:?}")] UnexpectedResponseError(bytes::Bytes), #[error("Failed to parse custom routing rules from merchant account")] RoutingRulesParsingError, #[error("Failed to obtain preferred connector from merchant account")] FailedToObtainPreferredConnector, #[error("An invalid connector name was provided")] InvalidConnectorName, #[error("An invalid Wallet was used")] InvalidWallet, #[error("Failed to handle connector response")] ResponseHandlingFailed, #[error("Missing required field: {field_name}")] MissingRequiredField { field_name: &'static str }, #[error("Missing required fields: {field_names:?}")] MissingRequiredFields { field_names: Vec<&'static str> }, #[error("Failed to obtain authentication type")] FailedToObtainAuthType, #[error("Failed to obtain certificate")] FailedToObtainCertificate, #[error("Connector meta data not found")] NoConnectorMetaData, #[error("Connector wallet details not found")] NoConnectorWalletDetails, #[error("Failed to obtain certificate key")] FailedToObtainCertificateKey, #[error("This step has not been implemented for: {0}")] NotImplemented(String), #[error("{message} is not supported by {connector}")] NotSupported { message: String, connector: &'static str, }, #[error("{flow} flow not supported by {connector} connector")] FlowNotSupported { flow: String, connector: String }, #[error("Capture method not supported")] CaptureMethodNotSupported, #[error("Missing connector mandate ID")] MissingConnectorMandateID, #[error("Missing connector mandate metadata")] MissingConnectorMandateMetadata, #[error("Missing connector transaction ID")] MissingConnectorTransactionID, #[error("Missing connector refund ID")] MissingConnectorRefundID, #[error("Missing apple pay tokenization data")] MissingApplePayTokenData, #[error("Webhooks not implemented for this connector")] WebhooksNotImplemented, #[error("Failed to decode webhook event body")] WebhookBodyDecodingFailed, #[error("Signature not found for incoming webhook")] WebhookSignatureNotFound, #[error("Failed to verify webhook source")] WebhookSourceVerificationFailed, #[error("Could not find merchant secret in DB for incoming webhook source verification")] WebhookVerificationSecretNotFound, #[error("Merchant secret found for incoming webhook source verification is invalid")] WebhookVerificationSecretInvalid, #[error("Incoming webhook object reference ID not found")] WebhookReferenceIdNotFound, #[error("Incoming webhook event type not found")] WebhookEventTypeNotFound, #[error("Incoming webhook event resource object not found")] WebhookResourceObjectNotFound, #[error("Could not respond to the incoming webhook event")] WebhookResponseEncodingFailed, #[error("Invalid Date/time format")] InvalidDateFormat, #[error("Date Formatting Failed")] DateFormattingFailed, #[error("Invalid Data format")] InvalidDataFormat { field_name: &'static str }, #[error("Payment Method data / Payment Method Type / Payment Experience Mismatch ")] MismatchedPaymentData, #[error("Failed to parse {wallet_name} wallet token")] InvalidWalletToken { wallet_name: String }, #[error("Missing Connector Related Transaction ID")] MissingConnectorRelatedTransactionID { id: String }, #[error("File Validation failed")] FileValidationFailed { reason: String }, #[error("Missing 3DS redirection payload: {field_name}")] MissingConnectorRedirectionPayload { field_name: &'static str }, #[error("Failed at connector's end with code '{code}'")] FailedAtConnector { message: String, code: String }, #[error("Payment Method Type not found")] MissingPaymentMethodType, #[error("Balance in the payment method is low")] InSufficientBalanceInPaymentMethod, #[error("Server responded with Request Timeout")] RequestTimeoutReceived, #[error("The given currency method is not configured with the given connector")] CurrencyNotSupported { message: String, connector: &'static str, }, #[error("Invalid Configuration")] InvalidConnectorConfig { config: &'static str }, #[error("Failed to convert amount to required type")] AmountConversionFailed, #[error("Generic Error")] GenericError { error_message: String, error_object: serde_json::Value, }, #[error("Field {fields} doesn't match with the ones used during mandate creation")] MandatePaymentDataMismatch { fields: String }, #[error("Field '{field_name}' is too long for connector '{connector}'")] MaxFieldLengthViolated { connector: String, field_name: String, max_length: usize, received_length: usize, }, } impl ConnectorError { /// fn is_connector_timeout pub fn is_connector_timeout(&self) -> bool { self == &Self::RequestTimeoutReceived } } impl ErrorSwitch<ConnectorError> for common_utils::errors::ParsingError { fn switch(&self) -> ConnectorError { ConnectorError::ParsingFailed } } impl ErrorSwitch<ApiErrorResponse> for ConnectorError { fn switch(&self) -> ApiErrorResponse { match self { Self::WebhookSourceVerificationFailed => ApiErrorResponse::WebhookAuthenticationFailed, Self::WebhookSignatureNotFound | Self::WebhookReferenceIdNotFound | Self::WebhookResourceObjectNotFound | Self::WebhookBodyDecodingFailed | Self::WebhooksNotImplemented => ApiErrorResponse::WebhookBadRequest, Self::WebhookEventTypeNotFound => ApiErrorResponse::WebhookUnprocessableEntity, Self::WebhookVerificationSecretInvalid => { ApiErrorResponse::WebhookInvalidMerchantSecret } _ => ApiErrorResponse::InternalServerError, } } } // http client errors #[allow(missing_docs, missing_debug_implementations)] #[derive(Debug, Clone, thiserror::Error, PartialEq)] pub enum HttpClientError { #[error("Header map construction failed")] HeaderMapConstructionFailed, #[error("Invalid proxy configuration")] InvalidProxyConfiguration, #[error("Client construction failed")] ClientConstructionFailed, #[error("Certificate decode failed")] CertificateDecodeFailed, #[error("Request body serialization failed")] BodySerializationFailed, #[error("Unexpected state reached/Invariants conflicted")] UnexpectedState, #[error("Failed to parse URL")] UrlParsingFailed, #[error("URL encoding of request payload failed")] UrlEncodingFailed, #[error("Failed to send request to connector {0}")] RequestNotSent(String), #[error("Failed to decode response")] ResponseDecodingFailed, #[error("Server responded with Request Timeout")] RequestTimeoutReceived, #[error("connection closed before a message could complete")] ConnectionClosedIncompleteMessage, #[error("Server responded with Internal Server Error")] InternalServerErrorReceived, #[error("Server responded with Bad Gateway")] BadGatewayReceived, #[error("Server responded with Service Unavailable")] ServiceUnavailableReceived, #[error("Server responded with Gateway Timeout")] GatewayTimeoutReceived, #[error("Server responded with unexpected response")] UnexpectedServerResponse, } impl ErrorSwitch<ApiClientError> for HttpClientError { fn switch(&self) -> ApiClientError { match self { Self::HeaderMapConstructionFailed => ApiClientError::HeaderMapConstructionFailed, Self::InvalidProxyConfiguration => ApiClientError::InvalidProxyConfiguration, Self::ClientConstructionFailed => ApiClientError::ClientConstructionFailed, Self::CertificateDecodeFailed => ApiClientError::CertificateDecodeFailed, Self::BodySerializationFailed => ApiClientError::BodySerializationFailed, Self::UnexpectedState => ApiClientError::UnexpectedState, Self::UrlParsingFailed => ApiClientError::UrlParsingFailed, Self::UrlEncodingFailed => ApiClientError::UrlEncodingFailed, Self::RequestNotSent(reason) => ApiClientError::RequestNotSent(reason.clone()), Self::ResponseDecodingFailed => ApiClientError::ResponseDecodingFailed, Self::RequestTimeoutReceived => ApiClientError::RequestTimeoutReceived, Self::ConnectionClosedIncompleteMessage => { ApiClientError::ConnectionClosedIncompleteMessage } Self::InternalServerErrorReceived => ApiClientError::InternalServerErrorReceived, Self::BadGatewayReceived => ApiClientError::BadGatewayReceived, Self::ServiceUnavailableReceived => ApiClientError::ServiceUnavailableReceived, Self::GatewayTimeoutReceived => ApiClientError::GatewayTimeoutReceived, Self::UnexpectedServerResponse => ApiClientError::UnexpectedServerResponse, } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/consts.rs
crates/hyperswitch_interfaces/src/consts.rs
//! connector integration related const declarations /// No error message string const pub const NO_ERROR_MESSAGE: &str = "No error message"; /// No error code string const pub const NO_ERROR_CODE: &str = "No error code"; /// Accepted format for request pub const ACCEPT_HEADER: &str = "text/html,application/json"; /// User agent for request send from backend server pub const USER_AGENT: &str = "Hyperswitch-Backend-Server"; /// Request timeout error code pub const REQUEST_TIMEOUT_ERROR_CODE: &str = "TIMEOUT"; /// error message for timed out request pub const REQUEST_TIMEOUT_ERROR_MESSAGE: &str = "Connector did not respond in specified time"; /// Header value indicating that signature-key-based authentication is used. pub const UCS_AUTH_SIGNATURE_KEY: &str = "signature-key"; /// Header value indicating that body-key-based authentication is used. pub const UCS_AUTH_BODY_KEY: &str = "body-key"; /// Header value indicating that header-key-based authentication is used. pub const UCS_AUTH_HEADER_KEY: &str = "header-key"; /// Header value indicating that currency-auth-key-based authentication is used. pub const UCS_AUTH_CURRENCY_AUTH_KEY: &str = "currency-auth-key"; /// Header value for content type JSON pub const CONTENT_TYPE: &str = "Content-Type"; /// Header name for flow name pub const X_FLOW_NAME: &str = "x-flow"; /// Header name for request ID pub const X_REQUEST_ID: &str = "x-request-id";
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/connector_integration_v2.rs
crates/hyperswitch_interfaces/src/connector_integration_v2.rs
//! definition of the new connector integration trait use common_utils::{ errors::CustomResult, request::{Method, Request, RequestBuilder, RequestContent}, }; use hyperswitch_domain_models::{router_data::ErrorResponse, router_data_v2::RouterDataV2}; use masking::Maskable; use serde_json::json; use crate::{ api::{self, subscriptions_v2, CaptureSyncMethod}, errors, events::connector_api_logs::ConnectorEvent, metrics, types, webhooks, }; /// ConnectorV2 trait pub trait ConnectorV2: Send + api::refunds_v2::RefundV2 + api::payments_v2::PaymentV2 + api::ConnectorRedirectResponse + webhooks::IncomingWebhook + api::ConnectorAuthenticationTokenV2 + api::ConnectorAccessTokenV2 + api::disputes_v2::DisputeV2 + api::files_v2::FileUploadV2 + api::ConnectorTransactionId + api::PayoutsV2 + api::ConnectorVerifyWebhookSourceV2 + api::FraudCheckV2 + api::ConnectorMandateRevokeV2 + api::authentication_v2::ExternalAuthenticationV2 + api::UnifiedAuthenticationServiceV2 + api::revenue_recovery_v2::RevenueRecoveryV2 + api::ExternalVaultV2 + subscriptions_v2::SubscriptionsV2 { } impl< T: api::refunds_v2::RefundV2 + api::payments_v2::PaymentV2 + api::ConnectorRedirectResponse + Send + webhooks::IncomingWebhook + api::ConnectorAuthenticationTokenV2 + api::ConnectorAccessTokenV2 + api::disputes_v2::DisputeV2 + api::files_v2::FileUploadV2 + api::ConnectorTransactionId + api::PayoutsV2 + api::ConnectorVerifyWebhookSourceV2 + api::FraudCheckV2 + api::ConnectorMandateRevokeV2 + api::authentication_v2::ExternalAuthenticationV2 + api::UnifiedAuthenticationServiceV2 + api::revenue_recovery_v2::RevenueRecoveryV2 + api::ExternalVaultV2 + subscriptions_v2::SubscriptionsV2, > ConnectorV2 for T { } /// Alias for Box<&'static (dyn ConnectorV2 + Sync)> pub type BoxedConnectorV2 = Box<&'static (dyn ConnectorV2 + Sync)>; impl api::ConnectorAccessTokenSuffix for BoxedConnectorV2 {} /// alias for Box of a type that implements trait ConnectorIntegrationV2 pub type BoxedConnectorIntegrationV2<'a, Flow, ResourceCommonData, Req, Resp> = Box<&'a (dyn ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp> + Send + Sync)>; /// trait with a function that returns BoxedConnectorIntegrationV2 pub trait ConnectorIntegrationAnyV2<Flow, ResourceCommonData, Req, Resp>: Send + Sync + 'static { /// function what returns BoxedConnectorIntegrationV2 fn get_connector_integration_v2( &self, ) -> BoxedConnectorIntegrationV2<'_, Flow, ResourceCommonData, Req, Resp>; } impl<S, Flow, ResourceCommonData, Req, Resp> ConnectorIntegrationAnyV2<Flow, ResourceCommonData, Req, Resp> for S where S: ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp> + Send + Sync, { fn get_connector_integration_v2( &self, ) -> BoxedConnectorIntegrationV2<'_, Flow, ResourceCommonData, Req, Resp> { Box::new(self) } } /// The new connector integration trait with an additional ResourceCommonData generic parameter pub trait ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp>: ConnectorIntegrationAnyV2<Flow, ResourceCommonData, Req, Resp> + Sync + api::ConnectorCommon { /// returns a vec of tuple of header key and value fn get_headers( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { Ok(vec![]) } /// returns content type fn get_content_type(&self) -> &'static str { mime::APPLICATION_JSON.essence_str() } /// primarily used when creating signature based on request method of payment flow fn get_http_method(&self) -> Method { Method::Post } /// returns url fn get_url( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<String, errors::ConnectorError> { metrics::UNIMPLEMENTED_FLOW .add(1, router_env::metric_attributes!(("connector", self.id()))); Ok(String::new()) } /// returns request body fn get_request_body( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<Option<RequestContent>, errors::ConnectorError> { Ok(None) } /// returns form data fn get_request_form_data( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<Option<reqwest::multipart::Form>, errors::ConnectorError> { Ok(None) } /// builds the request and returns it fn build_request_v2( &self, req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(self.get_http_method()) .url(self.get_url(req)?.as_str()) .attach_default_headers() .headers(self.get_headers(req)?) .set_optional_body(self.get_request_body(req)?) .add_certificate(self.get_certificate(req)?) .add_certificate_key(self.get_certificate_key(req)?) .build(), )) } /// accepts the raw api response and decodes it fn handle_response_v2( &self, data: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, event_builder: Option<&mut ConnectorEvent>, _res: types::Response, ) -> CustomResult<RouterDataV2<Flow, ResourceCommonData, Req, Resp>, errors::ConnectorError> where Flow: Clone, ResourceCommonData: Clone, Req: Clone, Resp: Clone, { event_builder.map(|e| e.set_error(json!({"error": "Not Implemented"}))); Ok(data.clone()) } /// accepts the raw api error response and decodes it fn get_error_response_v2( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); Ok(ErrorResponse::get_not_implemented()) } /// accepts the raw 5xx error response and decodes it fn get_5xx_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); let error_message = match res.status_code { 500 => "internal_server_error", 501 => "not_implemented", 502 => "bad_gateway", 503 => "service_unavailable", 504 => "gateway_timeout", 505 => "http_version_not_supported", 506 => "variant_also_negotiates", 507 => "insufficient_storage", 508 => "loop_detected", 510 => "not_extended", 511 => "network_authentication_required", _ => "unknown_error", }; Ok(ErrorResponse { code: res.status_code.to_string(), message: error_message.to_string(), reason: String::from_utf8(res.response.to_vec()).ok(), status_code: res.status_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } // whenever capture sync is implemented at the connector side, this method should be overridden /// retunes the capture sync method fn get_multiple_capture_sync_method( &self, ) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("multiple capture sync".into()).into()) } /// returns certificate string fn get_certificate( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<Option<masking::Secret<String>>, errors::ConnectorError> { Ok(None) } /// returns private key string fn get_certificate_key( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<Option<masking::Secret<String>>, errors::ConnectorError> { Ok(None) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/lib.rs
crates/hyperswitch_interfaces/src/lib.rs
//! Hyperswitch interface #![warn(missing_docs, missing_debug_implementations)] pub mod api; /// API client interface module pub mod api_client; pub mod authentication; /// Configuration related functionalities pub mod configs; /// Connector integration interface module pub mod connector_integration_interface; /// definition of the new connector integration trait pub mod connector_integration_v2; /// Constants used throughout the application pub mod consts; /// Conversion implementations pub mod conversion_impls; pub mod disputes; pub mod encryption_interface; pub mod errors; /// Event handling interface pub mod events; /// helper utils pub mod helpers; /// connector integrity check interface pub mod integrity; pub mod metrics; pub mod secrets_interface; pub mod types; /// ucs handlers pub mod unified_connector_service; pub mod webhooks; /// Crm interface pub mod crm;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/disputes.rs
crates/hyperswitch_interfaces/src/disputes.rs
//! Disputes interface use common_utils::types::StringMinorUnit; use hyperswitch_domain_models::router_response_types::DisputeSyncResponse; use time::PrimitiveDateTime; /// struct DisputePayload #[derive(Default, Debug)] pub struct DisputePayload { /// amount pub amount: StringMinorUnit, /// currency pub currency: common_enums::enums::Currency, /// dispute_stage pub dispute_stage: common_enums::enums::DisputeStage, /// connector_status pub connector_status: String, /// connector_dispute_id pub connector_dispute_id: String, /// connector_reason pub connector_reason: Option<String>, /// connector_reason_code pub connector_reason_code: Option<String>, /// challenge_required_by pub challenge_required_by: Option<PrimitiveDateTime>, /// created_at pub created_at: Option<PrimitiveDateTime>, /// updated_at pub updated_at: Option<PrimitiveDateTime>, } impl From<DisputeSyncResponse> for DisputePayload { fn from(dispute_sync_data: DisputeSyncResponse) -> Self { Self { amount: dispute_sync_data.amount, currency: dispute_sync_data.currency, dispute_stage: dispute_sync_data.dispute_stage, connector_status: dispute_sync_data.connector_status, connector_dispute_id: dispute_sync_data.connector_dispute_id, connector_reason: dispute_sync_data.connector_reason, connector_reason_code: dispute_sync_data.connector_reason_code, challenge_required_by: dispute_sync_data.challenge_required_by, created_at: dispute_sync_data.created_at, updated_at: dispute_sync_data.updated_at, } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/secrets_interface.rs
crates/hyperswitch_interfaces/src/secrets_interface.rs
//! Secrets management interface pub mod secret_handler; pub mod secret_state; use common_utils::errors::CustomResult; use masking::Secret; /// Trait defining the interface for managing application secrets #[async_trait::async_trait] pub trait SecretManagementInterface: Send + Sync { /* /// Given an input, encrypt/store the secret async fn store_secret( &self, input: Secret<String>, ) -> CustomResult<String, SecretsManagementError>; */ /// Given an input, decrypt/retrieve the secret async fn get_secret( &self, input: Secret<String>, ) -> CustomResult<Secret<String>, SecretsManagementError>; } /// Errors that may occur during secret management #[derive(Debug, thiserror::Error)] pub enum SecretsManagementError { /// An error occurred when retrieving raw data. #[error("Failed to fetch the raw data")] FetchSecretFailed, /// Failed while creating kms client #[error("Failed while creating a secrets management client")] ClientCreationFailed, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/helpers.rs
crates/hyperswitch_interfaces/src/helpers.rs
use common_utils::{ consts::{X_CONNECTOR_NAME, X_SUB_FLOW_NAME}, errors as common_utils_errors, request, }; use error_stack::ResultExt; use hyperswitch_domain_models::router_data; use masking; use router_env::{logger, tracing}; use crate::{api_client, consts, errors, types}; /// Trait for converting from one foreign type to another pub trait ForeignTryFrom<F>: Sized { /// Custom error for conversion failure type Error; /// Convert from a foreign type to the current type and return an error if the conversion fails fn foreign_try_from(from: F) -> Result<Self, Self::Error>; } /// Data structure to hold comparison data between Hyperswitch and UCS #[derive(serde::Serialize, Debug)] pub struct ComparisonData { /// Hyperswitch router data pub hyperswitch_data: masking::Secret<serde_json::Value>, /// Unified Connector Service router data pub unified_connector_service_data: masking::Secret<serde_json::Value>, } /// Trait to get comparison service configuration pub trait GetComparisonServiceConfig { /// Retrieve the comparison service configuration if available fn get_comparison_service_config(&self) -> Option<types::ComparisonServiceConfig>; } /// Generic function to serialize router data and send comparison to external service /// Works for both payments and refunds pub async fn serialize_router_data_and_send_to_comparison_service<F, RouterDReq, RouterDResp>( state: &dyn api_client::ApiClientWrapper, hyperswitch_router_data: router_data::RouterData<F, RouterDReq, RouterDResp>, unified_connector_service_router_data: router_data::RouterData<F, RouterDReq, RouterDResp>, comparison_service_config: types::ComparisonServiceConfig, request_id: Option<String>, ) -> common_utils_errors::CustomResult<(), errors::HttpClientError> where F: Send + Clone + Sync + 'static, RouterDReq: Send + Sync + Clone + 'static + serde::Serialize, RouterDResp: Send + Sync + Clone + 'static + serde::Serialize, { logger::info!("Simulating UCS call for shadow mode comparison"); let connector_name = hyperswitch_router_data.connector.clone(); let sub_flow_name = api_client::get_flow_name::<F>().ok(); let [hyperswitch_data, unified_connector_service_data] = [ (hyperswitch_router_data, "hyperswitch"), (unified_connector_service_router_data, "ucs"), ] .map(|(data, source)| { serde_json::to_value(data) .map(masking::Secret::new) .unwrap_or_else(|e| { masking::Secret::new(serde_json::json!({ "error": e.to_string(), "source": source })) }) }); let comparison_data = ComparisonData { hyperswitch_data, unified_connector_service_data, }; let _ = send_comparison_data( state, comparison_data, comparison_service_config, connector_name, sub_flow_name, request_id, ) .await .map_err(|e| { logger::debug!("Failed to send comparison data: {:?}", e); }); Ok(()) } /// Sends router data comparison to external service pub async fn send_comparison_data( state: &dyn api_client::ApiClientWrapper, comparison_data: ComparisonData, comparison_service_config: types::ComparisonServiceConfig, connector_name: String, sub_flow_name: Option<String>, request_id: Option<String>, ) -> common_utils_errors::CustomResult<(), errors::HttpClientError> { let mut request = request::RequestBuilder::new() .method(request::Method::Post) .url(comparison_service_config.url.get_string_repr()) .header(consts::CONTENT_TYPE, "application/json") .header(consts::X_FLOW_NAME, "router-data") .set_body(request::RequestContent::Json(Box::new(comparison_data))) .build(); request.add_header(X_CONNECTOR_NAME, masking::Maskable::Normal(connector_name)); if let Some(sub_flow_name) = sub_flow_name.filter(|name| !name.is_empty()) { request.add_header(X_SUB_FLOW_NAME, masking::Maskable::Normal(sub_flow_name)); } if let Some(req_id) = request_id { request.add_header(consts::X_REQUEST_ID, masking::Maskable::Normal(req_id)); } let _ = state .get_api_client() .send_request( state, request, comparison_service_config.timeout_secs, false, ) .await .inspect_err(|e| { tracing::debug!("Error sending comparison data: {:?}", e); }) .change_context(errors::HttpClientError::RequestNotSent( "Failed to send comparison data to comparison service".to_string(), ))?; Ok(()) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/encryption_interface.rs
crates/hyperswitch_interfaces/src/encryption_interface.rs
//! Encryption related interface and error types #![warn(missing_docs, missing_debug_implementations)] use common_utils::errors::CustomResult; /// Trait defining the interface for encryption management #[async_trait::async_trait] pub trait EncryptionManagementInterface: Sync + Send + dyn_clone::DynClone { /// Encrypt the given input data async fn encrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError>; /// Decrypt the given input data async fn decrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError>; } dyn_clone::clone_trait_object!(EncryptionManagementInterface); /// Errors that may occur during above encryption functionalities #[derive(Debug, thiserror::Error)] pub enum EncryptionError { /// An error occurred when encrypting input data. #[error("Failed to encrypt input data")] EncryptionFailed, /// An error occurred when decrypting input data. #[error("Failed to decrypt input data")] DecryptionFailed, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/webhooks.rs
crates/hyperswitch_interfaces/src/webhooks.rs
//! Webhooks interface use common_utils::{crypto, errors::CustomResult, ext_traits::ValueExt}; use error_stack::ResultExt; use hyperswitch_domain_models::{ api::ApplicationResponse, errors::api_error_response::ApiErrorResponse, }; use masking::{ExposeInterface, Secret}; use crate::{api::ConnectorCommon, errors}; /// struct IncomingWebhookRequestDetails #[derive(Debug)] pub struct IncomingWebhookRequestDetails<'a> { /// method pub method: http::Method, /// uri pub uri: http::Uri, /// headers pub headers: &'a actix_web::http::header::HeaderMap, /// body pub body: &'a [u8], /// query_params pub query_params: String, } /// IncomingWebhookFlowError enum defining the error type for incoming webhook #[derive(Debug)] pub enum IncomingWebhookFlowError { /// Resource not found for the webhook ResourceNotFound, /// Internal error for the webhook InternalError, } impl From<&ApiErrorResponse> for IncomingWebhookFlowError { fn from(api_error_response: &ApiErrorResponse) -> Self { match api_error_response { ApiErrorResponse::WebhookResourceNotFound | ApiErrorResponse::DisputeNotFound { .. } | ApiErrorResponse::PayoutNotFound | ApiErrorResponse::MandateNotFound | ApiErrorResponse::PaymentNotFound | ApiErrorResponse::RefundNotFound | ApiErrorResponse::AuthenticationNotFound { .. } => Self::ResourceNotFound, _ => Self::InternalError, } } } /// Trait defining incoming webhook #[async_trait::async_trait] pub trait IncomingWebhook: ConnectorCommon + Sync { /// fn get_webhook_body_decoding_algorithm fn get_webhook_body_decoding_algorithm( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::DecodeMessage + Send>, errors::ConnectorError> { Ok(Box::new(crypto::NoAlgorithm)) } /// fn get_webhook_body_decoding_message fn get_webhook_body_decoding_message( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { Ok(request.body.to_vec()) } /// fn decode_webhook_body async fn decode_webhook_body( &self, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, connector_name: &str, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let algorithm = self.get_webhook_body_decoding_algorithm(request)?; let message = self .get_webhook_body_decoding_message(request) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; let secret = self .get_webhook_source_verification_merchant_secret( merchant_id, connector_name, connector_webhook_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; algorithm .decode_message(&secret.secret, message.into()) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed) } /// fn get_webhook_source_verification_algorithm fn get_webhook_source_verification_algorithm( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(crypto::NoAlgorithm)) } /// fn get_webhook_source_verification_merchant_secret async fn get_webhook_source_verification_merchant_secret( &self, merchant_id: &common_utils::id_type::MerchantId, connector_name: &str, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<api_models::webhooks::ConnectorWebhookSecrets, errors::ConnectorError> { let debug_suffix = format!("For merchant_id: {merchant_id:?}, and connector_name: {connector_name}"); let default_secret = "default_secret".to_string(); let merchant_secret = match connector_webhook_details { Some(merchant_connector_webhook_details) => { let connector_webhook_details = merchant_connector_webhook_details .parse_value::<api_models::admin::MerchantConnectorWebhookDetails>( "MerchantConnectorWebhookDetails", ) .change_context_lazy(|| errors::ConnectorError::WebhookSourceVerificationFailed) .attach_printable_lazy(|| { format!( "Deserializing MerchantConnectorWebhookDetails failed {debug_suffix}", ) })?; api_models::webhooks::ConnectorWebhookSecrets { secret: connector_webhook_details .merchant_secret .expose() .into_bytes(), additional_secret: connector_webhook_details.additional_secret, } } None => api_models::webhooks::ConnectorWebhookSecrets { secret: default_secret.into_bytes(), additional_secret: None, }, }; //need to fetch merchant secret from config table with caching in future for enhanced performance //If merchant has not set the secret for webhook source verification, "default_secret" is returned. //So it will fail during verification step and goes to psync flow. Ok(merchant_secret) } /// fn get_webhook_source_verification_signature fn get_webhook_source_verification_signature( &self, _request: &IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { Ok(Vec::new()) } /// fn get_webhook_source_verification_message fn get_webhook_source_verification_message( &self, _request: &IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { Ok(Vec::new()) } /// fn verify_webhook_source async fn verify_webhook_source( &self, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_name: &str, ) -> CustomResult<bool, errors::ConnectorError> { let algorithm = self .get_webhook_source_verification_algorithm(request) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( merchant_id, connector_name, connector_webhook_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let signature = self .get_webhook_source_verification_signature(request, &connector_webhook_secrets) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let message = self .get_webhook_source_verification_message( request, merchant_id, &connector_webhook_secrets, ) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; algorithm .verify_signature(&connector_webhook_secrets.secret, &signature, &message) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) } /// fn get_webhook_object_reference_id fn get_webhook_object_reference_id( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError>; /// fn get_status_update_object #[cfg(feature = "payouts")] fn get_payout_webhook_details( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::PayoutWebhookUpdate, errors::ConnectorError> { Ok(api_models::webhooks::PayoutWebhookUpdate { error_code: None, error_message: None, }) } /// fn get_webhook_event_type fn get_webhook_event_type( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError>; /// fn get_webhook_resource_object fn get_webhook_resource_object( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError>; /// fn get_webhook_api_response fn get_webhook_api_response( &self, _request: &IncomingWebhookRequestDetails<'_>, _error_kind: Option<IncomingWebhookFlowError>, ) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> { Ok(ApplicationResponse::StatusOk) } /// fn get_dispute_details fn get_dispute_details( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<crate::disputes::DisputePayload, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_dispute_details method".to_string()).into()) } /// fn get_external_authentication_details fn get_external_authentication_details( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<crate::authentication::ExternalAuthenticationPayload, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented( "get_external_authentication_details method".to_string(), ) .into()) } /// fn get_mandate_details fn get_mandate_details( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< Option<hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails>, errors::ConnectorError, > { Ok(None) } /// fn get_network_txn_id fn get_network_txn_id( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< Option<hyperswitch_domain_models::router_flow_types::ConnectorNetworkTxnId>, errors::ConnectorError, > { Ok(None) } /// fn to get additional payment method data from connector if any fn get_additional_payment_method_data( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< Option<api_models::payment_methods::PaymentMethodUpdate>, errors::ConnectorError, > { Ok(None) } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] /// get revenue recovery invoice details fn get_revenue_recovery_attempt_details( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< hyperswitch_domain_models::revenue_recovery::RevenueRecoveryAttemptData, errors::ConnectorError, > { Err(errors::ConnectorError::NotImplemented( "get_revenue_recovery_attempt_details method".to_string(), ) .into()) } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] /// get revenue recovery transaction details fn get_revenue_recovery_invoice_details( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< hyperswitch_domain_models::revenue_recovery::RevenueRecoveryInvoiceData, errors::ConnectorError, > { Err(errors::ConnectorError::NotImplemented( "get_revenue_recovery_invoice_details method".to_string(), ) .into()) } /// get subscription MIT payment data from webhook fn get_subscription_mit_payment_data( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< hyperswitch_domain_models::router_flow_types::SubscriptionMitPaymentData, errors::ConnectorError, > { Err(errors::ConnectorError::NotImplemented( "get_subscription_mit_payment_data method".to_string(), ) .into()) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api.rs
crates/hyperswitch_interfaces/src/api.rs
//! API interface /// authentication module pub mod authentication; /// authentication_v2 module pub mod authentication_v2; pub mod disputes; pub mod disputes_v2; pub mod files; pub mod files_v2; #[cfg(feature = "frm")] pub mod fraud_check; #[cfg(feature = "frm")] pub mod fraud_check_v2; pub mod gateway; pub mod payments; pub mod payments_v2; #[cfg(feature = "payouts")] pub mod payouts; #[cfg(feature = "payouts")] pub mod payouts_v2; pub mod refunds; pub mod refunds_v2; pub mod revenue_recovery; pub mod revenue_recovery_v2; pub mod subscriptions; pub mod subscriptions_v2; pub mod vault; pub mod vault_v2; use std::fmt::Debug; use common_enums::{ enums::{ self, CallConnectorAction, CaptureMethod, EventClass, PaymentAction, PaymentMethodType, }, PaymentMethod, }; use common_utils::{ errors::CustomResult, request::{Method, Request, RequestContent}, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ connector_endpoints::Connectors, errors::api_error_response::ApiErrorResponse, payment_method_data::PaymentMethodData, router_data::{ AccessToken, AccessTokenAuthenticationResponse, ConnectorAuthType, ErrorResponse, RouterData, }, router_data_v2::{ flow_common_types::{AuthenticationTokenFlowData, WebhookSourceVerifyData}, AccessTokenFlowData, MandateRevokeFlowData, UasFlowData, }, router_flow_types::{ mandate_revoke::MandateRevoke, AccessTokenAuth, AccessTokenAuthentication, Authenticate, AuthenticationConfirmation, PostAuthenticate, PreAuthenticate, VerifyWebhookSource, }, router_request_types::{ self, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, AccessTokenAuthenticationRequestData, AccessTokenRequestData, MandateRevokeRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ self, ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, SupportedPaymentMethods, VerifyWebhookSourceResponseData, }, }; use masking::Maskable; use serde_json::json; #[cfg(feature = "frm")] pub use self::fraud_check::*; #[cfg(feature = "frm")] pub use self::fraud_check_v2::*; #[cfg(feature = "payouts")] pub use self::payouts::*; #[cfg(feature = "payouts")] pub use self::payouts_v2::*; pub use self::{payments::*, refunds::*, vault::*, vault_v2::*}; use crate::{ api::subscriptions::Subscriptions, connector_integration_v2::ConnectorIntegrationV2, consts, errors, events::connector_api_logs::ConnectorEvent, metrics, types, webhooks, }; /// Connector trait pub trait Connector: Send + Refund + Payment + ConnectorRedirectResponse + webhooks::IncomingWebhook + ConnectorAccessToken + ConnectorAuthenticationToken + disputes::Dispute + files::FileUpload + ConnectorTransactionId + Payouts + ConnectorVerifyWebhookSource + FraudCheck + ConnectorMandateRevoke + authentication::ExternalAuthentication + TaxCalculation + UnifiedAuthenticationService + revenue_recovery::RevenueRecovery + ExternalVault + Subscriptions { } impl< T: Refund + Payment + ConnectorRedirectResponse + Send + webhooks::IncomingWebhook + ConnectorAccessToken + ConnectorAuthenticationToken + disputes::Dispute + files::FileUpload + ConnectorTransactionId + Payouts + ConnectorVerifyWebhookSource + FraudCheck + ConnectorMandateRevoke + authentication::ExternalAuthentication + TaxCalculation + UnifiedAuthenticationService + revenue_recovery::RevenueRecovery + ExternalVault + Subscriptions, > Connector for T { } /// Alias for Box<&'static (dyn Connector + Sync)> pub type BoxedConnector = Box<&'static (dyn Connector + Sync)>; /// type BoxedConnectorIntegration pub type BoxedConnectorIntegration<'a, T, Req, Resp> = Box<&'a (dyn ConnectorIntegration<T, Req, Resp> + Send + Sync)>; /// trait ConnectorIntegrationAny pub trait ConnectorIntegrationAny<T, Req, Resp>: Send + Sync + 'static { /// fn get_connector_integration fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp>; } impl<S, T, Req, Resp> ConnectorIntegrationAny<T, Req, Resp> for S where S: ConnectorIntegration<T, Req, Resp> + Send + Sync, { fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp> { Box::new(self) } } /// trait ConnectorIntegration pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Resp> + Sync + ConnectorCommon { /// fn get_headers fn get_headers( &self, _req: &RouterData<T, Req, Resp>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { Ok(vec![]) } /// fn get_content_type fn get_content_type(&self) -> &'static str { mime::APPLICATION_JSON.essence_str() } /// fn get_content_type fn get_accept_type(&self) -> &'static str { mime::APPLICATION_JSON.essence_str() } /// primarily used when creating signature based on request method of payment flow fn get_http_method(&self) -> Method { Method::Post } /// fn get_url fn get_url( &self, _req: &RouterData<T, Req, Resp>, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(String::new()) } /// fn get_request_body fn get_request_body( &self, _req: &RouterData<T, Req, Resp>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { Ok(RequestContent::Json(Box::new(json!(r#"{}"#)))) } /// fn get_request_form_data fn get_request_form_data( &self, _req: &RouterData<T, Req, Resp>, ) -> CustomResult<Option<reqwest::multipart::Form>, errors::ConnectorError> { Ok(None) } /// fn build_request fn build_request( &self, req: &RouterData<T, Req, Resp>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { metrics::UNIMPLEMENTED_FLOW.add( 1, router_env::metric_attributes!(("connector", req.connector.clone())), ); Ok(None) } /// fn handle_response fn handle_response( &self, data: &RouterData<T, Req, Resp>, event_builder: Option<&mut ConnectorEvent>, _res: types::Response, ) -> CustomResult<RouterData<T, Req, Resp>, errors::ConnectorError> where T: Clone, Req: Clone, Resp: Clone, { event_builder.map(|e| e.set_error(json!({"error": "Not Implemented"}))); Ok(data.clone()) } /// fn get_error_response fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); Ok(ErrorResponse::get_not_implemented()) } /// fn get_5xx_error_response fn get_5xx_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); let error_message = match res.status_code { 500 => "internal_server_error", 501 => "not_implemented", 502 => "bad_gateway", 503 => "service_unavailable", 504 => "gateway_timeout", 505 => "http_version_not_supported", 506 => "variant_also_negotiates", 507 => "insufficient_storage", 508 => "loop_detected", 510 => "not_extended", 511 => "network_authentication_required", _ => "unknown_error", }; Ok(ErrorResponse { code: res.status_code.to_string(), message: error_message.to_string(), reason: String::from_utf8(res.response.to_vec()).ok(), status_code: res.status_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } /// whenever capture sync is implemented at the connector side, this method should be overridden fn get_multiple_capture_sync_method( &self, ) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("multiple capture sync".into()).into()) } /// fn get_certificate fn get_certificate( &self, _req: &RouterData<T, Req, Resp>, ) -> CustomResult<Option<String>, errors::ConnectorError> { Ok(None) } /// fn get_certificate_key fn get_certificate_key( &self, _req: &RouterData<T, Req, Resp>, ) -> CustomResult<Option<String>, errors::ConnectorError> { Ok(None) } } /// Sync Methods for multiple captures #[derive(Debug)] pub enum CaptureSyncMethod { /// For syncing multiple captures individually Individual, /// For syncing multiple captures together Bulk, } /// Connector accepted currency unit as either "Base" or "Minor" #[derive(Debug)] pub enum CurrencyUnit { /// Base currency unit Base, /// Minor currency unit Minor, } /// The trait that provides the common pub trait ConnectorCommon { /// Name of the connector (in lowercase). fn id(&self) -> &'static str; /// Connector accepted currency unit as either "Base" or "Minor" fn get_currency_unit(&self) -> CurrencyUnit { CurrencyUnit::Minor // Default implementation should be remove once it is implemented in all connectors } /// HTTP header used for authorization. fn get_auth_header( &self, _auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { Ok(Vec::new()) } /// HTTP `Content-Type` to be used for POST requests. /// Defaults to `application/json`. fn common_get_content_type(&self) -> &'static str { "application/json" } // FIXME write doc - think about this // fn headers(&self) -> Vec<(&str, &str)>; /// The base URL for interacting with the connector's API. fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str; /// common error response for a connector if it is same in all case fn build_error_response( &self, res: types::Response, _event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { Ok(ErrorResponse { status_code: res.status_code, code: consts::NO_ERROR_CODE.to_string(), message: consts::NO_ERROR_MESSAGE.to_string(), reason: None, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl ConnectorAccessTokenSuffix for BoxedConnector {} /// Current flow information passed to the connector specifications trait /// /// In order to make some desicion about the preprocessing or alternate flow #[derive(Clone, Debug)] pub enum CurrentFlowInfo<'a> { /// Authorize flow information Authorize { /// The authentication type being used auth_type: &'a enums::AuthenticationType, /// The payment authorize request data request_data: &'a router_request_types::PaymentsAuthorizeData, }, /// CompleteAuthorize flow information CompleteAuthorize { /// The payment authorize request data request_data: &'a router_request_types::CompleteAuthorizeData, /// The payment method that is used payment_method: Option<PaymentMethod>, }, } /// Alternate API flow that must be made instead of the current flow. /// For example, PreAuthenticate flow must be made instead of Authorize flow. #[derive(Debug, Clone, Copy)] pub enum AlternateFlow { /// Pre-authentication flow PreAuthenticate, } /// The Preprocessing flow that must be made before the current flow. /// /// For example, PreProcessing flow must be made before Authorize flow. /// Or PostAuthenticate flow must be made before CompleteAuthorize flow for cybersource. #[derive(Debug, Clone, Copy)] pub enum PreProcessingFlowName { /// Authentication flow Authenticate, /// Post-authentication flow PostAuthenticate, } /// Response of the preprocessing flow #[derive(Debug)] pub struct PreProcessingFlowResponse<'a> { /// Payment response data from the preprocessing flow pub response: &'a Result<router_response_types::PaymentsResponseData, ErrorResponse>, /// Attempt status after the preprocessing flow pub attempt_status: enums::AttemptStatus, } /// The trait that provides specifications about the connector pub trait ConnectorSpecifications { /// Check if pre-authentication flow is required fn is_order_create_flow_required(&self, _current_flow: CurrentFlowInfo<'_>) -> bool { false } /// Check if pre-authentication flow is required fn is_pre_authentication_flow_required(&self, _current_flow: CurrentFlowInfo<'_>) -> bool { false } /// Check if authentication flow is required fn is_authentication_flow_required(&self, _current_flow: CurrentFlowInfo<'_>) -> bool { false } /// Check if post-authentication flow is required fn is_post_authentication_flow_required(&self, _current_flow: CurrentFlowInfo<'_>) -> bool { false } /// Preprocessing flow name if any, that must be made before the current flow. fn get_preprocessing_flow_if_needed( &self, _current_flow: CurrentFlowInfo<'_>, ) -> Option<PreProcessingFlowName> { None } /// If Some is returned, the returned api flow must be made instead of the current flow. fn get_alternate_flow_if_needed( &self, _current_flow: CurrentFlowInfo<'_>, ) -> Option<AlternateFlow> { None } /// Details related to payment method supported by the connector fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { None } /// Supported webhooks flows fn get_supported_webhook_flows(&self) -> Option<&'static [EventClass]> { None } /// About the connector fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { None } /// Check if connector should make another request to create an access token /// Connectors should override this method if they require an authentication token to create a new access token fn authentication_token_for_token_creation(&self) -> bool { false } /// Check if connector should make another request to create an customer /// Connectors should override this method if they require to create a connector customer fn should_call_connector_customer( &self, _payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> bool { false } /// Whether SDK session token generation is enabled for this connector fn is_sdk_client_token_generation_enabled(&self) -> bool { false } /// Payment method types that support SDK session token generation fn supported_payment_method_types_for_sdk_client_token_generation( &self, ) -> Vec<PaymentMethodType> { vec![] } /// Validate if SDK session token generation is allowed for given payment method type fn validate_sdk_session_token_for_payment_method( &self, current_core_payment_method_type: &PaymentMethodType, ) -> bool { self.is_sdk_client_token_generation_enabled() && self .supported_payment_method_types_for_sdk_client_token_generation() .contains(current_core_payment_method_type) } #[cfg(not(feature = "v2"))] /// Generate connector request reference ID fn generate_connector_request_reference_id( &self, _payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, is_config_enabled_to_send_payment_id_as_connector_request_id: bool, ) -> String { // Send payment_id if config is enabled for a merchant, else send attempt_id if is_config_enabled_to_send_payment_id_as_connector_request_id { payment_attempt.payment_id.get_string_repr().to_owned() } else { payment_attempt.attempt_id.to_owned() } } #[cfg(feature = "v2")] /// Generate connector request reference ID fn generate_connector_request_reference_id( &self, payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> String { payment_intent .merchant_reference_id .as_ref() .map(|id| id.get_string_repr().to_owned()) .unwrap_or_else(|| payment_attempt.id.get_string_repr().to_owned()) } /// Is Authorize session token required before authorize fn is_authorize_session_token_call_required(&self) -> bool { false } #[cfg(feature = "v1")] /// Generate connector customer reference ID for payments fn generate_connector_customer_id( &self, _customer_id: &Option<common_utils::id_type::CustomerId>, _merchant_id: &common_utils::id_type::MerchantId, ) -> Option<String> { None } #[cfg(feature = "v2")] /// Generate connector customer reference ID for payments fn generate_connector_customer_id( &self, _customer_id: &Option<common_utils::id_type::CustomerId>, _merchant_id: &common_utils::id_type::MerchantId, ) -> Option<String> { todo!() } /// Check if connector needs tokenization call before setup mandate flow fn should_call_tokenization_before_setup_mandate(&self) -> bool { true } } /// Extended trait for connector common to allow functions with generic type pub trait ConnectorCommonExt<Flow, Req, Resp>: ConnectorCommon + ConnectorIntegration<Flow, Req, Resp> { /// common header builder when every request for the connector have same headers fn build_headers( &self, _req: &RouterData<Flow, Req, Resp>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { Ok(Vec::new()) } } /// trait ConnectorMandateRevoke pub trait ConnectorMandateRevoke: ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData> { } /// trait ConnectorMandateRevokeV2 pub trait ConnectorMandateRevokeV2: ConnectorIntegrationV2< MandateRevoke, MandateRevokeFlowData, MandateRevokeRequestData, MandateRevokeResponseData, > { } /// trait ConnectorAuthenticationToken pub trait ConnectorAuthenticationToken: ConnectorIntegration< AccessTokenAuthentication, AccessTokenAuthenticationRequestData, AccessTokenAuthenticationResponse, > { } /// trait ConnectorAuthenticationTokenV2 pub trait ConnectorAuthenticationTokenV2: ConnectorIntegrationV2< AccessTokenAuthentication, AuthenticationTokenFlowData, AccessTokenAuthenticationRequestData, AccessTokenAuthenticationResponse, > { } /// trait ConnectorAccessToken pub trait ConnectorAccessToken: ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> { } /// trait ConnectorAccessTokenV2 pub trait ConnectorAccessTokenV2: ConnectorIntegrationV2<AccessTokenAuth, AccessTokenFlowData, AccessTokenRequestData, AccessToken> { } /// trait ConnectorVerifyWebhookSource pub trait ConnectorVerifyWebhookSource: ConnectorIntegration< VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, > { } /// trait ConnectorVerifyWebhookSourceV2 pub trait ConnectorVerifyWebhookSourceV2: ConnectorIntegrationV2< VerifyWebhookSource, WebhookSourceVerifyData, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, > { } /// trait UnifiedAuthenticationService pub trait UnifiedAuthenticationService: ConnectorCommon + UasPreAuthentication + UasPostAuthentication + UasAuthenticationConfirmation + UasAuthentication { } /// trait UasPreAuthentication pub trait UasPreAuthentication: ConnectorIntegration< PreAuthenticate, UasPreAuthenticationRequestData, UasAuthenticationResponseData, > { } /// trait UasPostAuthentication pub trait UasPostAuthentication: ConnectorIntegration< PostAuthenticate, UasPostAuthenticationRequestData, UasAuthenticationResponseData, > { } /// trait UasAuthenticationConfirmation pub trait UasAuthenticationConfirmation: ConnectorIntegration< AuthenticationConfirmation, UasConfirmationRequestData, UasAuthenticationResponseData, > { } /// trait UasAuthentication pub trait UasAuthentication: ConnectorIntegration<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData> { } /// trait UnifiedAuthenticationServiceV2 pub trait UnifiedAuthenticationServiceV2: ConnectorCommon + UasPreAuthenticationV2 + UasPostAuthenticationV2 + UasAuthenticationV2 + UasAuthenticationConfirmationV2 { } ///trait UasPreAuthenticationV2 pub trait UasPreAuthenticationV2: ConnectorIntegrationV2< PreAuthenticate, UasFlowData, UasPreAuthenticationRequestData, UasAuthenticationResponseData, > { } /// trait UasPostAuthenticationV2 pub trait UasPostAuthenticationV2: ConnectorIntegrationV2< PostAuthenticate, UasFlowData, UasPostAuthenticationRequestData, UasAuthenticationResponseData, > { } /// trait UasAuthenticationConfirmationV2 pub trait UasAuthenticationConfirmationV2: ConnectorIntegrationV2< AuthenticationConfirmation, UasFlowData, UasConfirmationRequestData, UasAuthenticationResponseData, > { } /// trait UasAuthenticationV2 pub trait UasAuthenticationV2: ConnectorIntegrationV2< Authenticate, UasFlowData, UasAuthenticationRequestData, UasAuthenticationResponseData, > { } /// trait ConnectorValidation pub trait ConnectorValidation: ConnectorCommon + ConnectorSpecifications { /// Validate, the payment request against the connector supported features fn validate_connector_against_payment_request( &self, capture_method: Option<CaptureMethod>, payment_method: PaymentMethod, pmt: Option<PaymentMethodType>, ) -> CustomResult<(), errors::ConnectorError> { let capture_method = capture_method.unwrap_or_default(); let is_default_capture_method = [CaptureMethod::Automatic, CaptureMethod::SequentialAutomatic] .contains(&capture_method); let is_feature_supported = match self.get_supported_payment_methods() { Some(supported_payment_methods) => { let connector_payment_method_type_info = get_connector_payment_method_type_info( supported_payment_methods, payment_method, pmt, self.id(), )?; connector_payment_method_type_info .map(|payment_method_type_info| { payment_method_type_info .supported_capture_methods .contains(&capture_method) }) .unwrap_or(true) } None => is_default_capture_method, }; if is_feature_supported { Ok(()) } else { Err(errors::ConnectorError::NotSupported { message: capture_method.to_string(), connector: self.id(), } .into()) } } /// fn validate_mandate_payment fn validate_mandate_payment( &self, pm_type: Option<PaymentMethodType>, _pm_data: PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { let connector = self.id(); match pm_type { Some(pm_type) => Err(errors::ConnectorError::NotSupported { message: format!("{pm_type} mandate payment"), connector, } .into()), None => Err(errors::ConnectorError::NotSupported { message: " mandate payment".to_string(), connector, } .into()), } } /// fn validate_psync_reference_id fn validate_psync_reference_id( &self, data: &router_request_types::PaymentsSyncData, _is_three_ds: bool, _status: enums::AttemptStatus, _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<(), errors::ConnectorError> { data.connector_transaction_id .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID) .map(|_| ()) } /// fn is_webhook_source_verification_mandatory fn is_webhook_source_verification_mandatory(&self) -> bool { false } } /// trait ConnectorRedirectResponse pub trait ConnectorRedirectResponse { /// fn get_flow_type fn get_flow_type( &self, _query_params: &str, _json_payload: Option<serde_json::Value>, _action: PaymentAction, ) -> CustomResult<CallConnectorAction, errors::ConnectorError> { Ok(CallConnectorAction::Avoid) } } /// Empty trait for when payouts feature is disabled #[cfg(not(feature = "payouts"))] pub trait Payouts {} /// Empty trait for when payouts feature is disabled #[cfg(not(feature = "payouts"))] pub trait PayoutsV2 {} /// Empty trait for when frm feature is disabled #[cfg(not(feature = "frm"))] pub trait FraudCheck {} /// Empty trait for when frm feature is disabled #[cfg(not(feature = "frm"))] pub trait FraudCheckV2 {} fn get_connector_payment_method_type_info( supported_payment_method: &SupportedPaymentMethods, payment_method: PaymentMethod, payment_method_type: Option<PaymentMethodType>, connector: &'static str, ) -> CustomResult<Option<PaymentMethodDetails>, errors::ConnectorError> { let payment_method_details = supported_payment_method .get(&payment_method) .ok_or_else(|| errors::ConnectorError::NotSupported { message: payment_method.to_string(), connector, })?; payment_method_type .map(|pmt| { payment_method_details.get(&pmt).cloned().ok_or_else(|| { errors::ConnectorError::NotSupported { message: format!("{payment_method} {pmt}"), connector, } .into() }) }) .transpose() } /// ConnectorTransactionId trait pub trait ConnectorTransactionId: ConnectorCommon + Sync { /// fn connector_transaction_id fn connector_transaction_id( &self, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> Result<Option<String>, ApiErrorResponse> { Ok(payment_attempt .get_connector_payment_id() .map(ToString::to_string)) } } /// Trait ConnectorAccessTokenSuffix pub trait ConnectorAccessTokenSuffix { /// Function to get dynamic access token key suffix from Connector fn get_access_token_key<F, Req, Res>( &self, router_data: &RouterData<F, Req, Res>, merchant_connector_id_or_connector_name: String, ) -> CustomResult<String, errors::ConnectorError> { Ok(common_utils::access_token::get_default_access_token_key( &router_data.merchant_id, merchant_connector_id_or_connector_name, )) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/types.rs
crates/hyperswitch_interfaces/src/types.rs
//! Types interface use common_utils::types::Url; use hyperswitch_domain_models::{ router_data::{AccessToken, AccessTokenAuthenticationResponse}, router_data_v2::flow_common_types, router_flow_types::{ access_token_auth::AccessTokenAuth, dispute::{Accept, Defend, Dsync, Evidence, Fetch}, files::{Retrieve, Upload}, mandate_revoke::MandateRevoke, payments::{ Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, ExtendAuthorization, IncrementalAuthorization, InitPayment, PSync, PaymentMethodToken, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, refunds::{Execute, RSync}, revenue_recovery::{BillingConnectorPaymentsSync, InvoiceRecordBack}, subscriptions::{ GetSubscriptionEstimate, GetSubscriptionItemPrices, GetSubscriptionItems, SubscriptionCancel, SubscriptionCreate, SubscriptionPause, SubscriptionResume, }, unified_authentication_service::{ Authenticate, AuthenticationConfirmation, PostAuthenticate, PreAuthenticate, }, vault::{ ExternalVaultCreateFlow, ExternalVaultDeleteFlow, ExternalVaultInsertFlow, ExternalVaultRetrieveFlow, }, webhooks::VerifyWebhookSource, AccessTokenAuthentication, BillingConnectorInvoiceSync, GiftCardBalanceCheck, }, router_request_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, InvoiceRecordBackRequest, }, subscriptions::{ GetSubscriptionEstimateRequest, GetSubscriptionItemPricesRequest, GetSubscriptionItemsRequest, SubscriptionCancelRequest, SubscriptionCreateRequest, SubscriptionPauseRequest, SubscriptionResumeRequest, }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, DefendDisputeRequestData, DisputeSyncData, FetchDisputesRequestData, GiftCardBalanceCheckRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData, PaymentsPostAuthenticateData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, SubmitEvidenceRequestData, UploadFileRequestData, VaultRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, InvoiceRecordBackResponse, }, subscriptions::{ GetSubscriptionEstimateResponse, GetSubscriptionItemPricesResponse, GetSubscriptionItemsResponse, SubscriptionCancelResponse, SubscriptionCreateResponse, SubscriptionPauseResponse, SubscriptionResumeResponse, }, AcceptDisputeResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, GiftCardBalanceCheckResponseData, MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, TaxCalculationResponseData, UploadFileResponse, VaultResponseData, VerifyWebhookSourceResponseData, }, }; #[cfg(feature = "payouts")] use hyperswitch_domain_models::{ router_flow_types::payouts::{ PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync, }, router_request_types::PayoutsData, router_response_types::PayoutsResponseData, }; use serde; use crate::{api::ConnectorIntegration, connector_integration_v2::ConnectorIntegrationV2}; /// struct Response #[derive(Clone, Debug)] pub struct Response { /// headers pub headers: Option<http::HeaderMap>, /// response pub response: bytes::Bytes, /// status code pub status_code: u16, } /// Type alias for `ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>` pub type PaymentsAuthorizeType = dyn ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>` pub type PaymentsTaxCalculationType = dyn ConnectorIntegration<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>; /// Type alias for `ConnectorIntegration<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>` pub type PaymentsPostSessionTokensType = dyn ConnectorIntegration< PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData, >; /// Type alias for `ConnectorIntegration<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData>` pub type PaymentsUpdateMetadataType = dyn ConnectorIntegration<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>` pub type SdkSessionUpdateType = dyn ConnectorIntegration<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>` pub type SetupMandateType = dyn ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>` pub type MandateRevokeType = dyn ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>; /// Type alias for `ConnectorIntegration<CreateOrder, CreateOrderRequestData, PaymentsResponseData>` pub type CreateOrderType = dyn ConnectorIntegration<CreateOrder, CreateOrderRequestData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>` pub type PaymentsPreProcessingType = dyn ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData>` pub type PaymentsPreAuthenticateType = dyn ConnectorIntegration<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<Authenticate, PaymentsAuthenticateData, PaymentsResponseData>` pub type PaymentsAuthenticateType = dyn ConnectorIntegration<Authenticate, PaymentsAuthenticateData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData>` pub type PaymentsPostAuthenticateType = dyn ConnectorIntegration<PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>` pub type PaymentsPostProcessingType = dyn ConnectorIntegration<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>` pub type PaymentsCompleteAuthorizeType = dyn ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>` pub type PaymentsPreAuthorizeType = dyn ConnectorIntegration< AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData, >; /// Type alias for `ConnectorIntegration<GiftCardBalanceCheck, GiftCardBalanceCheckRequestData, GiftCardBalanceCheckResponseData>` pub type PaymentsGiftCardBalanceCheckType = dyn ConnectorIntegration< GiftCardBalanceCheck, GiftCardBalanceCheckRequestData, GiftCardBalanceCheckResponseData, >; /// Type alias for `ConnectorIntegration<InitPayment, PaymentsAuthorizeData, PaymentsResponseData>` pub type PaymentsInitType = dyn ConnectorIntegration<InitPayment, PaymentsAuthorizeData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<Balance, PaymentsAuthorizeData, PaymentsResponseData` pub type PaymentsBalanceType = dyn ConnectorIntegration<Balance, PaymentsAuthorizeData, PaymentsResponseData>; /// Type alias for `PaymentsSyncType = dyn ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData>` pub type PaymentsSyncType = dyn ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData>` pub type PaymentsCaptureType = dyn ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData>` pub type PaymentsSessionType = dyn ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData>` pub type PaymentsVoidType = dyn ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData>` pub type PaymentsPostCaptureVoidType = dyn ConnectorIntegration<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>` pub type TokenizationType = dyn ConnectorIntegration< PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData, >; /// Type alias for `ConnectorIntegration<IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData>` pub type IncrementalAuthorizationType = dyn ConnectorIntegration< IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData, >; /// Type alias for `ConnectorIntegration<ExtendAuthorization, PaymentsExtendAuthorizationData, PaymentsResponseData>` pub type ExtendedAuthorizationType = dyn ConnectorIntegration< ExtendAuthorization, PaymentsExtendAuthorizationData, PaymentsResponseData, >; /// Type alias for ConnectorIntegration<GetSubscriptionItemPrices, GetSubscriptionItemPricesRequest, GetSubscriptionItemPricesResponse> pub type GetSubscriptionPlanPricesType = dyn ConnectorIntegration< GetSubscriptionItemPrices, GetSubscriptionItemPricesRequest, GetSubscriptionItemPricesResponse, >; /// Type alias for `ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>` pub type ConnectorCustomerType = dyn ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<Execute, RefundsData, RefundsResponseData>` pub type RefundExecuteType = dyn ConnectorIntegration<Execute, RefundsData, RefundsResponseData>; /// Type alias for `ConnectorIntegration<RSync, RefundsData, RefundsResponseData>` pub type RefundSyncType = dyn ConnectorIntegration<RSync, RefundsData, RefundsResponseData>; /// Type alias for `ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData>` #[cfg(feature = "payouts")] pub type PayoutCancelType = dyn ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData>; /// Type alias for `ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData>` #[cfg(feature = "payouts")] pub type PayoutCreateType = dyn ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData>; /// Type alias for `ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData>` #[cfg(feature = "payouts")] pub type PayoutEligibilityType = dyn ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData>; /// Type alias for `ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData>` #[cfg(feature = "payouts")] pub type PayoutFulfillType = dyn ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData>; /// Type alias for `ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData>` #[cfg(feature = "payouts")] pub type PayoutRecipientType = dyn ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData>; /// Type alias for `ConnectorIntegration<PoRecipientAccount, PayoutsData, PayoutsResponseData>` #[cfg(feature = "payouts")] pub type PayoutRecipientAccountType = dyn ConnectorIntegration<PoRecipientAccount, PayoutsData, PayoutsResponseData>; /// Type alias for `ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData>` #[cfg(feature = "payouts")] pub type PayoutQuoteType = dyn ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData>; /// Type alias for `ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData>` #[cfg(feature = "payouts")] pub type PayoutSyncType = dyn ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData>; /// Type alias for `ConnectorIntegration<AccessTokenAuthentication, AccessTokenAuthenticationRequestData, AccessTokenAuthenticationResponse>` pub type AuthenticationTokenType = dyn ConnectorIntegration< AccessTokenAuthentication, AccessTokenAuthenticationRequestData, AccessTokenAuthenticationResponse, >; /// Type alias for `ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>` pub type RefreshTokenType = dyn ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>; /// Type alias for `ConnectorIntegration<Accept, AcceptDisputeRequestData, AcceptDisputeResponse>` pub type AcceptDisputeType = dyn ConnectorIntegration<Accept, AcceptDisputeRequestData, AcceptDisputeResponse>; /// Type alias for `ConnectorIntegration<VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData>` pub type VerifyWebhookSourceType = dyn ConnectorIntegration< VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, >; /// Type alias for `ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>` pub type SubmitEvidenceType = dyn ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>; /// Type alias for `ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse>` pub type UploadFileType = dyn ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse>; /// Type alias for `ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>` pub type RetrieveFileType = dyn ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>; /// Type alias for `ConnectorIntegration<Defend, DefendDisputeRequestData, DefendDisputeResponse>` pub type DefendDisputeType = dyn ConnectorIntegration<Defend, DefendDisputeRequestData, DefendDisputeResponse>; /// Type alias for `ConnectorIntegration<Fetch, FetchDisputesRequestData, FetchDisputesResponse>` pub type FetchDisputesType = dyn ConnectorIntegration<Fetch, FetchDisputesRequestData, FetchDisputesResponse>; /// Type alias for `ConnectorIntegration<Dsync, DisputeSyncData, DisputeSyncResponse>` pub type DisputeSyncType = dyn ConnectorIntegration<Dsync, DisputeSyncData, DisputeSyncResponse>; /// Type alias for `ConnectorIntegration<PreAuthenticate, UasPreAuthenticationRequestData, UasAuthenticationResponseData>` pub type UasPreAuthenticationType = dyn ConnectorIntegration< PreAuthenticate, UasPreAuthenticationRequestData, UasAuthenticationResponseData, >; /// Type alias for `ConnectorIntegration<PostAuthenticate, UasPostAuthenticationRequestData, UasAuthenticationResponseData>` pub type UasPostAuthenticationType = dyn ConnectorIntegration< PostAuthenticate, UasPostAuthenticationRequestData, UasAuthenticationResponseData, >; /// Type alias for `ConnectorIntegration<Confirmation, UasConfirmationRequestData, UasAuthenticationResponseData>` pub type UasAuthenticationConfirmationType = dyn ConnectorIntegration< AuthenticationConfirmation, UasConfirmationRequestData, UasAuthenticationResponseData, >; /// Type alias for `ConnectorIntegration<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData>` pub type UasAuthenticationType = dyn ConnectorIntegration< Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData, >; /// Type alias for `ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse>` pub type InvoiceRecordBackType = dyn ConnectorIntegration< InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse, >; /// Type alias for `ConnectorIntegration<SubscriptionCreate, SubscriptionCreateRequest, SubscriptionCreateResponse>` pub type SubscriptionCreateType = dyn ConnectorIntegration< SubscriptionCreate, SubscriptionCreateRequest, SubscriptionCreateResponse, >; /// Type alias for `ConnectorIntegration<BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse>` pub type BillingConnectorPaymentsSyncType = dyn ConnectorIntegration< BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse, >; /// Type alias for `ConnectorIntegration<BillingConnectorInvoiceSync, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse>` pub type BillingConnectorInvoiceSyncType = dyn ConnectorIntegration< BillingConnectorInvoiceSync, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse, >; /// Type alias for `ConnectorIntegrationV2<InvoiceRecordBack, InvoiceRecordBackData, InvoiceRecordBackRequest, InvoiceRecordBackResponse>` pub type InvoiceRecordBackTypeV2 = dyn ConnectorIntegrationV2< InvoiceRecordBack, flow_common_types::InvoiceRecordBackData, InvoiceRecordBackRequest, InvoiceRecordBackResponse, >; /// Type alias for `ConnectorIntegrationV2<BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse>` pub type BillingConnectorPaymentsSyncTypeV2 = dyn ConnectorIntegrationV2< BillingConnectorPaymentsSync, flow_common_types::BillingConnectorPaymentsSyncFlowData, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse, >; /// Type alias for `ConnectorIntegrationV2<BillingConnectorInvoiceSync, BillingConnectorInvoiceSyncFlowData, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse>` pub type BillingConnectorInvoiceSyncTypeV2 = dyn ConnectorIntegrationV2< BillingConnectorInvoiceSync, flow_common_types::BillingConnectorInvoiceSyncFlowData, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse, >; /// Type alias for `ConnectorIntegration<GetSubscriptionItems, GetSubscriptionItemsRequest, GetSubscriptionItemsResponse>` pub type GetSubscriptionPlansType = dyn ConnectorIntegration< GetSubscriptionItems, GetSubscriptionItemsRequest, GetSubscriptionItemsResponse, >; /// Type alias for `ConnectorIntegration<GetSubscriptionEstimate, GetSubscriptionEstimateRequest, GetSubscriptionEstimateResponse>` pub type GetSubscriptionEstimateType = dyn ConnectorIntegration< GetSubscriptionEstimate, GetSubscriptionEstimateRequest, GetSubscriptionEstimateResponse, >; /// Type alias for `ConnectorIntegration<SubscriptionPause, SubscriptionPauseRequest, SubscriptionPauseResponse>` pub type SubscriptionPauseType = dyn ConnectorIntegration< SubscriptionPause, SubscriptionPauseRequest, SubscriptionPauseResponse, >; /// Type alias for `ConnectorIntegration<SubscriptionResume, SubscriptionResumeRequest, SubscriptionResumeResponse>` pub type SubscriptionResumeType = dyn ConnectorIntegration< SubscriptionResume, SubscriptionResumeRequest, SubscriptionResumeResponse, >; /// Type alias for `ConnectorIntegration<SubscriptionCancel, SubscriptionCancelRequest, SubscriptionCancelResponse>` pub type SubscriptionCancelType = dyn ConnectorIntegration< SubscriptionCancel, SubscriptionCancelRequest, SubscriptionCancelResponse, >; /// Type alias for `ConnectorIntegration<ExternalVaultInsertFlow, VaultRequestData, VaultResponseData>` pub type ExternalVaultInsertType = dyn ConnectorIntegration<ExternalVaultInsertFlow, VaultRequestData, VaultResponseData>; /// Type alias for `ConnectorIntegration<ExternalVaultRetrieveFlow, VaultRequestData, VaultResponseData>` pub type ExternalVaultRetrieveType = dyn ConnectorIntegration<ExternalVaultRetrieveFlow, VaultRequestData, VaultResponseData>; /// Type alias for `ConnectorIntegration<ExternalVaultDeleteFlow, VaultRequestData, VaultResponseData>` pub type ExternalVaultDeleteType = dyn ConnectorIntegration<ExternalVaultDeleteFlow, VaultRequestData, VaultResponseData>; /// Type alias for `ConnectorIntegration<ExternalVaultCreateFlow, VaultRequestData, VaultResponseData>` pub type ExternalVaultCreateType = dyn ConnectorIntegration<ExternalVaultCreateFlow, VaultRequestData, VaultResponseData>; /// Proxy configuration structure #[derive(Debug, serde::Deserialize, Clone, PartialEq, Eq, Hash)] #[serde(default)] pub struct Proxy { /// The URL of the HTTP proxy server. pub http_url: Option<String>, /// The URL of the HTTPS proxy server. pub https_url: Option<String>, /// The timeout duration (in seconds) for idle connections in the proxy pool. pub idle_pool_connection_timeout: Option<u64>, /// A comma-separated list of hosts that should bypass the proxy. pub bypass_proxy_hosts: Option<String>, /// The CA certificate used for man-in-the-middle (MITM) proxying, if enabled. pub mitm_ca_certificate: Option<masking::Secret<String>>, /// Whether man-in-the-middle (MITM) proxying is enabled. pub mitm_enabled: Option<bool>, } impl Default for Proxy { fn default() -> Self { Self { http_url: Default::default(), https_url: Default::default(), idle_pool_connection_timeout: Some(90), bypass_proxy_hosts: Default::default(), mitm_ca_certificate: None, mitm_enabled: None, } } } impl Proxy { /// Check if any proxy configuration is present pub fn has_proxy_config(&self) -> bool { self.http_url.is_some() || self.https_url.is_some() } } /// Proxy override configuration for rollout-based proxy switching #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ProxyOverride { /// Override HTTP proxy URL pub http_url: Option<String>, /// Override HTTPS proxy URL pub https_url: Option<String>, } /// Type alias for `ConnectorIntegrationV2<CreateConnectorCustomer, PaymentFlowData, ConnectorCustomerData, PaymentsResponseData>` pub type CreateCustomerTypeV2 = dyn ConnectorIntegrationV2< CreateConnectorCustomer, flow_common_types::PaymentFlowData, ConnectorCustomerData, PaymentsResponseData, >; /// Configuration for the comparison service /// /// This struct contains configuration parameters for the external comparison service /// used to compare results between different execution paths (e.g., Direct vs UCS). #[derive(Debug, serde::Deserialize, Clone)] pub struct ComparisonServiceConfig { /// The URL of the comparison service endpoint pub url: Url, /// Whether the comparison service is enabled pub enabled: bool, /// Timeout in seconds for comparison service requests pub timeout_secs: Option<u64>, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api_client.rs
crates/hyperswitch_interfaces/src/api_client.rs
use std::{ fmt::Debug, time::{Duration, Instant}, }; use common_enums::ApiClientError; use common_utils::{ consts::{X_CONNECTOR_NAME, X_FLOW_NAME, X_REQUEST_ID}, errors::CustomResult, request::{Request, RequestContent}, }; use error_stack::{report, ResultExt}; use http::Method; use hyperswitch_domain_models::{ errors::api_error_response, router_data::{ErrorResponse, RouterData}, }; use masking::Maskable; use reqwest::multipart::Form; use router_env::{instrument, logger, tracing, RequestId}; use serde_json::json; use crate::{ configs, connector_integration_interface::{ BoxedConnectorIntegrationInterface, ConnectorEnum, RouterDataConversion, }, consts, errors::ConnectorError, events, events::connector_api_logs::ConnectorEvent, metrics, types, types::Proxy, }; /// A trait representing a converter for connector names to their corresponding enum variants. pub trait ConnectorConverter: Send + Sync { /// Get the connector enum variant by its name fn get_connector_enum_by_name( &self, connector: &str, ) -> CustomResult<ConnectorEnum, api_error_response::ApiErrorResponse>; } /// A trait representing a builder for HTTP requests. pub trait RequestBuilder: Send + Sync { /// Build a JSON request fn json(&mut self, body: serde_json::Value); /// Build a URL encoded form request fn url_encoded_form(&mut self, body: serde_json::Value); /// Set the timeout duration for the request fn timeout(&mut self, timeout: Duration); /// Build a multipart request fn multipart(&mut self, form: Form); /// Add a header to the request fn header(&mut self, key: String, value: Maskable<String>) -> CustomResult<(), ApiClientError>; /// Send the request and return a future that resolves to the response fn send( self, ) -> CustomResult< Box<dyn core::future::Future<Output = Result<reqwest::Response, reqwest::Error>> + 'static>, ApiClientError, >; } /// A trait representing an API client capable of making HTTP requests. #[async_trait::async_trait] pub trait ApiClient: dyn_clone::DynClone where Self: Send + Sync, { /// Create a new request with the specified HTTP method and URL fn request( &self, method: Method, url: String, ) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError>; /// Create a new request with the specified HTTP method, URL, and client certificate fn request_with_certificate( &self, method: Method, url: String, certificate: Option<masking::Secret<String>>, certificate_key: Option<masking::Secret<String>>, ) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError>; /// Send a request and return the response async fn send_request( &self, state: &dyn ApiClientWrapper, request: Request, option_timeout_secs: Option<u64>, forward_to_kafka: bool, ) -> CustomResult<reqwest::Response, ApiClientError>; /// Add a request ID to the client for tracking purposes fn add_request_id(&mut self, request_id: RequestId); /// Get the current request ID, if any fn get_request_id(&self) -> Option<RequestId>; /// Get the current request ID as a string, if any fn get_request_id_str(&self) -> Option<String>; /// Add a flow name to the client for tracking purposes fn add_flow_name(&mut self, flow_name: String); } dyn_clone::clone_trait_object!(ApiClient); /// A wrapper trait to get the ApiClient and Proxy from the state pub trait ApiClientWrapper: Send + Sync { /// Get the ApiClient instance fn get_api_client(&self) -> &dyn ApiClient; /// Get the Proxy configuration fn get_proxy(&self) -> Proxy; /// Get the request ID as String if any fn get_request_id_str(&self) -> Option<String>; /// Get the request ID as &RequestId if any fn get_request_id(&self) -> Option<RequestId>; /// Get the tenant information fn get_tenant(&self) -> configs::Tenant; /// Get connectors configuration fn get_connectors(&self) -> configs::Connectors; /// Get the event handler fn event_handler(&self) -> &dyn events::EventHandlerInterface; } /// Handle the flow by interacting with connector module /// `connector_request` is applicable only in case if the `CallConnectorAction` is `Trigger` /// In other cases, It will be created if required, even if it is not passed #[instrument(skip_all, fields(connector_name, payment_method))] pub async fn execute_connector_processing_step< 'b, 'a, T, ResourceCommonData: Clone + RouterDataConversion<T, Req, Resp> + 'static, Req: Debug + Clone + 'static, Resp: Debug + Clone + 'static, >( state: &dyn ApiClientWrapper, connector_integration: BoxedConnectorIntegrationInterface<T, ResourceCommonData, Req, Resp>, req: &'b RouterData<T, Req, Resp>, call_connector_action: common_enums::CallConnectorAction, connector_request: Option<Request>, return_raw_connector_response: Option<bool>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where T: Clone + Debug + 'static, // BoxedConnectorIntegration<T, Req, Resp>: 'b, { // If needed add an error stack as follows // connector_integration.build_request(req).attach_printable("Failed to build request"); tracing::Span::current().record("connector_name", &req.connector); tracing::Span::current().record("payment_method", req.payment_method.to_string()); logger::debug!(connector_request=?connector_request); let mut router_data = req.clone(); match call_connector_action { common_enums::CallConnectorAction::HandleResponse(res) => { let response = types::Response { headers: None, response: res.into(), status_code: 200, }; connector_integration.handle_response(req, None, response) } common_enums::CallConnectorAction::UCSConsumeResponse(_) | common_enums::CallConnectorAction::UCSHandleResponse(_) => { Err(ConnectorError::ProcessingStepFailed(Some( "CallConnectorAction UCSHandleResponse/UCSConsumeResponse used in Direct gateway system flow. These actions are only valid in UCS gateway system" .to_string() .into(), )) .into()) } common_enums::CallConnectorAction::Avoid => Ok(router_data), common_enums::CallConnectorAction::StatusUpdate { status, error_code, error_message, } => { router_data.status = status; let error_response = if error_code.is_some() | error_message.is_some() { Some(ErrorResponse { code: error_code.unwrap_or(consts::NO_ERROR_CODE.to_string()), message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), status_code: 200, // This status code is ignored in redirection response it will override with 302 status code. reason: None, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { None }; router_data.response = error_response.map(Err).unwrap_or(router_data.response); Ok(router_data) } common_enums::CallConnectorAction::Trigger => { metrics::CONNECTOR_CALL_COUNT.add( 1, router_env::metric_attributes!( ("connector", req.connector.to_string()), ( "flow", get_flow_name::<T>().unwrap_or_else(|_| "UnknownFlow".to_string()) ), ), ); let connector_request = match connector_request { Some(connector_request) => Some(connector_request), None => connector_integration .build_request(req, &state.get_connectors()) .inspect_err(|error| { if matches!( error.current_context(), &ConnectorError::RequestEncodingFailed | &ConnectorError::RequestEncodingFailedWithReason(_) ) { metrics::REQUEST_BUILD_FAILURE.add( 1, router_env::metric_attributes!(( "connector", req.connector.clone() )), ) } })?, }; match connector_request { Some(mut request) => { let masked_request_body = match &request.body { Some(request) => match request { RequestContent::Json(i) | RequestContent::FormUrlEncoded(i) | RequestContent::Xml(i) => i .masked_serialize() .unwrap_or(json!({ "error": "failed to mask serialize"})), RequestContent::FormData((_, i)) => i .masked_serialize() .unwrap_or(json!({ "error": "failed to mask serialize"})), RequestContent::RawBytes(_) => json!({"request_type": "RAW_BYTES"}), }, None => serde_json::Value::Null, }; let flow_name = get_flow_name::<T>().unwrap_or_else(|_| "UnknownFlow".to_string()); request.headers.insert(( X_FLOW_NAME.to_string(), Maskable::Masked(masking::Secret::new(flow_name.to_string())), )); let connector_name = req.connector.clone(); request.headers.insert(( X_CONNECTOR_NAME.to_string(), Maskable::Masked(masking::Secret::new(connector_name.clone().to_string())), )); state.get_request_id().as_ref().map(|id| { let request_id = id.to_string(); request.headers.insert(( X_REQUEST_ID.to_string(), Maskable::Normal(request_id.clone()), )); request_id }); let request_url = request.url.clone(); let request_method = request.method; let current_time = Instant::now(); let response = call_connector_api(state, request, "execute_connector_processing_step") .await; let external_latency = current_time.elapsed().as_millis(); logger::info!(raw_connector_request=?masked_request_body); let status_code = response .as_ref() .map(|i| { i.as_ref() .map_or_else(|value| value.status_code, |value| value.status_code) }) .unwrap_or_default(); let mut connector_event = ConnectorEvent::new( state.get_tenant().tenant_id.clone(), req.connector.clone(), std::any::type_name::<T>(), masked_request_body, request_url, request_method, req.payment_id.clone(), req.merchant_id.clone(), state.get_request_id().as_ref(), external_latency, req.refund_id.clone(), req.dispute_id.clone(), req.payout_id.clone(), status_code, ); match response { Ok(body) => { let response = match body { Ok(body) => { let connector_http_status_code = Some(body.status_code); let handle_response_result = connector_integration .handle_response( req, Some(&mut connector_event), body.clone(), ) .inspect_err(|error| { if error.current_context() == &ConnectorError::ResponseDeserializationFailed { metrics::RESPONSE_DESERIALIZATION_FAILURE.add( 1, router_env::metric_attributes!(( "connector", req.connector.clone(), )), ) } }); match handle_response_result { Ok(mut data) => { state .event_handler() .log_connector_event(&connector_event); data.connector_http_status_code = connector_http_status_code; // Add up multiple external latencies in case of multiple external calls within the same request. data.external_latency = Some( data.external_latency .map_or(external_latency, |val| { val + external_latency }), ); store_raw_connector_response_if_required( return_raw_connector_response, &mut data, &body, )?; Ok(data) } Err(err) => { connector_event .set_error(json!({"error": err.to_string()})); state .event_handler() .log_connector_event(&connector_event); Err(err) } }? } Err(body) => { router_data.connector_http_status_code = Some(body.status_code); router_data.external_latency = Some( router_data .external_latency .map_or(external_latency, |val| val + external_latency), ); metrics::CONNECTOR_ERROR_RESPONSE_COUNT.add( 1, router_env::metric_attributes!(( "connector", req.connector.clone(), )), ); store_raw_connector_response_if_required( return_raw_connector_response, &mut router_data, &body, )?; let error = match body.status_code { 500..=511 => { let error_res = connector_integration .get_5xx_error_response( body, Some(&mut connector_event), )?; state .event_handler() .log_connector_event(&connector_event); error_res } _ => { let error_res = connector_integration .get_error_response( body, Some(&mut connector_event), )?; if let Some(status) = error_res.attempt_status { router_data.status = status; }; state .event_handler() .log_connector_event(&connector_event); error_res } }; router_data.response = Err(error); router_data } }; Ok(response) } Err(error) => { connector_event.set_error(json!({"error": error.to_string()})); state.event_handler().log_connector_event(&connector_event); if error.current_context().is_upstream_timeout() { let error_response = ErrorResponse { code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(), message: consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string(), reason: Some(consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string()), status_code: 504, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }; router_data.response = Err(error_response); router_data.connector_http_status_code = Some(504); router_data.external_latency = Some( router_data .external_latency .map_or(external_latency, |val| val + external_latency), ); Ok(router_data) } else { Err(error .change_context(ConnectorError::ProcessingStepFailed(None))) } } } } None => Ok(router_data), } } } } /// Calls the connector API and handles the response #[instrument(skip_all)] pub async fn call_connector_api( state: &dyn ApiClientWrapper, request: Request, flow_name: &str, ) -> CustomResult<Result<types::Response, types::Response>, ApiClientError> { let current_time = Instant::now(); let headers = request.headers.clone(); let url = request.url.clone(); let response = state .get_api_client() .send_request(state, request, None, true) .await; match response.as_ref() { Ok(resp) => { let status_code = resp.status().as_u16(); let elapsed_time = current_time.elapsed(); logger::info!( ?headers, url, status_code, flow=?flow_name, ?elapsed_time ); } Err(err) => { logger::info!( call_connector_api_error=?err ); } } handle_response(response).await } /// Handle the response from the API call #[instrument(skip_all)] pub async fn handle_response( response: CustomResult<reqwest::Response, ApiClientError>, ) -> CustomResult<Result<types::Response, types::Response>, ApiClientError> { response .map(|response| async { logger::info!(?response); let status_code = response.status().as_u16(); let headers = Some(response.headers().to_owned()); match status_code { 200..=202 | 302 | 204 => { // If needed add log line // logger:: error!( error_parsing_response=?err); let response = response .bytes() .await .change_context(ApiClientError::ResponseDecodingFailed) .attach_printable("Error while waiting for response")?; Ok(Ok(types::Response { headers, response, status_code, })) } status_code @ 500..=599 => { let bytes = response.bytes().await.map_err(|error| { report!(error) .change_context(ApiClientError::ResponseDecodingFailed) .attach_printable("Client error response received") })?; // let error = match status_code { // 500 => ApiClientError::InternalServerErrorReceived, // 502 => ApiClientError::BadGatewayReceived, // 503 => ApiClientError::ServiceUnavailableReceived, // 504 => ApiClientError::GatewayTimeoutReceived, // _ => ApiClientError::UnexpectedServerResponse, // }; Ok(Err(types::Response { headers, response: bytes, status_code, })) } status_code @ 400..=499 => { let bytes = response.bytes().await.map_err(|error| { report!(error) .change_context(ApiClientError::ResponseDecodingFailed) .attach_printable("Client error response received") })?; /* let error = match status_code { 400 => ApiClientError::BadRequestReceived(bytes), 401 => ApiClientError::UnauthorizedReceived(bytes), 403 => ApiClientError::ForbiddenReceived, 404 => ApiClientError::NotFoundReceived(bytes), 405 => ApiClientError::MethodNotAllowedReceived, 408 => ApiClientError::RequestTimeoutReceived, 422 => ApiClientError::UnprocessableEntityReceived(bytes), 429 => ApiClientError::TooManyRequestsReceived, _ => ApiClientError::UnexpectedServerResponse, }; Err(report!(error).attach_printable("Client error response received")) */ Ok(Err(types::Response { headers, response: bytes, status_code, })) } _ => Err(report!(ApiClientError::UnexpectedServerResponse) .attach_printable("Unexpected response from server")), } })? .await } /// Store the raw connector response in the router data if required pub fn store_raw_connector_response_if_required<T, Req, Resp>( return_raw_connector_response: Option<bool>, router_data: &mut RouterData<T, Req, Resp>, body: &types::Response, ) -> CustomResult<(), ConnectorError> where T: Clone + Debug + 'static, Req: Debug + Clone + 'static, Resp: Debug + Clone + 'static, { if return_raw_connector_response == Some(true) { let mut decoded = String::from_utf8(body.response.as_ref().to_vec()) .change_context(ConnectorError::ResponseDeserializationFailed)?; if decoded.starts_with('\u{feff}') { decoded = decoded.trim_start_matches('\u{feff}').to_string(); } router_data.raw_connector_response = Some(masking::Secret::new(decoded)); } Ok(()) } /// Get the flow name from the type #[inline] pub fn get_flow_name<F>() -> CustomResult<String, api_error_response::ApiErrorResponse> { Ok(std::any::type_name::<F>() .to_string() .rsplit("::") .next() .ok_or(api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Flow stringify failed")? .to_string()) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/authentication.rs
crates/hyperswitch_interfaces/src/authentication.rs
//! Authentication interface /// struct ExternalAuthenticationPayload #[derive(Clone, serde::Deserialize, Debug, serde::Serialize, PartialEq, Eq)] pub struct ExternalAuthenticationPayload { /// trans_status pub trans_status: common_enums::TransactionStatus, /// authentication_value pub authentication_value: Option<masking::Secret<String>>, /// eci pub eci: Option<String>, /// Indicates whether the challenge was canceled by the user or system. pub challenge_cancel: Option<String>, /// Reason for the challenge code, if applicable. pub challenge_code_reason: Option<String>, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/events.rs
crates/hyperswitch_interfaces/src/events.rs
use crate::events::connector_api_logs::ConnectorEvent; pub mod connector_api_logs; pub mod routing_api_logs; /// Event handling interface #[async_trait::async_trait] pub trait EventHandlerInterface: dyn_clone::DynClone where Self: Send + Sync, { /// Logs connector events #[track_caller] fn log_connector_event(&self, event: &ConnectorEvent); }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/metrics.rs
crates/hyperswitch_interfaces/src/metrics.rs
//! Metrics interface use router_env::{counter_metric, global_meter}; global_meter!(GLOBAL_METER, "ROUTER_API"); counter_metric!(UNIMPLEMENTED_FLOW, GLOBAL_METER); counter_metric!(CONNECTOR_CALL_COUNT, GLOBAL_METER); // Attributes needed counter_metric!(RESPONSE_DESERIALIZATION_FAILURE, GLOBAL_METER); counter_metric!(CONNECTOR_ERROR_RESPONSE_COUNT, GLOBAL_METER); // Connector Level Metric counter_metric!(REQUEST_BUILD_FAILURE, GLOBAL_METER);
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/connector_integration_interface.rs
crates/hyperswitch_interfaces/src/connector_integration_interface.rs
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; use common_enums::PaymentAction; use common_utils::{crypto, errors::CustomResult, request::Request}; use hyperswitch_domain_models::{ api::ApplicationResponse, connector_endpoints::Connectors, errors::api_error_response::ApiErrorResponse, payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_data_v2::RouterDataV2, router_response_types::{ConnectorInfo, SupportedPaymentMethods}, }; use crate::{ api, api::{ BoxedConnectorIntegration, CaptureSyncMethod, Connector, ConnectorAccessTokenSuffix, ConnectorCommon, ConnectorIntegration, ConnectorRedirectResponse, ConnectorSpecifications, ConnectorValidation, CurrencyUnit, }, authentication::ExternalAuthenticationPayload, connector_integration_v2::{BoxedConnectorIntegrationV2, ConnectorIntegrationV2, ConnectorV2}, disputes, errors, events::connector_api_logs::ConnectorEvent, types, webhooks::{IncomingWebhook, IncomingWebhookFlowError, IncomingWebhookRequestDetails}, }; /// RouterDataConversion trait /// /// This trait must be implemented for conversion between Router data and RouterDataV2 pub trait RouterDataConversion<T, Req: Clone, Resp: Clone> { /// Convert RouterData to RouterDataV2 /// /// # Arguments /// /// * `old_router_data` - A reference to the old RouterData /// /// # Returns /// /// A `CustomResult` containing the new RouterDataV2 or a ConnectorError fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, errors::ConnectorError> where Self: Sized; /// Convert RouterDataV2 back to RouterData /// /// # Arguments /// /// * `new_router_data` - The new RouterDataV2 /// /// # Returns /// /// A `CustomResult` containing the old RouterData or a ConnectorError fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, errors::ConnectorError> where Self: Sized; } /// Alias for Box<&'static (dyn Connector + Sync)> pub type BoxedConnector = Box<&'static (dyn Connector + Sync)>; /// Alias for Box<&'static (dyn ConnectorV2 + Sync)> pub type BoxedConnectorV2 = Box<&'static (dyn ConnectorV2 + Sync)>; /// Enum representing the Connector #[derive(Clone)] pub enum ConnectorEnum { /// Old connector type Old(BoxedConnector), /// New connector type New(BoxedConnectorV2), } impl std::fmt::Debug for ConnectorEnum { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Old(_) => f .debug_tuple("Old") .field(&std::any::type_name::<BoxedConnector>().to_string()) .finish(), Self::New(_) => f .debug_tuple("New") .field(&std::any::type_name::<BoxedConnectorV2>().to_string()) .finish(), } } } #[allow(missing_debug_implementations)] /// Enum representing the Connector Integration #[derive(Clone)] pub enum ConnectorIntegrationEnum<'a, F, ResourceCommonData, Req, Resp> { /// Old connector integration type Old(BoxedConnectorIntegration<'a, F, Req, Resp>), /// New connector integration type New(BoxedConnectorIntegrationV2<'a, F, ResourceCommonData, Req, Resp>), } /// Alias for Box<dyn ConnectorIntegrationInterface> pub type BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp> = Box<dyn ConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp> + Send + Sync>; impl ConnectorEnum { /// Get the connector integration /// /// # Returns /// /// A `BoxedConnectorIntegrationInterface` containing the connector integration pub fn get_connector_integration<F, ResourceCommonData, Req, Resp>( &self, ) -> BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp> where dyn Connector + Sync: ConnectorIntegration<F, Req, Resp>, dyn ConnectorV2 + Sync: ConnectorIntegrationV2<F, ResourceCommonData, Req, Resp>, ResourceCommonData: RouterDataConversion<F, Req, Resp> + Clone + 'static, F: Clone + 'static, Req: Clone + 'static, Resp: Clone + 'static, { match self { Self::Old(old_integration) => Box::new(ConnectorIntegrationEnum::Old( old_integration.get_connector_integration(), )), Self::New(new_integration) => Box::new(ConnectorIntegrationEnum::New( new_integration.get_connector_integration_v2(), )), } } /// validates the file upload pub fn validate_file_upload( &self, purpose: api::files::FilePurpose, file_size: i32, file_type: mime::Mime, ) -> CustomResult<(), errors::ConnectorError> { match self { Self::Old(connector) => connector.validate_file_upload(purpose, file_size, file_type), Self::New(connector) => { connector.validate_file_upload_v2(purpose, file_size, file_type) } } } } #[async_trait::async_trait] impl IncomingWebhook for ConnectorEnum { fn get_webhook_body_decoding_algorithm( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::DecodeMessage + Send>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_body_decoding_algorithm(request), Self::New(connector) => connector.get_webhook_body_decoding_algorithm(request), } } fn get_webhook_body_decoding_message( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_body_decoding_message(request), Self::New(connector) => connector.get_webhook_body_decoding_message(request), } } async fn decode_webhook_body( &self, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, connector_name: &str, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { match self { Self::Old(connector) => { connector .decode_webhook_body( request, merchant_id, connector_webhook_details, connector_name, ) .await } Self::New(connector) => { connector .decode_webhook_body( request, merchant_id, connector_webhook_details, connector_name, ) .await } } } fn get_webhook_source_verification_algorithm( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_source_verification_algorithm(request), Self::New(connector) => connector.get_webhook_source_verification_algorithm(request), } } async fn get_webhook_source_verification_merchant_secret( &self, merchant_id: &common_utils::id_type::MerchantId, connector_name: &str, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<api_models::webhooks::ConnectorWebhookSecrets, errors::ConnectorError> { match self { Self::Old(connector) => { connector .get_webhook_source_verification_merchant_secret( merchant_id, connector_name, connector_webhook_details, ) .await } Self::New(connector) => { connector .get_webhook_source_verification_merchant_secret( merchant_id, connector_name, connector_webhook_details, ) .await } } } fn get_webhook_source_verification_signature( &self, request: &IncomingWebhookRequestDetails<'_>, connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { match self { Self::Old(connector) => connector .get_webhook_source_verification_signature(request, connector_webhook_secrets), Self::New(connector) => connector .get_webhook_source_verification_signature(request, connector_webhook_secrets), } } fn get_webhook_source_verification_message( &self, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_source_verification_message( request, merchant_id, connector_webhook_secrets, ), Self::New(connector) => connector.get_webhook_source_verification_message( request, merchant_id, connector_webhook_secrets, ), } } async fn verify_webhook_source( &self, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, connector_account_details: crypto::Encryptable<masking::Secret<serde_json::Value>>, connector_name: &str, ) -> CustomResult<bool, errors::ConnectorError> { match self { Self::Old(connector) => { connector .verify_webhook_source( request, merchant_id, connector_webhook_details, connector_account_details, connector_name, ) .await } Self::New(connector) => { connector .verify_webhook_source( request, merchant_id, connector_webhook_details, connector_account_details, connector_name, ) .await } } } fn get_webhook_object_reference_id( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<ObjectReferenceId, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_object_reference_id(request), Self::New(connector) => connector.get_webhook_object_reference_id(request), } } #[cfg(feature = "payouts")] fn get_payout_webhook_details( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::PayoutWebhookUpdate, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_payout_webhook_details(request), Self::New(connector) => connector.get_payout_webhook_details(request), } } fn get_webhook_event_type( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_event_type(request), Self::New(connector) => connector.get_webhook_event_type(request), } } fn get_webhook_resource_object( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_resource_object(request), Self::New(connector) => connector.get_webhook_resource_object(request), } } fn get_webhook_api_response( &self, request: &IncomingWebhookRequestDetails<'_>, error_kind: Option<IncomingWebhookFlowError>, ) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_api_response(request, error_kind), Self::New(connector) => connector.get_webhook_api_response(request, error_kind), } } fn get_dispute_details( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<disputes::DisputePayload, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_dispute_details(request), Self::New(connector) => connector.get_dispute_details(request), } } fn get_external_authentication_details( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<ExternalAuthenticationPayload, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_external_authentication_details(request), Self::New(connector) => connector.get_external_authentication_details(request), } } fn get_mandate_details( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< Option<hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails>, errors::ConnectorError, > { match self { Self::Old(connector) => connector.get_mandate_details(request), Self::New(connector) => connector.get_mandate_details(request), } } fn get_network_txn_id( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< Option<hyperswitch_domain_models::router_flow_types::ConnectorNetworkTxnId>, errors::ConnectorError, > { match self { Self::Old(connector) => connector.get_network_txn_id(request), Self::New(connector) => connector.get_network_txn_id(request), } } fn get_additional_payment_method_data( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< Option<api_models::payment_methods::PaymentMethodUpdate>, errors::ConnectorError, > { match self { Self::Old(connector) => connector.get_additional_payment_method_data(request), Self::New(connector) => connector.get_additional_payment_method_data(request), } } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] fn get_revenue_recovery_invoice_details( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< hyperswitch_domain_models::revenue_recovery::RevenueRecoveryInvoiceData, errors::ConnectorError, > { match self { Self::Old(connector) => connector.get_revenue_recovery_invoice_details(request), Self::New(connector) => connector.get_revenue_recovery_invoice_details(request), } } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] fn get_revenue_recovery_attempt_details( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< hyperswitch_domain_models::revenue_recovery::RevenueRecoveryAttemptData, errors::ConnectorError, > { match self { Self::Old(connector) => connector.get_revenue_recovery_attempt_details(request), Self::New(connector) => connector.get_revenue_recovery_attempt_details(request), } } fn get_subscription_mit_payment_data( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< hyperswitch_domain_models::router_flow_types::SubscriptionMitPaymentData, errors::ConnectorError, > { match self { Self::Old(connector) => connector.get_subscription_mit_payment_data(request), Self::New(connector) => connector.get_subscription_mit_payment_data(request), } } } impl ConnectorRedirectResponse for ConnectorEnum { fn get_flow_type( &self, query_params: &str, json_payload: Option<serde_json::Value>, action: PaymentAction, ) -> CustomResult<common_enums::CallConnectorAction, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_flow_type(query_params, json_payload, action), Self::New(connector) => connector.get_flow_type(query_params, json_payload, action), } } } impl ConnectorValidation for ConnectorEnum { fn validate_connector_against_payment_request( &self, capture_method: Option<common_enums::CaptureMethod>, payment_method: common_enums::PaymentMethod, pmt: Option<common_enums::PaymentMethodType>, ) -> CustomResult<(), errors::ConnectorError> { match self { Self::Old(connector) => connector.validate_connector_against_payment_request( capture_method, payment_method, pmt, ), Self::New(connector) => connector.validate_connector_against_payment_request( capture_method, payment_method, pmt, ), } } fn validate_mandate_payment( &self, pm_type: Option<common_enums::PaymentMethodType>, pm_data: PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { match self { Self::Old(connector) => connector.validate_mandate_payment(pm_type, pm_data), Self::New(connector) => connector.validate_mandate_payment(pm_type, pm_data), } } fn validate_psync_reference_id( &self, data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData, is_three_ds: bool, status: common_enums::enums::AttemptStatus, connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<(), errors::ConnectorError> { match self { Self::Old(connector) => connector.validate_psync_reference_id( data, is_three_ds, status, connector_meta_data, ), Self::New(connector) => connector.validate_psync_reference_id( data, is_three_ds, status, connector_meta_data, ), } } fn is_webhook_source_verification_mandatory(&self) -> bool { match self { Self::Old(connector) => connector.is_webhook_source_verification_mandatory(), Self::New(connector) => connector.is_webhook_source_verification_mandatory(), } } } impl ConnectorSpecifications for ConnectorEnum { fn is_order_create_flow_required(&self, current_flow: api::CurrentFlowInfo<'_>) -> bool { match self { Self::Old(connector) => connector.is_order_create_flow_required(current_flow), Self::New(connector) => connector.is_order_create_flow_required(current_flow), } } fn is_pre_authentication_flow_required(&self, current_flow: api::CurrentFlowInfo<'_>) -> bool { match self { Self::Old(connector) => connector.is_pre_authentication_flow_required(current_flow), Self::New(connector) => connector.is_pre_authentication_flow_required(current_flow), } } fn is_authentication_flow_required(&self, current_flow: api::CurrentFlowInfo<'_>) -> bool { match self { Self::Old(connector) => connector.is_authentication_flow_required(current_flow), Self::New(connector) => connector.is_authentication_flow_required(current_flow), } } fn is_post_authentication_flow_required(&self, current_flow: api::CurrentFlowInfo<'_>) -> bool { match self { Self::Old(connector) => connector.is_post_authentication_flow_required(current_flow), Self::New(connector) => connector.is_post_authentication_flow_required(current_flow), } } fn get_preprocessing_flow_if_needed( &self, current_flow_info: api::CurrentFlowInfo<'_>, ) -> Option<api::PreProcessingFlowName> { match self { Self::Old(connector) => connector.get_preprocessing_flow_if_needed(current_flow_info), Self::New(connector) => connector.get_preprocessing_flow_if_needed(current_flow_info), } } fn get_alternate_flow_if_needed( &self, current_flow: api::CurrentFlowInfo<'_>, ) -> Option<api::AlternateFlow> { match self { Self::Old(connector) => connector.get_alternate_flow_if_needed(current_flow), Self::New(connector) => connector.get_alternate_flow_if_needed(current_flow), } } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { match self { Self::Old(connector) => connector.get_supported_payment_methods(), Self::New(connector) => connector.get_supported_payment_methods(), } } /// Supported webhooks flows fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::EventClass]> { match self { Self::Old(connector) => connector.get_supported_webhook_flows(), Self::New(connector) => connector.get_supported_webhook_flows(), } } /// Details related to connector fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { match self { Self::Old(connector) => connector.get_connector_about(), Self::New(connector) => connector.get_connector_about(), } } /// Check if connector supports authentication token fn authentication_token_for_token_creation(&self) -> bool { match self { Self::Old(connector) => connector.authentication_token_for_token_creation(), Self::New(connector) => connector.authentication_token_for_token_creation(), } } /// If connector supports session token generation fn is_sdk_client_token_generation_enabled(&self) -> bool { match self { Self::Old(connector) => connector.is_sdk_client_token_generation_enabled(), Self::New(connector) => connector.is_sdk_client_token_generation_enabled(), } } /// Supported payment methods for session token generation fn supported_payment_method_types_for_sdk_client_token_generation( &self, ) -> Vec<common_enums::PaymentMethodType> { match self { Self::Old(connector) => { connector.supported_payment_method_types_for_sdk_client_token_generation() } Self::New(connector) => { connector.supported_payment_method_types_for_sdk_client_token_generation() } } } /// Validate whether session token is generated for payment payment type fn validate_sdk_session_token_for_payment_method( &self, current_core_payment_method_type: &common_enums::PaymentMethodType, ) -> bool { match self { Self::Old(connector) => connector .validate_sdk_session_token_for_payment_method(current_core_payment_method_type), Self::New(connector) => connector .validate_sdk_session_token_for_payment_method(current_core_payment_method_type), } } /// Check if the connector needs authorize session token call fn is_authorize_session_token_call_required(&self) -> bool { match self { Self::Old(connector) => connector.is_authorize_session_token_call_required(), Self::New(connector) => connector.is_authorize_session_token_call_required(), } } #[cfg(feature = "v1")] fn generate_connector_request_reference_id( &self, payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, is_config_enabled_to_send_payment_id_as_connector_request_id: bool, ) -> String { match self { Self::Old(connector) => connector.generate_connector_request_reference_id( payment_intent, payment_attempt, is_config_enabled_to_send_payment_id_as_connector_request_id, ), Self::New(connector) => connector.generate_connector_request_reference_id( payment_intent, payment_attempt, is_config_enabled_to_send_payment_id_as_connector_request_id, ), } } #[cfg(feature = "v2")] /// Generate connector request reference ID fn generate_connector_request_reference_id( &self, payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> String { match self { Self::Old(connector) => { connector.generate_connector_request_reference_id(payment_intent, payment_attempt) } Self::New(connector) => { connector.generate_connector_request_reference_id(payment_intent, payment_attempt) } } } #[cfg(feature = "v1")] fn generate_connector_customer_id( &self, customer_id: &Option<common_utils::id_type::CustomerId>, merchant_id: &common_utils::id_type::MerchantId, ) -> Option<String> { match self { Self::Old(connector) => { connector.generate_connector_customer_id(customer_id, merchant_id) } Self::New(connector) => { connector.generate_connector_customer_id(customer_id, merchant_id) } } } #[cfg(feature = "v2")] fn generate_connector_customer_id( &self, customer_id: &Option<common_utils::id_type::CustomerId>, merchant_id: &common_utils::id_type::MerchantId, ) -> Option<String> { todo!() } /// Check if connector requires create customer call fn should_call_connector_customer( &self, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> bool { match self { Self::Old(connector) => connector.should_call_connector_customer(payment_attempt), Self::New(connector) => connector.should_call_connector_customer(payment_attempt), } } fn should_call_tokenization_before_setup_mandate(&self) -> bool { match self { Self::Old(connector) => connector.should_call_tokenization_before_setup_mandate(), Self::New(connector) => connector.should_call_tokenization_before_setup_mandate(), } } } impl ConnectorCommon for ConnectorEnum { fn id(&self) -> &'static str { match self { Self::Old(connector) => connector.id(), Self::New(connector) => connector.id(), } } fn get_currency_unit(&self) -> CurrencyUnit { match self { Self::Old(connector) => connector.get_currency_unit(), Self::New(connector) => connector.get_currency_unit(), } } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_auth_header(auth_type), Self::New(connector) => connector.get_auth_header(auth_type), } } fn common_get_content_type(&self) -> &'static str { match self { Self::Old(connector) => connector.common_get_content_type(), Self::New(connector) => connector.common_get_content_type(), } } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { match self { Self::Old(connector) => connector.base_url(connectors), Self::New(connector) => connector.base_url(connectors), } } fn build_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { match self { Self::Old(connector) => connector.build_error_response(res, event_builder), Self::New(connector) => connector.build_error_response(res, event_builder), } } } impl ConnectorAccessTokenSuffix for ConnectorEnum { fn get_access_token_key<F, Req, Res>( &self, router_data: &RouterData<F, Req, Res>, merchant_connector_id_or_connector_name: String, ) -> CustomResult<String, errors::ConnectorError> { match self { Self::Old(connector) => { connector.get_access_token_key(router_data, merchant_connector_id_or_connector_name) } Self::New(connector) => { connector.get_access_token_key(router_data, merchant_connector_id_or_connector_name) } } } } /// Trait representing the connector integration interface /// /// This trait defines the methods required for a connector integration interface. pub trait ConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>: Send + Sync { /// Clone the connector integration interface /// /// # Returns /// /// A `Box` containing the cloned connector integration interface fn clone_box( &self, ) -> Box<dyn ConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp> + Send + Sync>; /// Get the multiple capture sync method /// /// # Returns /// /// A `CustomResult` containing the `CaptureSyncMethod` or a `ConnectorError` fn get_multiple_capture_sync_method( &self, ) -> CustomResult<CaptureSyncMethod, errors::ConnectorError>; /// Build a request for the connector integration /// /// # Arguments /// /// * `req` - A reference to the RouterData /// # Returns /// /// A `CustomResult` containing an optional Request or a ConnectorError fn build_request( &self, req: &RouterData<F, Req, Resp>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError>; /// handles response from the connector fn handle_response( &self, data: &RouterData<F, Req, Resp>, event_builder: Option<&mut ConnectorEvent>, _res: types::Response, ) -> CustomResult<RouterData<F, Req, Resp>, errors::ConnectorError> where F: Clone, Req: Clone, Resp: Clone; /// Get the error response /// /// # Arguments /// /// * `res` - The response /// * `event_builder` - An optional event builder /// /// # Returns /// /// A `CustomResult` containing the `ErrorResponse` or a `ConnectorError` fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError>; /// Get the 5xx error response /// /// # Arguments /// /// * `res` - The response /// * `event_builder` - An optional event builder /// /// # Returns /// /// A `CustomResult` containing the `ErrorResponse` or a `ConnectorError` fn get_5xx_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError>; } impl<T: 'static, ResourceCommonData: 'static, Req: 'static, Resp: 'static> ConnectorIntegrationInterface<T, ResourceCommonData, Req, Resp>
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/configs.rs
crates/hyperswitch_interfaces/src/configs.rs
use common_utils::{crypto::Encryptable, errors::CustomResult, id_type}; pub use hyperswitch_domain_models::{ connector_endpoints::Connectors, errors::api_error_response, merchant_connector_account, }; use masking::{PeekInterface, Secret}; use serde::Deserialize; #[allow(missing_docs)] #[derive(Debug, Clone)] pub struct Tenant { pub tenant_id: id_type::TenantId, pub base_url: String, pub schema: String, pub accounts_schema: String, pub redis_key_prefix: String, pub clickhouse_database: String, pub user: TenantUserConfig, } #[allow(missing_docs)] #[derive(Debug, Deserialize, Clone)] pub struct TenantUserConfig { pub control_center_url: String, } impl common_utils::types::TenantConfig for Tenant { fn get_tenant_id(&self) -> &id_type::TenantId { &self.tenant_id } fn get_accounts_schema(&self) -> &str { self.accounts_schema.as_str() } fn get_schema(&self) -> &str { self.schema.as_str() } fn get_redis_key_prefix(&self) -> &str { self.redis_key_prefix.as_str() } fn get_clickhouse_database(&self) -> &str { self.clickhouse_database.as_str() } } #[allow(missing_docs)] // Todo: Global tenant should not be part of tenant config(https://github.com/juspay/hyperswitch/issues/7237) #[derive(Debug, Deserialize, Clone)] pub struct GlobalTenant { #[serde(default = "id_type::TenantId::get_default_global_tenant_id")] pub tenant_id: id_type::TenantId, pub schema: String, pub redis_key_prefix: String, pub clickhouse_database: String, } // Todo: Global tenant should not be part of tenant config impl common_utils::types::TenantConfig for GlobalTenant { fn get_tenant_id(&self) -> &id_type::TenantId { &self.tenant_id } fn get_accounts_schema(&self) -> &str { self.schema.as_str() } fn get_schema(&self) -> &str { self.schema.as_str() } fn get_redis_key_prefix(&self) -> &str { self.redis_key_prefix.as_str() } fn get_clickhouse_database(&self) -> &str { self.clickhouse_database.as_str() } } impl Default for GlobalTenant { fn default() -> Self { Self { tenant_id: id_type::TenantId::get_default_global_tenant_id(), schema: String::from("global"), redis_key_prefix: String::from("global"), clickhouse_database: String::from("global"), } } } #[allow(missing_docs)] #[derive(Debug, Clone, Default, Deserialize)] #[serde(default)] pub struct InternalMerchantIdProfileIdAuthSettings { pub enabled: bool, pub internal_api_key: Secret<String>, } #[allow(missing_docs)] #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct InternalServicesConfig { pub payments_base_url: String, } #[allow(missing_docs)] #[derive(Debug, Clone)] pub enum MerchantConnectorAccountType { DbVal(Box<merchant_connector_account::MerchantConnectorAccount>), CacheVal(api_models::admin::MerchantConnectorDetails), } #[allow(missing_docs)] impl MerchantConnectorAccountType { pub fn get_metadata(&self) -> Option<Secret<serde_json::Value>> { match self { Self::DbVal(val) => val.metadata.to_owned(), Self::CacheVal(val) => val.metadata.to_owned(), } } pub fn get_connector_account_details(&self) -> serde_json::Value { match self { Self::DbVal(val) => val.connector_account_details.peek().to_owned(), Self::CacheVal(val) => val.connector_account_details.peek().to_owned(), } } pub fn get_connector_wallets_details(&self) -> Option<Secret<serde_json::Value>> { match self { Self::DbVal(val) => val.connector_wallets_details.as_deref().cloned(), Self::CacheVal(_) => None, } } pub fn is_disabled(&self) -> bool { match self { Self::DbVal(ref inner) => inner.disabled.unwrap_or(false), // Cached merchant connector account, only contains the account details, // the merchant connector account must only be cached if it's not disabled Self::CacheVal(_) => false, } } #[cfg(feature = "v1")] pub fn is_test_mode_on(&self) -> Option<bool> { match self { Self::DbVal(val) => val.test_mode, Self::CacheVal(_) => None, } } #[cfg(feature = "v2")] pub fn is_test_mode_on(&self) -> Option<bool> { None } pub fn get_mca_id(&self) -> Option<id_type::MerchantConnectorAccountId> { match self { Self::DbVal(db_val) => Some(db_val.get_id()), Self::CacheVal(_) => None, } } #[cfg(feature = "v1")] pub fn get_connector_name(&self) -> Option<String> { match self { Self::DbVal(db_val) => Some(db_val.connector_name.to_string()), Self::CacheVal(_) => None, } } #[cfg(feature = "v2")] pub fn get_connector_name(&self) -> Option<common_enums::connector_enums::Connector> { match self { Self::DbVal(db_val) => Some(db_val.connector_name), Self::CacheVal(_) => None, } } pub fn get_additional_merchant_data(&self) -> Option<Encryptable<Secret<serde_json::Value>>> { match self { Self::DbVal(db_val) => db_val.additional_merchant_data.clone(), Self::CacheVal(_) => None, } } pub fn get_webhook_details( &self, ) -> CustomResult<Option<&Secret<serde_json::Value>>, api_error_response::ApiErrorResponse> { match self { Self::DbVal(db_val) => Ok(db_val.connector_webhook_details.as_ref()), Self::CacheVal(_) => Ok(None), } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/crm.rs
crates/hyperswitch_interfaces/src/crm.rs
use common_enums::CountryAlpha2; use common_utils::{ errors::CustomResult, request::{Request, RequestContent}, }; use masking::Secret; use super::types::Proxy; use crate::errors::HttpClientError; /// Crm Payload structure #[derive(Clone, Debug, serde::Serialize, Default)] pub struct CrmPayload { /// The legal name of the business. pub legal_business_name: Option<String>, /// A label or tag associated with the business. pub business_label: Option<String>, /// The location of the business, represented as a country code (ISO Alpha-2 format). pub business_location: Option<CountryAlpha2>, /// The display name of the business. pub display_name: Option<String>, /// The email address of the point of contact (POC) for the business. pub poc_email: Option<Secret<String>>, /// The type of business (e.g., LLC, Corporation, etc.). pub business_type: Option<String>, /// A unique identifier for the business. pub business_identifier: Option<String>, /// The website URL of the business. pub business_website: Option<String>, /// The name of the point of contact (POC) for the business. pub poc_name: Option<Secret<String>>, /// The contact number of the point of contact (POC) for the business. pub poc_contact: Option<Secret<String>>, /// Additional comments or notes about the business. pub comments: Option<String>, /// Indicates whether the Crm process for the business is completed. pub is_completed: bool, /// The name of the country where the business is located. pub business_country_name: Option<String>, } /// Trait defining the interface for encryption management #[async_trait::async_trait] pub trait CrmInterface: Send + Sync { /// Make body for the request async fn make_body(&self, details: CrmPayload) -> RequestContent; /// Encrypt the given input data async fn make_request(&self, body: RequestContent, origin_base_url: String) -> Request; /// Decrypt the given input data async fn send_request( &self, proxy: &Proxy, request: Request, ) -> CustomResult<reqwest::Response, HttpClientError>; }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/conversion_impls.rs
crates/hyperswitch_interfaces/src/conversion_impls.rs
use common_utils::{errors::CustomResult, id_type}; use error_stack::ResultExt; #[cfg(feature = "frm")] use hyperswitch_domain_models::router_data_v2::flow_common_types::FrmFlowData; #[cfg(feature = "payouts")] use hyperswitch_domain_models::router_data_v2::flow_common_types::PayoutFlowData; use hyperswitch_domain_models::{ payment_address::PaymentAddress, router_data::{self, RouterData}, router_data_v2::{ flow_common_types::{ AccessTokenFlowData, AuthenticationTokenFlowData, BillingConnectorInvoiceSyncFlowData, BillingConnectorPaymentsSyncFlowData, DisputesFlowData, ExternalAuthenticationFlowData, ExternalVaultProxyFlowData, FilesFlowData, GetSubscriptionEstimateData, GetSubscriptionItemPricesData, GetSubscriptionItemsData, GiftCardBalanceCheckFlowData, InvoiceRecordBackData, MandateRevokeFlowData, PaymentFlowData, RefundFlowData, SubscriptionCancelData, SubscriptionCreateData, SubscriptionCustomerData, SubscriptionPauseData, SubscriptionResumeData, UasFlowData, VaultConnectorFlowData, WebhookSourceVerifyData, }, RouterDataV2, }, }; use crate::{connector_integration_interface::RouterDataConversion, errors::ConnectorError}; fn get_irrelevant_id_string(id_name: &str, flow_name: &str) -> String { format!("irrelevant {id_name} in {flow_name} flow") } fn get_default_router_data<F, Req, Resp>( tenant_id: id_type::TenantId, flow_name: &str, request: Req, response: Result<Resp, router_data::ErrorResponse>, ) -> RouterData<F, Req, Resp> { RouterData { tenant_id, flow: std::marker::PhantomData, merchant_id: id_type::MerchantId::get_irrelevant_merchant_id(), customer_id: None, connector_customer: None, connector: get_irrelevant_id_string("connector", flow_name), payment_id: id_type::PaymentId::get_irrelevant_id(flow_name) .get_string_repr() .to_owned(), attempt_id: get_irrelevant_id_string("attempt_id", flow_name), status: common_enums::AttemptStatus::default(), payment_method: common_enums::PaymentMethod::default(), connector_auth_type: router_data::ConnectorAuthType::default(), description: None, address: PaymentAddress::default(), auth_type: common_enums::AuthenticationType::default(), connector_meta_data: None, connector_wallets_details: None, amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_token: None, recurring_mandate_payment_data: None, preprocessing_id: None, payment_method_balance: None, connector_api_version: None, request, response, connector_request_reference_id: get_irrelevant_id_string( "connector_request_reference_id", flow_name, ), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, dispute_id: None, refund_id: None, payout_id: None, connector_response: None, payment_method_status: None, minor_amount_captured: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: None, payment_method_type: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for AuthenticationTokenFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self {}; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self {} = new_router_data.resource_common_data; let request = new_router_data.request.clone(); let response = new_router_data.response.clone(); let router_data = get_default_router_data( new_router_data.tenant_id.clone(), "authentication token", request, response, ); Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for AccessTokenFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self {}; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self {} = new_router_data.resource_common_data; let request = new_router_data.request.clone(); let response = new_router_data.response.clone(); let router_data = get_default_router_data( new_router_data.tenant_id.clone(), "access token", request, response, ); Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for GiftCardBalanceCheckFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let request = new_router_data.request.clone(); let response = new_router_data.response.clone(); let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "gift card balance check", request, response, ); router_data.connector_auth_type = new_router_data.connector_auth_type; Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for PaymentFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { merchant_id: old_router_data.merchant_id.clone(), customer_id: old_router_data.customer_id.clone(), connector_customer: old_router_data.connector_customer.clone(), connector: old_router_data.connector.clone(), payment_id: old_router_data.payment_id.clone(), attempt_id: old_router_data.attempt_id.clone(), status: old_router_data.status, payment_method: old_router_data.payment_method, description: old_router_data.description.clone(), address: old_router_data.address.clone(), auth_type: old_router_data.auth_type, connector_meta_data: old_router_data.connector_meta_data.clone(), amount_captured: old_router_data.amount_captured, minor_amount_captured: old_router_data.minor_amount_captured, access_token: old_router_data.access_token.clone(), session_token: old_router_data.session_token.clone(), reference_id: old_router_data.reference_id.clone(), payment_method_token: old_router_data.payment_method_token.clone(), recurring_mandate_payment_data: old_router_data.recurring_mandate_payment_data.clone(), preprocessing_id: old_router_data.preprocessing_id.clone(), payment_method_balance: old_router_data.payment_method_balance.clone(), connector_api_version: old_router_data.connector_api_version.clone(), connector_request_reference_id: old_router_data.connector_request_reference_id.clone(), test_mode: old_router_data.test_mode, connector_http_status_code: old_router_data.connector_http_status_code, external_latency: old_router_data.external_latency, apple_pay_flow: old_router_data.apple_pay_flow.clone(), connector_response: old_router_data.connector_response.clone(), payment_method_status: old_router_data.payment_method_status, }; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { merchant_id, customer_id, connector_customer, connector, payment_id, attempt_id, status, payment_method, description, address, auth_type, connector_meta_data, amount_captured, minor_amount_captured, access_token, session_token, reference_id, payment_method_token, recurring_mandate_payment_data, preprocessing_id, payment_method_balance, connector_api_version, connector_request_reference_id, test_mode, connector_http_status_code, external_latency, apple_pay_flow, connector_response, payment_method_status, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "payment", new_router_data.request, new_router_data.response, ); router_data.merchant_id = merchant_id; router_data.customer_id = customer_id; router_data.connector_customer = connector_customer; router_data.connector = connector; router_data.payment_id = payment_id; router_data.attempt_id = attempt_id; router_data.status = status; router_data.payment_method = payment_method; router_data.description = description; router_data.address = address; router_data.auth_type = auth_type; router_data.connector_meta_data = connector_meta_data; router_data.amount_captured = amount_captured; router_data.minor_amount_captured = minor_amount_captured; router_data.access_token = access_token; router_data.session_token = session_token; router_data.reference_id = reference_id; router_data.payment_method_token = payment_method_token; router_data.recurring_mandate_payment_data = recurring_mandate_payment_data; router_data.preprocessing_id = preprocessing_id; router_data.payment_method_balance = payment_method_balance; router_data.connector_api_version = connector_api_version; router_data.connector_request_reference_id = connector_request_reference_id; router_data.test_mode = test_mode; router_data.connector_http_status_code = connector_http_status_code; router_data.external_latency = external_latency; router_data.apple_pay_flow = apple_pay_flow; router_data.connector_response = connector_response; router_data.payment_method_status = payment_method_status; router_data.connector_auth_type = new_router_data.connector_auth_type; Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for RefundFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { merchant_id: old_router_data.merchant_id.clone(), customer_id: old_router_data.customer_id.clone(), payment_id: old_router_data.payment_id.clone(), attempt_id: old_router_data.attempt_id.clone(), status: old_router_data.status, payment_method: old_router_data.payment_method, connector_meta_data: old_router_data.connector_meta_data.clone(), amount_captured: old_router_data.amount_captured, minor_amount_captured: old_router_data.minor_amount_captured, connector_request_reference_id: old_router_data.connector_request_reference_id.clone(), refund_id: old_router_data.refund_id.clone().ok_or( ConnectorError::MissingRequiredField { field_name: "refund_id", }, )?, }; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { merchant_id, customer_id, payment_id, attempt_id, status, payment_method, connector_meta_data, amount_captured, minor_amount_captured, connector_request_reference_id, refund_id, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "refund", new_router_data.request, new_router_data.response, ); router_data.merchant_id = merchant_id; router_data.customer_id = customer_id; router_data.payment_id = payment_id; router_data.attempt_id = attempt_id; router_data.status = status; router_data.payment_method = payment_method; router_data.connector_meta_data = connector_meta_data; router_data.amount_captured = amount_captured; router_data.minor_amount_captured = minor_amount_captured; router_data.connector_request_reference_id = connector_request_reference_id; router_data.refund_id = Some(refund_id); Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for DisputesFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { merchant_id: old_router_data.merchant_id.clone(), payment_id: old_router_data.payment_id.clone(), attempt_id: old_router_data.attempt_id.clone(), payment_method: old_router_data.payment_method, connector_meta_data: old_router_data.connector_meta_data.clone(), amount_captured: old_router_data.amount_captured, minor_amount_captured: old_router_data.minor_amount_captured, connector_request_reference_id: old_router_data.connector_request_reference_id.clone(), dispute_id: old_router_data.dispute_id.clone().ok_or( ConnectorError::MissingRequiredField { field_name: "dispute_id", }, )?, }; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { merchant_id, payment_id, attempt_id, payment_method, connector_meta_data, amount_captured, minor_amount_captured, connector_request_reference_id, dispute_id, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "Disputes", new_router_data.request, new_router_data.response, ); router_data.merchant_id = merchant_id; router_data.payment_id = payment_id; router_data.attempt_id = attempt_id; router_data.payment_method = payment_method; router_data.connector_meta_data = connector_meta_data; router_data.amount_captured = amount_captured; router_data.minor_amount_captured = minor_amount_captured; router_data.connector_request_reference_id = connector_request_reference_id; router_data.dispute_id = Some(dispute_id); Ok(router_data) } } #[cfg(feature = "frm")] impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for FrmFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { merchant_id: old_router_data.merchant_id.clone(), payment_id: old_router_data.payment_id.clone(), attempt_id: old_router_data.attempt_id.clone(), payment_method: old_router_data.payment_method, connector_request_reference_id: old_router_data.connector_request_reference_id.clone(), auth_type: old_router_data.auth_type, connector_wallets_details: old_router_data.connector_wallets_details.clone(), connector_meta_data: old_router_data.connector_meta_data.clone(), amount_captured: old_router_data.amount_captured, minor_amount_captured: old_router_data.minor_amount_captured, }; Ok(RouterDataV2 { tenant_id: old_router_data.tenant_id.clone(), flow: std::marker::PhantomData, resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { merchant_id, payment_id, attempt_id, payment_method, connector_request_reference_id, auth_type, connector_wallets_details, connector_meta_data, amount_captured, minor_amount_captured, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "frm", new_router_data.request, new_router_data.response, ); router_data.merchant_id = merchant_id; router_data.payment_id = payment_id; router_data.attempt_id = attempt_id; router_data.payment_method = payment_method; router_data.connector_request_reference_id = connector_request_reference_id; router_data.auth_type = auth_type; router_data.connector_wallets_details = connector_wallets_details; router_data.connector_meta_data = connector_meta_data; router_data.amount_captured = amount_captured; router_data.minor_amount_captured = minor_amount_captured; Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for FilesFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { merchant_id: old_router_data.merchant_id.clone(), payment_id: old_router_data.payment_id.clone(), attempt_id: old_router_data.attempt_id.clone(), connector_meta_data: old_router_data.connector_meta_data.clone(), connector_request_reference_id: old_router_data.connector_request_reference_id.clone(), }; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { merchant_id, payment_id, attempt_id, connector_meta_data, connector_request_reference_id, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "files", new_router_data.request, new_router_data.response, ); router_data.merchant_id = merchant_id; router_data.payment_id = payment_id; router_data.attempt_id = attempt_id; router_data.connector_meta_data = connector_meta_data; router_data.connector_request_reference_id = connector_request_reference_id; Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for WebhookSourceVerifyData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { merchant_id: old_router_data.merchant_id.clone(), }; Ok(RouterDataV2 { tenant_id: old_router_data.tenant_id.clone(), flow: std::marker::PhantomData, resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { merchant_id } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "webhook source verify", new_router_data.request, new_router_data.response, ); router_data.merchant_id = merchant_id; Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for MandateRevokeFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { merchant_id: old_router_data.merchant_id.clone(), customer_id: old_router_data.customer_id.clone().ok_or( ConnectorError::MissingRequiredField { field_name: "customer_id", }, )?, payment_id: Some(old_router_data.payment_id.clone()), }; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { merchant_id, customer_id, payment_id, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "mandate revoke", new_router_data.request, new_router_data.response, ); router_data.merchant_id = merchant_id; router_data.customer_id = Some(customer_id); router_data.payment_id = payment_id .unwrap_or_else(|| { id_type::PaymentId::get_irrelevant_id("mandate revoke") .get_string_repr() .to_owned() }) .to_owned(); Ok(router_data) } } #[cfg(feature = "payouts")] impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for PayoutFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { merchant_id: old_router_data.merchant_id.clone(), customer_id: old_router_data.customer_id.clone(), connector_customer: old_router_data.connector_customer.clone(), address: old_router_data.address.clone(), connector_meta_data: old_router_data.connector_meta_data.clone(), connector_wallets_details: old_router_data.connector_wallets_details.clone(), connector_request_reference_id: old_router_data.connector_request_reference_id.clone(), payout_method_data: old_router_data.payout_method_data.clone(), quote_id: old_router_data.quote_id.clone(), }; Ok(RouterDataV2 { tenant_id: old_router_data.tenant_id.clone(), flow: std::marker::PhantomData, resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { merchant_id, customer_id, connector_customer, address, connector_meta_data, connector_wallets_details, connector_request_reference_id, payout_method_data, quote_id, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "payout", new_router_data.request, new_router_data.response, ); router_data.merchant_id = merchant_id; router_data.customer_id = customer_id; router_data.connector_customer = connector_customer; router_data.address = address; router_data.connector_meta_data = connector_meta_data; router_data.connector_wallets_details = connector_wallets_details; router_data.connector_request_reference_id = connector_request_reference_id; router_data.payout_method_data = payout_method_data; router_data.quote_id = quote_id; Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for ExternalAuthenticationFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { merchant_id: old_router_data.merchant_id.clone(), connector_meta_data: old_router_data.connector_meta_data.clone(), address: old_router_data.address.clone(), }; Ok(RouterDataV2 { tenant_id: old_router_data.tenant_id.clone(), flow: std::marker::PhantomData, resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { merchant_id, connector_meta_data, address, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "external authentication", new_router_data.request, new_router_data.response, ); router_data.merchant_id = merchant_id; router_data.connector_meta_data = connector_meta_data; router_data.address = address; Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for InvoiceRecordBackData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { connector_meta_data: old_router_data.connector_meta_data.clone(), }; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { connector_meta_data, } = new_router_data.resource_common_data;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/integrity.rs
crates/hyperswitch_interfaces/src/integrity.rs
use common_utils::errors::IntegrityCheckError; use hyperswitch_domain_models::router_request_types::{ AuthoriseIntegrityObject, CaptureIntegrityObject, PaymentsAuthorizeData, PaymentsCaptureData, PaymentsSyncData, RefundIntegrityObject, RefundsData, SyncIntegrityObject, }; /// Connector Integrity trait to check connector data integrity pub trait FlowIntegrity { /// Output type for the connector type IntegrityObject; /// helps in connector integrity check fn compare( req_integrity_object: Self::IntegrityObject, res_integrity_object: Self::IntegrityObject, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError>; } /// Trait to get connector integrity object based on request and response pub trait GetIntegrityObject<T: FlowIntegrity> { /// function to get response integrity object fn get_response_integrity_object(&self) -> Option<T::IntegrityObject>; /// function to get request integrity object fn get_request_integrity_object(&self) -> T::IntegrityObject; } /// Trait to check flow type, based on which various integrity checks will be performed pub trait CheckIntegrity<Request, T> { /// Function to check to initiate integrity check fn check_integrity( &self, request: &Request, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError>; } impl<T, Request> CheckIntegrity<Request, T> for RefundsData where T: FlowIntegrity, Request: GetIntegrityObject<T>, { fn check_integrity( &self, request: &Request, connector_refund_id: Option<String>, ) -> Result<(), IntegrityCheckError> { match request.get_response_integrity_object() { Some(res_integrity_object) => { let req_integrity_object = request.get_request_integrity_object(); T::compare( req_integrity_object, res_integrity_object, connector_refund_id, ) } None => Ok(()), } } } impl<T, Request> CheckIntegrity<Request, T> for PaymentsAuthorizeData where T: FlowIntegrity, Request: GetIntegrityObject<T>, { fn check_integrity( &self, request: &Request, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { match request.get_response_integrity_object() { Some(res_integrity_object) => { let req_integrity_object = request.get_request_integrity_object(); T::compare( req_integrity_object, res_integrity_object, connector_transaction_id, ) } None => Ok(()), } } } impl<T, Request> CheckIntegrity<Request, T> for PaymentsCaptureData where T: FlowIntegrity, Request: GetIntegrityObject<T>, { fn check_integrity( &self, request: &Request, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { match request.get_response_integrity_object() { Some(res_integrity_object) => { let req_integrity_object = request.get_request_integrity_object(); T::compare( req_integrity_object, res_integrity_object, connector_transaction_id, ) } None => Ok(()), } } } impl<T, Request> CheckIntegrity<Request, T> for PaymentsSyncData where T: FlowIntegrity, Request: GetIntegrityObject<T>, { fn check_integrity( &self, request: &Request, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { match request.get_response_integrity_object() { Some(res_integrity_object) => { let req_integrity_object = request.get_request_integrity_object(); T::compare( req_integrity_object, res_integrity_object, connector_transaction_id, ) } None => Ok(()), } } } impl FlowIntegrity for RefundIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); if req_integrity_object.currency != res_integrity_object.currency { mismatched_fields.push(format_mismatch( "currency", &req_integrity_object.currency.to_string(), &res_integrity_object.currency.to_string(), )); } if req_integrity_object.refund_amount != res_integrity_object.refund_amount { mismatched_fields.push(format_mismatch( "refund_amount", &req_integrity_object.refund_amount.to_string(), &res_integrity_object.refund_amount.to_string(), )); } if mismatched_fields.is_empty() { Ok(()) } else { let field_names = mismatched_fields.join(", "); Err(IntegrityCheckError { field_names, connector_transaction_id, }) } } } impl FlowIntegrity for AuthoriseIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); if req_integrity_object.amount != res_integrity_object.amount { mismatched_fields.push(format_mismatch( "amount", &req_integrity_object.amount.to_string(), &res_integrity_object.amount.to_string(), )); } if req_integrity_object.currency != res_integrity_object.currency { mismatched_fields.push(format_mismatch( "currency", &req_integrity_object.currency.to_string(), &res_integrity_object.currency.to_string(), )); } if mismatched_fields.is_empty() { Ok(()) } else { let field_names = mismatched_fields.join(", "); Err(IntegrityCheckError { field_names, connector_transaction_id, }) } } } impl FlowIntegrity for SyncIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); res_integrity_object .amount .zip(req_integrity_object.amount) .map(|(res_amount, req_amount)| { if res_amount != req_amount { mismatched_fields.push(format_mismatch( "amount", &req_amount.to_string(), &res_amount.to_string(), )); } }); res_integrity_object .currency .zip(req_integrity_object.currency) .map(|(res_currency, req_currency)| { if res_currency != req_currency { mismatched_fields.push(format_mismatch( "currency", &req_currency.to_string(), &res_currency.to_string(), )); } }); if mismatched_fields.is_empty() { Ok(()) } else { let field_names = mismatched_fields.join(", "); Err(IntegrityCheckError { field_names, connector_transaction_id, }) } } } impl FlowIntegrity for CaptureIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); res_integrity_object .capture_amount .zip(req_integrity_object.capture_amount) .map(|(res_amount, req_amount)| { if res_amount != req_amount { mismatched_fields.push(format_mismatch( "capture_amount", &req_amount.to_string(), &res_amount.to_string(), )); } }); if req_integrity_object.currency != res_integrity_object.currency { mismatched_fields.push(format_mismatch( "currency", &req_integrity_object.currency.to_string(), &res_integrity_object.currency.to_string(), )); } if mismatched_fields.is_empty() { Ok(()) } else { let field_names = mismatched_fields.join(", "); Err(IntegrityCheckError { field_names, connector_transaction_id, }) } } } impl GetIntegrityObject<CaptureIntegrityObject> for PaymentsCaptureData { fn get_response_integrity_object(&self) -> Option<CaptureIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> CaptureIntegrityObject { CaptureIntegrityObject { capture_amount: Some(self.minor_amount_to_capture), currency: self.currency, } } } impl GetIntegrityObject<RefundIntegrityObject> for RefundsData { fn get_response_integrity_object(&self) -> Option<RefundIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> RefundIntegrityObject { RefundIntegrityObject { currency: self.currency, refund_amount: self.minor_refund_amount, } } } impl GetIntegrityObject<AuthoriseIntegrityObject> for PaymentsAuthorizeData { fn get_response_integrity_object(&self) -> Option<AuthoriseIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> AuthoriseIntegrityObject { AuthoriseIntegrityObject { amount: self.minor_amount, currency: self.currency, } } } impl GetIntegrityObject<SyncIntegrityObject> for PaymentsSyncData { fn get_response_integrity_object(&self) -> Option<SyncIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> SyncIntegrityObject { SyncIntegrityObject { amount: Some(self.amount), currency: Some(self.currency), } } } #[inline] fn format_mismatch(field: &str, expected: &str, found: &str) -> String { format!("{field} expected {expected} but found {found}") }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/unified_connector_service.rs
crates/hyperswitch_interfaces/src/unified_connector_service.rs
use common_enums::AttemptStatus; use common_utils::errors::CustomResult; use error_stack::ResultExt; use hyperswitch_domain_models::{ router_data::ErrorResponse, router_response_types::PaymentsResponseData, }; use unified_connector_service_client::payments as payments_grpc; use crate::helpers::ForeignTryFrom; /// Unified Connector Service (UCS) related transformers pub mod transformers; pub use transformers::{ UnifiedConnectorServiceError, WebhookTransformData, WebhookTransformationStatus, }; /// Type alias for return type used by unified connector service response handlers type UnifiedConnectorServiceResult = CustomResult< ( Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>, u16, ), UnifiedConnectorServiceError, >; #[allow(missing_docs)] pub fn handle_unified_connector_service_response_for_payment_get( response: payments_grpc::PaymentServiceGetResponse, ) -> UnifiedConnectorServiceResult { let status_code = transformers::convert_connector_service_status_code(response.status_code)?; let router_data_response = Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(response)?; Ok((router_data_response, status_code)) } /// Extracts the payments response from UCS webhook content pub fn get_payments_response_from_ucs_webhook_content( webhook_content: payments_grpc::WebhookResponseContent, ) -> CustomResult<payments_grpc::PaymentServiceGetResponse, UnifiedConnectorServiceError> { match webhook_content.content { Some(unified_connector_service_client::payments::webhook_response_content::Content::PaymentsResponse(payments_response)) => { Ok(payments_response) }, Some(unified_connector_service_client::payments::webhook_response_content::Content::RefundsResponse(_)) => { Err(UnifiedConnectorServiceError::WebhookProcessingFailure) .attach_printable("UCS webhook contains refunds response but payments response was expected")? }, Some(unified_connector_service_client::payments::webhook_response_content::Content::DisputesResponse(_)) => { Err(UnifiedConnectorServiceError::WebhookProcessingFailure) .attach_printable("UCS webhook contains disputes response but payments response was expected")? }, Some(unified_connector_service_client::payments::webhook_response_content::Content::IncompleteTransformation(_)) => { Err(UnifiedConnectorServiceError::WebhookProcessingFailure) .attach_printable("UCS webhook contains incomplete transformation but payments response was expected")? }, None => { Err(UnifiedConnectorServiceError::WebhookProcessingFailure) .attach_printable("Missing payments response in UCS webhook content")? } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
use common_enums::AttemptStatus; use common_types::primitive_wrappers::{ExtendedAuthorizationAppliedBool, OvercaptureEnabledBool}; use hyperswitch_domain_models::{ router_data::{ AdditionalPaymentMethodConnectorResponse, ConnectorResponseData, ErrorResponse, ExtendedAuthorizationResponseData, }, router_response_types::PaymentsResponseData, }; use crate::{helpers::ForeignTryFrom, unified_connector_service::payments_grpc}; /// Unified Connector Service error variants #[derive(Debug, Clone, thiserror::Error)] pub enum UnifiedConnectorServiceError { /// Error occurred while communicating with the gRPC server. #[error("Error from gRPC Server : {0}")] ConnectionError(String), /// Failed to encode the request to the unified connector service. #[error("Failed to encode unified connector service request")] RequestEncodingFailed, /// Failed to process webhook from unified connector service. #[error("Failed to process webhook from unified connector service")] WebhookProcessingFailure, /// Request encoding failed due to a specific reason. #[error("Request encoding failed : {0}")] RequestEncodingFailedWithReason(String), /// Failed to deserialize the response from the connector. #[error("Failed to deserialize connector response")] ResponseDeserializationFailed, /// The connector name provided is invalid or unrecognized. #[error("An invalid connector name was provided")] InvalidConnectorName, /// Connector name is missing #[error("Connector name is missing")] MissingConnectorName, /// A required field was missing in the request. #[error("Missing required field: {field_name}")] MissingRequiredField { /// Missing Field field_name: &'static str, }, /// Multiple required fields were missing in the request. #[error("Missing required fields: {field_names:?}")] MissingRequiredFields { /// Missing Fields field_names: Vec<&'static str>, }, /// The requested step or feature is not yet implemented. #[error("This step has not been implemented for: {0}")] NotImplemented(String), /// Parsing of some value or input failed. #[error("Parsing failed")] ParsingFailed, /// Data format provided is invalid #[error("Invalid Data format")] InvalidDataFormat { /// Field Name for which data is invalid field_name: &'static str, }, /// Failed to obtain authentication type #[error("Failed to obtain authentication type")] FailedToObtainAuthType, /// Failed to inject metadata into request headers #[error("Failed to inject metadata into request headers: {0}")] HeaderInjectionFailed(String), /// Failed to perform Create Order from gRPC Server #[error("Failed to perform Create Order from gRPC Server")] PaymentCreateOrderFailure, /// Failed to perform Payment Authorize from gRPC Server #[error("Failed to perform. Granular Payment Authorize from gRPC Server")] PaymentAuthorizeGranularFailure, /// Failed to perform Payment Authorize from gRPC Server #[error("Failed to perform Payment Session Token Create from gRPC Server")] PaymentCreateSessionTokenFailure, /// Failed to perform Payment Authorize from gRPC Server #[error("Failed to perform Payment Access Token Create from gRPC Server")] PaymentCreateAccessTokenFailure, /// Failed to perform Payment Authorize from gRPC Server #[error("Failed to perform Payment Method Token Create from gRPC Server")] PaymentMethodTokenCreateFailure, /// Failed to perform Payment Authorize from gRPC Server #[error("Failed to perform Connector Customer Create from gRPC Server")] PaymentConnectorCustomerCreateFailure, /// Failed to perform Payment Authorize from gRPC Server #[error("Failed to perform Payment Authorize from gRPC Server")] PaymentAuthorizeFailure, /// Failed to perform Payment Authenticate from gRPC Server #[error("Failed to perform Payment Pre Authenticate from gRPC Server")] PaymentPreAuthenticateFailure, /// Failed to perform Payment Authenticate from gRPC Server #[error("Failed to perform Payment Authenticate from gRPC Server")] PaymentAuthenticateFailure, /// Failed to perform Payment Authenticate from gRPC Server #[error("Failed to perform Payment Post Authenticate from gRPC Server")] PaymentPostAuthenticateFailure, /// Failed to perform Payment Get from gRPC Server #[error("Failed to perform Payment Get from gRPC Server")] PaymentGetFailure, /// Failed to perform Payment Capture from gRPC Server #[error("Failed to perform Payment Capture from gRPC Server")] PaymentCaptureFailure, /// Failed to perform Payment Setup Mandate from gRPC Server #[error("Failed to perform Setup Mandate from gRPC Server")] PaymentRegisterFailure, /// Failed to perform Payment Repeat Payment from gRPC Server #[error("Failed to perform Repeat Payment from gRPC Server")] PaymentRepeatEverythingFailure, /// Failed to perform Payment Refund from gRPC Server #[error("Failed to perform Payment Refund from gRPC Server")] PaymentRefundFailure, /// Failed to perform Refund Sync from gRPC Server #[error("Failed to perform Refund Sync from gRPC Server")] RefundSyncFailure, /// Failed to transform incoming webhook from gRPC Server #[error("Failed to transform incoming webhook from gRPC Server")] WebhookTransformFailure, /// Failed to perform Payment Cancel from gRPC Server #[error("Failed to perform Cancel from gRPC Server")] PaymentCancelFailure, /// Failed to perform Sdk Session Token from gRPC Server #[error("Failed to perform Sdk Session Token from gRPC Server")] SdkSessionTokenFailure, } /// UCS Webhook transformation status #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub enum WebhookTransformationStatus { /// Transformation completed successfully, no further action needed Complete, /// Transformation incomplete, requires second call for final status Incomplete, } #[allow(missing_docs)] /// Webhook transform data structure containing UCS response information #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct WebhookTransformData { pub event_type: api_models::webhooks::IncomingWebhookEvent, pub source_verified: bool, pub webhook_content: Option<payments_grpc::WebhookResponseContent>, pub response_ref_id: Option<String>, pub webhook_transformation_status: WebhookTransformationStatus, } impl ForeignTryFrom<payments_grpc::PaymentServiceGetResponse> for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse> { type Error = error_stack::Report<UnifiedConnectorServiceError>; fn foreign_try_from( response: payments_grpc::PaymentServiceGetResponse, ) -> Result<Self, Self::Error> { let connector_response_reference_id = response.response_ref_id.as_ref().and_then(|identifier| { identifier .id_type .clone() .and_then(|id_type| match id_type { payments_grpc::identifier::IdType::Id(id) => Some(id), payments_grpc::identifier::IdType::EncodedData(encoded_data) => { Some(encoded_data) } payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None, }) }); let status_code = convert_connector_service_status_code(response.status_code)?; let resource_id: hyperswitch_domain_models::router_request_types::ResponseId = match response.transaction_id.as_ref().and_then(|id| id.id_type.clone()) { Some(payments_grpc::identifier::IdType::Id(id)) => hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(id), Some(payments_grpc::identifier::IdType::EncodedData(encoded_data)) => hyperswitch_domain_models::router_request_types::ResponseId::EncodedData(encoded_data), Some(payments_grpc::identifier::IdType::NoResponseIdMarker(_)) | None => hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId, }; let response = if response.error_code.is_some() { let attempt_status = match response.status() { payments_grpc::PaymentStatus::AttemptStatusUnspecified => None, _ => Some(AttemptStatus::foreign_try_from(response.status())?), }; Err(ErrorResponse { code: response.error_code().to_owned(), message: response.error_message().to_owned(), reason: Some(response.error_message().to_owned()), status_code, attempt_status, connector_transaction_id: connector_response_reference_id, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_metadata: None, }) } else { let status = AttemptStatus::foreign_try_from(response.status())?; Ok(( PaymentsResponseData::TransactionResponse { resource_id, redirection_data: Box::new(None), mandate_reference: Box::new(response.mandate_reference.map(|grpc_mandate| { hyperswitch_domain_models::router_response_types::MandateReference { connector_mandate_id: grpc_mandate.mandate_id, payment_method_id: grpc_mandate.payment_method_id, mandate_metadata: None, connector_mandate_request_reference_id: None, } })), connector_metadata: None, network_txn_id: response.network_txn_id.clone(), connector_response_reference_id, incremental_authorization_allowed: None, charges: None, }, status, )) }; Ok(response) } } impl ForeignTryFrom<payments_grpc::PaymentStatus> for AttemptStatus { type Error = error_stack::Report<UnifiedConnectorServiceError>; fn foreign_try_from(grpc_status: payments_grpc::PaymentStatus) -> Result<Self, Self::Error> { match grpc_status { payments_grpc::PaymentStatus::Started => Ok(Self::Started), payments_grpc::PaymentStatus::AuthenticationFailed => Ok(Self::AuthenticationFailed), payments_grpc::PaymentStatus::RouterDeclined => Ok(Self::RouterDeclined), payments_grpc::PaymentStatus::AuthenticationPending => Ok(Self::AuthenticationPending), payments_grpc::PaymentStatus::AuthenticationSuccessful => { Ok(Self::AuthenticationSuccessful) } payments_grpc::PaymentStatus::Authorized => Ok(Self::Authorized), payments_grpc::PaymentStatus::AuthorizationFailed => Ok(Self::AuthorizationFailed), payments_grpc::PaymentStatus::Charged => Ok(Self::Charged), payments_grpc::PaymentStatus::Authorizing => Ok(Self::Authorizing), payments_grpc::PaymentStatus::CodInitiated => Ok(Self::CodInitiated), payments_grpc::PaymentStatus::Voided => Ok(Self::Voided), payments_grpc::PaymentStatus::VoidInitiated => Ok(Self::VoidInitiated), payments_grpc::PaymentStatus::CaptureInitiated => Ok(Self::CaptureInitiated), payments_grpc::PaymentStatus::CaptureFailed => Ok(Self::CaptureFailed), payments_grpc::PaymentStatus::VoidFailed => Ok(Self::VoidFailed), payments_grpc::PaymentStatus::AutoRefunded => Ok(Self::AutoRefunded), payments_grpc::PaymentStatus::PartialCharged => Ok(Self::PartialCharged), payments_grpc::PaymentStatus::PartialChargedAndChargeable => { Ok(Self::PartialChargedAndChargeable) } payments_grpc::PaymentStatus::Unresolved => Ok(Self::Unresolved), payments_grpc::PaymentStatus::Pending => Ok(Self::Pending), payments_grpc::PaymentStatus::Failure => Ok(Self::Failure), payments_grpc::PaymentStatus::PaymentMethodAwaited => Ok(Self::PaymentMethodAwaited), payments_grpc::PaymentStatus::ConfirmationAwaited => Ok(Self::ConfirmationAwaited), payments_grpc::PaymentStatus::DeviceDataCollectionPending => { Ok(Self::DeviceDataCollectionPending) } payments_grpc::PaymentStatus::VoidedPostCapture => Ok(Self::Voided), payments_grpc::PaymentStatus::AttemptStatusUnspecified => Ok(Self::Unresolved), payments_grpc::PaymentStatus::PartiallyAuthorized => Ok(Self::PartiallyAuthorized), payments_grpc::PaymentStatus::Expired => Ok(Self::Expired), } } } // Transformer for ConnectorResponseData from UCS proto to Hyperswitch domain type impl ForeignTryFrom<payments_grpc::ConnectorResponseData> for ConnectorResponseData { type Error = error_stack::Report<UnifiedConnectorServiceError>; fn foreign_try_from(value: payments_grpc::ConnectorResponseData) -> Result<Self, Self::Error> { // Extract additional_payment_method_data let additional_payment_method_data = value .additional_payment_method_data .map(AdditionalPaymentMethodConnectorResponse::foreign_try_from) .transpose()?; let extended_authorization_response_data = value.extended_authorization_response_data.map(|data| { ExtendedAuthorizationResponseData { capture_before: data .capture_before .and_then(|ts| time::OffsetDateTime::from_unix_timestamp(ts).ok()) .map(|offset_dt| { time::PrimitiveDateTime::new(offset_dt.date(), offset_dt.time()) }), extended_authentication_applied: data .extended_authentication_applied .map(ExtendedAuthorizationAppliedBool::from), extended_authorization_last_applied_at: None, // This field has to be added to UCS } }); let is_overcapture_enabled = value .is_overcapture_enabled .map(OvercaptureEnabledBool::new); Ok(Self::new( additional_payment_method_data, is_overcapture_enabled, extended_authorization_response_data, None, )) } } // Transformer for AdditionalPaymentMethodConnectorResponse impl ForeignTryFrom<payments_grpc::AdditionalPaymentMethodConnectorResponse> for AdditionalPaymentMethodConnectorResponse { type Error = error_stack::Report<UnifiedConnectorServiceError>; fn foreign_try_from( value: payments_grpc::AdditionalPaymentMethodConnectorResponse, ) -> Result<Self, Self::Error> { let card_data = value.card.unwrap_or_default(); Ok(Self::Card { authentication_data: card_data.authentication_data.and_then(|data| { serde_json::from_slice(&data) .inspect_err(|e| { router_env::logger::warn!( deserialization_error=?e, "Failed to deserialize authentication_data from UCS connector response" ); }) .ok() }), payment_checks: card_data.payment_checks.and_then(|data| { serde_json::from_slice(&data) .inspect_err(|e| { router_env::logger::warn!( deserialization_error=?e, "Failed to deserialize payment_checks from UCS connector response" ); }) .ok() }), card_network: card_data.card_network, domestic_network: card_data.domestic_network, }) } } #[allow(missing_docs)] pub fn convert_connector_service_status_code( status_code: u32, ) -> Result<u16, error_stack::Report<UnifiedConnectorServiceError>> { u16::try_from(status_code).map_err(|err| { UnifiedConnectorServiceError::RequestEncodingFailedWithReason(format!( "Failed to convert connector service status code to u16: {err}" )) .into() }) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs
crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs
//! Module to manage encrypted and decrypted states for a given type. use std::marker::PhantomData; use serde::{Deserialize, Deserializer}; /// Trait defining the states of a secret pub trait SecretState {} /// Decrypted state #[derive(Debug, Clone, Deserialize, Default)] pub struct RawSecret {} /// Encrypted state #[derive(Debug, Clone, Deserialize, Default)] pub struct SecuredSecret {} impl SecretState for RawSecret {} impl SecretState for SecuredSecret {} /// Struct for managing the encrypted and decrypted states of a given type #[derive(Debug, Clone, Default)] pub struct SecretStateContainer<T, S: SecretState> { inner: T, marker: PhantomData<S>, } impl<T: Clone, S: SecretState> SecretStateContainer<T, S> { /// Get the inner data while consuming self #[inline] pub fn into_inner(self) -> T { self.inner } /// Get the reference to inner value #[inline] pub fn get_inner(&self) -> &T { &self.inner } } impl<'de, T: Deserialize<'de>, S: SecretState> Deserialize<'de> for SecretStateContainer<T, S> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let val = Deserialize::deserialize(deserializer)?; Ok(Self { inner: val, marker: PhantomData, }) } } impl<T> SecretStateContainer<T, SecuredSecret> { /// Transition the secret state from `SecuredSecret` to `RawSecret` pub fn transition_state( mut self, decryptor_fn: impl FnOnce(T) -> T, ) -> SecretStateContainer<T, RawSecret> { self.inner = decryptor_fn(self.inner); SecretStateContainer { inner: self.inner, marker: PhantomData, } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/secrets_interface/secret_handler.rs
crates/hyperswitch_interfaces/src/secrets_interface/secret_handler.rs
//! Module containing trait for raw secret retrieval use common_utils::errors::CustomResult; use crate::secrets_interface::{ secret_state::{RawSecret, SecretStateContainer, SecuredSecret}, SecretManagementInterface, SecretsManagementError, }; /// Trait defining the interface for retrieving a raw secret value, given a secured value #[async_trait::async_trait] pub trait SecretsHandler where Self: Sized, { /// Construct `Self` with raw secret value and transitions its type from `SecuredSecret` to `RawSecret` async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, kms_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError>; }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/refunds_v2.rs
crates/hyperswitch_interfaces/src/api/refunds_v2.rs
//! Refunds V2 interface use hyperswitch_domain_models::{ router_data_v2::flow_common_types::RefundFlowData, router_flow_types::refunds::{Execute, RSync}, router_request_types::RefundsData, router_response_types::RefundsResponseData, }; use crate::api::{ConnectorCommon, ConnectorIntegrationV2}; /// trait RefundExecuteV2 pub trait RefundExecuteV2: ConnectorIntegrationV2<Execute, RefundFlowData, RefundsData, RefundsResponseData> { } /// trait RefundSyncV2 pub trait RefundSyncV2: ConnectorIntegrationV2<RSync, RefundFlowData, RefundsData, RefundsResponseData> { } /// trait RefundV2 pub trait RefundV2: ConnectorCommon + RefundExecuteV2 + RefundSyncV2 {}
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/vault.rs
crates/hyperswitch_interfaces/src/api/vault.rs
//! Vault interface use hyperswitch_domain_models::{ router_flow_types::vault::{ ExternalVaultCreateFlow, ExternalVaultDeleteFlow, ExternalVaultInsertFlow, ExternalVaultRetrieveFlow, }, router_request_types::VaultRequestData, router_response_types::VaultResponseData, }; use super::ConnectorCommon; use crate::api::ConnectorIntegration; /// trait ExternalVaultInsert pub trait ExternalVaultInsert: ConnectorIntegration<ExternalVaultInsertFlow, VaultRequestData, VaultResponseData> { } /// trait ExternalVaultRetrieve pub trait ExternalVaultRetrieve: ConnectorIntegration<ExternalVaultRetrieveFlow, VaultRequestData, VaultResponseData> { } /// trait ExternalVaultDelete pub trait ExternalVaultDelete: ConnectorIntegration<ExternalVaultDeleteFlow, VaultRequestData, VaultResponseData> { } /// trait ExternalVaultDelete pub trait ExternalVaultCreate: ConnectorIntegration<ExternalVaultCreateFlow, VaultRequestData, VaultResponseData> { } /// trait ExternalVault pub trait ExternalVault: ConnectorCommon + ExternalVaultInsert + ExternalVaultRetrieve + ExternalVaultDelete + ExternalVaultCreate { }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/vault_v2.rs
crates/hyperswitch_interfaces/src/api/vault_v2.rs
//! Vault V2 interface use hyperswitch_domain_models::{ router_data_v2::flow_common_types::VaultConnectorFlowData, router_flow_types::vault::{ ExternalVaultCreateFlow, ExternalVaultDeleteFlow, ExternalVaultInsertFlow, ExternalVaultRetrieveFlow, }, router_request_types::VaultRequestData, router_response_types::VaultResponseData, }; use super::ConnectorCommon; use crate::api::ConnectorIntegrationV2; /// trait ExternalVaultInsertV2 pub trait ExternalVaultInsertV2: ConnectorIntegrationV2< ExternalVaultInsertFlow, VaultConnectorFlowData, VaultRequestData, VaultResponseData, > { } /// trait ExternalVaultRetrieveV2 pub trait ExternalVaultRetrieveV2: ConnectorIntegrationV2< ExternalVaultRetrieveFlow, VaultConnectorFlowData, VaultRequestData, VaultResponseData, > { } /// trait ExternalVaultDeleteV2 pub trait ExternalVaultDeleteV2: ConnectorIntegrationV2< ExternalVaultDeleteFlow, VaultConnectorFlowData, VaultRequestData, VaultResponseData, > { } /// trait ExternalVaultDeleteV2 pub trait ExternalVaultCreateV2: ConnectorIntegrationV2< ExternalVaultCreateFlow, VaultConnectorFlowData, VaultRequestData, VaultResponseData, > { } /// trait ExternalVaultV2 pub trait ExternalVaultV2: ConnectorCommon + ExternalVaultInsertV2 + ExternalVaultRetrieveV2 + ExternalVaultDeleteV2 + ExternalVaultCreateV2 { }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/fraud_check.rs
crates/hyperswitch_interfaces/src/api/fraud_check.rs
//! FRM interface use hyperswitch_domain_models::{ router_flow_types::{Checkout, Fulfillment, RecordReturn, Sale, Transaction}, router_request_types::fraud_check::{ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, FraudCheckSaleData, FraudCheckTransactionData, }, router_response_types::fraud_check::FraudCheckResponseData, }; use crate::api::ConnectorIntegration; /// trait FraudCheckSale pub trait FraudCheckSale: ConnectorIntegration<Sale, FraudCheckSaleData, FraudCheckResponseData> { } /// trait FraudCheckCheckout pub trait FraudCheckCheckout: ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseData> { } /// trait FraudCheckTransaction pub trait FraudCheckTransaction: ConnectorIntegration<Transaction, FraudCheckTransactionData, FraudCheckResponseData> { } /// trait FraudCheckFulfillment pub trait FraudCheckFulfillment: ConnectorIntegration<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData> { } /// trait FraudCheckRecordReturn pub trait FraudCheckRecordReturn: ConnectorIntegration<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData> { } /// trait FraudCheck pub trait FraudCheck: super::ConnectorCommon + FraudCheckSale + FraudCheckTransaction + FraudCheckCheckout + FraudCheckFulfillment + FraudCheckRecordReturn { }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/payments_v2.rs
crates/hyperswitch_interfaces/src/api/payments_v2.rs
//! Payments V2 interface use hyperswitch_domain_models::{ router_data_v2::{flow_common_types::GiftCardBalanceCheckFlowData, PaymentFlowData}, router_flow_types::{ payments::{ Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, ExtendAuthorization, ExternalVaultProxy, IncrementalAuthorization, PSync, PaymentMethodToken, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, Authenticate, GiftCardBalanceCheck, PostAuthenticate, PreAuthenticate, }, router_request_types::{ AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, ExternalVaultProxyPaymentsData, GiftCardBalanceCheckRequestData, PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData, PaymentsPostAuthenticateData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, }, router_response_types::{ GiftCardBalanceCheckResponseData, PaymentsResponseData, TaxCalculationResponseData, }, }; use crate::api::{ ConnectorCommon, ConnectorIntegrationV2, ConnectorSpecifications, ConnectorValidation, }; /// trait PaymentAuthorizeV2 pub trait PaymentAuthorizeV2: ConnectorIntegrationV2<Authorize, PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData> { } /// trait PaymentAuthorizeSessionTokenV2 pub trait PaymentAuthorizeSessionTokenV2: ConnectorIntegrationV2< AuthorizeSessionToken, PaymentFlowData, AuthorizeSessionTokenData, PaymentsResponseData, > { } /// trait PaymentSyncV2 pub trait PaymentSyncV2: ConnectorIntegrationV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData> { } /// trait PaymentVoidV2 pub trait PaymentVoidV2: ConnectorIntegrationV2<Void, PaymentFlowData, PaymentsCancelData, PaymentsResponseData> { } /// trait PaymentPostCaptureVoidV2 pub trait PaymentPostCaptureVoidV2: ConnectorIntegrationV2< PostCaptureVoid, PaymentFlowData, PaymentsCancelPostCaptureData, PaymentsResponseData, > { } /// trait PaymentApproveV2 pub trait PaymentApproveV2: ConnectorIntegrationV2<Approve, PaymentFlowData, PaymentsApproveData, PaymentsResponseData> { } /// trait PaymentRejectV2 pub trait PaymentRejectV2: ConnectorIntegrationV2<Reject, PaymentFlowData, PaymentsRejectData, PaymentsResponseData> { } /// trait PaymentCaptureV2 pub trait PaymentCaptureV2: ConnectorIntegrationV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData> { } /// trait PaymentSessionV2 pub trait PaymentSessionV2: ConnectorIntegrationV2<Session, PaymentFlowData, PaymentsSessionData, PaymentsResponseData> { } /// trait MandateSetupV2 pub trait MandateSetupV2: ConnectorIntegrationV2<SetupMandate, PaymentFlowData, SetupMandateRequestData, PaymentsResponseData> { } /// trait PaymentIncrementalAuthorizationV2 pub trait PaymentIncrementalAuthorizationV2: ConnectorIntegrationV2< IncrementalAuthorization, PaymentFlowData, PaymentsIncrementalAuthorizationData, PaymentsResponseData, > { } /// trait PaymentExtendAuthorizationV2 pub trait PaymentExtendAuthorizationV2: ConnectorIntegrationV2< ExtendAuthorization, PaymentFlowData, PaymentsExtendAuthorizationData, PaymentsResponseData, > { } ///trait TaxCalculationV2 pub trait TaxCalculationV2: ConnectorIntegrationV2< CalculateTax, PaymentFlowData, PaymentsTaxCalculationData, TaxCalculationResponseData, > { } ///trait PaymentSessionUpdateV2 pub trait PaymentSessionUpdateV2: ConnectorIntegrationV2< SdkSessionUpdate, PaymentFlowData, SdkPaymentsSessionUpdateData, PaymentsResponseData, > { } ///trait PaymentPostSessionTokensV2 pub trait PaymentPostSessionTokensV2: ConnectorIntegrationV2< PostSessionTokens, PaymentFlowData, PaymentsPostSessionTokensData, PaymentsResponseData, > { } /// trait ConnectorCreateOrderV2 pub trait PaymentCreateOrderV2: ConnectorIntegrationV2<CreateOrder, PaymentFlowData, CreateOrderRequestData, PaymentsResponseData> { } /// trait PaymentUpdateMetadataV2 pub trait PaymentUpdateMetadataV2: ConnectorIntegrationV2< UpdateMetadata, PaymentFlowData, PaymentsUpdateMetadataData, PaymentsResponseData, > { } /// trait PaymentsCompleteAuthorizeV2 pub trait PaymentsCompleteAuthorizeV2: ConnectorIntegrationV2< CompleteAuthorize, PaymentFlowData, CompleteAuthorizeData, PaymentsResponseData, > { } /// trait PaymentTokenV2 pub trait PaymentTokenV2: ConnectorIntegrationV2< PaymentMethodToken, PaymentFlowData, PaymentMethodTokenizationData, PaymentsResponseData, > { } /// trait ConnectorCustomerV2 pub trait ConnectorCustomerV2: ConnectorIntegrationV2< CreateConnectorCustomer, PaymentFlowData, ConnectorCustomerData, PaymentsResponseData, > { } /// trait PaymentsPreProcessingV2 pub trait PaymentsPreProcessingV2: ConnectorIntegrationV2< PreProcessing, PaymentFlowData, PaymentsPreProcessingData, PaymentsResponseData, > { } /// trait PaymentsGiftCardBalanceCheckV2 pub trait PaymentsGiftCardBalanceCheckV2: ConnectorIntegrationV2< GiftCardBalanceCheck, GiftCardBalanceCheckFlowData, GiftCardBalanceCheckRequestData, GiftCardBalanceCheckResponseData, > { } /// trait PaymentsPreAuthenticateV2 pub trait PaymentsPreAuthenticateV2: ConnectorIntegrationV2< PreAuthenticate, PaymentFlowData, PaymentsPreAuthenticateData, PaymentsResponseData, > { } /// trait PaymentsAuthenticateV2 pub trait PaymentsAuthenticateV2: ConnectorIntegrationV2< Authenticate, PaymentFlowData, PaymentsAuthenticateData, PaymentsResponseData, > { } /// trait PaymentsPostAuthenticateV2 pub trait PaymentsPostAuthenticateV2: ConnectorIntegrationV2< PostAuthenticate, PaymentFlowData, PaymentsPostAuthenticateData, PaymentsResponseData, > { } /// trait PaymentsPostProcessingV2 pub trait PaymentsPostProcessingV2: ConnectorIntegrationV2< PostProcessing, PaymentFlowData, PaymentsPostProcessingData, PaymentsResponseData, > { } /// trait ExternalVaultProxyPaymentsCreate pub trait ExternalVaultProxyPaymentsCreate: ConnectorIntegrationV2< ExternalVaultProxy, PaymentFlowData, ExternalVaultProxyPaymentsData, PaymentsResponseData, > { } /// trait PaymentV2 pub trait PaymentV2: ConnectorCommon + ConnectorSpecifications + ConnectorValidation + PaymentAuthorizeV2 + PaymentsPreAuthenticateV2 + PaymentsAuthenticateV2 + PaymentsPostAuthenticateV2 + PaymentAuthorizeSessionTokenV2 + PaymentsCompleteAuthorizeV2 + PaymentSyncV2 + PaymentCaptureV2 + PaymentVoidV2 + PaymentPostCaptureVoidV2 + PaymentApproveV2 + PaymentRejectV2 + MandateSetupV2 + PaymentSessionV2 + PaymentTokenV2 + PaymentsPreProcessingV2 + PaymentsPostProcessingV2 + ConnectorCustomerV2 + PaymentIncrementalAuthorizationV2 + PaymentExtendAuthorizationV2 + TaxCalculationV2 + PaymentSessionUpdateV2 + PaymentPostSessionTokensV2 + PaymentUpdateMetadataV2 + PaymentCreateOrderV2 + ExternalVaultProxyPaymentsCreate + PaymentsGiftCardBalanceCheckV2 { }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/payouts_v2.rs
crates/hyperswitch_interfaces/src/api/payouts_v2.rs
//! Payouts V2 interface use hyperswitch_domain_models::{ router_data_v2::flow_common_types::PayoutFlowData, router_flow_types::payouts::{ PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync, }, router_request_types::PayoutsData, router_response_types::PayoutsResponseData, }; use super::ConnectorCommon; use crate::api::ConnectorIntegrationV2; /// trait PayoutCancelV2 pub trait PayoutCancelV2: ConnectorIntegrationV2<PoCancel, PayoutFlowData, PayoutsData, PayoutsResponseData> { } /// trait PayoutCreateV2 pub trait PayoutCreateV2: ConnectorIntegrationV2<PoCreate, PayoutFlowData, PayoutsData, PayoutsResponseData> { } /// trait PayoutEligibilityV2 pub trait PayoutEligibilityV2: ConnectorIntegrationV2<PoEligibility, PayoutFlowData, PayoutsData, PayoutsResponseData> { } /// trait PayoutFulfillV2 pub trait PayoutFulfillV2: ConnectorIntegrationV2<PoFulfill, PayoutFlowData, PayoutsData, PayoutsResponseData> { } /// trait PayoutQuoteV2 pub trait PayoutQuoteV2: ConnectorIntegrationV2<PoQuote, PayoutFlowData, PayoutsData, PayoutsResponseData> { } /// trait PayoutRecipientV2 pub trait PayoutRecipientV2: ConnectorIntegrationV2<PoRecipient, PayoutFlowData, PayoutsData, PayoutsResponseData> { } /// trait PayoutRecipientAccountV2 pub trait PayoutRecipientAccountV2: ConnectorIntegrationV2<PoRecipientAccount, PayoutFlowData, PayoutsData, PayoutsResponseData> { } /// trait PayoutSyncV2 pub trait PayoutSyncV2: ConnectorIntegrationV2<PoSync, PayoutFlowData, PayoutsData, PayoutsResponseData> { } #[cfg(feature = "payouts")] /// trait Payouts pub trait PayoutsV2: ConnectorCommon + PayoutCancelV2 + PayoutCreateV2 + PayoutEligibilityV2 + PayoutFulfillV2 + PayoutQuoteV2 + PayoutRecipientV2 + PayoutRecipientAccountV2 + PayoutSyncV2 { } /// Empty trait for when payouts feature is disabled #[cfg(not(feature = "payouts"))] pub trait PayoutsV2 {}
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/refunds.rs
crates/hyperswitch_interfaces/src/api/refunds.rs
//! Refunds interface use hyperswitch_domain_models::{ router_flow_types::{Execute, RSync}, router_request_types::RefundsData, router_response_types::RefundsResponseData, }; use crate::api::{self, ConnectorCommon}; /// trait RefundExecute pub trait RefundExecute: api::ConnectorIntegration<Execute, RefundsData, RefundsResponseData> { } /// trait RefundSync pub trait RefundSync: api::ConnectorIntegration<RSync, RefundsData, RefundsResponseData> {} /// trait Refund pub trait Refund: ConnectorCommon + RefundExecute + RefundSync {}
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs
crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs
//! SubscriptionsV2 use hyperswitch_domain_models::{ router_data_v2::flow_common_types::{ GetSubscriptionEstimateData, GetSubscriptionItemPricesData, GetSubscriptionItemsData, InvoiceRecordBackData, SubscriptionCancelData, SubscriptionCreateData, SubscriptionCustomerData, SubscriptionPauseData, SubscriptionResumeData, }, router_flow_types::{ revenue_recovery::InvoiceRecordBack, subscriptions::{ GetSubscriptionEstimate, GetSubscriptionItemPrices, GetSubscriptionItems, SubscriptionCancel, SubscriptionCreate, SubscriptionPause, SubscriptionResume, }, CreateConnectorCustomer, }, router_request_types::{ revenue_recovery::InvoiceRecordBackRequest, subscriptions::{ GetSubscriptionEstimateRequest, GetSubscriptionItemPricesRequest, GetSubscriptionItemsRequest, SubscriptionCancelRequest, SubscriptionCreateRequest, SubscriptionPauseRequest, SubscriptionResumeRequest, }, ConnectorCustomerData, }, router_response_types::{ revenue_recovery::InvoiceRecordBackResponse, subscriptions::{ GetSubscriptionEstimateResponse, GetSubscriptionItemPricesResponse, GetSubscriptionItemsResponse, SubscriptionCancelResponse, SubscriptionCreateResponse, SubscriptionPauseResponse, SubscriptionResumeResponse, }, PaymentsResponseData, }, }; use crate::connector_integration_v2::ConnectorIntegrationV2; /// trait SubscriptionsV2 pub trait SubscriptionsV2: GetSubscriptionPlansV2 + SubscriptionsCreateV2 + SubscriptionConnectorCustomerV2 + GetSubscriptionPlanPricesV2 + SubscriptionRecordBackV2 + GetSubscriptionEstimateV2 + SubscriptionCancelV2 + SubscriptionPauseV2 + SubscriptionResumeV2 { } /// trait GetSubscriptionItems for V2 pub trait GetSubscriptionPlansV2: ConnectorIntegrationV2< GetSubscriptionItems, GetSubscriptionItemsData, GetSubscriptionItemsRequest, GetSubscriptionItemsResponse, > { } /// trait SubscriptionRecordBack for V2 pub trait SubscriptionRecordBackV2: ConnectorIntegrationV2< InvoiceRecordBack, InvoiceRecordBackData, InvoiceRecordBackRequest, InvoiceRecordBackResponse, > { } /// trait GetSubscriptionPlanPricesV2 for V2 pub trait GetSubscriptionPlanPricesV2: ConnectorIntegrationV2< GetSubscriptionItemPrices, GetSubscriptionItemPricesData, GetSubscriptionItemPricesRequest, GetSubscriptionItemPricesResponse, > { } /// trait SubscriptionsCreateV2 pub trait SubscriptionsCreateV2: ConnectorIntegrationV2< SubscriptionCreate, SubscriptionCreateData, SubscriptionCreateRequest, SubscriptionCreateResponse, > { } /// trait SubscriptionConnectorCustomerV2 pub trait SubscriptionConnectorCustomerV2: ConnectorIntegrationV2< CreateConnectorCustomer, SubscriptionCustomerData, ConnectorCustomerData, PaymentsResponseData, > { } /// trait GetSubscriptionEstimate for V2 pub trait GetSubscriptionEstimateV2: ConnectorIntegrationV2< GetSubscriptionEstimate, GetSubscriptionEstimateData, GetSubscriptionEstimateRequest, GetSubscriptionEstimateResponse, > { } /// trait SubscriptionCancel for V2 pub trait SubscriptionCancelV2: ConnectorIntegrationV2< SubscriptionCancel, SubscriptionCancelData, SubscriptionCancelRequest, SubscriptionCancelResponse, > { } /// trait SubscriptionPause for V2 pub trait SubscriptionPauseV2: ConnectorIntegrationV2< SubscriptionPause, SubscriptionPauseData, SubscriptionPauseRequest, SubscriptionPauseResponse, > { } /// trait SubscriptionResume for V2 pub trait SubscriptionResumeV2: ConnectorIntegrationV2< SubscriptionResume, SubscriptionResumeData, SubscriptionResumeRequest, SubscriptionResumeResponse, > { }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/disputes.rs
crates/hyperswitch_interfaces/src/api/disputes.rs
//! Disputes interface use hyperswitch_domain_models::{ router_flow_types::dispute::{Accept, Defend, Dsync, Evidence, Fetch}, router_request_types::{ AcceptDisputeRequestData, DefendDisputeRequestData, DisputeSyncData, FetchDisputesRequestData, SubmitEvidenceRequestData, }, router_response_types::{ AcceptDisputeResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, SubmitEvidenceResponse, }, }; use crate::api::ConnectorIntegration; /// trait AcceptDispute pub trait AcceptDispute: ConnectorIntegration<Accept, AcceptDisputeRequestData, AcceptDisputeResponse> { } /// trait SubmitEvidence pub trait SubmitEvidence: ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse> { } /// trait DefendDispute pub trait DefendDispute: ConnectorIntegration<Defend, DefendDisputeRequestData, DefendDisputeResponse> { } /// trait Dispute pub trait Dispute: super::ConnectorCommon + AcceptDispute + SubmitEvidence + DefendDispute + FetchDisputes + DisputeSync { } /// trait FetchDisputes pub trait FetchDisputes: ConnectorIntegration<Fetch, FetchDisputesRequestData, FetchDisputesResponse> { } /// trait SyncDisputes pub trait DisputeSync: ConnectorIntegration<Dsync, DisputeSyncData, DisputeSyncResponse> {}
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/revenue_recovery.rs
crates/hyperswitch_interfaces/src/api/revenue_recovery.rs
//! Revenue Recovery Interface use hyperswitch_domain_models::{ router_flow_types::{ BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, InvoiceRecordBack, }, router_request_types::revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, InvoiceRecordBackRequest, }, router_response_types::revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, InvoiceRecordBackResponse, }, }; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use super::ConnectorCommon; use super::ConnectorIntegration; /// trait RevenueRecovery #[cfg(all(feature = "v2", feature = "revenue_recovery"))] pub trait RevenueRecovery: ConnectorCommon + BillingConnectorPaymentsSyncIntegration + RevenueRecoveryRecordBack + BillingConnectorInvoiceSyncIntegration { } /// trait BillingConnectorPaymentsSyncIntegration pub trait BillingConnectorPaymentsSyncIntegration: ConnectorIntegration< BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse, > { } /// trait RevenueRecoveryRecordBack pub trait RevenueRecoveryRecordBack: ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse> { } /// trait BillingConnectorInvoiceSyncIntegration pub trait BillingConnectorInvoiceSyncIntegration: ConnectorIntegration< BillingConnectorInvoiceSync, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse, > { } #[cfg(not(all(feature = "v2", feature = "revenue_recovery")))] /// trait RevenueRecovery pub trait RevenueRecovery {}
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/payouts.rs
crates/hyperswitch_interfaces/src/api/payouts.rs
//! Payouts interface use hyperswitch_domain_models::{ router_flow_types::payouts::{ PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync, }, router_request_types::PayoutsData, router_response_types::PayoutsResponseData, }; use super::ConnectorCommon; use crate::api::ConnectorIntegration; /// trait PayoutCancel pub trait PayoutCancel: ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData> {} /// trait PayoutCreate pub trait PayoutCreate: ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData> {} /// trait PayoutEligibility pub trait PayoutEligibility: ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData> { } /// trait PayoutFulfill pub trait PayoutFulfill: ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> {} /// trait PayoutQuote pub trait PayoutQuote: ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData> {} /// trait PayoutRecipient pub trait PayoutRecipient: ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData> { } /// trait PayoutRecipientAccount pub trait PayoutRecipientAccount: ConnectorIntegration<PoRecipientAccount, PayoutsData, PayoutsResponseData> { } /// trait PayoutSync pub trait PayoutSync: ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData> {} #[cfg(feature = "payouts")] /// trait Payouts pub trait Payouts: ConnectorCommon + PayoutCancel + PayoutCreate + PayoutEligibility + PayoutFulfill + PayoutQuote + PayoutRecipient + PayoutRecipientAccount + PayoutSync { } /// Empty trait for when payouts feature is disabled #[cfg(not(feature = "payouts"))] pub trait Payouts {}
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/gateway.rs
crates/hyperswitch_interfaces/src/api/gateway.rs
//! Gateway abstraction layer for unified connector execution //! //! This module provides a unified interface for executing payment operations through either: //! - Direct connector integration (traditional HTTP-based) //! - Unified Connector Service (UCS) via gRPC //! //! The gateway abstraction allows seamless switching between execution paths without //! requiring changes to individual flow implementations. use async_trait::async_trait; use common_enums::{CallConnectorAction, ExecutionMode, ExecutionPath}; use common_utils::{errors::CustomResult, request::Request}; use error_stack::ResultExt; use hyperswitch_domain_models::router_data::RouterData; use router_env::{logger, tracing::Instrument}; use crate::{ api_client::{self, ApiClientWrapper}, connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion}, errors::ConnectorError, helpers, }; /// Minimal trait that gateway context must implement /// /// This allows the framework to extract execution metadata without knowing /// the concrete context structure. Implementation crates define their own /// context types with whatever fields they need. pub trait GatewayContext: Clone + Send + Sync { /// Get the execution path (Direct, UCS, or Shadow) fn execution_path(&self) -> ExecutionPath; /// Get the execution mode (Primary, Shadow, etc.) fn execution_mode(&self) -> ExecutionMode; } /// Trait to extract RouterData from various output types /// pub trait GetRouterData<F, Req, Resp> { /// Get a reference to the RouterData fn get_router_data(&self) -> &RouterData<F, Req, Resp>; } impl<F, Req, Resp> GetRouterData<F, Req, Resp> for RouterData<F, Req, Resp> { fn get_router_data(&self) -> &Self { self } } impl<F, Req, Resp, T> GetRouterData<F, Req, Resp> for (RouterData<F, Req, Resp>, Option<T>) { fn get_router_data(&self) -> &RouterData<F, Req, Resp> { &self.0 } } /// Payment gateway trait /// /// Defines the interface for executing payment operations through different gateway types. /// Implementations include DirectGateway and flow-specific UCS gateways. /// /// # Type Parameters /// * `State` - Application state (e.g., SessionState) /// * `ConnectorData` - Connector-specific data type /// * `F` - Flow type (e.g., domain::Authorize, domain::PSync) /// * `Req` - Request data type /// * `Resp` - Response data type /// * `Context` - Gateway context type (must implement GatewayContext trait) #[async_trait] #[allow(clippy::too_many_arguments)] pub trait PaymentGateway< State, ConnectorData, F, Req, Resp, Context, FlowOutput = RouterData<F, Req, Resp>, >: Send + Sync where State: Clone + Send + Sync + 'static + ApiClientWrapper, ConnectorData: Clone + RouterDataConversion<F, Req, Resp> + Send + Sync + 'static, F: Clone + std::fmt::Debug + Send + Sync + 'static, Req: std::fmt::Debug + Clone + Send + Sync + 'static, Resp: std::fmt::Debug + Clone + Send + Sync + 'static, Context: GatewayContext, { /// Execute payment gateway operation async fn execute( self: Box<Self>, state: &State, connector_integration: BoxedConnectorIntegrationInterface<F, ConnectorData, Req, Resp>, router_data: &RouterData<F, Req, Resp>, call_connector_action: CallConnectorAction, connector_request: Option<Request>, return_raw_connector_response: Option<bool>, context: Context, ) -> CustomResult<FlowOutput, ConnectorError>; } /// Direct gateway implementation /// /// Executes payment operations through traditional HTTP connector integration. /// This is the default execution path and maintains backward compatibility. #[derive(Debug, Clone, Copy)] pub struct DirectGateway; #[async_trait] impl<State, ConnectorData, F, Req, Resp, Context> PaymentGateway<State, ConnectorData, F, Req, Resp, Context> for DirectGateway where State: Clone + Send + Sync + 'static + ApiClientWrapper, ConnectorData: Clone + RouterDataConversion<F, Req, Resp> + Send + Sync + 'static, F: Clone + std::fmt::Debug + Send + Sync + 'static, Req: std::fmt::Debug + Clone + Send + Sync + 'static, Resp: std::fmt::Debug + Clone + Send + Sync + 'static, Context: GatewayContext + 'static, { async fn execute( self: Box<Self>, state: &State, connector_integration: BoxedConnectorIntegrationInterface<F, ConnectorData, Req, Resp>, router_data: &RouterData<F, Req, Resp>, call_connector_action: CallConnectorAction, connector_request: Option<Request>, return_raw_connector_response: Option<bool>, _context: Context, ) -> CustomResult<RouterData<F, Req, Resp>, ConnectorError> { // Direct gateway delegates to the existing execute_connector_processing_step // This maintains backward compatibility with the traditional HTTP-based flow api_client::execute_connector_processing_step( state, connector_integration, router_data, call_connector_action, connector_request, return_raw_connector_response, ) .await } } #[async_trait] impl<State, ConnectorData, F, Req, Resp, Context, T> PaymentGateway< State, ConnectorData, F, Req, Resp, Context, (RouterData<F, Req, Resp>, Option<T>), > for DirectGateway where State: Clone + Send + Sync + 'static + ApiClientWrapper, ConnectorData: Clone + RouterDataConversion<F, Req, Resp> + Send + Sync + 'static, F: Clone + std::fmt::Debug + Send + Sync + 'static, Req: std::fmt::Debug + Clone + Send + Sync + 'static, Resp: std::fmt::Debug + Clone + Send + Sync + 'static, Context: GatewayContext + 'static, { async fn execute( self: Box<Self>, state: &State, connector_integration: BoxedConnectorIntegrationInterface<F, ConnectorData, Req, Resp>, router_data: &RouterData<F, Req, Resp>, call_connector_action: CallConnectorAction, connector_request: Option<Request>, return_raw_connector_response: Option<bool>, _context: Context, ) -> CustomResult<(RouterData<F, Req, Resp>, Option<T>), ConnectorError> { // Direct gateway delegates to the existing execute_connector_processing_step // This maintains backward compatibility with the traditional HTTP-based flow api_client::execute_connector_processing_step( state, connector_integration, router_data, call_connector_action, connector_request, return_raw_connector_response, ) .await .map(|router_data| (router_data, None)) } } /// Flow gateway trait for determining execution path /// /// This trait allows flows to specify which gateway implementation should be used /// based on the execution path. Each flow implements this trait to provide /// flow-specific gateway selection logic. pub trait FlowGateway< State, ConnectorData, Req, Resp, Context, FlowOutput = RouterData<Self, Req, Resp>, >: Clone + std::fmt::Debug + Send + Sync + 'static where State: Clone + Send + Sync + 'static + ApiClientWrapper, ConnectorData: Clone + RouterDataConversion<Self, Req, Resp> + Send + Sync + 'static, Req: std::fmt::Debug + Clone + Send + Sync + 'static, Resp: std::fmt::Debug + Clone + Send + Sync + 'static, Context: GatewayContext, { /// Get the appropriate gateway for this flow based on execution path /// /// Returns a boxed gateway implementation that can be either: /// - DirectGateway for traditional HTTP connector integration /// - Flow-specific UCS gateway for gRPC integration fn get_gateway( execution_path: ExecutionPath, ) -> Box<dyn PaymentGateway<State, ConnectorData, Self, Req, Resp, Context, FlowOutput>>; } /// Execute payment gateway operation (backward compatible version) /// /// This version maintains backward compatibility by using direct execution when no context is provided. /// Use `execute_payment_gateway_with_context` for UCS support. pub async fn execute_payment_gateway<State, ConnectorData, F, Req, Resp, Context, FlowOutput>( state: &State, connector_integration: BoxedConnectorIntegrationInterface<F, ConnectorData, Req, Resp>, router_data: &RouterData<F, Req, Resp>, call_connector_action: CallConnectorAction, connector_request: Option<Request>, return_raw_connector_response: Option<bool>, context: Context, ) -> CustomResult<FlowOutput, ConnectorError> where State: Clone + Send + Sync + 'static + ApiClientWrapper + helpers::GetComparisonServiceConfig, ConnectorData: Clone + RouterDataConversion<F, Req, Resp> + Send + Sync + 'static, F: Clone + std::fmt::Debug + Send + Sync + 'static + FlowGateway<State, ConnectorData, Req, Resp, Context, FlowOutput>, Req: std::fmt::Debug + Clone + Send + Sync + serde::Serialize + 'static, Resp: std::fmt::Debug + Clone + Send + Sync + serde::Serialize + 'static, Context: GatewayContext + 'static, FlowOutput: Clone + Send + Sync + GetRouterData<F, Req, Resp> + 'static, { let execution_path = context.execution_path(); match execution_path { ExecutionPath::Direct => { let gateway: Box< dyn PaymentGateway<State, ConnectorData, F, Req, Resp, Context, FlowOutput>, > = F::get_gateway(ExecutionPath::Direct); gateway .execute( state, connector_integration, router_data, call_connector_action, connector_request, return_raw_connector_response, context, ) .await } ExecutionPath::UnifiedConnectorService => { let gateway: Box< dyn PaymentGateway<State, ConnectorData, F, Req, Resp, Context, FlowOutput>, > = F::get_gateway(ExecutionPath::UnifiedConnectorService); // Execute through selected gateway let ucs_result = gateway .execute( state, connector_integration, router_data, call_connector_action, connector_request, return_raw_connector_response, context, ) .await .attach_printable("Gateway execution failed")?; Ok(ucs_result) } ExecutionPath::ShadowUnifiedConnectorService => { let gateway: Box< dyn PaymentGateway<State, ConnectorData, F, Req, Resp, Context, FlowOutput>, > = F::get_gateway(ExecutionPath::Direct); let direct_router_data = gateway .execute( state, connector_integration.clone_box(), router_data, call_connector_action.clone(), connector_request, return_raw_connector_response, context.clone(), ) .await?; let state_clone = state.clone(); let router_data_clone = router_data.clone(); let direct_router_data_clone = direct_router_data.clone(); let return_raw_connector_response_clone = return_raw_connector_response; let context_clone = context; tokio::spawn( async move { let gateway: Box< dyn PaymentGateway<State, ConnectorData, F, Req, Resp, Context, FlowOutput>, > = F::get_gateway(ExecutionPath::ShadowUnifiedConnectorService); let ucs_shadow_result = gateway .execute( &state_clone, connector_integration, &router_data_clone, call_connector_action, None, return_raw_connector_response_clone, context_clone, ) .await .attach_printable("Gateway execution failed"); // Send comparison data asynchronously match ucs_shadow_result { Ok(ucs_router_data) => { // Send comparison data asynchronously if let Some(comparison_service_config) = state_clone.get_comparison_service_config() { let request_id = state_clone.get_request_id_str(); let _ = helpers::serialize_router_data_and_send_to_comparison_service( &state_clone, direct_router_data_clone.get_router_data().clone(), ucs_router_data.get_router_data().clone(), comparison_service_config, request_id, ) .await; }; } Err(e) => { logger::error!(error=?e, "UCS shadow execution failed"); } } } .instrument(router_env::tracing::Span::current()), ); Ok(direct_router_data) } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/files_v2.rs
crates/hyperswitch_interfaces/src/api/files_v2.rs
//! Files V2 interface use hyperswitch_domain_models::{ router_data_v2::FilesFlowData, router_flow_types::{Retrieve, Upload}, router_request_types::{RetrieveFileRequestData, UploadFileRequestData}, router_response_types::{RetrieveFileResponse, UploadFileResponse}, }; use crate::api::{errors, files::FilePurpose, ConnectorCommon, ConnectorIntegrationV2}; /// trait UploadFileV2 pub trait UploadFileV2: ConnectorIntegrationV2<Upload, FilesFlowData, UploadFileRequestData, UploadFileResponse> { } /// trait RetrieveFileV2 pub trait RetrieveFileV2: ConnectorIntegrationV2<Retrieve, FilesFlowData, RetrieveFileRequestData, RetrieveFileResponse> { } /// trait FileUploadV2 pub trait FileUploadV2: ConnectorCommon + Sync + UploadFileV2 + RetrieveFileV2 { /// fn validate_file_upload_v2 fn validate_file_upload_v2( &self, _purpose: FilePurpose, _file_size: i32, _file_type: mime::Mime, ) -> common_utils::errors::CustomResult<(), errors::ConnectorError> { Err(errors::ConnectorError::FileValidationFailed { reason: "".to_owned(), } .into()) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/fraud_check_v2.rs
crates/hyperswitch_interfaces/src/api/fraud_check_v2.rs
//! FRM V2 interface use hyperswitch_domain_models::{ router_data_v2::flow_common_types::FrmFlowData, router_flow_types::{Checkout, Fulfillment, RecordReturn, Sale, Transaction}, router_request_types::fraud_check::{ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, FraudCheckSaleData, FraudCheckTransactionData, }, router_response_types::fraud_check::FraudCheckResponseData, }; use crate::api::ConnectorIntegrationV2; /// trait FraudCheckSaleV2 pub trait FraudCheckSaleV2: ConnectorIntegrationV2<Sale, FrmFlowData, FraudCheckSaleData, FraudCheckResponseData> { } /// trait FraudCheckCheckoutV2 pub trait FraudCheckCheckoutV2: ConnectorIntegrationV2<Checkout, FrmFlowData, FraudCheckCheckoutData, FraudCheckResponseData> { } /// trait FraudCheckTransactionV2 pub trait FraudCheckTransactionV2: ConnectorIntegrationV2<Transaction, FrmFlowData, FraudCheckTransactionData, FraudCheckResponseData> { } /// trait FraudCheckFulfillmentV2 pub trait FraudCheckFulfillmentV2: ConnectorIntegrationV2<Fulfillment, FrmFlowData, FraudCheckFulfillmentData, FraudCheckResponseData> { } /// trait FraudCheckRecordReturnV2 pub trait FraudCheckRecordReturnV2: ConnectorIntegrationV2< RecordReturn, FrmFlowData, FraudCheckRecordReturnData, FraudCheckResponseData, > { } /// trait FraudCheckV2 pub trait FraudCheckV2: super::ConnectorCommon + FraudCheckSaleV2 + FraudCheckTransactionV2 + FraudCheckCheckoutV2 + FraudCheckFulfillmentV2 + FraudCheckRecordReturnV2 { }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/authentication_v2.rs
crates/hyperswitch_interfaces/src/api/authentication_v2.rs
use hyperswitch_domain_models::{ router_data_v2::ExternalAuthenticationFlowData, router_flow_types::authentication::{ Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall, }, router_request_types::authentication::{ ConnectorAuthenticationRequestData, ConnectorPostAuthenticationRequestData, PreAuthNRequestData, }, router_response_types::AuthenticationResponseData, }; use crate::api::ConnectorIntegrationV2; /// trait ConnectorAuthenticationV2 pub trait ConnectorAuthenticationV2: ConnectorIntegrationV2< Authentication, ExternalAuthenticationFlowData, ConnectorAuthenticationRequestData, AuthenticationResponseData, > { } /// trait ConnectorPreAuthenticationV2 pub trait ConnectorPreAuthenticationV2: ConnectorIntegrationV2< PreAuthentication, ExternalAuthenticationFlowData, PreAuthNRequestData, AuthenticationResponseData, > { } /// trait ConnectorPreAuthenticationVersionCallV2 pub trait ConnectorPreAuthenticationVersionCallV2: ConnectorIntegrationV2< PreAuthenticationVersionCall, ExternalAuthenticationFlowData, PreAuthNRequestData, AuthenticationResponseData, > { } /// trait ConnectorPostAuthenticationV2 pub trait ConnectorPostAuthenticationV2: ConnectorIntegrationV2< PostAuthentication, ExternalAuthenticationFlowData, ConnectorPostAuthenticationRequestData, AuthenticationResponseData, > { } /// trait ExternalAuthenticationV2 pub trait ExternalAuthenticationV2: super::ConnectorCommon + ConnectorAuthenticationV2 + ConnectorPreAuthenticationV2 + ConnectorPreAuthenticationVersionCallV2 + ConnectorPostAuthenticationV2 { }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/revenue_recovery_v2.rs
crates/hyperswitch_interfaces/src/api/revenue_recovery_v2.rs
//! Revenue Recovery Interface V2 use hyperswitch_domain_models::{ router_data_v2::flow_common_types::{ BillingConnectorInvoiceSyncFlowData, BillingConnectorPaymentsSyncFlowData, InvoiceRecordBackData, }, router_flow_types::{ BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, InvoiceRecordBack, }, router_request_types::revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, InvoiceRecordBackRequest, }, router_response_types::revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, InvoiceRecordBackResponse, }, }; use crate::connector_integration_v2::ConnectorIntegrationV2; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] /// trait RevenueRecoveryV2 pub trait RevenueRecoveryV2: BillingConnectorPaymentsSyncIntegrationV2 + RevenueRecoveryRecordBackV2 + BillingConnectorInvoiceSyncIntegrationV2 { } #[cfg(not(all(feature = "v2", feature = "revenue_recovery")))] /// trait RevenueRecoveryV2 pub trait RevenueRecoveryV2 {} /// trait BillingConnectorPaymentsSyncIntegrationV2 pub trait BillingConnectorPaymentsSyncIntegrationV2: ConnectorIntegrationV2< BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncFlowData, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse, > { } /// trait RevenueRecoveryRecordBackV2 pub trait RevenueRecoveryRecordBackV2: ConnectorIntegrationV2< InvoiceRecordBack, InvoiceRecordBackData, InvoiceRecordBackRequest, InvoiceRecordBackResponse, > { } /// trait BillingConnectorInvoiceSyncIntegrationV2 pub trait BillingConnectorInvoiceSyncIntegrationV2: ConnectorIntegrationV2< BillingConnectorInvoiceSync, BillingConnectorInvoiceSyncFlowData, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse, > { }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/subscriptions.rs
crates/hyperswitch_interfaces/src/api/subscriptions.rs
//! Subscriptions Interface for V1 use hyperswitch_domain_models::{ router_flow_types::{ subscriptions::{ GetSubscriptionEstimate, GetSubscriptionItemPrices, GetSubscriptionItems, SubscriptionCreate as SubscriptionCreateFlow, }, InvoiceRecordBack, }, router_request_types::{ revenue_recovery::InvoiceRecordBackRequest, subscriptions::{ GetSubscriptionEstimateRequest, GetSubscriptionItemPricesRequest, GetSubscriptionItemsRequest, SubscriptionCreateRequest, }, }, router_response_types::{ revenue_recovery::InvoiceRecordBackResponse, subscriptions::{ GetSubscriptionEstimateResponse, GetSubscriptionItemPricesResponse, GetSubscriptionItemsResponse, SubscriptionCreateResponse, }, }, }; use super::{ payments::ConnectorCustomer as PaymentsConnectorCustomer, ConnectorCommon, ConnectorIntegration, }; /// trait GetSubscriptionItems for V1 pub trait GetSubscriptionItemsFlow: ConnectorIntegration< GetSubscriptionItems, GetSubscriptionItemsRequest, GetSubscriptionItemsResponse, > { } /// trait SubscriptionRecordBack for V1 pub trait SubscriptionRecordBackFlow: ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse> { } /// trait SubscriptionPause for V1 pub trait SubscriptionPauseFlow: ConnectorIntegration< hyperswitch_domain_models::router_flow_types::subscriptions::SubscriptionPause, hyperswitch_domain_models::router_request_types::subscriptions::SubscriptionPauseRequest, hyperswitch_domain_models::router_response_types::subscriptions::SubscriptionPauseResponse, > { } /// trait SubscriptionResume for V1 pub trait SubscriptionResumeFlow: ConnectorIntegration< hyperswitch_domain_models::router_flow_types::subscriptions::SubscriptionResume, hyperswitch_domain_models::router_request_types::subscriptions::SubscriptionResumeRequest, hyperswitch_domain_models::router_response_types::subscriptions::SubscriptionResumeResponse, > { } /// trait SubscriptionCancel for V1 pub trait SubscriptionCancelFlow: ConnectorIntegration< hyperswitch_domain_models::router_flow_types::subscriptions::SubscriptionCancel, hyperswitch_domain_models::router_request_types::subscriptions::SubscriptionCancelRequest, hyperswitch_domain_models::router_response_types::subscriptions::SubscriptionCancelResponse, > { } /// trait GetSubscriptionItemPrices for V1 pub trait GetSubscriptionPlanPricesFlow: ConnectorIntegration< GetSubscriptionItemPrices, GetSubscriptionItemPricesRequest, GetSubscriptionItemPricesResponse, > { } /// trait SubscriptionCreate pub trait SubscriptionCreate: ConnectorIntegration<SubscriptionCreateFlow, SubscriptionCreateRequest, SubscriptionCreateResponse> { } /// trait GetSubscriptionEstimate for V1 pub trait GetSubscriptionEstimateFlow: ConnectorIntegration< GetSubscriptionEstimate, GetSubscriptionEstimateRequest, GetSubscriptionEstimateResponse, > { } /// trait Subscriptions pub trait Subscriptions: ConnectorCommon + GetSubscriptionItemsFlow + GetSubscriptionPlanPricesFlow + SubscriptionCreate + PaymentsConnectorCustomer + SubscriptionRecordBackFlow + GetSubscriptionEstimateFlow + SubscriptionPauseFlow + SubscriptionResumeFlow + SubscriptionCancelFlow { }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/authentication.rs
crates/hyperswitch_interfaces/src/api/authentication.rs
use hyperswitch_domain_models::{ router_flow_types::authentication::{ Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall, }, router_request_types::authentication::{ ConnectorAuthenticationRequestData, ConnectorPostAuthenticationRequestData, PreAuthNRequestData, }, router_response_types::AuthenticationResponseData, }; use crate::api::ConnectorIntegration; /// trait ConnectorAuthentication pub trait ConnectorAuthentication: ConnectorIntegration<Authentication, ConnectorAuthenticationRequestData, AuthenticationResponseData> { } /// trait ConnectorPreAuthentication pub trait ConnectorPreAuthentication: ConnectorIntegration<PreAuthentication, PreAuthNRequestData, AuthenticationResponseData> { } /// trait ConnectorPreAuthenticationVersionCall pub trait ConnectorPreAuthenticationVersionCall: ConnectorIntegration<PreAuthenticationVersionCall, PreAuthNRequestData, AuthenticationResponseData> { } /// trait ConnectorPostAuthentication pub trait ConnectorPostAuthentication: ConnectorIntegration< PostAuthentication, ConnectorPostAuthenticationRequestData, AuthenticationResponseData, > { } /// trait ExternalAuthentication pub trait ExternalAuthentication: super::ConnectorCommon + ConnectorAuthentication + ConnectorPreAuthentication + ConnectorPreAuthenticationVersionCall + ConnectorPostAuthentication { }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/files.rs
crates/hyperswitch_interfaces/src/api/files.rs
//! Files interface use hyperswitch_domain_models::{ router_flow_types::files::{Retrieve, Upload}, router_request_types::{RetrieveFileRequestData, UploadFileRequestData}, router_response_types::{RetrieveFileResponse, UploadFileResponse}, }; use crate::{ api::{ConnectorCommon, ConnectorIntegration}, errors, }; /// enum FilePurpose #[derive(Debug, serde::Deserialize, strum::Display, Clone, serde::Serialize)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FilePurpose { /// DisputeEvidence DisputeEvidence, } /// trait UploadFile pub trait UploadFile: ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse> { } /// trait RetrieveFile pub trait RetrieveFile: ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse> { } /// trait FileUpload pub trait FileUpload: ConnectorCommon + Sync + UploadFile + RetrieveFile { /// fn validate_file_upload fn validate_file_upload( &self, _purpose: FilePurpose, _file_size: i32, _file_type: mime::Mime, ) -> common_utils::errors::CustomResult<(), errors::ConnectorError> { Err(errors::ConnectorError::FileValidationFailed { reason: "".to_owned(), } .into()) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/disputes_v2.rs
crates/hyperswitch_interfaces/src/api/disputes_v2.rs
//! Disputes V2 interface use hyperswitch_domain_models::{ router_data_v2::DisputesFlowData, router_flow_types::dispute::{Accept, Defend, Dsync, Evidence, Fetch}, router_request_types::{ AcceptDisputeRequestData, DefendDisputeRequestData, DisputeSyncData, FetchDisputesRequestData, SubmitEvidenceRequestData, }, router_response_types::{ AcceptDisputeResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, SubmitEvidenceResponse, }, }; use crate::api::ConnectorIntegrationV2; /// trait AcceptDisputeV2 pub trait AcceptDisputeV2: ConnectorIntegrationV2<Accept, DisputesFlowData, AcceptDisputeRequestData, AcceptDisputeResponse> { } /// trait SubmitEvidenceV2 pub trait SubmitEvidenceV2: ConnectorIntegrationV2< Evidence, DisputesFlowData, SubmitEvidenceRequestData, SubmitEvidenceResponse, > { } /// trait DefendDisputeV2 pub trait DefendDisputeV2: ConnectorIntegrationV2<Defend, DisputesFlowData, DefendDisputeRequestData, DefendDisputeResponse> { } /// trait DisputeV2 pub trait DisputeV2: super::ConnectorCommon + AcceptDisputeV2 + SubmitEvidenceV2 + DefendDisputeV2 + FetchDisputesV2 + DisputeSyncV2 { } /// trait FetchDisputeV2 pub trait FetchDisputesV2: ConnectorIntegrationV2<Fetch, DisputesFlowData, FetchDisputesRequestData, FetchDisputesResponse> { } /// trait DisputeSyncV2 pub trait DisputeSyncV2: ConnectorIntegrationV2<Dsync, DisputesFlowData, DisputeSyncData, DisputeSyncResponse> { }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/api/payments.rs
crates/hyperswitch_interfaces/src/api/payments.rs
//! Payments interface use hyperswitch_domain_models::{ router_flow_types::{ payments::{ Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, ExtendAuthorization, IncrementalAuthorization, PSync, PaymentMethodToken, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, Authenticate, CreateOrder, ExternalVaultProxy, GiftCardBalanceCheck, PostAuthenticate, PreAuthenticate, }, router_request_types::{ AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, ExternalVaultProxyPaymentsData, GiftCardBalanceCheckRequestData, PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData, PaymentsPostAuthenticateData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, }, router_response_types::{ GiftCardBalanceCheckResponseData, PaymentsResponseData, TaxCalculationResponseData, }, }; use crate::api; /// trait Payment pub trait Payment: api::ConnectorCommon + api::ConnectorSpecifications + api::ConnectorValidation + PaymentAuthorize + PaymentsPreAuthenticate + PaymentsAuthenticate + PaymentsPostAuthenticate + PaymentAuthorizeSessionToken + PaymentsCompleteAuthorize + PaymentSync + PaymentCapture + PaymentVoid + PaymentPostCaptureVoid + PaymentApprove + PaymentReject + MandateSetup + PaymentSession + PaymentToken + PaymentsPreProcessing + PaymentsPostProcessing + ConnectorCustomer + PaymentIncrementalAuthorization + PaymentExtendAuthorization + PaymentSessionUpdate + PaymentPostSessionTokens + PaymentUpdateMetadata + PaymentsCreateOrder + ExternalVaultProxyPaymentsCreateV1 + PaymentsGiftCardBalanceCheck { } /// trait PaymentSession pub trait PaymentSession: api::ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> { } /// trait MandateSetup pub trait MandateSetup: api::ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> { } /// trait PaymentAuthorize pub trait PaymentAuthorize: api::ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> { } /// trait PaymentCapture pub trait PaymentCapture: api::ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> { } /// trait PaymentSync pub trait PaymentSync: api::ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> { } /// trait PaymentVoid pub trait PaymentVoid: api::ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> { } /// trait PaymentPostCaptureVoid pub trait PaymentPostCaptureVoid: api::ConnectorIntegration<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData> { } /// trait PaymentExtendAuthorization pub trait PaymentExtendAuthorization: api::ConnectorIntegration< ExtendAuthorization, PaymentsExtendAuthorizationData, PaymentsResponseData, > { } /// trait PaymentApprove pub trait PaymentApprove: api::ConnectorIntegration<Approve, PaymentsApproveData, PaymentsResponseData> { } /// trait PaymentReject pub trait PaymentReject: api::ConnectorIntegration<Reject, PaymentsRejectData, PaymentsResponseData> { } /// trait PaymentToken pub trait PaymentToken: api::ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> { } /// trait PaymentAuthorizeSessionToken pub trait PaymentAuthorizeSessionToken: api::ConnectorIntegration<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData> { } /// trait PaymentIncrementalAuthorization pub trait PaymentIncrementalAuthorization: api::ConnectorIntegration< IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData, > { } /// trait TaxCalculation pub trait TaxCalculation: api::ConnectorIntegration<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData> { } /// trait SessionUpdate pub trait PaymentSessionUpdate: api::ConnectorIntegration<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData> { } /// trait PostSessionTokens pub trait PaymentPostSessionTokens: api::ConnectorIntegration<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData> { } /// trait UpdateMetadata pub trait PaymentUpdateMetadata: api::ConnectorIntegration<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData> { } /// trait PaymentsCompleteAuthorize pub trait PaymentsCompleteAuthorize: api::ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> { } /// trait ConnectorCustomer pub trait ConnectorCustomer: api::ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData> { } /// trait PaymentsPreProcessing pub trait PaymentsPreProcessing: api::ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> { } /// trait PaymentsPreAuthenticate pub trait PaymentsPreAuthenticate: api::ConnectorIntegration<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData> { } /// trait PaymentsAuthenticate pub trait PaymentsAuthenticate: api::ConnectorIntegration<Authenticate, PaymentsAuthenticateData, PaymentsResponseData> { } /// trait PaymentsPostAuthenticate pub trait PaymentsPostAuthenticate: api::ConnectorIntegration<PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData> { } /// trait PaymentsPostProcessing pub trait PaymentsPostProcessing: api::ConnectorIntegration<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData> { } /// trait PaymentsCreateOrder pub trait PaymentsCreateOrder: api::ConnectorIntegration<CreateOrder, CreateOrderRequestData, PaymentsResponseData> { } /// trait ExternalVaultProxyPaymentsCreate pub trait ExternalVaultProxyPaymentsCreateV1: api::ConnectorIntegration<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData> { } /// trait PaymentsGiftCardBalanceCheck pub trait PaymentsGiftCardBalanceCheck: api::ConnectorIntegration< GiftCardBalanceCheck, GiftCardBalanceCheckRequestData, GiftCardBalanceCheckResponseData, > { }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/events/routing_api_logs.rs
crates/hyperswitch_interfaces/src/events/routing_api_logs.rs
//! Routing API logs interface use std::fmt; use api_models::routing::RoutableConnectorChoice; use common_utils::request::Method; use router_env::RequestId; use serde::Serialize; use serde_json::json; use time::OffsetDateTime; /// RoutingEngine enum #[derive(Debug, Clone, Copy, Serialize)] #[serde(rename_all = "snake_case")] pub enum RoutingEngine { /// Dynamo for routing IntelligentRouter, /// Decision engine for routing DecisionEngine, } /// Method type enum #[derive(Debug, Clone, Copy, Serialize)] #[serde(rename_all = "snake_case")] pub enum ApiMethod { /// grpc call Grpc, /// Rest call Rest(Method), } impl fmt::Display for ApiMethod { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Grpc => write!(f, "Grpc"), Self::Rest(method) => write!(f, "Rest ({method})"), } } } #[derive(Debug, Serialize)] /// RoutingEvent type pub struct RoutingEvent { tenant_id: common_utils::id_type::TenantId, routable_connectors: String, payment_connector: Option<String>, flow: String, request: String, response: Option<String>, error: Option<String>, url: String, method: String, payment_id: String, profile_id: common_utils::id_type::ProfileId, merchant_id: common_utils::id_type::MerchantId, created_at: i128, status_code: Option<u16>, request_id: String, routing_engine: RoutingEngine, routing_approach: Option<String>, } impl RoutingEvent { /// fn new RoutingEvent #[allow(clippy::too_many_arguments)] pub fn new( tenant_id: common_utils::id_type::TenantId, routable_connectors: String, flow: &str, request: serde_json::Value, url: String, method: ApiMethod, payment_id: String, profile_id: common_utils::id_type::ProfileId, merchant_id: common_utils::id_type::MerchantId, request_id: Option<RequestId>, routing_engine: RoutingEngine, ) -> Self { Self { tenant_id, routable_connectors, flow: flow.to_string(), request: request.to_string(), response: None, error: None, url, method: method.to_string(), payment_id, profile_id, merchant_id, created_at: OffsetDateTime::now_utc().unix_timestamp_nanos(), status_code: None, request_id: request_id .map(|i| i.to_string()) .unwrap_or("NO_REQUEST_ID".to_string()), routing_engine, payment_connector: None, routing_approach: None, } } /// fn set_response_body pub fn set_response_body<T: Serialize>(&mut self, response: &T) { match masking::masked_serialize(response) { Ok(masked) => { self.response = Some(masked.to_string()); } Err(er) => self.set_error(json!({"error": er.to_string()})), } } /// fn set_error_response_body pub fn set_error_response_body<T: Serialize>(&mut self, response: &T) { match masking::masked_serialize(response) { Ok(masked) => { self.error = Some(masked.to_string()); } Err(er) => self.set_error(json!({"error": er.to_string()})), } } /// fn set_error pub fn set_error(&mut self, error: serde_json::Value) { self.error = Some(error.to_string()); } /// set response status code pub fn set_status_code(&mut self, code: u16) { self.status_code = Some(code); } /// set response status code pub fn set_routable_connectors(&mut self, connectors: Vec<RoutableConnectorChoice>) { let connectors = connectors .into_iter() .map(|c| { format!( "{:?}:{:?}", c.connector, c.merchant_connector_id .map(|id| id.get_string_repr().to_string()) .unwrap_or(String::from("")) ) }) .collect::<Vec<_>>() .join(","); self.routable_connectors = connectors; } /// set payment connector pub fn set_payment_connector(&mut self, connector: RoutableConnectorChoice) { self.payment_connector = Some(format!( "{:?}:{:?}", connector.connector, connector .merchant_connector_id .map(|id| id.get_string_repr().to_string()) .unwrap_or(String::from("")) )); } /// set routing approach pub fn set_routing_approach(&mut self, approach: String) { self.routing_approach = Some(approach); } /// Returns the request ID of the event. pub fn get_request_id(&self) -> &str { &self.request_id } /// Returns the merchant ID of the event. pub fn get_merchant_id(&self) -> &str { self.merchant_id.get_string_repr() } /// Returns the payment ID of the event. pub fn get_payment_id(&self) -> &str { &self.payment_id } /// Returns the profile ID of the event. pub fn get_profile_id(&self) -> &str { self.profile_id.get_string_repr() } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs
crates/hyperswitch_interfaces/src/events/connector_api_logs.rs
//! Connector API logs interface use common_utils::request::Method; use router_env::RequestId; use serde::Serialize; use serde_json::json; use time::OffsetDateTime; /// struct ConnectorEvent #[derive(Debug, Serialize)] pub struct ConnectorEvent { tenant_id: common_utils::id_type::TenantId, connector_name: String, flow: String, request: String, masked_response: Option<String>, error: Option<String>, url: String, method: String, merchant_id: common_utils::id_type::MerchantId, created_at: i128, /// Connector Event Request ID pub request_id: String, latency: u128, status_code: u16, #[serde(flatten)] connector_event_type: common_utils::events::ConnectorEventsType, } impl ConnectorEvent { /// fn new ConnectorEvent #[allow(clippy::too_many_arguments)] pub fn new( tenant_id: common_utils::id_type::TenantId, connector_name: String, flow: &str, request: serde_json::Value, url: String, method: Method, payment_id: String, merchant_id: common_utils::id_type::MerchantId, request_id: Option<&RequestId>, latency: u128, refund_id: Option<String>, dispute_id: Option<String>, payout_id: Option<String>, status_code: u16, ) -> Self { let connector_event_type = common_utils::events::ConnectorEventsType::new( payment_id, refund_id, payout_id, dispute_id, ); Self { tenant_id, connector_name, flow: flow .rsplit_once("::") .map(|(_, s)| s) .unwrap_or(flow) .to_string(), request: request.to_string(), masked_response: None, error: None, url, method: method.to_string(), merchant_id, created_at: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000, request_id: request_id .map(|i| i.to_string()) .unwrap_or("NO_REQUEST_ID".to_string()), latency, status_code, connector_event_type, } } /// fn set_response_body pub fn set_response_body<T: Serialize>(&mut self, response: &T) { match masking::masked_serialize(response) { Ok(masked) => { self.masked_response = Some(masked.to_string()); } Err(er) => self.set_error(json!({"error": er.to_string()})), } } /// fn set_error_response_body pub fn set_error_response_body<T: Serialize>(&mut self, response: &T) { match masking::masked_serialize(response) { Ok(masked) => { self.error = Some(masked.to_string()); } Err(er) => self.set_error(json!({"error": er.to_string()})), } } /// fn set_error pub fn set_error(&mut self, error: serde_json::Value) { self.error = Some(error.to_string()); } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_derive/src/lib.rs
crates/router_derive/src/lib.rs
//! Utility macros for the `router` crate. #![warn(missing_docs)] use syn::parse_macro_input; use crate::macros::diesel::DieselEnumMeta; mod macros; /// Uses the [`Debug`][Debug] implementation of a type to derive its [`Display`][Display] /// implementation. /// /// Causes a compilation error if the type doesn't implement the [`Debug`][Debug] trait. /// /// [Debug]: ::core::fmt::Debug /// [Display]: ::core::fmt::Display /// /// # Example /// /// ``` /// use router_derive::DebugAsDisplay; /// /// #[derive(Debug, DebugAsDisplay)] /// struct Point { /// x: f32, /// y: f32, /// } /// /// #[derive(Debug, DebugAsDisplay)] /// enum Color { /// Red, /// Green, /// Blue, /// } /// ``` #[proc_macro_derive(DebugAsDisplay)] pub fn debug_as_display_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::debug_as_display_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } /// Derives the boilerplate code required for using an enum with `diesel` and a PostgreSQL database. /// The enum is required to implement (or derive) the [`ToString`][ToString] and the /// [`FromStr`][FromStr] traits for this derive macro to be used. /// /// Works in tandem with the [`diesel_enum`][diesel_enum] attribute macro to achieve the desired /// results. /// /// [diesel_enum]: macro@crate::diesel_enum /// [FromStr]: ::core::str::FromStr /// [ToString]: ::std::string::ToString /// /// # Example /// /// ``` /// use router_derive::diesel_enum; /// /// // Deriving `FromStr` and `ToString` using the `strum` crate, you can also implement it /// // yourself if required. /// #[derive(strum::Display, strum::EnumString)] /// #[derive(Debug)] /// #[diesel_enum(storage_type = "db_enum")] /// enum Color { /// Red, /// Green, /// Blue, /// } /// ``` #[proc_macro_derive(DieselEnum, attributes(storage_type))] pub fn diesel_enum_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } /// Similar to [`DieselEnum`] but uses text when storing in the database, this is to avoid /// making changes to the database when the enum variants are added or modified /// /// # Example /// [DieselEnum]: macro@crate::diesel_enum /// /// ``` /// use router_derive::{diesel_enum}; /// /// // Deriving `FromStr` and `ToString` using the `strum` crate, you can also implement it /// // yourself if required. /// #[derive(strum::Display, strum::EnumString)] /// #[derive(Debug)] /// #[diesel_enum(storage_type = "text")] /// enum Color { /// Red, /// Green, /// Blue, /// } /// ``` #[proc_macro_derive(DieselEnumText)] pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_text_derive_inner(&ast) .unwrap_or_else(|error| error.to_compile_error()); tokens.into() } /// Derives the boilerplate code required for using an enum with `diesel` and a PostgreSQL database. /// /// Storage Type can either be "text" or "db_enum" /// Choosing text will store the enum as text in the database, whereas db_enum will map it to the /// corresponding database enum /// /// Works in tandem with the [`DieselEnum`][DieselEnum] derive macro to achieve the desired results. /// The enum is required to implement (or derive) the [`ToString`][ToString] and the /// [`FromStr`][FromStr] traits for the [`DieselEnum`][DieselEnum] derive macro to be used. /// /// [DieselEnum]: crate::DieselEnum /// [FromStr]: ::core::str::FromStr /// [ToString]: ::std::string::ToString /// /// # Example /// /// ``` /// use router_derive::{diesel_enum}; /// /// // Deriving `FromStr` and `ToString` using the `strum` crate, you can also implement it /// // yourself if required. (Required by the DieselEnum derive macro.) /// #[derive(strum::Display, strum::EnumString)] /// #[derive(Debug)] /// #[diesel_enum(storage_type = "text")] /// enum Color { /// Red, /// Green, /// Blue, /// } /// ``` #[proc_macro_attribute] pub fn diesel_enum( args: proc_macro::TokenStream, item: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let args_parsed = parse_macro_input!(args as DieselEnumMeta); let item = syn::parse_macro_input!(item as syn::ItemEnum); macros::diesel::diesel_enum_attribute_macro(args_parsed, &item) .unwrap_or_else(|error| error.to_compile_error()) .into() } /// A derive macro which generates the setter functions for any struct with fields /// # Example /// ``` /// use router_derive::Setter; /// /// #[derive(Setter)] /// struct Test { /// test:u32 /// } /// ``` /// The above Example will expand to /// ```rust, ignore /// impl Test { /// fn set_test(&mut self, val: u32) -> &mut Self { /// self.test = val; /// self /// } /// } /// ``` /// /// # Panics /// /// Panics if a struct without named fields is provided as input to the macro // FIXME: Remove allowed warnings, raise compile errors in a better manner instead of panicking #[allow(clippy::panic, clippy::unwrap_used)] #[proc_macro_derive(Setter, attributes(auth_based))] pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); let ident = &input.ident; // All the fields in the parent struct let fields = if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), .. }) = input.data { named } else { // FIXME: Use `compile_error!()` instead panic!("You can't use this proc-macro on structs without fields"); }; // Methods in the build struct like if the struct is // Struct i {n: u32} // this will be // pub fn set_n(&mut self,n: u32) let build_methods = fields.iter().map(|f| { let name = f.ident.as_ref().unwrap(); let method_name = format!("set_{name}"); let method_ident = syn::Ident::new(&method_name, name.span()); let ty = &f.ty; if check_if_auth_based_attr_is_present(f, "auth_based") { quote::quote! { pub fn #method_ident(&mut self, val:#ty, is_merchant_flow: bool)->&mut Self{ if is_merchant_flow { self.#name = val; } self } } } else { quote::quote! { pub fn #method_ident(&mut self, val:#ty)->&mut Self{ self.#name = val; self } } } }); let output = quote::quote! { #[automatically_derived] impl #ident { #(#build_methods)* } }; output.into() } #[inline] fn check_if_auth_based_attr_is_present(f: &syn::Field, ident: &str) -> bool { for i in f.attrs.iter() { if i.path().is_ident(ident) { return true; } } false } /// Derives the [`Serialize`][Serialize] implementation for error responses that are returned by /// the API server. /// /// This macro can be only used with enums. In addition to deriving [`Serialize`][Serialize], this /// macro provides three methods: `error_type()`, `error_code()` and `error_message()`. Each enum /// variant must have three required fields: /// /// - `error_type`: This must be an enum variant which is returned by the `error_type()` method. /// - `code`: A string error code, returned by the `error_code()` method. /// - `message`: A string error message, returned by the `error_message()` method. The message /// provided will directly be passed to `format!()`. /// /// The return type of the `error_type()` method is provided by the `error_type_enum` field /// annotated to the entire enum. Thus, all enum variants provided to the `error_type` field must /// be variants of the enum provided to `error_type_enum` field. In addition, the enum passed to /// the `error_type_enum` field must implement [`Serialize`][Serialize]. /// /// **NOTE:** This macro does not implement the [`Display`][Display] trait. /// /// # Example /// /// ``` /// use router_derive::ApiError; /// /// #[derive(Clone, Debug, serde::Serialize)] /// enum ErrorType { /// StartupError, /// InternalError, /// SerdeError, /// } /// /// #[derive(Debug, ApiError)] /// #[error(error_type_enum = ErrorType)] /// enum MyError { /// #[error(error_type = ErrorType::StartupError, code = "E001", message = "Failed to read configuration")] /// ConfigurationError, /// #[error(error_type = ErrorType::InternalError, code = "E002", message = "A database error occurred")] /// DatabaseError, /// #[error(error_type = ErrorType::SerdeError, code = "E003", message = "Failed to deserialize object")] /// DeserializationError, /// #[error(error_type = ErrorType::SerdeError, code = "E004", message = "Failed to serialize object")] /// SerializationError, /// } /// /// impl ::std::fmt::Display for MyError { /// fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> { /// f.write_str(&self.error_message()) /// } /// } /// ``` /// /// # The Generated `Serialize` Implementation /// /// - For a simple enum variant with no fields, the generated [`Serialize`][Serialize] /// implementation has only three fields, `type`, `code` and `message`: /// /// ``` /// # use router_derive::ApiError; /// # #[derive(Clone, Debug, serde::Serialize)] /// # enum ErrorType { /// # StartupError, /// # } /// #[derive(Debug, ApiError)] /// #[error(error_type_enum = ErrorType)] /// enum MyError { /// #[error(error_type = ErrorType::StartupError, code = "E001", message = "Failed to read configuration")] /// ConfigurationError, /// // ... /// } /// # impl ::std::fmt::Display for MyError { /// # fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> { /// # f.write_str(&self.error_message()) /// # } /// # } /// /// let json = serde_json::json!({ /// "type": "StartupError", /// "code": "E001", /// "message": "Failed to read configuration" /// }); /// assert_eq!(serde_json::to_value(MyError::ConfigurationError).unwrap(), json); /// ``` /// /// - For an enum variant with named fields, the generated [`Serialize`][Serialize] implementation /// includes three mandatory fields, `type`, `code` and `message`, and any other fields not /// included in the message: /// /// ``` /// # use router_derive::ApiError; /// # #[derive(Clone, Debug, serde::Serialize)] /// # enum ErrorType { /// # StartupError, /// # } /// #[derive(Debug, ApiError)] /// #[error(error_type_enum = ErrorType)] /// enum MyError { /// #[error(error_type = ErrorType::StartupError, code = "E001", message = "Failed to read configuration file: {file_path}")] /// ConfigurationError { file_path: String, reason: String }, /// // ... /// } /// # impl ::std::fmt::Display for MyError { /// # fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> { /// # f.write_str(&self.error_message()) /// # } /// # } /// /// let json = serde_json::json!({ /// "type": "StartupError", /// "code": "E001", /// "message": "Failed to read configuration file: config.toml", /// "reason": "File not found" /// }); /// let error = MyError::ConfigurationError{ /// file_path: "config.toml".to_string(), /// reason: "File not found".to_string(), /// }; /// assert_eq!(serde_json::to_value(error).unwrap(), json); /// ``` /// /// [Serialize]: https://docs.rs/serde/latest/serde/trait.Serialize.html /// [Display]: ::core::fmt::Display #[proc_macro_derive(ApiError, attributes(error))] pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::api_error_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } /// Derives the `core::payments::Operation` trait on a type with a default base /// implementation. /// /// ## Usage /// On deriving, the conversion functions to be implemented need to be specified in an helper /// attribute `#[operation(..)]`. To derive all conversion functions, use `#[operation(all)]`. To /// derive specific conversion functions, pass the required identifiers to the attribute. /// `#[operation(validate_request, get_tracker)]`. Available conversions are listed below :- /// /// - validate_request /// - get_tracker /// - domain /// - update_tracker /// /// ## Example /// ```rust, ignore /// use router_derive::Operation; /// /// #[derive(Operation)] /// #[operation(all)] /// struct Point { /// x: u64, /// y: u64 /// } /// /// // The above will expand to this /// const _: () = { /// use crate::core::errors::RouterResult; /// use crate::core::payments::{GetTracker, PaymentData, UpdateTracker, ValidateRequest}; /// impl crate::core::payments::Operation for Point { /// fn to_validate_request(&self) -> RouterResult<&dyn ValidateRequest> { /// Ok(self) /// } /// fn to_get_tracker(&self) -> RouterResult<&dyn GetTracker<PaymentData>> { /// Ok(self) /// } /// fn to_domain(&self) -> RouterResult<&dyn Domain> { /// Ok(self) /// } /// fn to_update_tracker(&self) -> RouterResult<&dyn UpdateTracker<PaymentData>> { /// Ok(self) /// } /// } /// impl crate::core::payments::Operation for &Point { /// fn to_validate_request(&self) -> RouterResult<&dyn ValidateRequest> { /// Ok(*self) /// } /// fn to_get_tracker(&self) -> RouterResult<&dyn GetTracker<PaymentData>> { /// Ok(*self) /// } /// fn to_domain(&self) -> RouterResult<&dyn Domain> { /// Ok(*self) /// } /// fn to_update_tracker(&self) -> RouterResult<&dyn UpdateTracker<PaymentData>> { /// Ok(*self) /// } /// } /// }; /// /// #[derive(Operation)] /// #[operation(validate_request, get_tracker)] /// struct Point3 { /// x: u64, /// y: u64, /// z: u64 /// } /// /// // The above will expand to this /// const _: () = { /// use crate::core::errors::RouterResult; /// use crate::core::payments::{GetTracker, PaymentData, UpdateTracker, ValidateRequest}; /// impl crate::core::payments::Operation for Point3 { /// fn to_validate_request(&self) -> RouterResult<&dyn ValidateRequest> { /// Ok(self) /// } /// fn to_get_tracker(&self) -> RouterResult<&dyn GetTracker<PaymentData>> { /// Ok(self) /// } /// } /// impl crate::core::payments::Operation for &Point3 { /// fn to_validate_request(&self) -> RouterResult<&dyn ValidateRequest> { /// Ok(*self) /// } /// fn to_get_tracker(&self) -> RouterResult<&dyn GetTracker<PaymentData>> { /// Ok(*self) /// } /// } /// }; /// /// ``` /// /// The `const _: () = {}` allows us to import stuff with `use` without affecting the module /// imports, since use statements are not allowed inside of impl blocks. This technique is /// used by `diesel`. #[proc_macro_derive(PaymentOperation, attributes(operation))] pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::operation::operation_derive_inner(input) .unwrap_or_else(|err| err.to_compile_error().into()) } /// Generates different schemas with the ability to mark few fields as mandatory for certain schema /// Usage /// ``` /// use router_derive::PolymorphicSchema; /// /// #[derive(PolymorphicSchema)] /// #[generate_schemas(PaymentsCreateRequest, PaymentsConfirmRequest)] /// struct PaymentsRequest { /// #[mandatory_in(PaymentsCreateRequest = u64)] /// amount: Option<u64>, /// #[mandatory_in(PaymentsCreateRequest = String)] /// currency: Option<String>, /// payment_method: String, /// } /// ``` /// /// This will create two structs `PaymentsCreateRequest` and `PaymentsConfirmRequest` as follows /// It will retain all the other attributes that are used in the original struct, and only consume /// the #[mandatory_in] attribute to generate schemas /// /// ``` /// #[derive(utoipa::ToSchema)] /// struct PaymentsCreateRequest { /// #[schema(required = true)] /// amount: Option<u64>, /// /// #[schema(required = true)] /// currency: Option<String>, /// /// payment_method: String, /// } /// /// #[derive(utoipa::ToSchema)] /// struct PaymentsConfirmRequest { /// amount: Option<u64>, /// currency: Option<String>, /// payment_method: String, /// } /// ``` #[proc_macro_derive( PolymorphicSchema, attributes(mandatory_in, generate_schemas, remove_in) )] pub fn polymorphic_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::polymorphic_macro_derive_inner(input) .unwrap_or_else(|error| error.into_compile_error()) .into() } /// Implements the `Validate` trait to check if the config variable is present /// Usage /// ``` /// use router_derive::ConfigValidate; /// /// #[derive(ConfigValidate)] /// struct ConnectorParams { /// base_url: String, /// } /// /// enum ApplicationError { /// InvalidConfigurationValueError(String), /// } /// /// #[derive(ConfigValidate)] /// struct Connectors { /// pub stripe: ConnectorParams, /// pub checkout: ConnectorParams /// } /// ``` /// /// This will call the `validate()` function for all the fields in the struct /// /// ```rust, ignore /// impl Connectors { /// fn validate(&self) -> Result<(), ApplicationError> { /// self.stripe.validate()?; /// self.checkout.validate()?; /// } /// } /// ``` #[proc_macro_derive(ConfigValidate)] pub fn validate_config(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::misc::validate_config(input) .unwrap_or_else(|error| error.into_compile_error()) .into() } /// Generates the function to get the value out of enum variant /// Usage /// ``` /// use router_derive::TryGetEnumVariant; /// /// impl std::fmt::Display for RedisError { /// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { /// match self { /// Self::UnknownResult => write!(f, "Unknown result") /// } /// } /// } /// /// impl std::error::Error for RedisError {} /// /// #[derive(Debug)] /// enum RedisError { /// UnknownResult /// } /// /// #[derive(TryGetEnumVariant)] /// #[error(RedisError::UnknownResult)] /// enum RedisResult { /// Set(String), /// Get(i32) /// } /// ``` /// /// This will generate the function to get `String` and `i32` out of the variants /// /// ```rust, ignore /// impl RedisResult { /// fn try_into_get(&self)-> Result<i32, RedisError> { /// match self { /// Self::Get(a) => Ok(a), /// _=>Err(RedisError::UnknownResult) /// } /// } /// /// fn try_into_set(&self)-> Result<String, RedisError> { /// match self { /// Self::Set(a) => Ok(a), /// _=> Err(RedisError::UnknownResult) /// } /// } /// } /// ``` #[proc_macro_derive(TryGetEnumVariant, attributes(error))] pub fn try_get_enum_variant(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::try_get_enum::try_get_enum_variant(input) .unwrap_or_else(|error| error.into_compile_error()) .into() } /// Uses the [`Serialize`] implementation of a type to derive a function implementation /// for converting nested keys structure into a HashMap of key, value where key is in /// the flattened form. /// /// Example /// /// ``` /// #[derive(Default, Serialize, FlatStruct)] /// pub struct User { /// name: String, /// address: Address, /// email: String, /// } /// /// #[derive(Default, Serialize)] /// pub struct Address { /// line1: String, /// line2: String, /// zip: String, /// } /// /// let user = User::default(); /// let flat_struct_map = user.flat_struct(); /// /// [ /// ("name", "Test"), /// ("address.line1", "1397"), /// ("address.line2", "Some street"), /// ("address.zip", "941222"), /// ("email", "test@example.com"), /// ] /// ``` #[proc_macro_derive(FlatStruct)] pub fn flat_struct_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = parse_macro_input!(input as syn::DeriveInput); let name = &input.ident; let expanded = quote::quote! { impl #name { pub fn flat_struct(&self) -> std::collections::HashMap<String, String> { use serde_json::Value; use std::collections::HashMap; fn flatten_value( value: &Value, prefix: &str, result: &mut HashMap<String, String> ) { match value { Value::Object(map) => { for (key, val) in map { let new_key = if prefix.is_empty() { key.to_string() } else { format!("{}.{}", prefix, key) }; flatten_value(val, &new_key, result); } } Value::String(s) => { result.insert(prefix.to_string(), s.clone()); } Value::Number(n) => { result.insert(prefix.to_string(), n.to_string()); } Value::Bool(b) => { result.insert(prefix.to_string(), b.to_string()); } _ => {} } } let mut result = HashMap::new(); let value = serde_json::to_value(self).unwrap(); flatten_value(&value, "", &mut result); result } } }; proc_macro::TokenStream::from(expanded) } /// Generates the permissions enum and implematations for the permissions /// /// **NOTE:** You have to make sure that all the identifiers used /// in the macro input are present in the respective enums as well. /// /// ## Usage /// ``` /// use router_derive::generate_permissions; /// /// enum Scope { /// Read, /// Write, /// } /// /// enum EntityType { /// Profile, /// Merchant, /// Org, /// } /// /// enum Resource { /// Payments, /// Refunds, /// } /// /// generate_permissions! { /// permissions: [ /// Payments: { /// scopes: [Read, Write], /// entities: [Profile, Merchant, Org] /// }, /// Refunds: { /// scopes: [Read], /// entities: [Profile, Org] /// } /// ] /// } /// ``` /// This will generate the following enum. /// ``` /// enum Permission { /// ProfilePaymentsRead, /// ProfilePaymentsWrite, /// MerchantPaymentsRead, /// MerchantPaymentsWrite, /// OrgPaymentsRead, /// OrgPaymentsWrite, /// ProfileRefundsRead, /// OrgRefundsRead, /// ``` #[proc_macro] pub fn generate_permissions(input: proc_macro::TokenStream) -> proc_macro::TokenStream { macros::generate_permissions_inner(input) } /// Generates the ToEncryptable trait for a type /// /// This macro generates the temporary structs which has the fields that needs to be encrypted /// /// fn to_encryptable: Convert the temp struct to a hashmap that can be sent over the network /// fn from_encryptable: Convert the hashmap back to temp struct #[proc_macro_derive(ToEncryption, attributes(encrypt))] pub fn derive_to_encryption_attr(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::derive_to_encryption(input) .unwrap_or_else(|err| err.into_compile_error()) .into() } /// Derives validation functionality for structs with string-based fields that have /// schema attributes specifying constraints like minimum and maximum lengths. /// /// This macro generates a `validate()` method that checks if string based fields /// meet the length requirements specified in their schema attributes. /// /// ## Supported Types /// - Option<T> or T: where T: String or Url /// /// ## Supported Schema Attributes /// /// - `min_length`: Specifies the minimum allowed character length /// - `max_length`: Specifies the maximum allowed character length /// /// ## Example /// /// ``` /// use utoipa::ToSchema; /// use router_derive::ValidateSchema; /// use url::Url; /// /// #[derive(Default, ToSchema, ValidateSchema)] /// pub struct PaymentRequest { /// #[schema(min_length = 10, max_length = 255)] /// pub description: String, /// /// #[schema(example = "https://example.com/return", max_length = 255)] /// pub return_url: Option<Url>, /// /// // Field without constraints /// pub amount: u64, /// } /// /// let payment = PaymentRequest { /// description: "Too short".to_string(), /// return_url: Some(Url::parse("https://very-long-domain.com/callback").unwrap()), /// amount: 1000, /// }; /// /// let validation_result = payment.validate(); /// assert!(validation_result.is_err()); /// assert_eq!( /// validation_result.unwrap_err(), /// "description must be at least 10 characters long. Received 9 characters" /// ); /// ``` /// /// ## Notes /// - For `Option` fields, validation is only performed when the value is `Some` /// - Fields without schema attributes or with unsupported types are ignored /// - The validation stops on the first error encountered /// - The generated `validate()` method returns `Ok(())` if all validations pass, or /// `Err(String)` with an error message if any validations fail. #[proc_macro_derive(ValidateSchema, attributes(schema))] pub fn validate_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::validate_schema_derive(input) .unwrap_or_else(|error| error.into_compile_error()) .into() }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_derive/src/macros.rs
crates/router_derive/src/macros.rs
pub(crate) mod api_error; pub(crate) mod diesel; pub(crate) mod generate_permissions; pub(crate) mod generate_schema; pub(crate) mod misc; pub(crate) mod operation; pub(crate) mod schema; pub(crate) mod to_encryptable; pub(crate) mod try_get_enum; mod helpers; use proc_macro2::TokenStream; use quote::quote; use syn::DeriveInput; pub(crate) use self::{ api_error::api_error_derive_inner, diesel::{diesel_enum_derive_inner, diesel_enum_text_derive_inner}, generate_permissions::generate_permissions_inner, generate_schema::polymorphic_macro_derive_inner, schema::validate_schema_derive, to_encryptable::derive_to_encryption, }; pub(crate) fn debug_as_display_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); Ok(quote! { #[automatically_derived] impl #impl_generics ::core::fmt::Display for #name #ty_generics #where_clause { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> { f.write_str(&format!("{:?}", self)) } } }) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_derive/src/macros/try_get_enum.rs
crates/router_derive/src/macros/try_get_enum.rs
use proc_macro2::Span; use quote::ToTokens; use syn::{parse::Parse, punctuated::Punctuated}; mod try_get_keyword { use syn::custom_keyword; custom_keyword!(error_type); } #[derive(Debug)] pub struct TryGetEnumMeta { error_type: syn::Ident, variant: syn::Ident, } impl Parse for TryGetEnumMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let error_type = input.parse()?; _ = input.parse::<syn::Token![::]>()?; let variant = input.parse()?; Ok(Self { error_type, variant, }) } } trait TryGetDeriveInputExt { /// Get all the error metadata associated with an enum. fn get_metadata(&self) -> syn::Result<Vec<TryGetEnumMeta>>; } impl TryGetDeriveInputExt for syn::DeriveInput { fn get_metadata(&self) -> syn::Result<Vec<TryGetEnumMeta>> { super::helpers::get_metadata_inner("error", &self.attrs) } } impl ToTokens for TryGetEnumMeta { fn to_tokens(&self, _: &mut proc_macro2::TokenStream) {} } /// Try and get the variants for an enum pub fn try_get_enum_variant( input: syn::DeriveInput, ) -> Result<proc_macro2::TokenStream, syn::Error> { let name = &input.ident; let parsed_error_type = input.get_metadata()?; let (error_type, error_variant) = parsed_error_type .first() .ok_or(syn::Error::new( Span::call_site(), "One error should be specified", )) .map(|error_struct| (&error_struct.error_type, &error_struct.variant))?; let (impl_generics, generics, where_clause) = input.generics.split_for_impl(); let variants = get_enum_variants(&input.data)?; let try_into_fns = variants.iter().map(|variant| { let variant_name = &variant.ident; let variant_field = get_enum_variant_field(variant)?; let variant_types = variant_field.iter().map(|f|f.ty.clone()); let try_into_fn = syn::Ident::new( &format!("try_into_{}", variant_name.to_string().to_lowercase()), Span::call_site(), ); Ok(quote::quote! { pub fn #try_into_fn(self)->Result<(#(#variant_types),*),error_stack::Report<#error_type>> { match self { Self::#variant_name(inner) => Ok(inner), _=> Err(error_stack::report!(#error_type::#error_variant)), } } }) }).collect::<Result<Vec<proc_macro2::TokenStream>,syn::Error>>()?; let expanded = quote::quote! { impl #impl_generics #name #generics #where_clause { #(#try_into_fns)* } }; Ok(expanded) } /// Get variants from Enum fn get_enum_variants(data: &syn::Data) -> syn::Result<Punctuated<syn::Variant, syn::token::Comma>> { if let syn::Data::Enum(syn::DataEnum { variants, .. }) = data { Ok(variants.clone()) } else { Err(super::helpers::non_enum_error()) } } /// Get Field from an enum variant fn get_enum_variant_field( variant: &syn::Variant, ) -> syn::Result<Punctuated<syn::Field, syn::token::Comma>> { let field = match variant.fields.clone() { syn::Fields::Unnamed(un) => un.unnamed, syn::Fields::Named(n) => n.named, syn::Fields::Unit => { return Err(super::helpers::syn_error( Span::call_site(), "The enum is a unit variant it's not supported", )) } }; Ok(field) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_derive/src/macros/misc.rs
crates/router_derive/src/macros/misc.rs
pub fn get_field_type(field_type: syn::Type) -> Option<syn::Ident> { if let syn::Type::Path(path) = field_type { path.path .segments .last() .map(|last_path_segment| last_path_segment.ident.to_owned()) } else { None } } /// Implement the `validate` function for the struct by calling `validate` function on the fields pub fn validate_config(input: syn::DeriveInput) -> Result<proc_macro2::TokenStream, syn::Error> { let fields = super::helpers::get_struct_fields(input.data) .map_err(|error| syn::Error::new(proc_macro2::Span::call_site(), error))?; let struct_name = input.ident; let function_expansions = fields .into_iter() .flat_map(|field| field.ident.to_owned().zip(get_field_type(field.ty))) .filter_map(|(field_ident, field_type_ident)| { // Check if a field is a leaf field, only String ( connector urls ) is supported for now let field_ident_string = field_ident.to_string(); let is_optional_field = field_type_ident.eq("Option"); let is_secret_field = field_type_ident.eq("Secret"); // Do not call validate if it is an optional field if !is_optional_field && !is_secret_field { let is_leaf_field = field_type_ident.eq("String"); let validate_expansion = if is_leaf_field { quote::quote!(common_utils::fp_utils::when( self.#field_ident.is_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( format!("{} must not be empty for {}", #field_ident_string, parent_field).into(), )) } )?; ) } else { quote::quote!( self.#field_ident.validate(#field_ident_string)?; ) }; Some(validate_expansion) } else { None } }) .collect::<Vec<_>>(); let expansion = quote::quote! { impl #struct_name { /// Validates that the configuration provided for the `parent_field` does not contain empty or default values pub fn validate(&self, parent_field: &str) -> Result<(), ApplicationError> { #(#function_expansions)* Ok(()) } } }; Ok(expansion) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_derive/src/macros/generate_schema.rs
crates/router_derive/src/macros/generate_schema.rs
use std::collections::{HashMap, HashSet}; use indexmap::IndexMap; use syn::{self, parse::Parse, parse_quote, punctuated::Punctuated, Token}; use crate::macros::helpers; /// Parse schemas from attribute /// Example /// /// #[mandatory_in(PaymentsCreateRequest, PaymentsUpdateRequest)] /// would return /// /// [PaymentsCreateRequest, PaymentsUpdateRequest] fn get_inner_path_ident(attribute: &syn::Attribute) -> syn::Result<Vec<syn::Ident>> { Ok(attribute .parse_args_with(Punctuated::<syn::Ident, Token![,]>::parse_terminated)? .into_iter() .collect::<Vec<_>>()) } #[allow(dead_code)] /// Get the type of field fn get_field_type(field_type: syn::Type) -> syn::Result<syn::Ident> { if let syn::Type::Path(path) = field_type { path.path .segments .last() .map(|last_path_segment| last_path_segment.ident.to_owned()) .ok_or(syn::Error::new( proc_macro2::Span::call_site(), "Atleast one ident must be specified", )) } else { Err(syn::Error::new( proc_macro2::Span::call_site(), "Only path fields are supported", )) } } #[allow(dead_code)] /// Get the inner type of option fn get_inner_option_type(field: &syn::Type) -> syn::Result<syn::Ident> { if let syn::Type::Path(ref path) = &field { if let Some(segment) = path.path.segments.last() { if let syn::PathArguments::AngleBracketed(ref args) = &segment.arguments { if let Some(syn::GenericArgument::Type(ty)) = args.args.first() { return get_field_type(ty.clone()); } } } } Err(syn::Error::new( proc_macro2::Span::call_site(), "Only path fields are supported", )) } mod schema_keyword { use syn::custom_keyword; custom_keyword!(schema); } #[derive(Debug, Clone)] pub struct SchemaMeta { struct_name: syn::Ident, type_ident: syn::Ident, } /// parse #[mandatory_in(PaymentsCreateRequest = u64)] impl Parse for SchemaMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let struct_name = input.parse::<syn::Ident>()?; input.parse::<syn::Token![=]>()?; let type_ident = input.parse::<syn::Ident>()?; Ok(Self { struct_name, type_ident, }) } } impl quote::ToTokens for SchemaMeta { fn to_tokens(&self, _: &mut proc_macro2::TokenStream) {} } pub fn polymorphic_macro_derive_inner( input: syn::DeriveInput, ) -> syn::Result<proc_macro2::TokenStream> { let schemas_to_create = helpers::get_metadata_inner::<syn::Ident>("generate_schemas", &input.attrs)?; let fields = helpers::get_struct_fields(input.data) .map_err(|error| syn::Error::new(proc_macro2::Span::call_site(), error))?; // Go through all the fields and create a mapping of required fields for a schema // PaymentsCreate -> ["amount","currency"] // This will be stored in the hashmap with key as // required_fields -> ((amount, PaymentsCreate), (currency, PaymentsCreate)) // and values as the type // // (amount, PaymentsCreate) -> Amount let mut required_fields = HashMap::<(syn::Ident, syn::Ident), syn::Ident>::new(); // These fields will be removed in the schema // PaymentsUpdate -> ["client_secret"] // This will be stored in a hashset // hide_fields -> ((client_secret, PaymentsUpdate)) let mut hide_fields = HashSet::<(syn::Ident, syn::Ident)>::new(); let mut all_fields = IndexMap::<syn::Field, Vec<syn::Attribute>>::new(); for field in fields { // Partition the attributes of a field into two vectors // One with #[mandatory_in] attributes present // Rest of the attributes ( include only the schema attribute, serde is not required) let (mandatory_attribute, other_attributes) = field .attrs .iter() .partition::<Vec<_>, _>(|attribute| attribute.path().is_ident("mandatory_in")); let hidden_fields = field .attrs .iter() .filter(|attribute| attribute.path().is_ident("remove_in")) .collect::<Vec<_>>(); // Other attributes ( schema ) are to be printed as is other_attributes .iter() .filter(|attribute| { attribute.path().is_ident("schema") || attribute.path().is_ident("doc") }) .for_each(|attribute| { // Since attributes will be modified, the field should not contain any attributes // So create a field, with previous attributes removed let mut field_without_attributes = field.clone(); field_without_attributes.attrs.clear(); all_fields .entry(field_without_attributes.to_owned()) .or_default() .push(attribute.to_owned().to_owned()); }); // Mandatory attributes are to be inserted into hashset // The hashset will store it in this format // ("amount", PaymentsCreateRequest) // ("currency", PaymentsConfirmRequest) // // For these attributes, we need to later add #[schema(required = true)] attribute let field_ident = field.ident.ok_or(syn::Error::new( proc_macro2::Span::call_site(), "Cannot use `mandatory_in` on unnamed fields", ))?; // Parse the #[mandatory_in(PaymentsCreateRequest = u64)] and insert into hashmap // key -> ("amount", PaymentsCreateRequest) // value -> u64 if let Some(mandatory_in_attribute) = helpers::get_metadata_inner::<SchemaMeta>("mandatory_in", mandatory_attribute)?.first() { let key = ( field_ident.clone(), mandatory_in_attribute.struct_name.clone(), ); let value = mandatory_in_attribute.type_ident.clone(); required_fields.insert(key, value); } // Hidden fields are to be inserted in the Hashset // The hashset will store it in this format // ("client_secret", PaymentsUpdate) // // These fields will not be added to the struct _ = hidden_fields .iter() // Filter only #[mandatory_in] attributes .map(|&attribute| get_inner_path_ident(attribute)) .try_for_each(|schemas| { let res = schemas .map_err(|error| syn::Error::new(proc_macro2::Span::call_site(), error))? .iter() .map(|schema| (field_ident.clone(), schema.to_owned())) .collect::<HashSet<_>>(); hide_fields.extend(res); Ok::<_, syn::Error>(()) }); } // iterate over the schemas and build them with their fields let schemas = schemas_to_create .iter() .map(|schema| { let fields = all_fields .iter() .filter_map(|(field, attributes)| { let mut final_attributes = attributes.clone(); if let Some(field_ident) = field.ident.to_owned() { // If the field is required for this schema, then add // #[schema(value_type = type)] for this field if let Some(required_field_type) = required_fields.get(&(field_ident.clone(), schema.to_owned())) { // This is a required field in the Schema // Add the value type and remove original value type ( if present ) let attribute_without_schema_type = attributes .iter() .filter(|attribute| !attribute.path().is_ident("schema")) .map(Clone::clone) .collect::<Vec<_>>(); final_attributes = attribute_without_schema_type; let value_type_attribute: syn::Attribute = parse_quote!(#[schema(value_type = #required_field_type)]); final_attributes.push(value_type_attribute); } } // If the field is to be not shown then let is_hidden_field = field .ident .clone() .map(|field_ident| hide_fields.contains(&(field_ident, schema.to_owned()))) .unwrap_or(false); if is_hidden_field { None } else { Some(quote::quote! { #(#final_attributes)* #field, }) } }) .collect::<Vec<_>>(); quote::quote! { #[derive(utoipa::ToSchema)] pub struct #schema { #(#fields)* } } }) .collect::<Vec<_>>(); Ok(quote::quote! { #(#schemas)* }) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_derive/src/macros/helpers.rs
crates/router_derive/src/macros/helpers.rs
use proc_macro2::Span; use quote::ToTokens; use syn::{parse::Parse, punctuated::Punctuated, spanned::Spanned, Attribute, Token}; pub fn non_enum_error() -> syn::Error { syn::Error::new(Span::call_site(), "This macro only supports enums.") } pub(super) fn occurrence_error<T: ToTokens>( first_keyword: T, second_keyword: T, attr: &str, ) -> syn::Error { let mut error = syn::Error::new_spanned( second_keyword, format!("Found multiple occurrences of error({attr})"), ); error.combine(syn::Error::new_spanned(first_keyword, "first one here")); error } pub(super) fn syn_error(span: Span, message: &str) -> syn::Error { syn::Error::new(span, message) } /// Get all the variants of a enum in the form of a string pub fn get_possible_values_for_enum<T>() -> String where T: strum::IntoEnumIterator + ToString, { T::iter() .map(|variants| variants.to_string()) .collect::<Vec<_>>() .join(", ") } pub(super) fn get_metadata_inner<'a, T: Parse + Spanned>( ident: &str, attrs: impl IntoIterator<Item = &'a Attribute>, ) -> syn::Result<Vec<T>> { attrs .into_iter() .filter(|attr| attr.path().is_ident(ident)) .try_fold(Vec::new(), |mut vec, attr| { vec.extend(attr.parse_args_with(Punctuated::<T, Token![,]>::parse_terminated)?); Ok(vec) }) } pub(super) fn get_struct_fields( data: syn::Data, ) -> syn::Result<Punctuated<syn::Field, syn::token::Comma>> { if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), .. }) = data { Ok(named.to_owned()) } else { Err(syn::Error::new( Span::call_site(), "This macro cannot be used on structs with no fields", )) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_derive/src/macros/to_encryptable.rs
crates/router_derive/src/macros/to_encryptable.rs
use std::iter::Iterator; use quote::{format_ident, quote}; use syn::{parse::Parse, punctuated::Punctuated, token::Comma, Field, Ident, Type as SynType}; use crate::macros::{helpers::get_struct_fields, misc::get_field_type}; pub struct FieldMeta { _meta_type: Ident, pub value: Ident, } impl Parse for FieldMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let _meta_type: Ident = input.parse()?; input.parse::<syn::Token![=]>()?; let value: Ident = input.parse()?; Ok(Self { _meta_type, value }) } } impl quote::ToTokens for FieldMeta { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { self.value.to_tokens(tokens); } } fn get_encryption_ty_meta(field: &Field) -> Option<FieldMeta> { let attrs = &field.attrs; attrs .iter() .flat_map(|s| s.parse_args::<FieldMeta>()) .find(|s| s._meta_type.eq("ty")) } fn get_inner_type(path: &syn::TypePath) -> syn::Result<syn::TypePath> { path.path .segments .last() .and_then(|segment| match &segment.arguments { syn::PathArguments::AngleBracketed(args) => args.args.first(), _ => None, }) .and_then(|arg| match arg { syn::GenericArgument::Type(SynType::Path(path)) => Some(path.clone()), _ => None, }) .ok_or_else(|| { syn::Error::new( proc_macro2::Span::call_site(), "Only path fields are supported", ) }) } /// This function returns the inner most type recursively /// For example: /// /// In the case of `Encryptable<Secret<String>>> this returns String fn get_inner_most_type(ty: SynType) -> syn::Result<Ident> { fn get_inner_type_recursive(path: syn::TypePath) -> syn::Result<syn::TypePath> { match get_inner_type(&path) { Ok(inner_path) => get_inner_type_recursive(inner_path), Err(_) => Ok(path), } } match ty { SynType::Path(path) => { let inner_path = get_inner_type_recursive(path)?; inner_path .path .segments .last() .map(|last_segment| last_segment.ident.to_owned()) .ok_or_else(|| { syn::Error::new( proc_macro2::Span::call_site(), "At least one ident must be specified", ) }) } _ => Err(syn::Error::new( proc_macro2::Span::call_site(), "Only path fields are supported", )), } } /// This returns the field which implement #[encrypt] attribute fn get_encryptable_fields(fields: Punctuated<Field, Comma>) -> Vec<Field> { fields .into_iter() .filter(|field| { field .attrs .iter() .any(|attr| attr.path().is_ident("encrypt")) }) .collect() } /// This function returns the inner most type of a field fn get_field_and_inner_types(fields: &[Field]) -> Vec<(Field, Ident)> { fields .iter() .flat_map(|field| { get_inner_most_type(field.ty.clone()).map(|field_name| (field.to_owned(), field_name)) }) .collect() } /// The type of the struct for which the batch encryption/decryption needs to be implemented #[derive(PartialEq, Copy, Clone)] enum StructType { Encrypted, Decrypted, DecryptedUpdate, FromRequest, Updated, } impl StructType { /// Generates the fields for temporary structs which consists of the fields that should be /// encrypted/decrypted fn generate_struct_fields(self, fields: &[(Field, Ident)]) -> Vec<proc_macro2::TokenStream> { fields .iter() .map(|(field, inner_ty)| { let provided_ty = get_encryption_ty_meta(field); let is_option = get_field_type(field.ty.clone()) .map(|f| f.eq("Option")) .unwrap_or_default(); let ident = &field.ident; let inner_ty = if let Some(ref ty) = provided_ty { &ty.value } else { inner_ty }; match (self, is_option) { (Self::Encrypted, true) => quote! { pub #ident: Option<Encryption> }, (Self::Encrypted, false) => quote! { pub #ident: Encryption }, (Self::Decrypted, true) => { quote! { pub #ident: Option<Encryptable<Secret<#inner_ty>>> } } (Self::Decrypted, false) => { quote! { pub #ident: Encryptable<Secret<#inner_ty>> } } (Self::DecryptedUpdate, _) => { quote! { pub #ident: Option<Encryptable<Secret<#inner_ty>>> } } (Self::FromRequest, true) => { quote! { pub #ident: Option<Secret<#inner_ty>> } } (Self::FromRequest, false) => quote! { pub #ident: Secret<#inner_ty> }, (Self::Updated, _) => quote! { pub #ident: Option<Secret<#inner_ty>> }, } }) .collect() } /// Generates the ToEncryptable trait implementation fn generate_impls( self, gen1: proc_macro2::TokenStream, gen2: proc_macro2::TokenStream, gen3: proc_macro2::TokenStream, impl_st: proc_macro2::TokenStream, inner: &[Field], ) -> proc_macro2::TokenStream { let map_length = inner.len(); let to_encryptable_impl = inner.iter().flat_map(|field| { get_field_type(field.ty.clone()).map(|field_ty| { let is_option = field_ty.eq("Option"); let field_ident = &field.ident; let field_ident_string = field_ident.as_ref().map(|s| s.to_string()); if is_option || self == Self::Updated { quote! { self.#field_ident.map(|s| map.insert(#field_ident_string.to_string(), s)) } } else { quote! { map.insert(#field_ident_string.to_string(), self.#field_ident) } } }) }); let from_encryptable_impl = inner.iter().flat_map(|field| { get_field_type(field.ty.clone()).map(|field_ty| { let is_option = field_ty.eq("Option"); let field_ident = &field.ident; let field_ident_string = field_ident.as_ref().map(|s| s.to_string()); if is_option || self == Self::Updated { quote! { #field_ident: map.remove(#field_ident_string) } } else { quote! { #field_ident: map.remove(#field_ident_string).ok_or( error_stack::report!(common_utils::errors::ParsingError::EncodeError( "Unable to convert from HashMap", )) )? } } }) }); quote! { impl ToEncryptable<#gen1, #gen2, #gen3> for #impl_st { fn to_encryptable(self) -> FxHashMap<String, #gen3> { let mut map = FxHashMap::with_capacity_and_hasher(#map_length, Default::default()); #(#to_encryptable_impl;)* map } fn from_encryptable( mut map: FxHashMap<String, Encryptable<#gen2>>, ) -> CustomResult<#gen1, common_utils::errors::ParsingError> { Ok(#gen1 { #(#from_encryptable_impl,)* }) } } } } } /// This function generates the temporary struct and ToEncryptable impls for the temporary structs fn generate_to_encryptable( struct_name: Ident, fields: Vec<Field>, ) -> syn::Result<proc_macro2::TokenStream> { let struct_types = [ // The first two are to be used as return types we do not need to implement ToEncryptable // on it ("Decrypted", StructType::Decrypted), ("DecryptedUpdate", StructType::DecryptedUpdate), ("FromRequestEncryptable", StructType::FromRequest), ("Encrypted", StructType::Encrypted), ("UpdateEncryptable", StructType::Updated), ]; let inner_types = get_field_and_inner_types(&fields); let inner_type = inner_types.first().ok_or_else(|| { syn::Error::new( proc_macro2::Span::call_site(), "Please use the macro with attribute #[encrypt] on the fields you want to encrypt", ) })?; let provided_ty = get_encryption_ty_meta(&inner_type.0) .map(|ty| ty.value.clone()) .unwrap_or(inner_type.1.clone()); let structs = struct_types.iter().map(|(prefix, struct_type)| { let name = format_ident!("{}{}", prefix, struct_name); let temp_fields = struct_type.generate_struct_fields(&inner_types); quote! { pub struct #name { #(#temp_fields,)* } } }); // These implementations shouldn't be implemented Decrypted and DecryptedUpdate temp structs // So skip the first two entries in the list let impls = struct_types .iter() .skip(2) .map(|(prefix, struct_type)| { let name = format_ident!("{}{}", prefix, struct_name); let impl_block = if *struct_type != StructType::DecryptedUpdate || *struct_type != StructType::Decrypted { let (gen1, gen2, gen3) = match struct_type { StructType::FromRequest => { let decrypted_name = format_ident!("Decrypted{}", struct_name); ( quote! { #decrypted_name }, quote! { Secret<#provided_ty> }, quote! { Secret<#provided_ty> }, ) } StructType::Encrypted => { let decrypted_name = format_ident!("Decrypted{}", struct_name); ( quote! { #decrypted_name }, quote! { Secret<#provided_ty> }, quote! { Encryption }, ) } StructType::Updated => { let decrypted_update_name = format_ident!("DecryptedUpdate{}", struct_name); ( quote! { #decrypted_update_name }, quote! { Secret<#provided_ty> }, quote! { Secret<#provided_ty> }, ) } //Unreachable statement _ => (quote! {}, quote! {}, quote! {}), }; struct_type.generate_impls(gen1, gen2, gen3, quote! { #name }, &fields) } else { quote! {} }; Ok(quote! { #impl_block }) }) .collect::<syn::Result<Vec<_>>>()?; Ok(quote! { #(#structs)* #(#impls)* }) } pub fn derive_to_encryption( input: syn::DeriveInput, ) -> Result<proc_macro2::TokenStream, syn::Error> { let struct_name = input.ident; let fields = get_encryptable_fields(get_struct_fields(input.data)?); generate_to_encryptable(struct_name, fields) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_derive/src/macros/schema.rs
crates/router_derive/src/macros/schema.rs
mod helpers; use quote::quote; use crate::macros::{ helpers as macro_helpers, schema::helpers::{HasSchemaParameters, IsSchemaFieldApplicableForValidation}, }; pub fn validate_schema_derive(input: syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> { let name = &input.ident; // Extract struct fields let fields = macro_helpers::get_struct_fields(input.data) .map_err(|error| syn::Error::new(proc_macro2::Span::call_site(), error))?; // Map over each field let validation_checks = fields.iter().filter_map(|field| { let field_name = field.ident.as_ref()?; let field_type = &field.ty; // Check if field type is valid for validation let is_field_valid = match IsSchemaFieldApplicableForValidation::from(field_type) { IsSchemaFieldApplicableForValidation::Invalid => return None, val => val, }; // Parse attribute parameters for 'schema' let schema_params = match field.get_schema_parameters() { Ok(params) => params, Err(_) => return None, }; let min_length = schema_params.min_length; let max_length = schema_params.max_length; // Skip if no length validation is needed if min_length.is_none() && max_length.is_none() { return None; } let min_check = min_length.map(|min_val| { quote! { if value_len < #min_val { return Err(format!("{} must be at least {} characters long. Received {} characters", stringify!(#field_name), #min_val, value_len)); } } }).unwrap_or_else(|| quote! {}); let max_check = max_length.map(|max_val| { quote! { if value_len > #max_val { return Err(format!("{} must be at most {} characters long. Received {} characters", stringify!(#field_name), #max_val, value_len)); } } }).unwrap_or_else(|| quote! {}); // Generate length validation if is_field_valid == IsSchemaFieldApplicableForValidation::ValidOptional { Some(quote! { if let Some(value) = &self.#field_name { let value_len = value.as_str().len(); #min_check #max_check } }) } else { Some(quote! { { let value_len = self.#field_name.as_str().len(); #min_check #max_check } }) } }).collect::<Vec<_>>(); Ok(quote! { impl #name { pub fn validate(&self) -> Result<(), String> { #(#validation_checks)* Ok(()) } } }) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_derive/src/macros/generate_permissions.rs
crates/router_derive/src/macros/generate_permissions.rs
use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::{ braced, bracketed, parse::{Parse, ParseBuffer, ParseStream}, parse_macro_input, punctuated::Punctuated, token::Comma, Ident, Token, }; struct ResourceInput { resource_name: Ident, scopes: Punctuated<Ident, Token![,]>, entities: Punctuated<Ident, Token![,]>, } struct Input { permissions: Punctuated<ResourceInput, Token![,]>, } impl Parse for Input { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { let (_permission_label, permissions) = parse_label_with_punctuated_data(input)?; Ok(Self { permissions }) } } impl Parse for ResourceInput { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { let resource_name: Ident = input.parse()?; input.parse::<Token![:]>()?; // Expect ':' let content; braced!(content in input); let (_scopes_label, scopes) = parse_label_with_punctuated_data(&content)?; content.parse::<Comma>()?; let (_entities_label, entities) = parse_label_with_punctuated_data(&content)?; Ok(Self { resource_name, scopes, entities, }) } } fn parse_label_with_punctuated_data<T: Parse>( input: &ParseBuffer<'_>, ) -> syn::Result<(Ident, Punctuated<T, Token![,]>)> { let label: Ident = input.parse()?; input.parse::<Token![:]>()?; // Expect ':' let content; bracketed!(content in input); // Parse the list inside [] let data = Punctuated::<T, Token![,]>::parse_terminated(&content)?; Ok((label, data)) } pub fn generate_permissions_inner(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as Input); let res = input.permissions.iter(); let mut enum_keys = Vec::new(); let mut scope_impl_per = Vec::new(); let mut entity_impl_per = Vec::new(); let mut resource_impl_per = Vec::new(); let mut entity_impl_res = Vec::new(); for per in res { let resource_name = &per.resource_name; let mut permissions = Vec::new(); for scope in per.scopes.iter() { for entity in per.entities.iter() { let key = format_ident!("{}{}{}", entity, per.resource_name, scope); enum_keys.push(quote! { #key }); scope_impl_per.push(quote! { Permission::#key => PermissionScope::#scope }); entity_impl_per.push(quote! { Permission::#key => EntityType::#entity }); resource_impl_per.push(quote! { Permission::#key => Resource::#resource_name }); permissions.push(quote! { Permission::#key }); } let entities_iter = per.entities.iter(); entity_impl_res .push(quote! { Resource::#resource_name => vec![#(EntityType::#entities_iter),*] }); } } let expanded = quote! { #[derive( Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, serde::Serialize, serde::Deserialize, strum::Display )] pub enum Permission { #(#enum_keys),* } impl Permission { pub fn scope(&self) -> PermissionScope { match self { #(#scope_impl_per),* } } pub fn entity_type(&self) -> EntityType { match self { #(#entity_impl_per),* } } pub fn resource(&self) -> Resource { match self { #(#resource_impl_per),* } } } pub trait ResourceExt { fn entities(&self) -> Vec<EntityType>; } impl ResourceExt for Resource { fn entities(&self) -> Vec<EntityType> { match self { #(#entity_impl_res),* } } } }; expanded.into() }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_derive/src/macros/api_error.rs
crates/router_derive/src/macros/api_error.rs
mod helpers; use std::collections::HashMap; use proc_macro2::TokenStream; use quote::quote; use syn::{ punctuated::Punctuated, token::Comma, Data, DeriveInput, Fields, Ident, ImplGenerics, TypeGenerics, Variant, WhereClause, }; use crate::macros::{ api_error::helpers::{ check_missing_attributes, get_unused_fields, ErrorTypeProperties, ErrorVariantProperties, HasErrorTypeProperties, HasErrorVariantProperties, }, helpers::non_enum_error, }; pub(crate) fn api_error_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); let variants = match &ast.data { Data::Enum(e) => &e.variants, _ => return Err(non_enum_error()), }; let type_properties = ast.get_type_properties()?; let mut variants_properties_map = HashMap::new(); for variant in variants { let variant_properties = variant.get_variant_properties()?; check_missing_attributes(variant, &variant_properties)?; variants_properties_map.insert(variant, variant_properties); } let error_type_fn = implement_error_type(name, &type_properties, &variants_properties_map); let error_code_fn = implement_error_code(name, &variants_properties_map); let error_message_fn = implement_error_message(name, &variants_properties_map); let serialize_impl = implement_serialize( name, (&impl_generics, &ty_generics, where_clause), &type_properties, &variants_properties_map, ); Ok(quote! { #[automatically_derived] impl #impl_generics std::error::Error for #name #ty_generics #where_clause {} #[automatically_derived] impl #impl_generics #name #ty_generics #where_clause { #error_type_fn #error_code_fn #error_message_fn } #serialize_impl }) } fn implement_error_type( enum_name: &Ident, type_properties: &ErrorTypeProperties, variants_properties_map: &HashMap<&Variant, ErrorVariantProperties>, ) -> TokenStream { let mut arms = Vec::new(); for (&variant, properties) in variants_properties_map.iter() { let ident = &variant.ident; let params = match variant.fields { Fields::Unit => quote! {}, Fields::Unnamed(..) => quote! { (..) }, Fields::Named(..) => quote! { {..} }, }; // Safety: Missing attributes are already checked before this function is called. #[allow(clippy::unwrap_used)] let error_type = properties.error_type.as_ref().unwrap(); arms.push(quote! { #enum_name::#ident #params => #error_type }); } // Safety: Missing attributes are already checked before this function is called. #[allow(clippy::unwrap_used)] let error_type_enum = type_properties.error_type_enum.as_ref().unwrap(); quote! { pub fn error_type(&self) -> #error_type_enum { match self { #(#arms),* } } } } fn implement_error_code( enum_name: &Ident, variants_properties_map: &HashMap<&Variant, ErrorVariantProperties>, ) -> TokenStream { let mut arms = Vec::new(); for (&variant, properties) in variants_properties_map.iter() { let ident = &variant.ident; let params = match variant.fields { Fields::Unit => quote! {}, Fields::Unnamed(..) => quote! { (..) }, Fields::Named(..) => quote! { {..} }, }; // Safety: Missing attributes are already checked before this function is called. #[allow(clippy::unwrap_used)] let error_code = properties.code.as_ref().unwrap(); arms.push(quote! { #enum_name::#ident #params => #error_code.to_string() }); } quote! { pub fn error_code(&self) -> String { match self { #(#arms),* } } } } fn implement_error_message( enum_name: &Ident, variants_properties_map: &HashMap<&Variant, ErrorVariantProperties>, ) -> TokenStream { let mut arms = Vec::new(); for (&variant, properties) in variants_properties_map.iter() { let ident = &variant.ident; let params = match variant.fields { Fields::Unit => quote! {}, Fields::Unnamed(..) => quote! { (..) }, Fields::Named(ref fields) => { let fields = fields .named .iter() .map(|f| { // Safety: Named fields are guaranteed to have an identifier. #[allow(clippy::unwrap_used)] f.ident.as_ref().unwrap() }) .collect::<Punctuated<&Ident, Comma>>(); quote! { {#fields} } } }; // Safety: Missing attributes are already checked before this function is called. #[allow(clippy::unwrap_used)] let error_message = properties.message.as_ref().unwrap(); arms.push(quote! { #enum_name::#ident #params => format!(#error_message) }); } quote! { // Some fields of enum variants may not be used in the message #[allow(unused_variables, unused_assignments)] pub fn error_message(&self) -> String { match self { #(#arms),* } } } } fn implement_serialize( enum_name: &Ident, generics: (&ImplGenerics<'_>, &TypeGenerics<'_>, Option<&WhereClause>), type_properties: &ErrorTypeProperties, variants_properties_map: &HashMap<&Variant, ErrorVariantProperties>, ) -> TokenStream { let (impl_generics, ty_generics, where_clause) = generics; let mut arms = Vec::new(); for (&variant, properties) in variants_properties_map.iter() { let ident = &variant.ident; let params = match variant.fields { Fields::Unit => quote! {}, Fields::Unnamed(..) => quote! { (..) }, Fields::Named(ref fields) => { let fields = fields .named .iter() .map(|f| { // Safety: Named fields are guaranteed to have an identifier. #[allow(clippy::unwrap_used)] f.ident.as_ref().unwrap() }) .collect::<Punctuated<&Ident, Comma>>(); quote! { {#fields} } } }; // Safety: Missing attributes are already checked before this function is called. #[allow(clippy::unwrap_used)] let error_message = properties.message.as_ref().unwrap(); let msg_unused_fields = get_unused_fields(&variant.fields, &error_message.value(), &properties.ignore); // Safety: Missing attributes are already checked before this function is called. #[allow(clippy::unwrap_used)] let error_type_enum = type_properties.error_type_enum.as_ref().unwrap(); let response_definition = if msg_unused_fields.is_empty() { quote! { #[derive(Clone, Debug, serde::Serialize)] struct ErrorResponse { #[serde(rename = "type")] error_type: #error_type_enum, code: String, message: String, } } } else { let mut extra_fields = Vec::new(); for field in &msg_unused_fields { let vis = &field.vis; // Safety: `msq_unused_fields` is expected to contain named fields only. #[allow(clippy::unwrap_used)] let ident = &field.ident.as_ref().unwrap(); let ty = &field.ty; extra_fields.push(quote! { #vis #ident: #ty }); } quote! { #[derive(Clone, Debug, serde::Serialize)] struct ErrorResponse #ty_generics #where_clause { #[serde(rename = "type")] error_type: #error_type_enum, code: String, message: String, #(#extra_fields),* } } }; // Safety: Missing attributes are already checked before this function is called. #[allow(clippy::unwrap_used)] let error_type = properties.error_type.as_ref().unwrap(); // Safety: Missing attributes are already checked before this function is called. #[allow(clippy::unwrap_used)] let code = properties.code.as_ref().unwrap(); // Safety: Missing attributes are already checked before this function is called. #[allow(clippy::unwrap_used)] let message = properties.message.as_ref().unwrap(); let extra_fields = msg_unused_fields .iter() .map(|field| { // Safety: `extra_fields` is expected to contain named fields only. #[allow(clippy::unwrap_used)] let field_name = field.ident.as_ref().unwrap(); quote! { #field_name: #field_name.to_owned() } }) .collect::<Vec<TokenStream>>(); arms.push(quote! { #enum_name::#ident #params => { #response_definition let response = ErrorResponse { error_type: #error_type, code: #code.to_string(), message: format!(#message), #(#extra_fields),* }; response.serialize(serializer) } }); } quote! { #[automatically_derived] impl #impl_generics serde::Serialize for #enum_name #ty_generics #where_clause { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { match self { #(#arms),* } } } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_derive/src/macros/diesel.rs
crates/router_derive/src/macros/diesel.rs
use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote, ToTokens}; use syn::{parse::Parse, Data, DeriveInput, ItemEnum}; use crate::macros::helpers; pub(crate) fn diesel_enum_text_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); match &ast.data { Data::Enum(_) => (), _ => return Err(helpers::non_enum_error()), }; Ok(quote! { #[automatically_derived] impl #impl_generics ::diesel::serialize::ToSql<::diesel::sql_types::Text, ::diesel::pg::Pg> for #name #ty_generics #where_clause { fn to_sql<'b>(&'b self, out: &mut ::diesel::serialize::Output<'b, '_, ::diesel::pg::Pg>) -> ::diesel::serialize::Result { use ::std::io::Write; out.write_all(self.to_string().as_bytes())?; Ok(::diesel::serialize::IsNull::No) } } #[automatically_derived] impl #impl_generics ::diesel::deserialize::FromSql<::diesel::sql_types::Text, ::diesel::pg::Pg> for #name #ty_generics #where_clause { fn from_sql(value: ::diesel::pg::PgValue) -> diesel::deserialize::Result<Self> { use ::core::str::FromStr; Self::from_str(::core::str::from_utf8(value.as_bytes())?) .map_err(|_| "Unrecognized enum variant".into()) } } }) } pub(crate) fn diesel_enum_db_enum_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); match &ast.data { Data::Enum(_) => (), _ => return Err(helpers::non_enum_error()), }; let struct_name = format_ident!("Db{name}"); let type_name = format!("{name}"); Ok(quote! { #[derive(::core::clone::Clone, ::core::marker::Copy, ::core::fmt::Debug, ::diesel::QueryId, ::diesel::SqlType)] #[diesel(postgres_type(name = #type_name))] pub struct #struct_name; #[automatically_derived] impl #impl_generics ::diesel::serialize::ToSql<#struct_name, ::diesel::pg::Pg> for #name #ty_generics #where_clause { fn to_sql<'b>(&'b self, out: &mut ::diesel::serialize::Output<'b, '_, ::diesel::pg::Pg>) -> ::diesel::serialize::Result { use ::std::io::Write; out.write_all(self.to_string().as_bytes())?; Ok(::diesel::serialize::IsNull::No) } } #[automatically_derived] impl #impl_generics ::diesel::deserialize::FromSql<#struct_name, ::diesel::pg::Pg> for #name #ty_generics #where_clause { fn from_sql(value: ::diesel::pg::PgValue) -> diesel::deserialize::Result<Self> { use ::core::str::FromStr; Self::from_str(::core::str::from_utf8(value.as_bytes())?) .map_err(|_| "Unrecognized enum variant".into()) } } }) } mod diesel_keyword { use syn::custom_keyword; custom_keyword!(storage_type); custom_keyword!(db_enum); custom_keyword!(text); } #[derive(Debug, strum::EnumString, strum::EnumIter, strum::Display)] #[strum(serialize_all = "snake_case")] pub enum StorageType { /// Store the Enum as Text value in the database Text, /// Store the Enum as Enum in the database. This requires a corresponding enum to be created /// in the database with the same name DbEnum, } #[derive(Debug)] pub enum DieselEnumMeta { StorageTypeEnum { keyword: diesel_keyword::storage_type, value: StorageType, }, } impl Parse for StorageType { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let text = input.parse::<syn::LitStr>()?; let value = text.value(); value.as_str().parse().map_err(|_| { syn::Error::new_spanned( &text, format!( "Unexpected value for storage_type: `{value}`. Possible values are `{}`", helpers::get_possible_values_for_enum::<Self>() ), ) }) } } impl DieselEnumMeta { pub fn get_storage_type(&self) -> &StorageType { match self { Self::StorageTypeEnum { value, .. } => value, } } } impl Parse for DieselEnumMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(diesel_keyword::storage_type) { let keyword = input.parse()?; input.parse::<syn::Token![=]>()?; let value = input.parse()?; Ok(Self::StorageTypeEnum { keyword, value }) } else { Err(lookahead.error()) } } } impl ToTokens for DieselEnumMeta { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::StorageTypeEnum { keyword, .. } => keyword.to_tokens(tokens), } } } trait DieselDeriveInputExt { /// Get all the error metadata associated with an enum. fn get_metadata(&self) -> syn::Result<Vec<DieselEnumMeta>>; } impl DieselDeriveInputExt for DeriveInput { fn get_metadata(&self) -> syn::Result<Vec<DieselEnumMeta>> { helpers::get_metadata_inner("storage_type", &self.attrs) } } pub(crate) fn diesel_enum_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let storage_type = ast.get_metadata()?; match storage_type .first() .ok_or(syn::Error::new( Span::call_site(), "Storage type must be specified", ))? .get_storage_type() { StorageType::Text => diesel_enum_text_derive_inner(ast), StorageType::DbEnum => diesel_enum_db_enum_derive_inner(ast), } } /// Based on the storage type, derive appropriate diesel traits /// This will add the appropriate #[diesel(sql_type)] /// Since the `FromSql` and `ToSql` have to be derived for all the enums, this will add the /// `DieselEnum` derive trait. pub(crate) fn diesel_enum_attribute_macro( diesel_enum_meta: DieselEnumMeta, item: &ItemEnum, ) -> syn::Result<TokenStream> { let diesel_derives = quote!(#[derive(diesel::AsExpression, diesel::FromSqlRow, router_derive::DieselEnum) ]); match diesel_enum_meta { DieselEnumMeta::StorageTypeEnum { value: storage_type, .. } => match storage_type { StorageType::Text => Ok(quote! { #diesel_derives #[diesel(sql_type = ::diesel::sql_types::Text)] #[storage_type(storage_type = "text")] #item }), StorageType::DbEnum => { let name = &item.ident; let type_name = format_ident!("Db{name}"); Ok(quote! { #diesel_derives #[diesel(sql_type = #type_name)] #[storage_type(storage_type= "db_enum")] #item }) } }, } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_derive/src/macros/operation.rs
crates/router_derive/src/macros/operation.rs
use std::str::FromStr; use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens}; use strum::IntoEnumIterator; use syn::{self, parse::Parse, DeriveInput}; use crate::macros::helpers; #[derive(Debug, Clone, Copy, strum::EnumString, strum::EnumIter, strum::Display)] #[strum(serialize_all = "snake_case")] pub enum Derives { Sync, Cancel, Reject, Capture, ApproveData, Authorize, AuthorizeData, SyncData, CancelData, CancelPostCapture, CancelPostCaptureData, CaptureData, CompleteAuthorizeData, RejectData, SetupMandateData, Start, Verify, Session, SessionData, IncrementalAuthorization, IncrementalAuthorizationData, ExtendAuthorization, ExtendAuthorizationData, SdkSessionUpdate, SdkSessionUpdateData, PostSessionTokens, PostSessionTokensData, UpdateMetadata, UpdateMetadataData, } impl Derives { fn to_operation( self, fns: impl Iterator<Item = TokenStream> + Clone, struct_name: &syn::Ident, ) -> TokenStream { let req_type = Conversion::get_req_type(self); quote! { #[automatically_derived] impl<F:Send+Clone+Sync> Operation<F,#req_type> for #struct_name { type Data = PaymentData<F>; #(#fns)* } } } fn to_ref_operation( self, ref_fns: impl Iterator<Item = TokenStream> + Clone, struct_name: &syn::Ident, ) -> TokenStream { let req_type = Conversion::get_req_type(self); quote! { #[automatically_derived] impl<F:Send+Clone+Sync> Operation<F,#req_type> for &#struct_name { type Data = PaymentData<F>; #(#ref_fns)* } } } } #[derive(Debug, Clone, strum::EnumString, strum::EnumIter, strum::Display)] #[strum(serialize_all = "snake_case")] pub enum Conversion { ValidateRequest, GetTracker, Domain, UpdateTracker, PostUpdateTracker, All, Invalid(String), } impl Conversion { fn get_req_type(ident: Derives) -> syn::Ident { match ident { Derives::Authorize => syn::Ident::new("PaymentsRequest", Span::call_site()), Derives::AuthorizeData => syn::Ident::new("PaymentsAuthorizeData", Span::call_site()), Derives::Sync => syn::Ident::new("PaymentsRetrieveRequest", Span::call_site()), Derives::SyncData => syn::Ident::new("PaymentsSyncData", Span::call_site()), Derives::Cancel => syn::Ident::new("PaymentsCancelRequest", Span::call_site()), Derives::CancelData => syn::Ident::new("PaymentsCancelData", Span::call_site()), Derives::ApproveData => syn::Ident::new("PaymentsApproveData", Span::call_site()), Derives::Reject => syn::Ident::new("PaymentsRejectRequest", Span::call_site()), Derives::RejectData => syn::Ident::new("PaymentsRejectData", Span::call_site()), Derives::Capture => syn::Ident::new("PaymentsCaptureRequest", Span::call_site()), Derives::CaptureData => syn::Ident::new("PaymentsCaptureData", Span::call_site()), Derives::CompleteAuthorizeData => { syn::Ident::new("CompleteAuthorizeData", Span::call_site()) } Derives::Start => syn::Ident::new("PaymentsStartRequest", Span::call_site()), Derives::Verify => syn::Ident::new("VerifyRequest", Span::call_site()), Derives::SetupMandateData => { syn::Ident::new("SetupMandateRequestData", Span::call_site()) } Derives::Session => syn::Ident::new("PaymentsSessionRequest", Span::call_site()), Derives::SessionData => syn::Ident::new("PaymentsSessionData", Span::call_site()), Derives::IncrementalAuthorization => { syn::Ident::new("PaymentsIncrementalAuthorizationRequest", Span::call_site()) } Derives::IncrementalAuthorizationData => { syn::Ident::new("PaymentsIncrementalAuthorizationData", Span::call_site()) } Derives::SdkSessionUpdate => { syn::Ident::new("PaymentsDynamicTaxCalculationRequest", Span::call_site()) } Derives::SdkSessionUpdateData => { syn::Ident::new("SdkPaymentsSessionUpdateData", Span::call_site()) } Derives::PostSessionTokens => { syn::Ident::new("PaymentsPostSessionTokensRequest", Span::call_site()) } Derives::PostSessionTokensData => { syn::Ident::new("PaymentsPostSessionTokensData", Span::call_site()) } Derives::UpdateMetadata => { syn::Ident::new("PaymentsUpdateMetadataRequest", Span::call_site()) } Derives::UpdateMetadataData => { syn::Ident::new("PaymentsUpdateMetadataData", Span::call_site()) } Derives::CancelPostCapture => { syn::Ident::new("PaymentsCancelPostCaptureRequest", Span::call_site()) } Derives::CancelPostCaptureData => { syn::Ident::new("PaymentsCancelPostCaptureData", Span::call_site()) } Derives::ExtendAuthorization => { syn::Ident::new("PaymentsExtendAuthorizationRequest", Span::call_site()) } Derives::ExtendAuthorizationData => { syn::Ident::new("PaymentsExtendAuthorizationData", Span::call_site()) } } } fn to_function(&self, ident: Derives) -> TokenStream { let req_type = Self::get_req_type(ident); match self { Self::ValidateRequest => quote! { fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F,#req_type, Self::Data> + Send + Sync)> { Ok(self) } }, Self::GetTracker => quote! { fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F, Self::Data, #req_type> + Send + Sync)> { Ok(self) } }, Self::Domain => quote! { fn to_domain(&self) -> RouterResult<&dyn Domain<F,#req_type, Self::Data>> { Ok(self) } }, Self::UpdateTracker => quote! { fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, #req_type> + Send + Sync)> { Ok(self) } }, Self::PostUpdateTracker => quote! { fn to_post_update_tracker(&self) -> RouterResult<&(dyn PostUpdateTracker<F, Self::Data, #req_type> + Send + Sync)> { Ok(self) } }, Self::Invalid(s) => { helpers::syn_error(Span::call_site(), &format!("Invalid identifier {s}")) .to_compile_error() } Self::All => { let validate_request = Self::ValidateRequest.to_function(ident); let get_tracker = Self::GetTracker.to_function(ident); let domain = Self::Domain.to_function(ident); let update_tracker = Self::UpdateTracker.to_function(ident); quote! { #validate_request #get_tracker #domain #update_tracker } } } } fn to_ref_function(&self, ident: Derives) -> TokenStream { let req_type = Self::get_req_type(ident); match self { Self::ValidateRequest => quote! { fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F, #req_type, Self::Data> + Send + Sync)> { Ok(*self) } }, Self::GetTracker => quote! { fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F, Self::Data,#req_type> + Send + Sync)> { Ok(*self) } }, Self::Domain => quote! { fn to_domain(&self) -> RouterResult<&(dyn Domain<F,#req_type, Self::Data>)> { Ok(*self) } }, Self::UpdateTracker => quote! { fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F, Self::Data,#req_type> + Send + Sync)> { Ok(*self) } }, Self::PostUpdateTracker => quote! { fn to_post_update_tracker(&self) -> RouterResult<&(dyn PostUpdateTracker<F, Self::Data, #req_type> + Send + Sync)> { Ok(*self) } }, Self::Invalid(s) => { helpers::syn_error(Span::call_site(), &format!("Invalid identifier {s}")) .to_compile_error() } Self::All => { let validate_request = Self::ValidateRequest.to_ref_function(ident); let get_tracker = Self::GetTracker.to_ref_function(ident); let domain = Self::Domain.to_ref_function(ident); let update_tracker = Self::UpdateTracker.to_ref_function(ident); quote! { #validate_request #get_tracker #domain #update_tracker } } } } } mod operations_keyword { use syn::custom_keyword; custom_keyword!(operations); custom_keyword!(flow); } #[derive(Debug)] pub enum OperationsEnumMeta { Operations { keyword: operations_keyword::operations, value: Vec<Conversion>, }, Flow { keyword: operations_keyword::flow, value: Vec<Derives>, }, } #[derive(Clone)] pub struct OperationProperties { operations: Vec<Conversion>, flows: Vec<Derives>, } fn get_operation_properties( operation_enums: Vec<OperationsEnumMeta>, ) -> syn::Result<OperationProperties> { let mut operations = vec![]; let mut flows = vec![]; for operation in operation_enums { match operation { OperationsEnumMeta::Operations { value, .. } => { operations = value; } OperationsEnumMeta::Flow { value, .. } => { flows = value; } } } if operations.is_empty() { Err(syn::Error::new( Span::call_site(), "atleast one operation must be specitied", ))?; } if flows.is_empty() { Err(syn::Error::new( Span::call_site(), "atleast one flow must be specitied", ))?; } Ok(OperationProperties { operations, flows }) } impl Parse for Derives { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let text = input.parse::<syn::LitStr>()?; let value = text.value(); value.as_str().parse().map_err(|_| { syn::Error::new_spanned( &text, format!( "Unexpected value for flow: `{value}`. Possible values are `{}`", helpers::get_possible_values_for_enum::<Self>() ), ) }) } } impl Parse for Conversion { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let text = input.parse::<syn::LitStr>()?; let value = text.value(); value.as_str().parse().map_err(|_| { syn::Error::new_spanned( &text, format!( "Unexpected value for operation: `{value}`. Possible values are `{}`", helpers::get_possible_values_for_enum::<Self>() ), ) }) } } fn parse_list_string<T>(list_string: String, keyword: &str) -> syn::Result<Vec<T>> where T: FromStr + IntoEnumIterator + ToString, { list_string .split(',') .map(str::trim) .map(T::from_str) .map(|result| { result.map_err(|_| { syn::Error::new( Span::call_site(), format!( "Unexpected {keyword}, possible values are {}", helpers::get_possible_values_for_enum::<T>() ), ) }) }) .collect() } fn get_conversions(input: syn::parse::ParseStream<'_>) -> syn::Result<Vec<Conversion>> { let lit_str_list = input.parse::<syn::LitStr>()?; parse_list_string(lit_str_list.value(), "operation") } fn get_derives(input: syn::parse::ParseStream<'_>) -> syn::Result<Vec<Derives>> { let lit_str_list = input.parse::<syn::LitStr>()?; parse_list_string(lit_str_list.value(), "flow") } impl Parse for OperationsEnumMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(operations_keyword::operations) { let keyword = input.parse()?; input.parse::<syn::Token![=]>()?; let value = get_conversions(input)?; Ok(Self::Operations { keyword, value }) } else if lookahead.peek(operations_keyword::flow) { let keyword = input.parse()?; input.parse::<syn::Token![=]>()?; let value = get_derives(input)?; Ok(Self::Flow { keyword, value }) } else { Err(lookahead.error()) } } } trait OperationsDeriveInputExt { /// Get all the error metadata associated with an enum. fn get_metadata(&self) -> syn::Result<Vec<OperationsEnumMeta>>; } impl OperationsDeriveInputExt for DeriveInput { fn get_metadata(&self) -> syn::Result<Vec<OperationsEnumMeta>> { helpers::get_metadata_inner("operation", &self.attrs) } } impl ToTokens for OperationsEnumMeta { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::Operations { keyword, .. } => keyword.to_tokens(tokens), Self::Flow { keyword, .. } => keyword.to_tokens(tokens), } } } pub fn operation_derive_inner(input: DeriveInput) -> syn::Result<proc_macro::TokenStream> { let struct_name = &input.ident; let operations_meta = input.get_metadata()?; let operation_properties = get_operation_properties(operations_meta)?; let current_crate = syn::Ident::new("crate", Span::call_site()); let trait_derive = operation_properties .clone() .flows .into_iter() .map(|derive| { let fns = operation_properties .operations .iter() .map(|conversion| conversion.to_function(derive)); derive.to_operation(fns, struct_name) }) .collect::<Vec<_>>(); let ref_trait_derive = operation_properties .flows .into_iter() .map(|derive| { let fns = operation_properties .operations .iter() .map(|conversion| conversion.to_ref_function(derive)); derive.to_ref_operation(fns, struct_name) }) .collect::<Vec<_>>(); let trait_derive = quote! { #(#ref_trait_derive)* #(#trait_derive)* }; let output = quote! { const _: () = { use #current_crate::core::errors::RouterResult; use #current_crate::core::payments::{PaymentData,operations::{ ValidateRequest, PostUpdateTracker, GetTracker, UpdateTracker, }}; use #current_crate::types::{ SetupMandateRequestData, PaymentsSyncData, PaymentsCaptureData, PaymentsCancelData, PaymentsApproveData, PaymentsRejectData, PaymentsAuthorizeData, PaymentsSessionData, CompleteAuthorizeData, PaymentsIncrementalAuthorizationData, SdkPaymentsSessionUpdateData, PaymentsPostSessionTokensData, PaymentsUpdateMetadataData, PaymentsCancelPostCaptureData, PaymentsExtendAuthorizationData, api::{ PaymentsCaptureRequest, PaymentsCancelRequest, PaymentsApproveRequest, PaymentsRejectRequest, PaymentsRetrieveRequest, PaymentsRequest, PaymentsStartRequest, PaymentsSessionRequest, VerifyRequest, PaymentsDynamicTaxCalculationRequest, PaymentsIncrementalAuthorizationRequest, PaymentsPostSessionTokensRequest, PaymentsUpdateMetadataRequest, PaymentsCancelPostCaptureRequest, PaymentsExtendAuthorizationRequest, } }; #trait_derive }; }; Ok(proc_macro::TokenStream::from(output)) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_derive/src/macros/schema/helpers.rs
crates/router_derive/src/macros/schema/helpers.rs
use proc_macro2::TokenStream; use quote::ToTokens; use syn::{parse::Parse, Field, LitInt, LitStr, Token, TypePath}; use crate::macros::helpers::{get_metadata_inner, occurrence_error}; mod keyword { use syn::custom_keyword; // Schema metadata custom_keyword!(value_type); custom_keyword!(min_length); custom_keyword!(max_length); custom_keyword!(example); } pub enum SchemaParameterVariant { ValueType { keyword: keyword::value_type, value: TypePath, }, MinLength { keyword: keyword::min_length, value: LitInt, }, MaxLength { keyword: keyword::max_length, value: LitInt, }, Example { keyword: keyword::example, value: LitStr, }, } impl Parse for SchemaParameterVariant { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(keyword::value_type) { let keyword = input.parse()?; input.parse::<Token![=]>()?; let value = input.parse()?; Ok(Self::ValueType { keyword, value }) } else if lookahead.peek(keyword::min_length) { let keyword = input.parse()?; input.parse::<Token![=]>()?; let value = input.parse()?; Ok(Self::MinLength { keyword, value }) } else if lookahead.peek(keyword::max_length) { let keyword = input.parse()?; input.parse::<Token![=]>()?; let value = input.parse()?; Ok(Self::MaxLength { keyword, value }) } else if lookahead.peek(keyword::example) { let keyword = input.parse()?; input.parse::<Token![=]>()?; let value = input.parse()?; Ok(Self::Example { keyword, value }) } else { Err(lookahead.error()) } } } impl ToTokens for SchemaParameterVariant { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::ValueType { keyword, .. } => keyword.to_tokens(tokens), Self::MinLength { keyword, .. } => keyword.to_tokens(tokens), Self::MaxLength { keyword, .. } => keyword.to_tokens(tokens), Self::Example { keyword, .. } => keyword.to_tokens(tokens), } } } pub trait FieldExt { /// Get all the schema metadata associated with a field. fn get_schema_metadata(&self) -> syn::Result<Vec<SchemaParameterVariant>>; } impl FieldExt for Field { fn get_schema_metadata(&self) -> syn::Result<Vec<SchemaParameterVariant>> { get_metadata_inner("schema", &self.attrs) } } #[derive(Clone, Debug, Default)] pub struct SchemaParameters { pub value_type: Option<TypePath>, pub min_length: Option<usize>, pub max_length: Option<usize>, pub example: Option<String>, } pub trait HasSchemaParameters { fn get_schema_parameters(&self) -> syn::Result<SchemaParameters>; } impl HasSchemaParameters for Field { fn get_schema_parameters(&self) -> syn::Result<SchemaParameters> { let mut output = SchemaParameters::default(); let mut value_type_keyword = None; let mut min_length_keyword = None; let mut max_length_keyword = None; let mut example_keyword = None; for meta in self.get_schema_metadata()? { match meta { SchemaParameterVariant::ValueType { keyword, value } => { if let Some(first_keyword) = value_type_keyword { return Err(occurrence_error(first_keyword, keyword, "value_type")); } value_type_keyword = Some(keyword); output.value_type = Some(value); } SchemaParameterVariant::MinLength { keyword, value } => { if let Some(first_keyword) = min_length_keyword { return Err(occurrence_error(first_keyword, keyword, "min_length")); } min_length_keyword = Some(keyword); let min_length = value.base10_parse::<usize>()?; output.min_length = Some(min_length); } SchemaParameterVariant::MaxLength { keyword, value } => { if let Some(first_keyword) = max_length_keyword { return Err(occurrence_error(first_keyword, keyword, "max_length")); } max_length_keyword = Some(keyword); let max_length = value.base10_parse::<usize>()?; output.max_length = Some(max_length); } SchemaParameterVariant::Example { keyword, value } => { if let Some(first_keyword) = example_keyword { return Err(occurrence_error(first_keyword, keyword, "example")); } example_keyword = Some(keyword); output.example = Some(value.value()); } } } Ok(output) } } /// Check if the field is applicable for running validations #[derive(PartialEq)] pub enum IsSchemaFieldApplicableForValidation { /// Not applicable for running validation checks Invalid, /// Applicable for running validation checks Valid, /// Applicable for validation but field is optional - this is needed for generating validation code only if the value of the field is present ValidOptional, } /// From implementation for checking if the field type is applicable for running schema validations impl From<&syn::Type> for IsSchemaFieldApplicableForValidation { fn from(ty: &syn::Type) -> Self { if let syn::Type::Path(type_path) = ty { if let Some(segment) = type_path.path.segments.last() { let ident = &segment.ident; if ident == "String" || ident == "Url" { return Self::Valid; } if ident == "Option" { if let syn::PathArguments::AngleBracketed(generic_args) = &segment.arguments { if let Some(syn::GenericArgument::Type(syn::Type::Path(inner_path))) = generic_args.args.first() { if let Some(inner_segment) = inner_path.path.segments.last() { if inner_segment.ident == "String" || inner_segment.ident == "Url" { return Self::ValidOptional; } } } } } } } Self::Invalid } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_derive/src/macros/api_error/helpers.rs
crates/router_derive/src/macros/api_error/helpers.rs
use proc_macro2::TokenStream; use quote::ToTokens; use syn::{ parse::Parse, spanned::Spanned, DeriveInput, Field, Fields, LitStr, Token, TypePath, Variant, }; use crate::macros::helpers::{get_metadata_inner, occurrence_error}; mod keyword { use syn::custom_keyword; // Enum metadata custom_keyword!(error_type_enum); // Variant metadata custom_keyword!(error_type); custom_keyword!(code); custom_keyword!(message); custom_keyword!(ignore); } enum EnumMeta { ErrorTypeEnum { keyword: keyword::error_type_enum, value: TypePath, }, } impl Parse for EnumMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(keyword::error_type_enum) { let keyword = input.parse()?; input.parse::<Token![=]>()?; let value = input.parse()?; Ok(Self::ErrorTypeEnum { keyword, value }) } else { Err(lookahead.error()) } } } impl ToTokens for EnumMeta { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::ErrorTypeEnum { keyword, .. } => keyword.to_tokens(tokens), } } } trait DeriveInputExt { /// Get all the error metadata associated with an enum. fn get_metadata(&self) -> syn::Result<Vec<EnumMeta>>; } impl DeriveInputExt for DeriveInput { fn get_metadata(&self) -> syn::Result<Vec<EnumMeta>> { get_metadata_inner("error", &self.attrs) } } pub(super) trait HasErrorTypeProperties { fn get_type_properties(&self) -> syn::Result<ErrorTypeProperties>; } #[derive(Clone, Debug, Default)] pub(super) struct ErrorTypeProperties { pub error_type_enum: Option<TypePath>, } impl HasErrorTypeProperties for DeriveInput { fn get_type_properties(&self) -> syn::Result<ErrorTypeProperties> { let mut output = ErrorTypeProperties::default(); let mut error_type_enum_keyword = None; for meta in self.get_metadata()? { match meta { EnumMeta::ErrorTypeEnum { keyword, value } => { if let Some(first_keyword) = error_type_enum_keyword { return Err(occurrence_error(first_keyword, keyword, "error_type_enum")); } error_type_enum_keyword = Some(keyword); output.error_type_enum = Some(value); } } } if output.error_type_enum.is_none() { return Err(syn::Error::new( self.span(), "error(error_type_enum) attribute not found", )); } Ok(output) } } enum VariantMeta { ErrorType { keyword: keyword::error_type, value: TypePath, }, Code { keyword: keyword::code, value: LitStr, }, Message { keyword: keyword::message, value: LitStr, }, Ignore { keyword: keyword::ignore, value: LitStr, }, } impl Parse for VariantMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(keyword::error_type) { let keyword = input.parse()?; let _: Token![=] = input.parse()?; let value = input.parse()?; Ok(Self::ErrorType { keyword, value }) } else if lookahead.peek(keyword::code) { let keyword = input.parse()?; let _: Token![=] = input.parse()?; let value = input.parse()?; Ok(Self::Code { keyword, value }) } else if lookahead.peek(keyword::message) { let keyword = input.parse()?; let _: Token![=] = input.parse()?; let value = input.parse()?; Ok(Self::Message { keyword, value }) } else if lookahead.peek(keyword::ignore) { let keyword = input.parse()?; let _: Token![=] = input.parse()?; let value = input.parse()?; Ok(Self::Ignore { keyword, value }) } else { Err(lookahead.error()) } } } impl ToTokens for VariantMeta { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::ErrorType { keyword, .. } => keyword.to_tokens(tokens), Self::Code { keyword, .. } => keyword.to_tokens(tokens), Self::Message { keyword, .. } => keyword.to_tokens(tokens), Self::Ignore { keyword, .. } => keyword.to_tokens(tokens), } } } trait VariantExt { /// Get all the error metadata associated with an enum variant. fn get_metadata(&self) -> syn::Result<Vec<VariantMeta>>; } impl VariantExt for Variant { fn get_metadata(&self) -> syn::Result<Vec<VariantMeta>> { get_metadata_inner("error", &self.attrs) } } pub(super) trait HasErrorVariantProperties { fn get_variant_properties(&self) -> syn::Result<ErrorVariantProperties>; } #[derive(Clone, Debug, Default, Eq, PartialEq)] pub(super) struct ErrorVariantProperties { pub error_type: Option<TypePath>, pub code: Option<LitStr>, pub message: Option<LitStr>, pub ignore: std::collections::HashSet<String>, } impl HasErrorVariantProperties for Variant { fn get_variant_properties(&self) -> syn::Result<ErrorVariantProperties> { let mut output = ErrorVariantProperties::default(); let mut error_type_keyword = None; let mut code_keyword = None; let mut message_keyword = None; let mut ignore_keyword = None; for meta in self.get_metadata()? { match meta { VariantMeta::ErrorType { keyword, value } => { if let Some(first_keyword) = error_type_keyword { return Err(occurrence_error(first_keyword, keyword, "error_type")); } error_type_keyword = Some(keyword); output.error_type = Some(value); } VariantMeta::Code { keyword, value } => { if let Some(first_keyword) = code_keyword { return Err(occurrence_error(first_keyword, keyword, "code")); } code_keyword = Some(keyword); output.code = Some(value); } VariantMeta::Message { keyword, value } => { if let Some(first_keyword) = message_keyword { return Err(occurrence_error(first_keyword, keyword, "message")); } message_keyword = Some(keyword); output.message = Some(value); } VariantMeta::Ignore { keyword, value } => { if let Some(first_keyword) = ignore_keyword { return Err(occurrence_error(first_keyword, keyword, "ignore")); } ignore_keyword = Some(keyword); output.ignore = value .value() .replace(' ', "") .split(',') .map(ToString::to_string) .collect(); } } } Ok(output) } } fn missing_attribute_error(variant: &Variant, attr: &str) -> syn::Error { syn::Error::new_spanned(variant, format!("{attr} must be specified")) } pub(super) fn check_missing_attributes( variant: &Variant, variant_properties: &ErrorVariantProperties, ) -> syn::Result<()> { if variant_properties.error_type.is_none() { return Err(missing_attribute_error(variant, "error_type")); } if variant_properties.code.is_none() { return Err(missing_attribute_error(variant, "code")); } if variant_properties.message.is_none() { return Err(missing_attribute_error(variant, "message")); } Ok(()) } /// Get all the fields not used in the error message. pub(super) fn get_unused_fields( fields: &Fields, message: &str, ignore: &std::collections::HashSet<String>, ) -> Vec<Field> { let fields = match fields { Fields::Unit => Vec::new(), Fields::Unnamed(_) => Vec::new(), Fields::Named(fields) => fields.named.iter().cloned().collect(), }; fields .iter() .filter(|&field| { // Safety: Named fields are guaranteed to have an identifier. #[allow(clippy::unwrap_used)] let field_name = format!("{}", field.ident.as_ref().unwrap()); !message.contains(&field_name) && !ignore.contains(&field_name) }) .cloned() .collect() }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/smithy-core/src/lib.rs
crates/smithy-core/src/lib.rs
// // crates/smithy-core/lib.rs pub mod generator; pub mod types; pub use generator::SmithyGenerator; pub use types::*;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/smithy-core/src/types.rs
crates/smithy-core/src/types.rs
// crates/smithy-core/types.rs use std::collections::HashMap; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SmithyModel { pub namespace: String, pub shapes: HashMap<String, SmithyShape>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "type")] pub enum SmithyShape { #[serde(rename = "structure")] Structure { members: HashMap<String, SmithyMember>, #[serde(skip_serializing_if = "Option::is_none")] documentation: Option<String>, #[serde(skip_serializing_if = "Vec::is_empty")] traits: Vec<SmithyTrait>, }, #[serde(rename = "string")] String { #[serde(skip_serializing_if = "Vec::is_empty")] traits: Vec<SmithyTrait>, }, #[serde(rename = "integer")] Integer { #[serde(skip_serializing_if = "Vec::is_empty")] traits: Vec<SmithyTrait>, }, #[serde(rename = "long")] Long { #[serde(skip_serializing_if = "Vec::is_empty")] traits: Vec<SmithyTrait>, }, #[serde(rename = "boolean")] Boolean { #[serde(skip_serializing_if = "Vec::is_empty")] traits: Vec<SmithyTrait>, }, #[serde(rename = "list")] List { member: Box<SmithyMember>, #[serde(skip_serializing_if = "Vec::is_empty")] traits: Vec<SmithyTrait>, }, #[serde(rename = "union")] Union { members: HashMap<String, SmithyMember>, #[serde(skip_serializing_if = "Option::is_none")] documentation: Option<String>, #[serde(skip_serializing_if = "Vec::is_empty")] traits: Vec<SmithyTrait>, }, #[serde(rename = "enum")] Enum { values: HashMap<String, SmithyEnumValue>, #[serde(skip_serializing_if = "Option::is_none")] documentation: Option<String>, #[serde(skip_serializing_if = "Vec::is_empty")] traits: Vec<SmithyTrait>, }, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SmithyMember { pub target: String, #[serde(skip_serializing_if = "Option::is_none")] pub documentation: Option<String>, #[serde(skip_serializing_if = "Vec::is_empty")] pub traits: Vec<SmithyTrait>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SmithyEnumValue { pub name: String, #[serde(skip_serializing_if = "Option::is_none")] pub documentation: Option<String>, pub is_default: bool, #[serde(skip_serializing_if = "Vec::is_empty")] pub traits: Vec<SmithyTrait>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "trait")] pub enum SmithyTrait { #[serde(rename = "smithy.api#pattern")] Pattern { pattern: String }, #[serde(rename = "smithy.api#range")] Range { min: Option<i64>, max: Option<i64> }, #[serde(rename = "smithy.api#required")] Required, #[serde(rename = "smithy.api#documentation")] Documentation { documentation: String }, #[serde(rename = "smithy.api#length")] Length { min: Option<u64>, max: Option<u64> }, #[serde(rename = "smithy.api#httpLabel")] HttpLabel, #[serde(rename = "smithy.api#httpQuery")] HttpQuery { name: String }, #[serde(rename = "smithy.api#mixin")] Mixin, #[serde(rename = "smithy.api#jsonName")] JsonName { name: String }, #[serde(rename = "smithy.api#enumValue")] EnumValue { value: String }, } #[derive(Debug, Clone)] pub struct SmithyField { pub name: String, pub value_type: String, pub constraints: Vec<SmithyConstraint>, pub documentation: Option<String>, pub optional: bool, pub flatten: bool, } #[derive(Debug, Clone)] pub struct SmithyEnumVariant { pub name: String, pub fields: Vec<SmithyField>, pub constraints: Vec<SmithyConstraint>, pub documentation: Option<String>, pub nested_value_type: bool, pub value_type: Option<String>, } #[derive(Debug, Clone)] pub enum SmithyConstraint { Pattern(String), Range(Option<i64>, Option<i64>), Length(Option<u64>, Option<u64>), Required, HttpLabel, HttpQuery(String), JsonName(String), EnumValue(String), } pub trait SmithyModelGenerator { fn generate_smithy_model() -> SmithyModel; } // Helper functions moved from the proc-macro crate to be accessible by it. pub fn resolve_type_and_generate_shapes( value_type: &str, shapes: &mut HashMap<String, SmithyShape>, ) -> Result<(String, HashMap<String, SmithyShape>), syn::Error> { let value_type = value_type.trim(); let value_type_span = proc_macro2::Span::call_site(); let mut generated_shapes = HashMap::new(); let target_type = match value_type { "String" | "str" => "smithy.api#String".to_string(), "i8" | "i16" | "i32" | "u8" | "u16" | "u32" => "smithy.api#Integer".to_string(), "i64" | "u64" | "i128" | "isize" | "usize" => "smithy.api#Long".to_string(), "f32" => "smithy.api#Float".to_string(), "f64" => "smithy.api#Double".to_string(), "bool" => "smithy.api#Boolean".to_string(), "PrimitiveDateTime" | "time::PrimitiveDateTime" => "smithy.api#Timestamp".to_string(), "Amount" | "MinorUnit" => "smithy.api#Long".to_string(), "serde_json::Value" | "Value" | "Object" => "smithy.api#Document".to_string(), "Url" | "url::Url" => "smithy.api#String".to_string(), vt if vt.starts_with("Option<") && vt.ends_with('>') => { let inner_type = extract_generic_inner_type(vt, "Option") .map_err(|e| syn::Error::new(value_type_span, e))?; let (resolved_type, new_shapes) = resolve_type_and_generate_shapes(inner_type, shapes)?; generated_shapes.extend(new_shapes); resolved_type } vt if vt.starts_with("Vec<") && vt.ends_with('>') => { let inner_type = extract_generic_inner_type(vt, "Vec") .map_err(|e| syn::Error::new(value_type_span, e))?; let (inner_smithy_type, new_shapes) = resolve_type_and_generate_shapes(inner_type, shapes)?; generated_shapes.extend(new_shapes); let list_shape_name = format!( "{}List", inner_smithy_type .split("::") .last() .unwrap_or(&inner_smithy_type) .split('#') .next_back() .unwrap_or(&inner_smithy_type) ); if !shapes.contains_key(&list_shape_name) && !generated_shapes.contains_key(&list_shape_name) { let list_shape = SmithyShape::List { member: Box::new(SmithyMember { target: inner_smithy_type, documentation: None, traits: vec![], }), traits: vec![], }; generated_shapes.insert(list_shape_name.clone(), list_shape); } list_shape_name } vt if vt.starts_with("Box<") && vt.ends_with('>') => { let inner_type = extract_generic_inner_type(vt, "Box") .map_err(|e| syn::Error::new(value_type_span, e))?; let (resolved_type, new_shapes) = resolve_type_and_generate_shapes(inner_type, shapes)?; generated_shapes.extend(new_shapes); resolved_type } vt if vt.starts_with("Secret<") && vt.ends_with('>') => { let inner_type = extract_generic_inner_type(vt, "Secret") .map_err(|e| syn::Error::new(value_type_span, e))?; let (resolved_type, new_shapes) = resolve_type_and_generate_shapes(inner_type, shapes)?; generated_shapes.extend(new_shapes); resolved_type } vt if vt.starts_with("HashMap<") && vt.ends_with('>') => { let inner_types = extract_generic_inner_type(vt, "HashMap") .map_err(|e| syn::Error::new(value_type_span, e))?; let (key_type, value_type) = parse_map_types(inner_types).map_err(|e| syn::Error::new(value_type_span, e))?; let (key_smithy_type, key_shapes) = resolve_type_and_generate_shapes(key_type, shapes)?; generated_shapes.extend(key_shapes); let (value_smithy_type, value_shapes) = resolve_type_and_generate_shapes(value_type, shapes)?; generated_shapes.extend(value_shapes); format!( "smithy.api#Map<key: {}, value: {}>", key_smithy_type, value_smithy_type ) } vt if vt.starts_with("BTreeMap<") && vt.ends_with('>') => { let inner_types = extract_generic_inner_type(vt, "BTreeMap") .map_err(|e| syn::Error::new(value_type_span, e))?; let (key_type, value_type) = parse_map_types(inner_types).map_err(|e| syn::Error::new(value_type_span, e))?; let (key_smithy_type, key_shapes) = resolve_type_and_generate_shapes(key_type, shapes)?; generated_shapes.extend(key_shapes); let (value_smithy_type, value_shapes) = resolve_type_and_generate_shapes(value_type, shapes)?; generated_shapes.extend(value_shapes); format!( "smithy.api#Map<key: {}, value: {}>", key_smithy_type, value_smithy_type ) } _ => { if value_type.contains("::") { value_type.replace("::", ".") } else { value_type.to_string() } } }; Ok((target_type, generated_shapes)) } fn extract_generic_inner_type<'a>(full_type: &'a str, wrapper: &str) -> Result<&'a str, String> { let expected_start = format!("{}<", wrapper); if !full_type.starts_with(&expected_start) || !full_type.ends_with('>') { return Err(format!("Invalid {} type format: {}", wrapper, full_type)); } let start_idx = expected_start.len(); let end_idx = full_type.len() - 1; if start_idx >= end_idx { return Err(format!("Empty {} type: {}", wrapper, full_type)); } if start_idx >= full_type.len() || end_idx > full_type.len() { return Err(format!( "Invalid index bounds for {} type: {}", wrapper, full_type )); } Ok(full_type .get(start_idx..end_idx) .ok_or_else(|| { format!( "Failed to extract inner type from {}: {}", wrapper, full_type ) })? .trim()) } fn parse_map_types(inner_types: &str) -> Result<(&str, &str), String> { // Handle nested generics by counting angle brackets let mut bracket_count = 0; let mut comma_pos = None; for (i, ch) in inner_types.char_indices() { match ch { '<' => bracket_count += 1, '>' => bracket_count -= 1, ',' if bracket_count == 0 => { comma_pos = Some(i); break; } _ => {} } } if let Some(pos) = comma_pos { let key_type = inner_types .get(..pos) .ok_or_else(|| format!("Invalid key type bounds in map: {}", inner_types))? .trim(); let value_type = inner_types .get(pos + 1..) .ok_or_else(|| format!("Invalid value type bounds in map: {}", inner_types))? .trim(); if key_type.is_empty() || value_type.is_empty() { return Err(format!("Invalid map type format: {}", inner_types)); } Ok((key_type, value_type)) } else { Err(format!( "Invalid map type format, missing comma: {}", inner_types )) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/smithy-core/src/generator.rs
crates/smithy-core/src/generator.rs
// crates/smithy-core/generator.rs use std::{collections::HashMap, fs, path::Path}; use crate::types::{self as types, SmithyModel}; /// Generator for creating Smithy IDL files from models pub struct SmithyGenerator { models: Vec<SmithyModel>, } impl SmithyGenerator { pub fn new() -> Self { Self { models: Vec::new() } } pub fn add_model(&mut self, model: SmithyModel) { self.models.push(model); } pub fn generate_idl(&self, output_dir: &Path) -> Result<(), Box<dyn std::error::Error>> { fs::create_dir_all(output_dir)?; let mut namespace_models: HashMap<String, Vec<&SmithyModel>> = HashMap::new(); let mut shape_to_namespace: HashMap<String, String> = HashMap::new(); // First, build a map of all shape names to their namespaces for model in &self.models { for shape_name in model.shapes.keys() { shape_to_namespace.insert(shape_name.clone(), model.namespace.clone()); } } // Group models by namespace for file generation for model in &self.models { namespace_models .entry(model.namespace.clone()) .or_default() .push(model); } for (namespace, models) in namespace_models { let filename = format!("{}.smithy", namespace.replace('.', "_")); let filepath = output_dir.join(filename); let mut content = String::new(); content.push_str("$version: \"2\"\n\n"); content.push_str(&format!("namespace {}\n\n", namespace)); // Collect all unique shape definitions for the current namespace let mut shapes_in_namespace = HashMap::new(); for model in models { for (shape_name, shape) in &model.shapes { shapes_in_namespace.insert(shape_name.clone(), shape.clone()); } } // Generate definitions for each shape in the namespace for (shape_name, shape) in &shapes_in_namespace { content.push_str(&self.generate_shape_definition( shape_name, shape, &namespace, &shape_to_namespace, )); content.push_str("\n\n"); } fs::write(filepath, content)?; } Ok(()) } fn generate_shape_definition( &self, name: &str, shape: &types::SmithyShape, current_namespace: &str, shape_to_namespace: &HashMap<String, String>, ) -> String { let resolve_target = |target: &str| self.resolve_type(target, current_namespace, shape_to_namespace); match shape { types::SmithyShape::Structure { members, documentation, traits, } => { let mut def = String::new(); if let Some(doc) = documentation { def.push_str(&format!("/// {}\n", doc)); } for smithy_trait in traits { def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait))); } def.push_str(&format!("structure {} {{\n", name)); for (member_name, member) in members { if let Some(doc) = &member.documentation { def.push_str(&format!(" /// {}\n", doc)); } for smithy_trait in &member.traits { def.push_str(&format!(" @{}\n", self.trait_to_string(smithy_trait))); } let resolved_target = resolve_target(&member.target); def.push_str(&format!(" {}: {}\n", member_name, resolved_target)); } def.push('}'); def } types::SmithyShape::Union { members, documentation, traits, } => { let mut def = String::new(); if let Some(doc) = documentation { def.push_str(&format!("/// {}\n", doc)); } for smithy_trait in traits { def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait))); } def.push_str(&format!("union {} {{\n", name)); for (member_name, member) in members { if let Some(doc) = &member.documentation { def.push_str(&format!(" /// {}\n", doc)); } for smithy_trait in &member.traits { def.push_str(&format!(" @{}\n", self.trait_to_string(smithy_trait))); } let resolved_target = resolve_target(&member.target); def.push_str(&format!(" {}: {}\n", member_name, resolved_target)); } def.push('}'); def } types::SmithyShape::Enum { values, documentation, traits, } => { let mut def = String::new(); if let Some(doc) = documentation { def.push_str(&format!("/// {}\n", doc)); } for smithy_trait in traits { def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait))); } def.push_str(&format!("enum {} {{\n", name)); for (value_name, enum_value) in values { if let Some(doc) = &enum_value.documentation { def.push_str(&format!(" /// {}\n", doc)); } for smithy_trait in &enum_value.traits { def.push_str(&format!(" @{}\n", self.trait_to_string(smithy_trait))); } def.push_str(&format!(" {}\n", value_name)); } def.push('}'); def } types::SmithyShape::String { traits } => { let mut def = String::new(); for smithy_trait in traits { def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait))); } def.push_str(&format!("string {}", name)); def } types::SmithyShape::Integer { traits } => { let mut def = String::new(); for smithy_trait in traits { def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait))); } def.push_str(&format!("integer {}", name)); def } types::SmithyShape::Long { traits } => { let mut def = String::new(); for smithy_trait in traits { def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait))); } def.push_str(&format!("long {}", name)); def } types::SmithyShape::Boolean { traits } => { let mut def = String::new(); for smithy_trait in traits { def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait))); } def.push_str(&format!("boolean {}", name)); def } types::SmithyShape::List { member, traits } => { let mut def = String::new(); for smithy_trait in traits { def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait))); } def.push_str(&format!("list {} {{\n", name)); let resolved_target = resolve_target(&member.target); def.push_str(&format!(" member: {}\n", resolved_target)); def.push('}'); def } } } fn resolve_type( &self, target: &str, current_namespace: &str, shape_to_namespace: &HashMap<String, String>, ) -> String { // If the target is a primitive or a fully qualified Smithy type, return it as is if target.starts_with("smithy.api#") { return target.to_string(); } // If the target is a custom type, resolve its namespace if let Some(target_namespace) = shape_to_namespace.get(target) { if target_namespace == current_namespace { // The type is in the same namespace, so no qualification is needed target.to_string() } else { // The type is in a different namespace, so it needs to be fully qualified format!("{}#{}", target_namespace, target) } } else { // If the type is not found in the shape map, it might be a primitive // or an unresolved type. For now, return it as is. target.to_string() } } fn trait_to_string(&self, smithy_trait: &types::SmithyTrait) -> String { match smithy_trait { types::SmithyTrait::Pattern { pattern } => { format!("pattern(\"{}\")", pattern) } types::SmithyTrait::Range { min, max } => match (min, max) { (Some(min), Some(max)) => format!("range(min: {}, max: {})", min, max), (Some(min), None) => format!("range(min: {})", min), (None, Some(max)) => format!("range(max: {})", max), (None, None) => "range".to_string(), }, types::SmithyTrait::Required => "required".to_string(), types::SmithyTrait::Documentation { documentation } => { format!("documentation(\"{}\")", documentation) } types::SmithyTrait::Length { min, max } => match (min, max) { (Some(min), Some(max)) => format!("length(min: {}, max: {})", min, max), (Some(min), None) => format!("length(min: {})", min), (None, Some(max)) => format!("length(max: {})", max), (None, None) => "length".to_string(), }, types::SmithyTrait::HttpLabel => "httpLabel".to_string(), types::SmithyTrait::HttpQuery { name } => { format!("httpQuery(\"{}\")", name) } types::SmithyTrait::Mixin => "mixin".to_string(), types::SmithyTrait::JsonName { name } => { format!("jsonName(\"{}\")", name) } types::SmithyTrait::EnumValue { value } => { format!("enumValue(\"{}\")", value) } } } } impl Default for SmithyGenerator { fn default() -> Self { Self::new() } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/errors.rs
crates/common_utils/src/errors.rs
//! Errors and error specific types for universal use use serde::Serialize; use crate::types::MinorUnit; /// Custom Result /// A custom datatype that wraps the error variant <E> into a report, allowing /// error_stack::Report<E> specific extendability /// /// Effectively, equivalent to `Result<T, error_stack::Report<E>>` pub type CustomResult<T, E> = error_stack::Result<T, E>; /// Parsing Errors #[allow(missing_docs)] // Only to prevent warnings about struct fields not being documented #[derive(Debug, thiserror::Error)] pub enum ParsingError { ///Failed to parse enum #[error("Failed to parse enum: {0}")] EnumParseFailure(&'static str), ///Failed to parse struct #[error("Failed to parse struct: {0}")] StructParseFailure(&'static str), /// Failed to encode data to given format #[error("Failed to serialize to {0} format")] EncodeError(&'static str), /// Failed to parse data #[error("Unknown error while parsing")] UnknownError, /// Failed to parse datetime #[error("Failed to parse datetime")] DateTimeParsingError, /// Failed to parse email #[error("Failed to parse email")] EmailParsingError, /// Failed to parse phone number #[error("Failed to parse phone number")] PhoneNumberParsingError, /// Failed to parse Float value for converting to decimal points #[error("Failed to parse Float value for converting to decimal points")] FloatToDecimalConversionFailure, /// Failed to parse Decimal value for i64 value conversion #[error("Failed to parse Decimal value for i64 value conversion")] DecimalToI64ConversionFailure, /// Failed to parse string value for f64 value conversion #[error("Failed to parse string value for f64 value conversion")] StringToFloatConversionFailure, /// Failed to parse i64 value for f64 value conversion #[error("Failed to parse i64 value for f64 value conversion")] I64ToDecimalConversionFailure, /// Failed to parse i64 value for String value conversion #[error("Failed to parse i64 value for String value conversion")] I64ToStringConversionFailure, /// Failed to parse String value to Decimal value conversion because `error` #[error("Failed to parse String value to Decimal value conversion because {error}")] StringToDecimalConversionFailure { error: String }, /// Failed to convert the given integer because of integer overflow error #[error("Integer Overflow error")] IntegerOverflow, /// Failed to parse url #[error("Failed to parse url")] UrlParsingError, } /// Validation errors. #[allow(missing_docs)] // Only to prevent warnings about struct fields not being documented #[derive(Debug, thiserror::Error, Clone, PartialEq)] pub enum ValidationError { /// The provided input is missing a required field. #[error("Missing required field: {field_name}")] MissingRequiredField { field_name: String }, /// An incorrect value was provided for the field specified by `field_name`. #[error("Incorrect value provided for field: {field_name}")] IncorrectValueProvided { field_name: &'static str }, /// An invalid input was provided. #[error("{message}")] InvalidValue { message: String }, } /// Integrity check errors. #[derive(Debug, Clone, PartialEq, Default, Serialize)] pub struct IntegrityCheckError { /// Field names for which integrity check failed! pub field_names: String, /// Connector transaction reference id pub connector_transaction_id: Option<String>, } /// Cryptographic algorithm errors #[derive(Debug, thiserror::Error)] pub enum CryptoError { /// The cryptographic algorithm was unable to encode the message #[error("Failed to encode given message")] EncodingFailed, /// The cryptographic algorithm was unable to decode the message #[error("Failed to decode given message")] DecodingFailed, /// The cryptographic algorithm was unable to sign the message #[error("Failed to sign message")] MessageSigningFailed, /// The cryptographic algorithm was unable to verify the given signature #[error("Failed to verify signature")] SignatureVerificationFailed, /// The provided key length is invalid for the cryptographic algorithm #[error("Invalid key length")] InvalidKeyLength, /// The provided IV length is invalid for the cryptographic algorithm #[error("Invalid IV length")] InvalidIvLength, /// The provided authentication tag length is invalid for the cryptographic algorithm #[error("Invalid authentication tag length")] InvalidTagLength, } /// Errors for Qr code handling #[derive(Debug, thiserror::Error)] pub enum QrCodeError { /// Failed to encode data into Qr code #[error("Failed to create Qr code")] FailedToCreateQrCode, /// Failed to parse hex color #[error("Invalid hex color code supplied")] InvalidHexColor, } /// Api Models construction error #[derive(Debug, Clone, thiserror::Error, PartialEq)] pub enum PercentageError { /// Percentage Value provided was invalid #[error("Invalid Percentage value")] InvalidPercentageValue, /// Error occurred while calculating percentage #[error("Failed apply percentage of {percentage} on {amount}")] UnableToApplyPercentage { /// percentage value percentage: f32, /// amount value amount: MinorUnit, }, } /// Allows [error_stack::Report] to change between error contexts /// using the dependent [ErrorSwitch] trait to define relations & mappings between traits pub trait ReportSwitchExt<T, U> { /// Switch to the intended report by calling switch /// requires error switch to be already implemented on the error type fn switch(self) -> Result<T, error_stack::Report<U>>; } impl<T, U, V> ReportSwitchExt<T, U> for Result<T, error_stack::Report<V>> where V: ErrorSwitch<U> + error_stack::Context, U: error_stack::Context, { #[track_caller] fn switch(self) -> Result<T, error_stack::Report<U>> { match self { Ok(i) => Ok(i), Err(er) => { let new_c = er.current_context().switch(); Err(er.change_context(new_c)) } } } } #[allow(missing_docs)] #[derive(Debug, thiserror::Error)] pub enum KeyManagerClientError { #[error("Failed to construct header from the given value")] FailedtoConstructHeader, #[error("Failed to send request to Keymanager")] RequestNotSent(String), #[error("URL encoding of request failed")] UrlEncodingFailed, #[error("Failed to build the reqwest client ")] ClientConstructionFailed, #[error("Failed to send the request to Keymanager")] RequestSendFailed, #[error("Internal Server Error Received {0:?}")] InternalServerError(bytes::Bytes), #[error("Bad request received {0:?}")] BadRequest(bytes::Bytes), #[error("Unexpected Error occurred while calling the KeyManager")] Unexpected(bytes::Bytes), #[error("Response Decoding failed")] ResponseDecodingFailed, } #[allow(missing_docs)] #[derive(Debug, thiserror::Error)] pub enum KeyManagerError { #[error("Failed to add key to the KeyManager")] KeyAddFailed, #[error("Failed to transfer the key to the KeyManager")] KeyTransferFailed, #[error("Failed to Encrypt the data in the KeyManager")] EncryptionFailed, #[error("Failed to Decrypt the data in the KeyManager")] DecryptionFailed, } /// Allow [error_stack::Report] to convert between error types /// This auto-implements [ReportSwitchExt] for the corresponding errors pub trait ErrorSwitch<T> { /// Get the next error type that the source error can be escalated into /// This does not consume the source error since we need to keep it in context fn switch(&self) -> T; } /// Allow [error_stack::Report] to convert between error types /// This serves as an alternative to [ErrorSwitch] pub trait ErrorSwitchFrom<T> { /// Convert to an error type that the source can be escalated into /// This does not consume the source error since we need to keep it in context fn switch_from(error: &T) -> Self; } impl<T, S> ErrorSwitch<T> for S where T: ErrorSwitchFrom<Self>, { fn switch(&self) -> T { T::switch_from(self) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/consts.rs
crates/common_utils/src/consts.rs
//! Commonly used constants /// Number of characters in a generated ID pub const ID_LENGTH: usize = 20; /// Characters to use for generating NanoID pub(crate) const ALPHABETS: [char; 62] = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ]; /// TTL for token pub const TOKEN_TTL: i64 = 900; ///an example of the frm_configs json pub static FRM_CONFIGS_EG: &str = r#" [{"gateway":"stripe","payment_methods":[{"payment_method":"card","payment_method_types":[{"payment_method_type":"credit","card_networks":["Visa"],"flow":"pre","action":"cancel_txn"},{"payment_method_type":"debit","card_networks":["Visa"],"flow":"pre"}]}]}] "#; /// Maximum limit for payments list get api pub const PAYMENTS_LIST_MAX_LIMIT_V1: u32 = 100; /// Maximum limit for payments list post api with filters pub const PAYMENTS_LIST_MAX_LIMIT_V2: u32 = 50; /// Default limit for payments list API pub fn default_payments_list_limit() -> u32 { 10 } /// Average delay (in seconds) between account onboarding's API response and the changes to actually reflect at Stripe's end pub const STRIPE_ACCOUNT_ONBOARDING_DELAY_IN_SECONDS: i64 = 15; /// Maximum limit for payment link list get api pub const PAYMENTS_LINK_LIST_LIMIT: u32 = 100; /// Maximum limit for payouts list get api pub const PAYOUTS_LIST_MAX_LIMIT_GET: u32 = 100; /// Maximum limit for payouts list post api pub const PAYOUTS_LIST_MAX_LIMIT_POST: u32 = 20; /// Default limit for payouts list API pub fn default_payouts_list_limit() -> u32 { 10 } /// surcharge percentage maximum precision length pub const SURCHARGE_PERCENTAGE_PRECISION_LENGTH: u8 = 2; /// Header Key for application overhead of a request pub const X_HS_LATENCY: &str = "x-hs-latency"; /// Redirect url for Prophetpay pub const PROPHETPAY_REDIRECT_URL: &str = "https://ccm-thirdparty.cps.golf/hp/tokenize/"; /// Variable which store the card token for Prophetpay pub const PROPHETPAY_TOKEN: &str = "cctoken"; /// Payment intent default client secret expiry (in seconds) pub const DEFAULT_SESSION_EXPIRY: i64 = 15 * 60; /// Payment intent fulfillment time (in seconds) pub const DEFAULT_INTENT_FULFILLMENT_TIME: i64 = 15 * 60; /// Payment order fulfillment time (in seconds) pub const DEFAULT_ORDER_FULFILLMENT_TIME: i64 = 15 * 60; /// Default ttl for Extended card info in redis (in seconds) pub const DEFAULT_TTL_FOR_EXTENDED_CARD_INFO: u16 = 15 * 60; /// Max ttl for Extended card info in redis (in seconds) pub const MAX_TTL_FOR_EXTENDED_CARD_INFO: u16 = 60 * 60 * 2; /// Default tenant to be used when multitenancy is disabled pub const DEFAULT_TENANT: &str = "public"; /// Default tenant to be used when multitenancy is disabled pub const TENANT_HEADER: &str = "x-tenant-id"; /// Max Length for MerchantReferenceId pub const MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH: u8 = 64; /// Maximum length allowed for a global id pub const MIN_GLOBAL_ID_LENGTH: u8 = 32; /// Minimum length required for a global id pub const MAX_GLOBAL_ID_LENGTH: u8 = 64; /// Minimum allowed length for MerchantReferenceId pub const MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH: u8 = 1; /// Length of a cell identifier in a distributed system pub const CELL_IDENTIFIER_LENGTH: u8 = 5; /// General purpose base64 engine pub const BASE64_ENGINE: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD; /// General purpose base64 engine standard nopad pub const BASE64_ENGINE_STD_NO_PAD: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD_NO_PAD; /// URL Safe base64 engine pub const BASE64_ENGINE_URL_SAFE: base64::engine::GeneralPurpose = base64::engine::general_purpose::URL_SAFE; /// URL Safe base64 engine without padding pub const BASE64_ENGINE_URL_SAFE_NO_PAD: base64::engine::GeneralPurpose = base64::engine::general_purpose::URL_SAFE_NO_PAD; /// Regex for matching a domain /// Eg - /// http://www.example.com /// https://www.example.com /// www.example.com /// example.io pub const STRICT_DOMAIN_REGEX: &str = r"^(https?://)?(([A-Za-z0-9][-A-Za-z0-9]\.)*[A-Za-z0-9][-A-Za-z0-9]*|(\d{1,3}\.){3}\d{1,3})+(:[0-9]{2,4})?$"; /// Regex for matching a wildcard domain /// Eg - /// *.example.com /// *.subdomain.domain.com /// *://example.com /// *example.com pub const WILDCARD_DOMAIN_REGEX: &str = r"^((\*|https?)?://)?((\*\.|[A-Za-z0-9][-A-Za-z0-9]*\.)*[A-Za-z0-9][-A-Za-z0-9]*|((\d{1,3}|\*)\.){3}(\d{1,3}|\*)|\*)(:\*|:[0-9]{2,4})?(/\*)?$"; /// Maximum allowed length for MerchantName pub const MAX_ALLOWED_MERCHANT_NAME_LENGTH: usize = 64; /// Default locale pub const DEFAULT_LOCALE: &str = "en"; /// Role ID for Tenant Admin pub const ROLE_ID_TENANT_ADMIN: &str = "tenant_admin"; /// Role ID for Org Admin pub const ROLE_ID_ORGANIZATION_ADMIN: &str = "org_admin"; /// Role ID for Internal View Only pub const ROLE_ID_INTERNAL_VIEW_ONLY_USER: &str = "internal_view_only"; /// Role ID for Internal Admin pub const ROLE_ID_INTERNAL_ADMIN: &str = "internal_admin"; /// Role ID for Internal Demo pub const ROLE_ID_INTERNAL_DEMO: &str = "internal_demo"; /// Max length allowed for Description pub const MAX_DESCRIPTION_LENGTH: u16 = 255; /// Max length allowed for Statement Descriptor pub const MAX_STATEMENT_DESCRIPTOR_LENGTH: u16 = 22; /// Payout flow identifier used for performing GSM operations pub const PAYOUT_FLOW_STR: &str = "payout_flow"; /// length of the publishable key pub const PUBLISHABLE_KEY_LENGTH: u16 = 39; /// The number of bytes allocated for the hashed connector transaction ID. /// Total number of characters equals CONNECTOR_TRANSACTION_ID_HASH_BYTES times 2. pub const CONNECTOR_TRANSACTION_ID_HASH_BYTES: usize = 25; /// Apple Pay validation url pub const APPLEPAY_VALIDATION_URL: &str = "https://apple-pay-gateway-cert.apple.com/paymentservices/startSession"; /// Request ID pub const X_REQUEST_ID: &str = "x-request-id"; /// Flow name pub const X_FLOW_NAME: &str = "x-flow"; /// Connector name pub const X_CONNECTOR_NAME: &str = "x-connector"; /// Sub-flow name pub const X_SUB_FLOW_NAME: &str = "x-sub-flow"; /// Unified Connector Service Mode pub const X_UNIFIED_CONNECTOR_SERVICE_MODE: &str = "x-shadow-mode"; /// Chat Session ID pub const X_CHAT_SESSION_ID: &str = "x-chat-session-id"; /// Merchant ID Header pub const X_MERCHANT_ID: &str = "x-merchant-id"; /// Default Tenant ID for the `Global` tenant pub const DEFAULT_GLOBAL_TENANT_ID: &str = "global"; /// Default status of Card IP Blocking pub const DEFAULT_CARD_IP_BLOCKING_STATUS: bool = false; /// Default Threshold for Card IP Blocking pub const DEFAULT_CARD_IP_BLOCKING_THRESHOLD: i32 = 3; /// Default status of Guest User Card Blocking pub const DEFAULT_GUEST_USER_CARD_BLOCKING_STATUS: bool = false; /// Default Threshold for Card Blocking for Guest Users pub const DEFAULT_GUEST_USER_CARD_BLOCKING_THRESHOLD: i32 = 10; /// Default status of Customer ID Blocking pub const DEFAULT_CUSTOMER_ID_BLOCKING_STATUS: bool = false; /// Default Threshold for Customer ID Blocking pub const DEFAULT_CUSTOMER_ID_BLOCKING_THRESHOLD: i32 = 5; /// Default Card Testing Guard Redis Expiry in seconds pub const DEFAULT_CARD_TESTING_GUARD_EXPIRY_IN_SECS: i32 = 3600; /// SOAP 1.1 Envelope Namespace pub const SOAP_ENV_NAMESPACE: &str = "http://schemas.xmlsoap.org/soap/envelope/"; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] /// Length of generated tokens pub const TOKEN_LENGTH: usize = 32; /// The tag name used for identifying the host in metrics. pub const METRICS_HOST_TAG_NAME: &str = "host"; /// API client request timeout (in seconds) pub const REQUEST_TIME_OUT: u64 = 30; /// API client request timeout for ai service (in seconds) pub const REQUEST_TIME_OUT_FOR_AI_SERVICE: u64 = 120; /// Default limit for list operations (can be used across different entities) pub const DEFAULT_LIST_LIMIT: i64 = 100; /// Default offset for list operations (can be used across different entities) pub const DEFAULT_LIST_OFFSET: i64 = 0;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_utils/src/payout_method_utils.rs
crates/common_utils/src/payout_method_utils.rs
//! This module has common utilities for payout method data in HyperSwitch use diesel::{sql_types::Jsonb, AsExpression, FromSqlRow}; use masking::Secret; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::new_type::{ MaskedBankAccount, MaskedBic, MaskedEmail, MaskedIban, MaskedPhoneNumber, MaskedPspToken, MaskedRoutingNumber, MaskedSortCode, }; /// Masked payout method details for storing in db #[derive( Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub enum AdditionalPayoutMethodData { /// Additional data for card payout method Card(Box<CardAdditionalData>), /// Additional data for bank payout method Bank(Box<BankAdditionalData>), /// Additional data for wallet payout method Wallet(Box<WalletAdditionalData>), /// Additional data for Bank Redirect payout method BankRedirect(Box<BankRedirectAdditionalData>), /// Additional data for Passthrough payout method Passthrough(Box<PassthroughAddtionalData>), } crate::impl_to_sql_from_sql_json!(AdditionalPayoutMethodData); /// Masked payout method details for card payout method #[derive( Eq, PartialEq, Clone, Debug, Serialize, Deserialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct CardAdditionalData { /// Issuer of the card pub card_issuer: Option<String>, /// Card network of the card #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<common_enums::CardNetwork>, /// Card type, can be either `credit` or `debit` pub card_type: Option<String>, /// Card issuing country pub card_issuing_country: Option<String>, /// Code for Card issuing bank pub bank_code: Option<String>, /// Last 4 digits of the card number pub last4: Option<String>, /// The ISIN of the card pub card_isin: Option<String>, /// Extended bin of card, contains the first 8 digits of card number pub card_extended_bin: Option<String>, /// Card expiry month #[schema(value_type = String, example = "01")] pub card_exp_month: Option<Secret<String>>, /// Card expiry year #[schema(value_type = String, example = "2026")] pub card_exp_year: Option<Secret<String>>, /// Card holder name #[schema(value_type = String, example = "John Doe")] pub card_holder_name: Option<Secret<String>>, } /// Masked payout method details for bank payout method #[derive( Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(untagged)] pub enum BankAdditionalData { /// Additional data for ach bank transfer payout method Ach(Box<AchBankTransferAdditionalData>), /// Additional data for bacs bank transfer payout method Bacs(Box<BacsBankTransferAdditionalData>), /// Additional data for sepa bank transfer payout method Sepa(Box<SepaBankTransferAdditionalData>), /// Additional data for pix bank transfer payout method Pix(Box<PixBankTransferAdditionalData>), } /// Masked payout method details for ach bank transfer payout method #[derive( Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct AchBankTransferAdditionalData { /// Partially masked account number for ach bank debit payment #[schema(value_type = String, example = "0001****3456")] pub bank_account_number: MaskedBankAccount, /// Partially masked routing number for ach bank debit payment #[schema(value_type = String, example = "110***000")] pub bank_routing_number: MaskedRoutingNumber, /// Name of the bank #[schema(value_type = Option<BankNames>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<common_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, } /// Masked payout method details for bacs bank transfer payout method #[derive( Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct BacsBankTransferAdditionalData { /// Partially masked sort code for Bacs payment method #[schema(value_type = String, example = "108800")] pub bank_sort_code: MaskedSortCode, /// Bank account's owner name #[schema(value_type = String, example = "0001****3456")] pub bank_account_number: MaskedBankAccount, /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<common_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, } /// Masked payout method details for sepa bank transfer payout method #[derive( Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct SepaBankTransferAdditionalData { /// Partially masked international bank account number (iban) for SEPA #[schema(value_type = String, example = "DE8937******013000")] pub iban: MaskedIban, /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<common_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// [8 / 11 digits] Bank Identifier Code (bic) / Swift Code - used in many countries for identifying a bank and it's branches #[schema(value_type = Option<String>, example = "HSBCGB2LXXX")] pub bic: Option<MaskedBic>, } /// Masked payout method details for pix bank transfer payout method #[derive( Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct PixBankTransferAdditionalData { /// Partially masked unique key for pix transfer #[schema(value_type = String, example = "a1f4102e ****** 6fa48899c1d1")] pub pix_key: MaskedBankAccount, /// Partially masked CPF - CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "**** 124689")] pub tax_id: Option<MaskedBankAccount>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "**** 23456")] pub bank_account_number: MaskedBankAccount, /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank branch #[schema(value_type = Option<String>, example = "3707")] pub bank_branch: Option<String>, } /// Masked payout method details for wallet payout method #[derive( Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(untagged)] pub enum WalletAdditionalData { /// Additional data for paypal wallet payout method Paypal(Box<PaypalAdditionalData>), /// Additional data for venmo wallet payout method Venmo(Box<VenmoAdditionalData>), /// Additional data for Apple pay decrypt wallet payout method ApplePayDecrypt(Box<ApplePayDecryptAdditionalData>), } /// Masked payout method details for paypal wallet payout method #[derive( Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct PaypalAdditionalData { /// Email linked with paypal account #[schema(value_type = Option<String>, example = "john.doe@example.com")] pub email: Option<MaskedEmail>, /// mobile number linked to paypal account #[schema(value_type = Option<String>, example = "******* 3349")] pub telephone_number: Option<MaskedPhoneNumber>, /// id of the paypal account #[schema(value_type = Option<String>, example = "G83K ***** HCQ2")] pub paypal_id: Option<MaskedBankAccount>, } /// Masked payout method details for venmo wallet payout method #[derive( Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct VenmoAdditionalData { /// mobile number linked to venmo account #[schema(value_type = Option<String>, example = "******* 3349")] pub telephone_number: Option<MaskedPhoneNumber>, } /// Masked payout method details for Apple pay decrypt wallet payout method #[derive( Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct ApplePayDecryptAdditionalData { /// Card expiry month #[schema(value_type = String, example = "01")] pub card_exp_month: Secret<String>, /// Card expiry year #[schema(value_type = String, example = "2026")] pub card_exp_year: Secret<String>, /// Card holder name #[schema(value_type = String, example = "John Doe")] pub card_holder_name: Option<Secret<String>>, } /// Masked payout method details for wallet payout method #[derive( Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(untagged)] pub enum BankRedirectAdditionalData { /// Additional data for interac bank redirect payout method Interac(Box<InteracAdditionalData>), } /// Masked payout method details for interac bank redirect payout method #[derive( Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct InteracAdditionalData { /// Email linked with interac account #[schema(value_type = Option<String>, example = "john.doe@example.com")] pub email: Option<MaskedEmail>, } /// additional payout method details for passthrough payout method #[derive( Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct PassthroughAddtionalData { /// Psp_token of the passthrough flow #[schema(value_type = String, example = "token_12345")] pub psp_token: MaskedPspToken, /// token_type of the passthrough flow #[schema(value_type = PaymentMethodType, example = "paypal")] pub token_type: common_enums::PaymentMethodType, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false