text
stringlengths
65
57.3k
file_path
stringlengths
22
92
module
stringclasses
38 values
type
stringclasses
7 values
struct_name
stringlengths
3
60
impl_count
int64
0
60
traits
listlengths
0
59
tokens
int64
16
8.19k
function_name
stringlengths
3
85
type_name
stringlengths
1
67
trait_name
stringclasses
573 values
method_count
int64
0
31
public_method_count
int64
0
19
submodule_count
int64
0
56
export_count
int64
0
9
// Struct: ChargebackNotification // File: crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ChargebackNotification
crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
hyperswitch_connectors
struct_definition
ChargebackNotification
0
[]
49
null
null
null
null
null
null
null
// Implementation: impl super::KafkaMessage for for RevenueRecovery // File: crates/router/src/services/kafka/revenue_recovery.rs // Module: router // Methods: 2 total (0 public) impl super::KafkaMessage for for RevenueRecovery
crates/router/src/services/kafka/revenue_recovery.rs
router
impl_block
null
null
null
55
null
RevenueRecovery
super::KafkaMessage for
2
0
null
null
// Implementation: impl ConnectorValidation for for Gpayments // File: crates/hyperswitch_connectors/src/connectors/gpayments.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl ConnectorValidation for for Gpayments
crates/hyperswitch_connectors/src/connectors/gpayments.rs
hyperswitch_connectors
impl_block
null
null
null
53
null
Gpayments
ConnectorValidation for
0
0
null
null
// Implementation: impl crate::core::payments::Operation for for Point3 // File: crates/router_derive/src/lib.rs // Module: router_derive // Methods: 2 total (0 public) impl crate::core::payments::Operation for for Point3
crates/router_derive/src/lib.rs
router_derive
impl_block
null
null
null
56
null
Point3
crate::core::payments::Operation for
2
0
null
null
// Function: insert // File: crates/diesel_models/src/query/capture.rs // Module: diesel_models pub fn insert(self, conn: &PgPooledConn) -> StorageResult<Capture>
crates/diesel_models/src/query/capture.rs
diesel_models
function_signature
null
null
null
43
insert
null
null
null
null
null
null
// Struct: GlobepayRefundResponse // File: crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct GlobepayRefundResponse
crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
hyperswitch_connectors
struct_definition
GlobepayRefundResponse
0
[]
55
null
null
null
null
null
null
null
// Struct: TokenizedBankRedirectValue1 // File: crates/hyperswitch_domain_models/src/payment_method_data.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct TokenizedBankRedirectValue1
crates/hyperswitch_domain_models/src/payment_method_data.rs
hyperswitch_domain_models
struct_definition
TokenizedBankRedirectValue1
0
[]
49
null
null
null
null
null
null
null
// Struct: ApplePayPredecrypt // File: crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ApplePayPredecrypt
crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
hyperswitch_connectors
struct_definition
ApplePayPredecrypt
0
[]
49
null
null
null
null
null
null
null
// Function: error_code // File: crates/router_derive/src/macros/api_error.rs // Module: router_derive pub fn error_code(&self) -> String
crates/router_derive/src/macros/api_error.rs
router_derive
function_signature
null
null
null
36
error_code
null
null
null
null
null
null
// Implementation: impl MerchantId // File: crates/common_utils/src/id_type/merchant.rs // Module: common_utils // Methods: 19 total (19 public) impl MerchantId
crates/common_utils/src/id_type/merchant.rs
common_utils
impl_block
null
null
null
41
null
MerchantId
null
19
19
null
null
// Struct: TokenDetails // File: crates/router/src/types/payment_methods.rs // Module: router // Implementations: 0 pub struct TokenDetails
crates/router/src/types/payment_methods.rs
router
struct_definition
TokenDetails
0
[]
33
null
null
null
null
null
null
null
// Struct: CardDetails // File: crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct CardDetails
crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
hyperswitch_connectors
struct_definition
CardDetails
0
[]
47
null
null
null
null
null
null
null
// Struct: KlarnaShippingAddress // File: crates/hyperswitch_connectors/src/connectors/klarna/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct KlarnaShippingAddress
crates/hyperswitch_connectors/src/connectors/klarna/transformers.rs
hyperswitch_connectors
struct_definition
KlarnaShippingAddress
0
[]
50
null
null
null
null
null
null
null
// Struct: Instruction // File: crates/hyperswitch_connectors/src/connectors/aci/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct Instruction
crates/hyperswitch_connectors/src/connectors/aci/transformers.rs
hyperswitch_connectors
struct_definition
Instruction
0
[]
43
null
null
null
null
null
null
null
// File: crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs // Module: analytics use std::collections::HashSet; use api_models::analytics::{ payment_intents::{ PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier, }, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::PaymentIntentMetricRow; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(crate) struct PaymentsDistribution; #[async_trait::async_trait] impl<T> super::PaymentIntentMetric<T> for PaymentsDistribution where T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[PaymentIntentDimensions], auth: &AuthInfo, filters: &PaymentIntentFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized); let mut dimensions = dimensions.to_vec(); dimensions.push(PaymentIntentDimensions::PaymentIntentStatus); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(Aggregate::Count { field: None, alias: Some("count"), }) .switch()?; query_builder .add_select_column("(attempt_count = 1) as first_attempt") .switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; auth.set_filter_clause(&mut query_builder).switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; for dim in dimensions.iter() { query_builder .add_group_by_clause(dim) .attach_printable("Error grouping by dimensions") .switch()?; } query_builder .add_group_by_clause("first_attempt") .attach_printable("Error grouping by first_attempt") .switch()?; if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } query_builder .execute_query::<PaymentIntentMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( PaymentIntentMetricsBucketIdentifier::new( None, i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), i.connector.clone(), i.authentication_type.as_ref().map(|i| i.0), i.payment_method.clone(), i.payment_method_type.clone(), i.card_network.clone(), i.merchant_id.clone(), i.card_last_4.clone(), i.card_issuer.clone(), i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result< HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs
analytics
full_file
null
null
null
989
null
null
null
null
null
null
null
// Struct: Amount // File: crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct Amount
crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
hyperswitch_connectors
struct_definition
Amount
0
[]
46
null
null
null
null
null
null
null
// Function: perform_authentication // File: crates/router/src/core/authentication.rs // Module: router pub fn perform_authentication( state: &SessionState, merchant_id: common_utils::id_type::MerchantId, authentication_connector: String, payment_method_data: domain::PaymentMethodData, payment_method: common_enums::PaymentMethod, billing_address: hyperswitch_domain_models::address::Address, shipping_address: Option<hyperswitch_domain_models::address::Address>, browser_details: Option<core_types::BrowserInformation>, merchant_connector_account: payments_core::helpers::MerchantConnectorAccountType, amount: Option<common_utils::types::MinorUnit>, currency: Option<Currency>, message_category: api::authentication::MessageCategory, device_channel: payments::DeviceChannel, authentication_data: storage::Authentication, return_url: Option<String>, sdk_information: Option<payments::SdkInformation>, threeds_method_comp_ind: payments::ThreeDsCompletionIndicator, email: Option<common_utils::pii::Email>, webhook_url: String, three_ds_requestor_url: String, psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, payment_id: common_utils::id_type::PaymentId, force_3ds_challenge: bool, merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, ) -> CustomResult<api::authentication::AuthenticationResponse, ApiErrorResponse>
crates/router/src/core/authentication.rs
router
function_signature
null
null
null
318
perform_authentication
null
null
null
null
null
null
// Function: payment_methods_session_create // File: crates/router/src/core/payment_methods.rs // Module: router pub fn payment_methods_session_create( state: SessionState, merchant_context: domain::MerchantContext, request: payment_methods::PaymentMethodSessionRequest, ) -> RouterResponse<payment_methods::PaymentMethodSessionResponse>
crates/router/src/core/payment_methods.rs
router
function_signature
null
null
null
70
payment_methods_session_create
null
null
null
null
null
null
// Implementation: impl api::PaymentCapture for for Iatapay // File: crates/hyperswitch_connectors/src/connectors/iatapay.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentCapture for for Iatapay
crates/hyperswitch_connectors/src/connectors/iatapay.rs
hyperswitch_connectors
impl_block
null
null
null
63
null
Iatapay
api::PaymentCapture for
0
0
null
null
// Function: is_key_deleted // File: crates/redis_interface/src/types.rs // Module: redis_interface pub fn is_key_deleted(&self) -> bool
crates/redis_interface/src/types.rs
redis_interface
function_signature
null
null
null
34
is_key_deleted
null
null
null
null
null
null
// Function: payment_connector_verify // File: crates/router/src/routes/verify_connector.rs // Module: router pub fn payment_connector_verify( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<VerifyConnectorRequest>, ) -> HttpResponse
crates/router/src/routes/verify_connector.rs
router
function_signature
null
null
null
59
payment_connector_verify
null
null
null
null
null
null
// Function: pg_connection_write // File: crates/storage_impl/src/utils.rs // Module: storage_impl pub fn pg_connection_write<T: DatabaseStore>( store: &T, ) -> error_stack::Result< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, StorageError, >
crates/storage_impl/src/utils.rs
storage_impl
function_signature
null
null
null
69
pg_connection_write
null
null
null
null
null
null
// Struct: NuveiMeta // File: crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct NuveiMeta
crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
hyperswitch_connectors
struct_definition
NuveiMeta
0
[]
51
null
null
null
null
null
null
null
// Struct: EbanxPayoutFulfillRequest // File: crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct EbanxPayoutFulfillRequest
crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs
hyperswitch_connectors
struct_definition
EbanxPayoutFulfillRequest
0
[]
59
null
null
null
null
null
null
null
// Module Structure // File: crates/hyperswitch_connectors/src/connectors/mpgs.rs // Module: hyperswitch_connectors // Public submodules: pub mod transformers;
crates/hyperswitch_connectors/src/connectors/mpgs.rs
hyperswitch_connectors
module_structure
null
null
null
38
null
null
null
null
null
1
0
// Implementation: impl ConnectorSpecifications for for Riskified // File: crates/hyperswitch_connectors/src/connectors/riskified.rs // Module: hyperswitch_connectors // Methods: 3 total (0 public) impl ConnectorSpecifications for for Riskified
crates/hyperswitch_connectors/src/connectors/riskified.rs
hyperswitch_connectors
impl_block
null
null
null
54
null
Riskified
ConnectorSpecifications for
3
0
null
null
// Function: user_merchant_account_create // File: crates/router/src/routes/user.rs // Module: router pub fn user_merchant_account_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<user_api::UserMerchantCreate>, ) -> HttpResponse
crates/router/src/routes/user.rs
router
function_signature
null
null
null
64
user_merchant_account_create
null
null
null
null
null
null
// Struct: AirwallexRedirectFormData // File: crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct AirwallexRedirectFormData
crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
hyperswitch_connectors
struct_definition
AirwallexRedirectFormData
0
[]
53
null
null
null
null
null
null
null
// Function: extract_token_from_body // File: crates/hyperswitch_connectors/src/connectors/dwolla/transformers.rs // Module: hyperswitch_connectors pub fn extract_token_from_body(body: &[u8]) -> CustomResult<String, errors::ConnectorError>
crates/hyperswitch_connectors/src/connectors/dwolla/transformers.rs
hyperswitch_connectors
function_signature
null
null
null
59
extract_token_from_body
null
null
null
null
null
null
// Implementation: impl ConnectorSpecifications for for Cryptopay // File: crates/hyperswitch_connectors/src/connectors/cryptopay.rs // Module: hyperswitch_connectors // Methods: 3 total (0 public) impl ConnectorSpecifications for for Cryptopay
crates/hyperswitch_connectors/src/connectors/cryptopay.rs
hyperswitch_connectors
impl_block
null
null
null
57
null
Cryptopay
ConnectorSpecifications for
3
0
null
null
// Function: get_action // File: crates/router/src/core/webhooks/recovery_incoming.rs // Module: router pub fn get_action( event_type: webhooks::IncomingWebhookEvent, attempt_triggered_by: Option<common_enums::TriggeredBy>, ) -> common_types::payments::RecoveryAction
crates/router/src/core/webhooks/recovery_incoming.rs
router
function_signature
null
null
null
68
get_action
null
null
null
null
null
null
// Implementation: impl api::Refund for for Cryptopay // File: crates/hyperswitch_connectors/src/connectors/cryptopay.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::Refund for for Cryptopay
crates/hyperswitch_connectors/src/connectors/cryptopay.rs
hyperswitch_connectors
impl_block
null
null
null
61
null
Cryptopay
api::Refund for
0
0
null
null
// Implementation: impl PaymentVoid for for Threedsecureio // File: crates/hyperswitch_connectors/src/connectors/threedsecureio.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl PaymentVoid for for Threedsecureio
crates/hyperswitch_connectors/src/connectors/threedsecureio.rs
hyperswitch_connectors
impl_block
null
null
null
59
null
Threedsecureio
PaymentVoid for
0
0
null
null
// Function: process_payment_attempt // File: crates/router/src/routes/dummy_connector/utils.rs // Module: router pub fn process_payment_attempt( state: &SessionState, payment_attempt: types::DummyConnectorPaymentAttempt, ) -> types::DummyConnectorResult<Self>
crates/router/src/routes/dummy_connector/utils.rs
router
function_signature
null
null
null
59
process_payment_attempt
null
null
null
null
null
null
// Function: user_signup_with_merchant_id // File: crates/router/src/routes/user.rs // Module: router pub fn user_signup_with_merchant_id( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<user_api::SignUpWithMerchantIdRequest>, query: web::Query<user_api::AuthIdAndThemeIdQueryParam>, ) -> HttpResponse
crates/router/src/routes/user.rs
router
function_signature
null
null
null
86
user_signup_with_merchant_id
null
null
null
null
null
null
// File: crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs // Module: hyperswitch_connectors // Public functions: 1 // Public structs: 55 use std::collections::BTreeMap; use api_models::{payments::AdditionalPaymentData, webhooks::IncomingWebhookEvent}; use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::{Encode, OptionExt, ValueExt}, id_type::CustomerId, pii::Email, request::Method, types::FloatMajorUnit, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{Card, PaymentMethodData, WalletData}, router_data::{ AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, ErrorResponse, RouterData, }, router_flow_types::RSync, router_request_types::ResponseId, router_response_types::{ ConnectorCustomerResponseData, MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, }, types::{ ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefundsRouterData, SetupMandateRouterData, }, }; use hyperswitch_interfaces::errors; use masking::{ExposeInterface, PeekInterface, Secret, StrongSecret}; use rand::distributions::{Alphanumeric, DistString}; use regex::Regex; use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ self, CardData, ForeignTryFrom, PaymentsAuthorizeRequestData, PaymentsSyncRequestData, RefundsRequestData, RouterData as OtherRouterData, WalletData as OtherWalletData, }, }; const MAX_ID_LENGTH: usize = 20; fn get_random_string() -> String { Alphanumeric.sample_string(&mut rand::thread_rng(), MAX_ID_LENGTH) } #[derive(Debug, Serialize)] pub enum TransactionType { #[serde(rename = "authCaptureTransaction")] Payment, #[serde(rename = "authOnlyTransaction")] Authorization, #[serde(rename = "priorAuthCaptureTransaction")] Capture, #[serde(rename = "refundTransaction")] Refund, #[serde(rename = "voidTransaction")] Void, #[serde(rename = "authOnlyContinueTransaction")] ContinueAuthorization, #[serde(rename = "authCaptureContinueTransaction")] ContinueCapture, } #[derive(Debug, Serialize)] pub struct AuthorizedotnetRouterData<T> { pub amount: FloatMajorUnit, pub router_data: T, } impl<T> TryFrom<(FloatMajorUnit, T)> for AuthorizedotnetRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from((amount, item): (FloatMajorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data: item, }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthorizedotnetAuthType { name: Secret<String>, transaction_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for AuthorizedotnetAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type { Ok(Self { name: api_key.to_owned(), transaction_key: key1.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? } } } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct CreditCardDetails { card_number: StrongSecret<String, cards::CardNumberStrategy>, expiration_date: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] card_code: Option<Secret<String>>, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] enum PaymentDetails { CreditCard(CreditCardDetails), OpaqueData(WalletDetails), PayPal(PayPalDetails), } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct PayPalDetails { pub success_url: Option<String>, pub cancel_url: Option<String>, } #[derive(Serialize, Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WalletDetails { pub data_descriptor: WalletMethod, pub data_value: Secret<String>, } #[derive(Serialize, Debug, Deserialize)] pub enum WalletMethod { #[serde(rename = "COMMON.GOOGLE.INAPP.PAYMENT")] Googlepay, #[serde(rename = "COMMON.APPLE.INAPP.PAYMENT")] Applepay, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct TransactionRequest { transaction_type: TransactionType, amount: FloatMajorUnit, currency_code: common_enums::Currency, #[serde(skip_serializing_if = "Option::is_none")] payment: Option<PaymentDetails>, #[serde(skip_serializing_if = "Option::is_none")] profile: Option<ProfileDetails>, order: Order, #[serde(skip_serializing_if = "Option::is_none")] customer: Option<CustomerDetails>, #[serde(skip_serializing_if = "Option::is_none")] bill_to: Option<BillTo>, #[serde(skip_serializing_if = "Option::is_none")] user_fields: Option<UserFields>, #[serde(skip_serializing_if = "Option::is_none")] processing_options: Option<ProcessingOptions>, #[serde(skip_serializing_if = "Option::is_none")] subsequent_auth_information: Option<SubsequentAuthInformation>, authorization_indicator_type: Option<AuthorizationIndicator>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct UserFields { user_field: Vec<UserField>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct UserField { name: String, value: String, } #[derive(Serialize, Deserialize, Debug)] #[serde(untagged)] enum ProfileDetails { CreateProfileDetails(CreateProfileDetails), CustomerProfileDetails(CustomerProfileDetails), } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct CreateProfileDetails { create_profile: bool, #[serde(skip_serializing_if = "Option::is_none")] customer_profile_id: Option<Secret<String>>, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct CustomerProfileDetails { customer_profile_id: Secret<String>, payment_profile: PaymentProfileDetails, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct PaymentProfileDetails { payment_profile_id: Secret<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CustomerDetails { id: String, email: Option<Email>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProcessingOptions { is_subsequent_auth: bool, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BillTo { first_name: Option<Secret<String>>, last_name: Option<Secret<String>>, address: Option<Secret<String>>, city: Option<String>, state: Option<Secret<String>>, zip: Option<Secret<String>>, country: Option<enums::CountryAlpha2>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Order { invoice_number: String, description: String, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct SubsequentAuthInformation { original_network_trans_id: Secret<String>, // original_auth_amount: String, Required for Discover, Diners Club, JCB, and China Union Pay transactions. reason: Reason, } #[derive(Debug, Serialize)] #[serde(rename_all = "lowercase")] pub enum Reason { Resubmission, #[serde(rename = "delayedCharge")] DelayedCharge, Reauthorization, #[serde(rename = "noShow")] NoShow, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct AuthorizationIndicator { authorization_indicator: AuthorizationType, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct TransactionVoidOrCaptureRequest { transaction_type: TransactionType, #[serde(skip_serializing_if = "Option::is_none")] amount: Option<FloatMajorUnit>, ref_trans_id: String, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthorizedotnetPaymentsRequest { merchant_authentication: AuthorizedotnetAuthType, ref_id: Option<String>, transaction_request: TransactionRequest, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthorizedotnetPaymentCancelOrCaptureRequest { merchant_authentication: AuthorizedotnetAuthType, transaction_request: TransactionVoidOrCaptureRequest, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] // The connector enforces field ordering, it expects fields to be in the same order as in their API documentation pub struct CustomerRequest { create_customer_profile_request: CreateCustomerRequest, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CreateCustomerRequest { merchant_authentication: AuthorizedotnetAuthType, profile: Profile, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CreateCustomerPaymentProfileRequest { create_customer_payment_profile_request: AuthorizedotnetPaymentProfileRequest, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthorizedotnetPaymentProfileRequest { merchant_authentication: AuthorizedotnetAuthType, customer_profile_id: Secret<String>, payment_profile: PaymentProfile, validation_mode: ValidationMode, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ShipToList { #[serde(skip_serializing_if = "Option::is_none")] first_name: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] last_name: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] address: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] city: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] state: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] zip: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] country: Option<enums::CountryAlpha2>, #[serde(skip_serializing_if = "Option::is_none")] phone_number: Option<Secret<String>>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct Profile { #[serde(skip_serializing_if = "Option::is_none")] merchant_customer_id: Option<CustomerId>, #[serde(skip_serializing_if = "Option::is_none")] description: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] email: Option<Email>, #[serde(skip_serializing_if = "Option::is_none")] payment_profiles: Option<PaymentProfiles>, #[serde(skip_serializing_if = "Option::is_none")] ship_to_list: Option<Vec<ShipToList>>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct PaymentProfiles { customer_type: CustomerType, #[serde(skip_serializing_if = "Option::is_none")] bill_to: Option<BillTo>, payment: PaymentDetails, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct PaymentProfile { #[serde(skip_serializing_if = "Option::is_none")] bill_to: Option<BillTo>, payment: PaymentDetails, } #[derive(Debug, Serialize)] #[serde(rename_all = "lowercase")] pub enum CustomerType { Individual, Business, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub enum ValidationMode { // testMode performs a Luhn mod-10 check on the card number, without further validation at connector. TestMode, // liveMode submits a zero-dollar or one-cent transaction (depending on card type and processor support) to confirm that the card number belongs to an active credit or debit account. LiveMode, } impl ForeignTryFrom<Value> for Vec<UserField> { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(metadata: Value) -> Result<Self, Self::Error> { let hashmap: BTreeMap<String, Value> = serde_json::from_str(&metadata.to_string()) .change_context(errors::ConnectorError::RequestEncodingFailedWithReason( "Failed to serialize request metadata".to_owned(), )) .attach_printable("")?; let mut vector: Self = Self::new(); for (key, value) in hashmap { vector.push(UserField { name: key, value: value.to_string(), }); } Ok(vector) } } impl TryFrom<&ConnectorCustomerRouterData> for CustomerRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &ConnectorCustomerRouterData) -> Result<Self, Self::Error> { let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?; let ship_to_list = item.get_optional_shipping().and_then(|shipping| { shipping.address.as_ref().map(|address| { vec![ShipToList { first_name: address.first_name.clone(), last_name: address.last_name.clone(), address: address.line1.clone(), city: address.city.clone(), state: address.state.clone(), zip: address.zip.clone(), country: address.country, phone_number: shipping .phone .as_ref() .and_then(|phone| phone.number.as_ref().map(|number| number.to_owned())), }] }) }); let merchant_customer_id = match item.customer_id.as_ref() { Some(cid) if cid.get_string_repr().len() <= MAX_ID_LENGTH => Some(cid.clone()), _ => None, }; Ok(Self { create_customer_profile_request: CreateCustomerRequest { merchant_authentication, profile: Profile { merchant_customer_id, description: None, email: item.request.email.clone(), payment_profiles: None, ship_to_list, }, }, }) } } impl TryFrom<&SetupMandateRouterData> for CreateCustomerPaymentProfileRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> { let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?; let validation_mode = match item.test_mode { Some(true) | None => ValidationMode::TestMode, Some(false) => ValidationMode::LiveMode, }; let customer_profile_id = item.get_connector_customer_id()?.into(); let bill_to = item .get_optional_billing() .and_then(|billing_address| billing_address.address.as_ref()) .map(|address| BillTo { first_name: address.first_name.clone(), last_name: address.last_name.clone(), address: address.line1.clone(), city: address.city.clone(), state: address.state.clone(), zip: address.zip.clone(), country: address.country, }); let payment_profile = match item.request.payment_method_data.clone() { PaymentMethodData::Card(ccard) => Ok(PaymentProfile { bill_to, payment: PaymentDetails::CreditCard(CreditCardDetails { card_number: (*ccard.card_number).clone(), expiration_date: ccard.get_expiry_date_as_yyyymm("-"), card_code: Some(ccard.card_cvc.clone()), }), }), PaymentMethodData::Wallet(wallet_data) => match wallet_data { WalletData::GooglePay(_) => Ok(PaymentProfile { bill_to, payment: PaymentDetails::OpaqueData(WalletDetails { data_descriptor: WalletMethod::Googlepay, data_value: Secret::new(wallet_data.get_encoded_wallet_token()?), }), }), WalletData::ApplePay(applepay_token) => { let apple_pay_encrypted_data = applepay_token .payment_data .get_encrypted_apple_pay_payment_data_mandatory() .change_context(errors::ConnectorError::MissingRequiredField { field_name: "Apple pay encrypted data", })?; Ok(PaymentProfile { bill_to, payment: PaymentDetails::OpaqueData(WalletDetails { data_descriptor: WalletMethod::Applepay, data_value: Secret::new(apple_pay_encrypted_data.clone()), }), }) } WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::BluecodeRedirect {} | WalletData::Skrill(_) | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MbWayRedirect(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalRedirect(_) | WalletData::AmazonPay(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::Mifinity(_) | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("authorizedotnet"), )), }, PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("authorizedotnet"), )) } }?; Ok(Self { create_customer_payment_profile_request: AuthorizedotnetPaymentProfileRequest { merchant_authentication, customer_profile_id, payment_profile, validation_mode, }, }) } } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthorizedotnetSetupMandateResponse { #[serde(default, skip_serializing_if = "Vec::is_empty")] customer_payment_profile_id_list: Vec<String>, customer_profile_id: Option<String>, #[serde(rename = "customerPaymentProfileId")] customer_payment_profile_id: Option<String>, validation_direct_response_list: Option<Vec<Secret<String>>>, pub messages: ResponseMessages, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthorizedotnetCustomerResponse { customer_profile_id: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] customer_payment_profile_id_list: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] customer_shipping_address_id_list: Vec<String>, pub messages: ResponseMessages, } fn extract_customer_id(text: &str) -> Option<String> { let re = Regex::new(r"ID (\d+)").ok()?; re.captures(text) .and_then(|captures| captures.get(1)) .map(|capture_match| capture_match.as_str().to_string()) } impl<F, T> TryFrom<ResponseRouterData<F, AuthorizedotnetCustomerResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, AuthorizedotnetCustomerResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { match item.response.messages.result_code { ResultCode::Ok => match item.response.customer_profile_id.clone() { Some(connector_customer_id) => Ok(Self { response: Ok(PaymentsResponseData::ConnectorCustomerResponse( ConnectorCustomerResponseData::new_with_customer_id(connector_customer_id), )), ..item.data }), None => Err( errors::ConnectorError::UnexpectedResponseError(bytes::Bytes::from( "Missing customer profile id from Authorizedotnet".to_string(), )) .into(), ), }, ResultCode::Error => { let error_message = item.response.messages.message.first(); if let Some(connector_customer_id) = error_message.and_then(|error| extract_customer_id(&error.text)) { Ok(Self { response: Ok(PaymentsResponseData::ConnectorCustomerResponse( ConnectorCustomerResponseData::new_with_customer_id( connector_customer_id, ), )), ..item.data }) } else { let error_code = error_message.map(|error| error.code.clone()); let error_code = error_code.unwrap_or_else(|| { hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string() }); let error_reason = item .response .messages .message .iter() .map(|error: &ResponseMessage| error.text.clone()) .collect::<Vec<String>>() .join(" "); let response = Err(ErrorResponse { code: error_code, message: item.response.messages.result_code.to_string(), reason: Some(error_reason), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }); Ok(Self { response, status: enums::AttemptStatus::Failure, ..item.data }) } } } } } // zero dollar response impl<F, T> TryFrom<ResponseRouterData<F, AuthorizedotnetSetupMandateResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, AuthorizedotnetSetupMandateResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let connector_customer_id = item.data.get_connector_customer_id()?; if item.response.customer_profile_id.is_some() { Ok(Self { status: enums::AttemptStatus::Charged, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(Some(MandateReference { connector_mandate_id: item .response .customer_payment_profile_id_list .first() .or(item.response.customer_payment_profile_id.as_ref()) .map(|payment_profile_id| { format!("{connector_customer_id}-{payment_profile_id}") }), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, })), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } else { let error_message = item.response.messages.message.first(); let error_code = error_message.map(|error| error.code.clone()); let error_code = error_code .unwrap_or_else(|| hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()); let error_reason = item .response .messages .message .iter() .map(|error: &ResponseMessage| error.text.clone()) .collect::<Vec<String>>() .join(" "); let response = Err(ErrorResponse { code: error_code, message: item.response.messages.result_code.to_string(), reason: Some(error_reason), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }); Ok(Self { response, status: enums::AttemptStatus::Failure, ..item.data }) } } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] // The connector enforces field ordering, it expects fields to be in the same order as in their API documentation pub struct CreateTransactionRequest { create_transaction_request: AuthorizedotnetPaymentsRequest, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CancelOrCaptureTransactionRequest { create_transaction_request: AuthorizedotnetPaymentCancelOrCaptureRequest, } #[derive(Debug, Serialize)] #[serde(rename_all = "lowercase")] pub enum AuthorizationType { Final, Pre, } impl TryFrom<enums::CaptureMethod> for AuthorizationType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(capture_method: enums::CaptureMethod) -> Result<Self, Self::Error> { match capture_method { enums::CaptureMethod::Manual => Ok(Self::Pre), enums::CaptureMethod::SequentialAutomatic | enums::CaptureMethod::Automatic => { Ok(Self::Final) } enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( utils::construct_not_supported_error_report(capture_method, "authorizedotnet"), )?, } } } impl TryFrom<&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>> for CreateTransactionRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?; let ref_id = if item.router_data.connector_request_reference_id.len() <= MAX_ID_LENGTH { Some(item.router_data.connector_request_reference_id.clone()) } else { None }; let transaction_request = match item .router_data .request .mandate_id .clone() .and_then(|mandate_ids| mandate_ids.mandate_reference_id) { Some(api_models::payments::MandateReferenceId::NetworkMandateId(network_trans_id)) => { TransactionRequest::try_from((item, network_trans_id))? } Some(api_models::payments::MandateReferenceId::ConnectorMandateId( connector_mandate_id, )) => TransactionRequest::try_from((item, connector_mandate_id))?, Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_)) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("authorizedotnet"), ))? } None => { match &item.router_data.request.payment_method_data { PaymentMethodData::Card(ccard) => TransactionRequest::try_from((item, ccard)), PaymentMethodData::Wallet(wallet_data) => { TransactionRequest::try_from((item, wallet_data)) } PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message( "authorizedotnet", ), ))? } } }?, }; Ok(Self { create_transaction_request: AuthorizedotnetPaymentsRequest { merchant_authentication, ref_id, transaction_request, }, }) } } impl TryFrom<( &AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>, String, )> for TransactionRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, network_trans_id): ( &AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>, String, ), ) -> Result<Self, Self::Error> { Ok(Self { transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?, amount: item.amount, currency_code: item.router_data.request.currency, payment: Some(match item.router_data.request.payment_method_data { PaymentMethodData::Card(ref ccard) => { PaymentDetails::CreditCard(CreditCardDetails { card_number: (*ccard.card_number).clone(), expiration_date: ccard.get_expiry_date_as_yyyymm("-"), card_code: None, }) } PaymentMethodData::CardRedirect(_) | PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("authorizedotnet"), ))? } }), profile: None, order: Order { invoice_number: match &item.router_data.request.merchant_order_reference_id { Some(merchant_order_reference_id) => { if merchant_order_reference_id.len() <= MAX_ID_LENGTH { merchant_order_reference_id.to_string() } else { get_random_string() } } None => get_random_string(), }, description: item.router_data.connector_request_reference_id.clone(), }, customer: Some(CustomerDetails { id: if item.router_data.payment_id.len() <= MAX_ID_LENGTH { item.router_data.payment_id.clone() } else { get_random_string() }, email: item.router_data.request.get_optional_email(), }), bill_to: item .router_data .get_optional_billing() .and_then(|billing_address| billing_address.address.as_ref()) .map(|address| BillTo { first_name: address.first_name.clone(), last_name: address.last_name.clone(), address: address.line1.clone(), city: address.city.clone(), state: address.state.clone(), zip: address.zip.clone(), country: address.country, }), user_fields: match item.router_data.request.metadata.clone() { Some(metadata) => Some(UserFields { user_field: Vec::<UserField>::foreign_try_from(metadata)?, }), None => None, }, processing_options: Some(ProcessingOptions { is_subsequent_auth: true, }), subsequent_auth_information: Some(SubsequentAuthInformation { original_network_trans_id: Secret::new(network_trans_id), reason: Reason::Resubmission, }), authorization_indicator_type: match item.router_data.request.capture_method { Some(capture_method) => Some(AuthorizationIndicator { authorization_indicator: capture_method.try_into()?, }), None => None, }, }) } } impl TryFrom<( &AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>, api_models::payments::ConnectorMandateReferenceId, )> for TransactionRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, connector_mandate_id): ( &AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>, api_models::payments::ConnectorMandateReferenceId, ), ) -> Result<Self, Self::Error> { let mandate_id = connector_mandate_id .get_connector_mandate_id() .ok_or(errors::ConnectorError::MissingConnectorMandateID)?; Ok(Self { transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?, amount: item.amount, currency_code: item.router_data.request.currency, payment: None, profile: mandate_id .split_once('-') .map(|(customer_profile_id, payment_profile_id)| { ProfileDetails::CustomerProfileDetails(CustomerProfileDetails { customer_profile_id: Secret::from(customer_profile_id.to_string()), payment_profile: PaymentProfileDetails { payment_profile_id: Secret::from(payment_profile_id.to_string()), }, }) }), order: Order { invoice_number: match &item.router_data.request.merchant_order_reference_id { Some(merchant_order_reference_id) => { if merchant_order_reference_id.len() <= MAX_ID_LENGTH { merchant_order_reference_id.to_string() } else { get_random_string() } } None => get_random_string(), }, description: item.router_data.connector_request_reference_id.clone(), }, customer: None, bill_to: None, user_fields: match item.router_data.request.metadata.clone() { Some(metadata) => Some(UserFields { user_field: Vec::<UserField>::foreign_try_from(metadata)?, }), None => None, }, processing_options: Some(ProcessingOptions { is_subsequent_auth: true, }), subsequent_auth_information: None, authorization_indicator_type: match item.router_data.request.capture_method { Some(capture_method) => Some(AuthorizationIndicator { authorization_indicator: capture_method.try_into()?, }), None => None, }, }) } } impl TryFrom<( &AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>, &Card, )> for TransactionRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, ccard): ( &AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>, &Card, ), ) -> Result<Self, Self::Error> { let profile = if item .router_data .request .is_customer_initiated_mandate_payment() { let connector_customer_id = Secret::new(item.router_data.connector_customer.clone().ok_or( errors::ConnectorError::MissingConnectorRelatedTransactionID { id: "connector_customer_id".to_string(), }, )?); Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails { create_profile: true, customer_profile_id: Some(connector_customer_id), })) } else { None }; let customer = if !item .router_data .request .is_customer_initiated_mandate_payment() { item.router_data.customer_id.as_ref().and_then(|customer| { let customer_id = customer.get_string_repr(); (customer_id.len() <= MAX_ID_LENGTH).then_some(CustomerDetails { id: customer_id.to_string(), email: item.router_data.request.get_optional_email(), }) }) } else { None }; Ok(Self { transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?, amount: item.amount, currency_code: item.router_data.request.currency, payment: Some(PaymentDetails::CreditCard(CreditCardDetails { card_number: (*ccard.card_number).clone(), expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs#chunk0
hyperswitch_connectors
chunk
null
null
null
8,183
null
null
null
null
null
null
null
// Struct: PaymentsResPaymentInstrument // File: crates/hyperswitch_connectors/src/connectors/worldpay/response.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PaymentsResPaymentInstrument
crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
hyperswitch_connectors
struct_definition
PaymentsResPaymentInstrument
0
[]
47
null
null
null
null
null
null
null
domain::payments::BankRedirectData::OnlineBankingSlovakia { .. } => { Self::OnlineBankingSlovakia } domain::payments::BankRedirectData::OpenBankingUk { .. } => Self::OpenBankingUk, domain::payments::BankRedirectData::Przelewy24 { .. } => Self::Przelewy24, domain::payments::BankRedirectData::Sofort { .. } => Self::Sofort, domain::payments::BankRedirectData::Trustly { .. } => Self::Trustly, domain::payments::BankRedirectData::OnlineBankingFpx { .. } => { Self::OnlineBankingFpx } domain::payments::BankRedirectData::OnlineBankingThailand { .. } => { Self::OnlineBankingThailand } domain::payments::BankRedirectData::LocalBankRedirect { } => { Self::LocalBankRedirect } } } domain::payments::PaymentMethodData::BankDebit(bank_debit_data) => { match bank_debit_data { domain::payments::BankDebitData::AchBankDebit { .. } => Self::AchBankDebit, domain::payments::BankDebitData::SepaBankDebit { .. } => Self::SepaBankDebit, domain::payments::BankDebitData::BecsBankDebit { .. } => Self::BecsBankDebit, domain::payments::BankDebitData::BacsBankDebit { .. } => Self::BacsBankDebit, } } domain::payments::PaymentMethodData::BankTransfer(bank_transfer_data) => { match *bank_transfer_data { domain::payments::BankTransferData::AchBankTransfer { .. } => { Self::AchBankTransfer } domain::payments::BankTransferData::SepaBankTransfer { .. } => { Self::SepaBankTransfer } domain::payments::BankTransferData::BacsBankTransfer { .. } => { Self::BacsBankTransfer } domain::payments::BankTransferData::MultibancoBankTransfer { .. } => { Self::MultibancoBankTransfer } domain::payments::BankTransferData::PermataBankTransfer { .. } => { Self::PermataBankTransfer } domain::payments::BankTransferData::BcaBankTransfer { .. } => { Self::BcaBankTransfer } domain::payments::BankTransferData::BniVaBankTransfer { .. } => { Self::BniVaBankTransfer } domain::payments::BankTransferData::BriVaBankTransfer { .. } => { Self::BriVaBankTransfer } domain::payments::BankTransferData::CimbVaBankTransfer { .. } => { Self::CimbVaBankTransfer } domain::payments::BankTransferData::DanamonVaBankTransfer { .. } => { Self::DanamonVaBankTransfer } domain::payments::BankTransferData::MandiriVaBankTransfer { .. } => { Self::MandiriVaBankTransfer } domain::payments::BankTransferData::Pix { .. } => Self::Pix, domain::payments::BankTransferData::Pse {} => Self::Pse, domain::payments::BankTransferData::LocalBankTransfer { .. } => { Self::LocalBankTransfer } domain::payments::BankTransferData::InstantBankTransfer {} => { Self::InstantBankTransfer } domain::payments::BankTransferData::InstantBankTransferFinland {} => { Self::InstantBankTransferFinland } domain::payments::BankTransferData::InstantBankTransferPoland {} => { Self::InstantBankTransferPoland } domain::payments::BankTransferData::IndonesianBankTransfer { .. } => { Self::IndonesianBankTransfer } } } domain::payments::PaymentMethodData::Crypto(_) => Self::Crypto, domain::payments::PaymentMethodData::MandatePayment => Self::MandatePayment, domain::payments::PaymentMethodData::Reward => Self::Reward, domain::payments::PaymentMethodData::Upi(_) => Self::Upi, domain::payments::PaymentMethodData::Voucher(voucher_data) => match voucher_data { domain::payments::VoucherData::Boleto(_) => Self::Boleto, domain::payments::VoucherData::Efecty => Self::Efecty, domain::payments::VoucherData::PagoEfectivo => Self::PagoEfectivo, domain::payments::VoucherData::RedCompra => Self::RedCompra, domain::payments::VoucherData::RedPagos => Self::RedPagos, domain::payments::VoucherData::Alfamart(_) => Self::Alfamart, domain::payments::VoucherData::Indomaret(_) => Self::Indomaret, domain::payments::VoucherData::Oxxo => Self::Oxxo, domain::payments::VoucherData::SevenEleven(_) => Self::SevenEleven, domain::payments::VoucherData::Lawson(_) => Self::Lawson, domain::payments::VoucherData::MiniStop(_) => Self::MiniStop, domain::payments::VoucherData::FamilyMart(_) => Self::FamilyMart, domain::payments::VoucherData::Seicomart(_) => Self::Seicomart, domain::payments::VoucherData::PayEasy(_) => Self::PayEasy, }, domain::PaymentMethodData::RealTimePayment(real_time_payment_data) => match *real_time_payment_data{ hyperswitch_domain_models::payment_method_data::RealTimePaymentData::DuitNow { } => Self::DuitNow, hyperswitch_domain_models::payment_method_data::RealTimePaymentData::Fps { } => Self::Fps, hyperswitch_domain_models::payment_method_data::RealTimePaymentData::PromptPay { } => Self::PromptPay, hyperswitch_domain_models::payment_method_data::RealTimePaymentData::VietQr { } => Self::VietQr, }, domain::payments::PaymentMethodData::GiftCard(gift_card_data) => { match *gift_card_data { domain::payments::GiftCardData::Givex(_) => Self::Givex, domain::payments::GiftCardData::BhnCardNetwork(_)=>Self::BhnCardNetwork, domain::payments::GiftCardData::PaySafeCard {} => Self::PaySafeCar, } } domain::payments::PaymentMethodData::CardToken(_) => Self::CardToken, domain::payments::PaymentMethodData::OpenBanking(data) => match data { hyperswitch_domain_models::payment_method_data::OpenBankingData::OpenBankingPIS { } => Self::OpenBanking }, domain::payments::PaymentMethodData::MobilePayment(mobile_payment_data) => match mobile_payment_data { hyperswitch_domain_models::payment_method_data::MobilePaymentData::DirectCarrierBilling { .. } => Self::DirectCarrierBilling, }, } } } pub fn convert_amount<T>( amount_convertor: &dyn AmountConvertor<Output = T>, amount: MinorUnit, currency: enums::Currency, ) -> Result<T, error_stack::Report<errors::ConnectorError>> { amount_convertor .convert(amount, currency) .change_context(errors::ConnectorError::AmountConversionFailed) } pub fn convert_back_amount_to_minor_units<T>( amount_convertor: &dyn AmountConvertor<Output = T>, amount: T, currency: enums::Currency, ) -> Result<MinorUnit, error_stack::Report<errors::ConnectorError>> { amount_convertor .convert_back(amount, currency) .change_context(errors::ConnectorError::AmountConversionFailed) } pub trait NetworkTokenData { fn get_card_issuer(&self) -> Result<CardIssuer, Error>; fn get_expiry_year_4_digit(&self) -> Secret<String>; fn get_network_token(&self) -> NetworkTokenNumber; fn get_network_token_expiry_month(&self) -> Secret<String>; fn get_network_token_expiry_year(&self) -> Secret<String>; fn get_cryptogram(&self) -> Option<Secret<String>>; } impl NetworkTokenData for domain::NetworkTokenData { #[cfg(feature = "v1")] fn get_card_issuer(&self) -> Result<CardIssuer, Error> { get_card_issuer(self.token_number.peek()) } #[cfg(feature = "v2")] fn get_card_issuer(&self) -> Result<CardIssuer, Error> { get_card_issuer(self.network_token.peek()) } #[cfg(feature = "v1")] fn get_expiry_year_4_digit(&self) -> Secret<String> { let mut year = self.token_exp_year.peek().clone(); if year.len() == 2 { year = format!("20{year}"); } Secret::new(year) } #[cfg(feature = "v2")] fn get_expiry_year_4_digit(&self) -> Secret<String> { let mut year = self.network_token_exp_year.peek().clone(); if year.len() == 2 { year = format!("20{year}"); } Secret::new(year) } #[cfg(feature = "v1")] fn get_network_token(&self) -> NetworkTokenNumber { self.token_number.clone() } #[cfg(feature = "v2")] fn get_network_token(&self) -> NetworkTokenNumber { self.network_token.clone() } #[cfg(feature = "v1")] fn get_network_token_expiry_month(&self) -> Secret<String> { self.token_exp_month.clone() } #[cfg(feature = "v2")] fn get_network_token_expiry_month(&self) -> Secret<String> { self.network_token_exp_month.clone() } #[cfg(feature = "v1")] fn get_network_token_expiry_year(&self) -> Secret<String> { self.token_exp_year.clone() } #[cfg(feature = "v2")] fn get_network_token_expiry_year(&self) -> Secret<String> { self.network_token_exp_year.clone() } #[cfg(feature = "v1")] fn get_cryptogram(&self) -> Option<Secret<String>> { self.token_cryptogram.clone() } #[cfg(feature = "v2")] fn get_cryptogram(&self) -> Option<Secret<String>> { self.cryptogram.clone() } } pub fn convert_uppercase<'de, D, T>(v: D) -> Result<T, D::Error> where D: serde::Deserializer<'de>, T: FromStr, <T as FromStr>::Err: std::fmt::Debug + std::fmt::Display + std::error::Error, { use serde::de::Error; let output = <&str>::deserialize(v)?; output.to_uppercase().parse::<T>().map_err(D::Error::custom) }
crates/router/src/connector/utils.rs#chunk3
router
chunk
null
null
null
2,450
null
null
null
null
null
null
null
UploadFileRequestData, UploadFileResponse, > for $path::$connector {} impl RetrieveFile for $path::$connector {} impl ConnectorIntegration< Retrieve, RetrieveFileRequestData, RetrieveFileResponse, > for $path::$connector {} )* }; } default_imp_for_file_upload!( connectors::Vgs, connectors::Aci, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Bluecode, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_payouts { ($($path:ident::$connector:ident),*) => { $( impl api::Payouts for $path::$connector {} )* }; } default_imp_for_payouts!( connectors::Paysafe, connectors::Affirm, connectors::Vgs, connectors::Aci, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Bluecode, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Cryptopay, connectors::Datatrans, connectors::Coinbase, connectors::Coingate, connectors::Custombilling, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Nexinets, connectors::Nexixpay, connectors::Nordea, connectors::Opayo, connectors::Opennode, connectors::Paybox, connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Square, connectors::Stax, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Volt, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_create { ($($path:ident::$connector:ident),*) => { $( impl PayoutCreate for $path::$connector {} impl ConnectorIntegration< PoCreate, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_payouts_create!( connectors::Paysafe, connectors::Vgs, connectors::Aci, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Bluecode, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Nordea, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_retrieve { ($($path:ident::$connector:ident),*) => { $( impl PayoutSync for $path::$connector {} impl ConnectorIntegration< PoSync, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_payouts_retrieve!( connectors::Paysafe, connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Bluecode, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Payone, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_eligibility { ($($path:ident::$connector:ident),*) => { $( impl PayoutEligibility for $path::$connector {} impl ConnectorIntegration< PoEligibility, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_payouts_eligibility!( connectors::Vgs, connectors::Aci, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Bluecode, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payone, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_fulfill { ($($path:ident::$connector:ident),*) => { $( impl PayoutFulfill for $path::$connector {} impl ConnectorIntegration< PoFulfill, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_payouts_fulfill!( connectors::Paysafe, connectors::Affirm, connectors::Vgs, connectors::Aci, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Bluecode, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nmi, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_cancel { ($($path:ident::$connector:ident),*) => { $( impl PayoutCancel for $path::$connector {} impl ConnectorIntegration< PoCancel, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_payouts_cancel!( connectors::Vgs, connectors::Aci, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Bluecode, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payone, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_quote { ($($path:ident::$connector:ident),*) => { $( impl PayoutQuote for $path::$connector {} impl ConnectorIntegration< PoQuote, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_payouts_quote!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Bluecode, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payone, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_recipient { ($($path:ident::$connector:ident),*) => { $( impl PayoutRecipient for $path::$connector {} impl ConnectorIntegration< PoRecipient, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_payouts_recipient!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Bluecode, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme,
crates/hyperswitch_connectors/src/default_implementations.rs#chunk3
hyperswitch_connectors
chunk
null
null
null
8,188
null
null
null
null
null
null
null
// Struct: Volt // File: crates/hyperswitch_connectors/src/connectors/volt.rs // Module: hyperswitch_connectors // Implementations: 17 // Traits: api::Payment, api::PaymentSession, api::ConnectorAccessToken, api::MandateSetup, api::PaymentAuthorize, api::PaymentSync, api::PaymentCapture, api::PaymentVoid, api::Refund, api::RefundExecute, api::RefundSync, api::PaymentToken, ConnectorCommon, ConnectorValidation, webhooks::IncomingWebhook, ConnectorSpecifications pub struct Volt
crates/hyperswitch_connectors/src/connectors/volt.rs
hyperswitch_connectors
struct_definition
Volt
17
[ "api::Payment", "api::PaymentSession", "api::ConnectorAccessToken", "api::MandateSetup", "api::PaymentAuthorize", "api::PaymentSync", "api::PaymentCapture", "api::PaymentVoid", "api::Refund", "api::RefundExecute", "api::RefundSync", "api::PaymentToken", "ConnectorCommon", "ConnectorValidation", "webhooks::IncomingWebhook", "ConnectorSpecifications" ]
123
null
null
null
null
null
null
null
// Implementation: impl api::Payment for for Authorizedotnet // File: crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::Payment for for Authorizedotnet
crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs
hyperswitch_connectors
impl_block
null
null
null
59
null
Authorizedotnet
api::Payment for
0
0
null
null
// File: crates/euclid_wasm/src/lib.rs // Module: euclid_wasm // Public functions: 29 #![allow(non_upper_case_globals)] mod types; mod utils; use std::{ collections::{HashMap, HashSet}, str::FromStr, sync::OnceLock, }; use api_models::{ enums as api_model_enums, routing::ConnectorSelection, surcharge_decision_configs::SurchargeDecisionConfigs, }; use common_enums::RoutableConnectors; use common_types::three_ds_decision_rule_engine::ThreeDSDecisionRule; use connector_configs::{ common_config::{ConnectorApiIntegrationPayload, DashboardRequestPayload}, connector, }; use currency_conversion::{ conversion::convert as convert_currency, types as currency_conversion_types, }; use euclid::{ backend::{inputs, interpreter::InterpreterBackend, EuclidBackend}, dssa::{self, analyzer, graph::CgraphExt, state_machine}, frontend::{ ast, dir::{self, enums as dir_enums, EuclidDirFilter}, }, }; use strum::{EnumMessage, EnumProperty, VariantNames}; use wasm_bindgen::prelude::*; use crate::utils::JsResultExt; type JsResult = Result<JsValue, JsValue>; use api_models::payment_methods::CountryCodeWithName; #[cfg(feature = "payouts")] use common_enums::PayoutStatus; use common_enums::{ CountryAlpha2, DisputeStatus, EventClass, EventType, IntentStatus, MandateStatus, MerchantCategoryCode, MerchantCategoryCodeWithName, RefundStatus, }; use strum::IntoEnumIterator; struct SeedData { cgraph: hyperswitch_constraint_graph::ConstraintGraph<dir::DirValue>, connectors: Vec<ast::ConnectorChoice>, } static SEED_DATA: OnceLock<SeedData> = OnceLock::new(); static SEED_FOREX: OnceLock<currency_conversion_types::ExchangeRates> = OnceLock::new(); /// This function can be used by the frontend to educate wasm about the forex rates data. /// The input argument is a struct fields base_currency and conversion where later is all the conversions associated with the base_currency /// to all different currencies present. #[wasm_bindgen(js_name = setForexData)] pub fn seed_forex(forex: JsValue) -> JsResult { let forex: currency_conversion_types::ExchangeRates = serde_wasm_bindgen::from_value(forex)?; SEED_FOREX .set(forex) .map_err(|_| "Forex has already been seeded".to_string()) .err_to_js()?; Ok(JsValue::NULL) } /// This function can be used to perform currency_conversion on the input amount, from_currency, /// to_currency which are all expected to be one of currencies we already have in our Currency /// enum. #[wasm_bindgen(js_name = convertCurrency)] pub fn convert_forex_value(amount: i64, from_currency: JsValue, to_currency: JsValue) -> JsResult { let forex_data = SEED_FOREX .get() .ok_or("Forex Data not seeded") .err_to_js()?; let from_currency: common_enums::Currency = serde_wasm_bindgen::from_value(from_currency)?; let to_currency: common_enums::Currency = serde_wasm_bindgen::from_value(to_currency)?; let converted_amount = convert_currency(forex_data, from_currency, to_currency, amount) .map_err(|_| "conversion not possible for provided values") .err_to_js()?; Ok(serde_wasm_bindgen::to_value(&converted_amount)?) } /// This function can be used by the frontend to get all the two letter country codes /// along with their country names. #[wasm_bindgen(js_name=getTwoLetterCountryCode)] pub fn get_two_letter_country_code() -> JsResult { let country_code_with_name = CountryAlpha2::iter() .map(|country_code| CountryCodeWithName { code: country_code, name: common_enums::Country::from_alpha2(country_code), }) .collect::<Vec<_>>(); Ok(serde_wasm_bindgen::to_value(&country_code_with_name)?) } /// This function can be used by the frontend to get all the merchant category codes /// along with their names. #[wasm_bindgen(js_name=getMerchantCategoryCodeWithName)] pub fn get_merchant_category_code_with_name() -> JsResult { let merchant_category_codes_with_name = MerchantCategoryCode::iter() .map(|mcc_value| MerchantCategoryCodeWithName { code: mcc_value, name: mcc_value.to_merchant_category_name(), }) .collect::<Vec<_>>(); Ok(serde_wasm_bindgen::to_value( &merchant_category_codes_with_name, )?) } /// This function can be used by the frontend to provide the WASM with information about /// all the merchant's connector accounts. The input argument is a vector of all the merchant's /// connector accounts from the API. #[cfg(feature = "v1")] #[wasm_bindgen(js_name = seedKnowledgeGraph)] pub fn seed_knowledge_graph(mcas: JsValue) -> JsResult { let mcas: Vec<api_models::admin::MerchantConnectorResponse> = serde_wasm_bindgen::from_value(mcas)?; let connectors: Vec<ast::ConnectorChoice> = mcas .iter() .map(|mca| { Ok::<_, strum::ParseError>(ast::ConnectorChoice { connector: RoutableConnectors::from_str(&mca.connector_name)?, }) }) .collect::<Result<_, _>>() .map_err(|_| "invalid connector name received") .err_to_js()?; let pm_filter = kgraph_utils::types::PaymentMethodFilters(HashMap::new()); let config = kgraph_utils::types::CountryCurrencyFilter { connector_configs: HashMap::new(), default_configs: Some(pm_filter), }; let mca_graph = kgraph_utils::mca::make_mca_graph(mcas, &config).err_to_js()?; let analysis_graph = hyperswitch_constraint_graph::ConstraintGraph::combine( &mca_graph, &dssa::truth::ANALYSIS_GRAPH, ) .err_to_js()?; SEED_DATA .set(SeedData { cgraph: analysis_graph, connectors, }) .map_err(|_| "Knowledge Graph has been already seeded".to_string()) .err_to_js()?; Ok(JsValue::NULL) } /// This function allows the frontend to get all the merchant's configured /// connectors that are valid for a rule based on the conditions specified in /// the rule #[wasm_bindgen(js_name = getValidConnectorsForRule)] pub fn get_valid_connectors_for_rule(rule: JsValue) -> JsResult { let seed_data = SEED_DATA.get().ok_or("Data not seeded").err_to_js()?; let rule: ast::Rule<ConnectorSelection> = serde_wasm_bindgen::from_value(rule)?; let dir_rule = ast::lowering::lower_rule(rule).err_to_js()?; let mut valid_connectors: Vec<(ast::ConnectorChoice, dir::DirValue)> = seed_data .connectors .iter() .cloned() .map(|choice| (choice.clone(), dir::DirValue::Connector(Box::new(choice)))) .collect(); let mut invalid_connectors: HashSet<ast::ConnectorChoice> = HashSet::new(); let mut ctx_manager = state_machine::RuleContextManager::new(&dir_rule, &[]); let dummy_meta = HashMap::new(); // For every conjunctive context in the Rule, verify validity of all still-valid connectors // using the knowledge graph while let Some(ctx) = ctx_manager.advance_mut().err_to_js()? { // Standalone conjunctive context analysis to ensure the context itself is valid before // checking it against merchant's connectors seed_data .cgraph .perform_context_analysis( ctx, &mut hyperswitch_constraint_graph::Memoization::new(), None, ) .err_to_js()?; // Update conjunctive context and run analysis on all of merchant's connectors. for (conn, choice) in &valid_connectors { if invalid_connectors.contains(conn) { continue; } let ctx_val = dssa::types::ContextValue::assertion(choice, &dummy_meta); ctx.push(ctx_val); let analysis_result = seed_data.cgraph.perform_context_analysis( ctx, &mut hyperswitch_constraint_graph::Memoization::new(), None, ); if analysis_result.is_err() { invalid_connectors.insert(conn.clone()); } ctx.pop(); } } valid_connectors.retain(|(k, _)| !invalid_connectors.contains(k)); let valid_connectors: Vec<ast::ConnectorChoice> = valid_connectors.into_iter().map(|c| c.0).collect(); Ok(serde_wasm_bindgen::to_value(&valid_connectors)?) } #[wasm_bindgen(js_name = analyzeProgram)] pub fn analyze_program(js_program: JsValue) -> JsResult { let program: ast::Program<ConnectorSelection> = serde_wasm_bindgen::from_value(js_program)?; analyzer::analyze(program, SEED_DATA.get().map(|sd| &sd.cgraph)).err_to_js()?; Ok(JsValue::NULL) } #[wasm_bindgen(js_name = runProgram)] pub fn run_program(program: JsValue, input: JsValue) -> JsResult { let program: ast::Program<ConnectorSelection> = serde_wasm_bindgen::from_value(program)?; let input: inputs::BackendInput = serde_wasm_bindgen::from_value(input)?; let backend = InterpreterBackend::with_program(program).err_to_js()?; let res: euclid::backend::BackendOutput<ConnectorSelection> = backend.execute(input).err_to_js()?; Ok(serde_wasm_bindgen::to_value(&res)?) } #[wasm_bindgen(js_name = getAllConnectors)] pub fn get_all_connectors() -> JsResult { Ok(serde_wasm_bindgen::to_value(RoutableConnectors::VARIANTS)?) } #[wasm_bindgen(js_name = getAllKeys)] pub fn get_all_keys() -> JsResult { let excluded_keys = [ "Connector", // 3DS Decision Rule Keys should not be included in the payument routing keys "issuer_name", "issuer_country", "customer_device_platform", "customer_device_type", "customer_device_display_size", "acquirer_country", "acquirer_fraud_rate", ]; let keys: Vec<&'static str> = dir::DirKeyKind::VARIANTS .iter() .copied() .filter(|s| !excluded_keys.contains(s)) .collect(); Ok(serde_wasm_bindgen::to_value(&keys)?) } #[wasm_bindgen(js_name = getKeyType)] pub fn get_key_type(key: &str) -> Result<String, String> { let key = dir::DirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?; let key_str = key.get_type().to_string(); Ok(key_str) } #[wasm_bindgen(js_name = getThreeDsKeys)] pub fn get_three_ds_keys() -> JsResult { let keys = <common_types::payments::ConditionalConfigs as EuclidDirFilter>::ALLOWED; Ok(serde_wasm_bindgen::to_value(keys)?) } #[wasm_bindgen(js_name= getSurchargeKeys)] pub fn get_surcharge_keys() -> JsResult { let keys = <SurchargeDecisionConfigs as EuclidDirFilter>::ALLOWED; Ok(serde_wasm_bindgen::to_value(keys)?) } #[wasm_bindgen(js_name= getThreeDsDecisionRuleKeys)] pub fn get_three_ds_decision_rule_keys() -> JsResult { let keys = <ThreeDSDecisionRule as EuclidDirFilter>::ALLOWED; Ok(serde_wasm_bindgen::to_value(keys)?) } #[wasm_bindgen(js_name=parseToString)] pub fn parser(val: String) -> String { ron_parser::my_parse(val) } #[wasm_bindgen(js_name = getVariantValues)] pub fn get_variant_values(key: &str) -> Result<JsValue, JsValue> { let key = dir::DirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?; let variants: &[&str] = match key { dir::DirKeyKind::PaymentMethod => dir_enums::PaymentMethod::VARIANTS, dir::DirKeyKind::CardType => dir_enums::CardType::VARIANTS, dir::DirKeyKind::CardNetwork => dir_enums::CardNetwork::VARIANTS, dir::DirKeyKind::PayLaterType => dir_enums::PayLaterType::VARIANTS, dir::DirKeyKind::WalletType => dir_enums::WalletType::VARIANTS, dir::DirKeyKind::BankRedirectType => dir_enums::BankRedirectType::VARIANTS, dir::DirKeyKind::CryptoType => dir_enums::CryptoType::VARIANTS, dir::DirKeyKind::RewardType => dir_enums::RewardType::VARIANTS, dir::DirKeyKind::AuthenticationType => dir_enums::AuthenticationType::VARIANTS, dir::DirKeyKind::CaptureMethod => dir_enums::CaptureMethod::VARIANTS, dir::DirKeyKind::PaymentCurrency => dir_enums::PaymentCurrency::VARIANTS, dir::DirKeyKind::BusinessCountry => dir_enums::Country::VARIANTS, dir::DirKeyKind::BillingCountry => dir_enums::Country::VARIANTS, dir::DirKeyKind::BankTransferType => dir_enums::BankTransferType::VARIANTS, dir::DirKeyKind::UpiType => dir_enums::UpiType::VARIANTS, dir::DirKeyKind::SetupFutureUsage => dir_enums::SetupFutureUsage::VARIANTS, dir::DirKeyKind::PaymentType => dir_enums::PaymentType::VARIANTS, dir::DirKeyKind::MandateType => dir_enums::MandateType::VARIANTS, dir::DirKeyKind::MandateAcceptanceType => dir_enums::MandateAcceptanceType::VARIANTS, dir::DirKeyKind::CardRedirectType => dir_enums::CardRedirectType::VARIANTS, dir::DirKeyKind::GiftCardType => dir_enums::GiftCardType::VARIANTS, dir::DirKeyKind::VoucherType => dir_enums::VoucherType::VARIANTS, dir::DirKeyKind::BankDebitType => dir_enums::BankDebitType::VARIANTS, dir::DirKeyKind::RealTimePaymentType => dir_enums::RealTimePaymentType::VARIANTS, dir::DirKeyKind::OpenBankingType => dir_enums::OpenBankingType::VARIANTS, dir::DirKeyKind::MobilePaymentType => dir_enums::MobilePaymentType::VARIANTS, dir::DirKeyKind::IssuerCountry => dir_enums::Country::VARIANTS, dir::DirKeyKind::AcquirerCountry => dir_enums::Country::VARIANTS, dir::DirKeyKind::CustomerDeviceType => dir_enums::CustomerDeviceType::VARIANTS, dir::DirKeyKind::CustomerDevicePlatform => dir_enums::CustomerDevicePlatform::VARIANTS, dir::DirKeyKind::CustomerDeviceDisplaySize => { dir_enums::CustomerDeviceDisplaySize::VARIANTS } dir::DirKeyKind::PaymentAmount | dir::DirKeyKind::Connector | dir::DirKeyKind::CardBin | dir::DirKeyKind::BusinessLabel | dir::DirKeyKind::MetaData | dir::DirKeyKind::IssuerName | dir::DirKeyKind::AcquirerFraudRate => Err("Key does not have variants".to_string())?, }; Ok(serde_wasm_bindgen::to_value(variants)?) } #[wasm_bindgen(js_name = addTwo)] pub fn add_two(n1: i64, n2: i64) -> i64 { n1 + n2 } #[wasm_bindgen(js_name = getDescriptionCategory)] pub fn get_description_category() -> JsResult { let keys = dir::DirKeyKind::VARIANTS .iter() .copied() .filter(|s| s != &"Connector") .collect::<Vec<&'static str>>(); let mut category: HashMap<Option<&str>, Vec<types::Details<'_>>> = HashMap::new(); for key in keys { let dir_key = dir::DirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?; let details = types::Details { description: dir_key.get_detailed_message(), kind: dir_key.clone(), }; category .entry(dir_key.get_str("Category")) .and_modify(|val| val.push(details.clone())) .or_insert(vec![details]); } Ok(serde_wasm_bindgen::to_value(&category)?) } #[wasm_bindgen(js_name = getConnectorConfig)] pub fn get_connector_config(key: &str) -> JsResult { let key = api_model_enums::Connector::from_str(key) .map_err(|_| "Invalid key received".to_string())?; let res = connector::ConnectorConfig::get_connector_config(key)?; Ok(serde_wasm_bindgen::to_value(&res)?) } #[cfg(feature = "payouts")] #[wasm_bindgen(js_name = getPayoutConnectorConfig)] pub fn get_payout_connector_config(key: &str) -> JsResult { let key = api_model_enums::PayoutConnectors::from_str(key) .map_err(|_| "Invalid key received".to_string())?; let res = connector::ConnectorConfig::get_payout_connector_config(key)?; Ok(serde_wasm_bindgen::to_value(&res)?) } #[wasm_bindgen(js_name = getAuthenticationConnectorConfig)] pub fn get_authentication_connector_config(key: &str) -> JsResult { let key = api_model_enums::AuthenticationConnectors::from_str(key) .map_err(|_| "Invalid key received".to_string())?; let res = connector::ConnectorConfig::get_authentication_connector_config(key)?; Ok(serde_wasm_bindgen::to_value(&res)?) } #[wasm_bindgen(js_name = getTaxProcessorConfig)] pub fn get_tax_processor_config(key: &str) -> JsResult { let key = api_model_enums::TaxConnectors::from_str(key) .map_err(|_| "Invalid key received".to_string())?; let res = connector::ConnectorConfig::get_tax_processor_config(key)?; Ok(serde_wasm_bindgen::to_value(&res)?) } #[wasm_bindgen(js_name = getPMAuthenticationProcessorConfig)] pub fn get_pm_authentication_processor_config(key: &str) -> JsResult { let key: api_model_enums::PmAuthConnectors = api_model_enums::PmAuthConnectors::from_str(key) .map_err(|_| "Invalid key received".to_string())?; let res = connector::ConnectorConfig::get_pm_authentication_processor_config(key)?; Ok(serde_wasm_bindgen::to_value(&res)?) } #[wasm_bindgen(js_name = getRequestPayload)] pub fn get_request_payload(input: JsValue, response: JsValue) -> JsResult { let input: DashboardRequestPayload = serde_wasm_bindgen::from_value(input)?; let api_response: ConnectorApiIntegrationPayload = serde_wasm_bindgen::from_value(response)?; let result = DashboardRequestPayload::create_connector_request(input, api_response); Ok(serde_wasm_bindgen::to_value(&result)?) } #[wasm_bindgen(js_name = getResponsePayload)] pub fn get_response_payload(input: JsValue) -> JsResult { let input: ConnectorApiIntegrationPayload = serde_wasm_bindgen::from_value(input)?; let result = ConnectorApiIntegrationPayload::get_transformed_response_payload(input); Ok(serde_wasm_bindgen::to_value(&result)?) } #[cfg(feature = "payouts")] #[wasm_bindgen(js_name = getAllPayoutKeys)] pub fn get_all_payout_keys() -> JsResult { let keys: Vec<&'static str> = dir::PayoutDirKeyKind::VARIANTS.to_vec(); Ok(serde_wasm_bindgen::to_value(&keys)?) } #[cfg(feature = "payouts")] #[wasm_bindgen(js_name = getPayoutVariantValues)] pub fn get_payout_variant_values(key: &str) -> Result<JsValue, JsValue> { let key = dir::PayoutDirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?; let variants: &[&str] = match key { dir::PayoutDirKeyKind::BusinessCountry => dir_enums::BusinessCountry::VARIANTS, dir::PayoutDirKeyKind::BillingCountry => dir_enums::BillingCountry::VARIANTS, dir::PayoutDirKeyKind::PayoutCurrency => dir_enums::PaymentCurrency::VARIANTS, dir::PayoutDirKeyKind::PayoutType => dir_enums::PayoutType::VARIANTS, dir::PayoutDirKeyKind::WalletType => dir_enums::PayoutWalletType::VARIANTS, dir::PayoutDirKeyKind::BankTransferType => dir_enums::PayoutBankTransferType::VARIANTS, dir::PayoutDirKeyKind::PayoutAmount | dir::PayoutDirKeyKind::BusinessLabel => { Err("Key does not have variants".to_string())? } }; Ok(serde_wasm_bindgen::to_value(variants)?) } #[cfg(feature = "payouts")] #[wasm_bindgen(js_name = getPayoutDescriptionCategory)] pub fn get_payout_description_category() -> JsResult { let keys = dir::PayoutDirKeyKind::VARIANTS.to_vec(); let mut category: HashMap<Option<&str>, Vec<types::PayoutDetails<'_>>> = HashMap::new(); for key in keys { let dir_key = dir::PayoutDirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?; let details = types::PayoutDetails { description: dir_key.get_detailed_message(), kind: dir_key.clone(), }; category .entry(dir_key.get_str("Category")) .and_modify(|val| val.push(details.clone())) .or_insert(vec![details]); } Ok(serde_wasm_bindgen::to_value(&category)?) } #[wasm_bindgen(js_name = getValidWebhookStatus)] pub fn get_valid_webhook_status(key: &str) -> JsResult { let event_class = EventClass::from_str(key) .map_err(|_| "Invalid webhook event type received".to_string()) .err_to_js()?; match event_class { EventClass::Payments => { let statuses: Vec<IntentStatus> = IntentStatus::iter() .filter(|intent_status| Into::<Option<EventType>>::into(*intent_status).is_some()) .collect(); Ok(serde_wasm_bindgen::to_value(&statuses)?) } EventClass::Refunds => { let statuses: Vec<RefundStatus> = RefundStatus::iter() .filter(|status| Into::<Option<EventType>>::into(*status).is_some()) .collect(); Ok(serde_wasm_bindgen::to_value(&statuses)?) } EventClass::Disputes => { let statuses: Vec<DisputeStatus> = DisputeStatus::iter().collect(); Ok(serde_wasm_bindgen::to_value(&statuses)?) } EventClass::Mandates => { let statuses: Vec<MandateStatus> = MandateStatus::iter() .filter(|status| Into::<Option<EventType>>::into(*status).is_some()) .collect(); Ok(serde_wasm_bindgen::to_value(&statuses)?) } #[cfg(feature = "payouts")] EventClass::Payouts => { let statuses: Vec<PayoutStatus> = PayoutStatus::iter() .filter(|status| Into::<Option<EventType>>::into(*status).is_some()) .collect(); Ok(serde_wasm_bindgen::to_value(&statuses)?) } } }
crates/euclid_wasm/src/lib.rs
euclid_wasm
full_file
null
null
null
5,371
null
null
null
null
null
null
null
// Struct: PaymentMethodsEnabled // File: crates/api_models/src/admin.rs // Module: api_models // Implementations: 1 pub struct PaymentMethodsEnabled
crates/api_models/src/admin.rs
api_models
struct_definition
PaymentMethodsEnabled
1
[]
35
null
null
null
null
null
null
null
// File: crates/analytics/src/sdk_events/metrics/sdk_initiated_count.rs // Module: analytics use std::collections::HashSet; use api_models::analytics::{ sdk_events::{ SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, }, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::SdkEventMetricRow; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(super) struct SdkInitiatedCount; #[async_trait::async_trait] impl<T> super::SdkEventMetric<T> for SdkInitiatedCount where T: AnalyticsDataSource + super::SdkEventMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); let dimensions = dimensions.to_vec(); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(Aggregate::Count { field: None, alias: Some("count"), }) .switch()?; if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; } filters.set_filter_clause(&mut query_builder).switch()?; query_builder .add_filter_clause("merchant_id", publishable_key) .switch()?; query_builder .add_bool_filter_clause("first_event", 1) .switch()?; query_builder .add_filter_clause("event_name", SdkEventNames::OrcaElementsCalled) .switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; for dim in dimensions.iter() { query_builder .add_group_by_clause(dim) .attach_printable("Error grouping by dimensions") .switch()?; } if let Some(_granularity) = granularity.as_ref() { query_builder .add_group_by_clause("time_bucket") .attach_printable("Error adding granularity") .switch()?; } query_builder .execute_query::<SdkEventMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( SdkEventMetricsBucketIdentifier::new( i.payment_method.clone(), i.platform.clone(), i.browser_name.clone(), i.source.clone(), i.component.clone(), i.payment_experience.clone(), i.time_bucket.clone(), ), i, )) }) .collect::<error_stack::Result< HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/sdk_events/metrics/sdk_initiated_count.rs
analytics
full_file
null
null
null
807
null
null
null
null
null
null
null
// Implementation: impl api::RefundExecute for for Xendit // File: crates/hyperswitch_connectors/src/connectors/xendit.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::RefundExecute for for Xendit
crates/hyperswitch_connectors/src/connectors/xendit.rs
hyperswitch_connectors
impl_block
null
null
null
62
null
Xendit
api::RefundExecute for
0
0
null
null
// Struct: GrpcClients // File: crates/external_services/src/grpc_client.rs // Module: external_services // Implementations: 0 pub struct GrpcClients
crates/external_services/src/grpc_client.rs
external_services
struct_definition
GrpcClients
0
[]
37
null
null
null
null
null
null
null
// Struct: PaymentMethod // File: crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PaymentMethod
crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs
hyperswitch_connectors
struct_definition
PaymentMethod
0
[]
46
null
null
null
null
null
null
null
// Function: payouts_confirm_core // File: crates/router/src/core/payouts.rs // Module: router pub fn payouts_confirm_core( state: SessionState, merchant_context: domain::MerchantContext, req: payouts::PayoutCreateRequest, ) -> RouterResponse<payouts::PayoutCreateResponse>
crates/router/src/core/payouts.rs
router
function_signature
null
null
null
68
payouts_confirm_core
null
null
null
null
null
null
// Function: merchant_account_kv_status // File: crates/openapi/src/routes/merchant_account.rs // Module: openapi pub fn merchant_account_kv_status()
crates/openapi/src/routes/merchant_account.rs
openapi
function_signature
null
null
null
34
merchant_account_kv_status
null
null
null
null
null
null
// Struct: Analytics // File: crates/router/src/analytics.rs // Module: router // Implementations: 1 pub struct Analytics
crates/router/src/analytics.rs
router
struct_definition
Analytics
1
[]
30
null
null
null
null
null
null
null
// Implementation: impl RefundMetricAccumulator for for SuccessRateAccumulator // File: crates/analytics/src/refunds/accumulator.rs // Module: analytics // Methods: 2 total (0 public) impl RefundMetricAccumulator for for SuccessRateAccumulator
crates/analytics/src/refunds/accumulator.rs
analytics
impl_block
null
null
null
60
null
SuccessRateAccumulator
RefundMetricAccumulator for
2
0
null
null
// Implementation: impl RefundExecute for for Wise // File: crates/hyperswitch_connectors/src/connectors/wise.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl RefundExecute for for Wise
crates/hyperswitch_connectors/src/connectors/wise.rs
hyperswitch_connectors
impl_block
null
null
null
53
null
Wise
RefundExecute for
0
0
null
null
// Implementation: impl api::PaymentToken for for Worldline // File: crates/hyperswitch_connectors/src/connectors/worldline.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentToken for for Worldline
crates/hyperswitch_connectors/src/connectors/worldline.rs
hyperswitch_connectors
impl_block
null
null
null
57
null
Worldline
api::PaymentToken for
0
0
null
null
// File: crates/hyperswitch_domain_models/src/types.rs // Module: hyperswitch_domain_models pub use diesel_models::types::OrderDetailsWithAmount; use crate::{ router_data::{AccessToken, AccessTokenAuthenticationResponse, RouterData}, router_data_v2::{self, RouterDataV2}, router_flow_types::{ mandate_revoke::MandateRevoke, revenue_recovery::InvoiceRecordBack, subscriptions::{ GetSubscriptionEstimate, GetSubscriptionPlanPrices, GetSubscriptionPlans, SubscriptionCreate, }, AccessTokenAuth, AccessTokenAuthentication, Authenticate, AuthenticationConfirmation, Authorize, AuthorizeSessionToken, BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, Execute, ExternalVaultProxy, GiftCardBalanceCheck, IncrementalAuthorization, PSync, PaymentMethodToken, PostAuthenticate, PostCaptureVoid, PostSessionTokens, PreAuthenticate, PreProcessing, RSync, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, VerifyWebhookSource, Void, }, router_request_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, InvoiceRecordBackRequest, }, subscriptions::{ GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, SubscriptionCreateRequest, }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, AccessTokenAuthenticationRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, ExternalVaultProxyPaymentsData, GiftCardBalanceCheckRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostAuthenticateData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, VaultRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, InvoiceRecordBackResponse, }, subscriptions::{ GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, SubscriptionCreateResponse, }, GiftCardBalanceCheckResponseData, MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData, TaxCalculationResponseData, VaultResponseData, VerifyWebhookSourceResponseData, }, }; #[cfg(feature = "payouts")] pub use crate::{router_request_types::PayoutsData, router_response_types::PayoutsResponseData}; pub type PaymentsAuthorizeRouterData = RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>; pub type ExternalVaultProxyPaymentsRouterData = RouterData<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData>; pub type PaymentsAuthorizeSessionTokenRouterData = RouterData<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>; pub type PaymentsPreProcessingRouterData = RouterData<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>; pub type PaymentsPreAuthenticateRouterData = RouterData<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData>; pub type PaymentsAuthenticateRouterData = RouterData<Authenticate, PaymentsAuthenticateData, PaymentsResponseData>; pub type PaymentsPostAuthenticateRouterData = RouterData<PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData>; pub type PaymentsSyncRouterData = RouterData<PSync, PaymentsSyncData, PaymentsResponseData>; pub type PaymentsCaptureRouterData = RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>; pub type PaymentsCancelRouterData = RouterData<Void, PaymentsCancelData, PaymentsResponseData>; pub type PaymentsCancelPostCaptureRouterData = RouterData<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData>; pub type SetupMandateRouterData = RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>; pub type RefundsRouterData<F> = RouterData<F, RefundsData, RefundsResponseData>; pub type RefundExecuteRouterData = RouterData<Execute, RefundsData, RefundsResponseData>; pub type RefundSyncRouterData = RouterData<RSync, RefundsData, RefundsResponseData>; pub type TokenizationRouterData = RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>; pub type ConnectorCustomerRouterData = RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>; pub type PaymentsCompleteAuthorizeRouterData = RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>; pub type PaymentsTaxCalculationRouterData = RouterData<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>; pub type AccessTokenAuthenticationRouterData = RouterData< AccessTokenAuthentication, AccessTokenAuthenticationRequestData, AccessTokenAuthenticationResponse, >; pub type PaymentsGiftCardBalanceCheckRouterData = RouterData< GiftCardBalanceCheck, GiftCardBalanceCheckRequestData, GiftCardBalanceCheckResponseData, >; pub type RefreshTokenRouterData = RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>; pub type PaymentsPostSessionTokensRouterData = RouterData<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>; pub type PaymentsSessionRouterData = RouterData<Session, PaymentsSessionData, PaymentsResponseData>; pub type PaymentsUpdateMetadataRouterData = RouterData<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData>; pub type CreateOrderRouterData = RouterData<CreateOrder, CreateOrderRequestData, PaymentsResponseData>; pub type UasPostAuthenticationRouterData = RouterData<PostAuthenticate, UasPostAuthenticationRequestData, UasAuthenticationResponseData>; pub type UasPreAuthenticationRouterData = RouterData<PreAuthenticate, UasPreAuthenticationRequestData, UasAuthenticationResponseData>; pub type UasAuthenticationConfirmationRouterData = RouterData< AuthenticationConfirmation, UasConfirmationRequestData, UasAuthenticationResponseData, >; pub type MandateRevokeRouterData = RouterData<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>; pub type PaymentsIncrementalAuthorizationRouterData = RouterData< IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData, >; pub type SdkSessionUpdateRouterData = RouterData<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>; pub type VerifyWebhookSourceRouterData = RouterData< VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, >; #[cfg(feature = "payouts")] pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>; pub type InvoiceRecordBackRouterData = RouterData<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse>; pub type GetSubscriptionPlansRouterData = RouterData<GetSubscriptionPlans, GetSubscriptionPlansRequest, GetSubscriptionPlansResponse>; pub type GetSubscriptionEstimateRouterData = RouterData< GetSubscriptionEstimate, GetSubscriptionEstimateRequest, GetSubscriptionEstimateResponse, >; pub type UasAuthenticationRouterData = RouterData<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData>; pub type BillingConnectorPaymentsSyncRouterData = RouterData< BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse, >; pub type BillingConnectorInvoiceSyncRouterData = RouterData< BillingConnectorInvoiceSync, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse, >; pub type BillingConnectorInvoiceSyncRouterDataV2 = RouterDataV2< BillingConnectorInvoiceSync, router_data_v2::flow_common_types::BillingConnectorInvoiceSyncFlowData, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse, >; pub type BillingConnectorPaymentsSyncRouterDataV2 = RouterDataV2< BillingConnectorPaymentsSync, router_data_v2::flow_common_types::BillingConnectorPaymentsSyncFlowData, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse, >; pub type InvoiceRecordBackRouterDataV2 = RouterDataV2< InvoiceRecordBack, router_data_v2::flow_common_types::InvoiceRecordBackData, InvoiceRecordBackRequest, InvoiceRecordBackResponse, >; pub type GetSubscriptionPlanPricesRouterData = RouterData< GetSubscriptionPlanPrices, GetSubscriptionPlanPricesRequest, GetSubscriptionPlanPricesResponse, >; pub type VaultRouterData<F> = RouterData<F, VaultRequestData, VaultResponseData>; pub type VaultRouterDataV2<F> = RouterDataV2< F, router_data_v2::flow_common_types::VaultConnectorFlowData, VaultRequestData, VaultResponseData, >; pub type ExternalVaultProxyPaymentsRouterDataV2 = RouterDataV2< ExternalVaultProxy, router_data_v2::flow_common_types::ExternalVaultProxyFlowData, ExternalVaultProxyPaymentsData, PaymentsResponseData, >; pub type SubscriptionCreateRouterData = RouterData<SubscriptionCreate, SubscriptionCreateRequest, SubscriptionCreateResponse>;
crates/hyperswitch_domain_models/src/types.rs
hyperswitch_domain_models
full_file
null
null
null
1,998
null
null
null
null
null
null
null
// Struct: PaymentAttempt // File: crates/hyperswitch_domain_models/src/payments/payment_attempt.rs // Module: hyperswitch_domain_models // Implementations: 7 // Traits: ForeignIDRef, ForeignIDRef, behaviour::Conversion, behaviour::Conversion pub struct PaymentAttempt
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
hyperswitch_domain_models
struct_definition
PaymentAttempt
7
[ "ForeignIDRef", "ForeignIDRef", "behaviour::Conversion", "behaviour::Conversion" ]
61
null
null
null
null
null
null
null
// Struct: RiskifiedPaymentsResponse // File: crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct RiskifiedPaymentsResponse
crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs
hyperswitch_connectors
struct_definition
RiskifiedPaymentsResponse
0
[]
51
null
null
null
null
null
null
null
// Function: update_process_status_by_ids // File: crates/diesel_models/src/query/process_tracker.rs // Module: diesel_models pub fn update_process_status_by_ids( conn: &PgPooledConn, task_ids: Vec<String>, task_update: ProcessTrackerUpdate, ) -> StorageResult<usize>
crates/diesel_models/src/query/process_tracker.rs
diesel_models
function_signature
null
null
null
67
update_process_status_by_ids
null
null
null
null
null
null
// Struct: CardAndNetworkTokenData // File: crates/hyperswitch_domain_models/src/payments.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct CardAndNetworkTokenData
crates/hyperswitch_domain_models/src/payments.rs
hyperswitch_domain_models
struct_definition
CardAndNetworkTokenData
0
[]
46
null
null
null
null
null
null
null
// Trait: SerializableSecret // File: crates/masking/src/serde.rs // Module: masking pub trait SerializableSecret: Serialize
crates/masking/src/serde.rs
masking
trait_definition
null
null
null
28
null
null
SerializableSecret
null
null
null
null
// Function: is_preprocessing_required_for_wallets // File: crates/router/src/core/payments.rs // Module: router pub fn is_preprocessing_required_for_wallets(connector_name: String) -> bool
crates/router/src/core/payments.rs
router
function_signature
null
null
null
44
is_preprocessing_required_for_wallets
null
null
null
null
null
null
// Implementation: impl super::KafkaMessage for for KafkaFraudCheckEvent // File: crates/router/src/services/kafka/fraud_check_event.rs // Module: router // Methods: 2 total (0 public) impl super::KafkaMessage for for KafkaFraudCheckEvent
crates/router/src/services/kafka/fraud_check_event.rs
router
impl_block
null
null
null
60
null
KafkaFraudCheckEvent
super::KafkaMessage for
2
0
null
null
// Implementation: impl Responder // File: crates/router/src/routes/routing.rs // Module: router // Methods: 0 total (0 public) impl Responder
crates/router/src/routes/routing.rs
router
impl_block
null
null
null
36
null
Responder
null
0
0
null
null
// Function: from_payments_request_and_payment_attempt // File: crates/hyperswitch_domain_models/src/payments/payment_attempt.rs // Module: hyperswitch_domain_models pub fn from_payments_request_and_payment_attempt( payments_request: &api_models::payments::PaymentsRequest, payment_attempt: Option<&PaymentAttempt>, ) -> Option<Self>
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
hyperswitch_domain_models
function_signature
null
null
null
72
from_payments_request_and_payment_attempt
null
null
null
null
null
null
// Struct: SingleUseTokenKey // File: crates/hyperswitch_domain_models/src/payment_method_data.rs // Module: hyperswitch_domain_models // Implementations: 1 pub struct SingleUseTokenKey
crates/hyperswitch_domain_models/src/payment_method_data.rs
hyperswitch_domain_models
struct_definition
SingleUseTokenKey
1
[]
45
null
null
null
null
null
null
null
// Implementation: impl ConnectorValidation for for Bitpay // File: crates/hyperswitch_connectors/src/connectors/bitpay.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl ConnectorValidation for for Bitpay
crates/hyperswitch_connectors/src/connectors/bitpay.rs
hyperswitch_connectors
impl_block
null
null
null
53
null
Bitpay
ConnectorValidation for
0
0
null
null
// Function: handle_unified_connector_service_response_for_payment_authorize // File: crates/router/src/core/unified_connector_service.rs // Module: router pub fn handle_unified_connector_service_response_for_payment_authorize( response: PaymentServiceAuthorizeResponse, ) -> UnifiedConnectorServiceResult
crates/router/src/core/unified_connector_service.rs
router
function_signature
null
null
null
59
handle_unified_connector_service_response_for_payment_authorize
null
null
null
null
null
null
// File: crates/drainer/src/types.rs // Module: drainer // Public functions: 1 // Public structs: 1 use std::collections::HashMap; use common_utils::errors; use error_stack::ResultExt; use serde::{de::value::MapDeserializer, Deserialize, Serialize}; use crate::{ kv, utils::{deserialize_db_op, deserialize_i64}, }; #[derive(Deserialize, Serialize)] pub struct StreamData { pub request_id: String, pub global_id: String, #[serde(deserialize_with = "deserialize_db_op")] pub typed_sql: kv::DBOperation, #[serde(deserialize_with = "deserialize_i64")] pub pushed_at: i64, } impl StreamData { pub fn from_hashmap( hashmap: HashMap<String, String>, ) -> errors::CustomResult<Self, errors::ParsingError> { let iter = MapDeserializer::< '_, std::collections::hash_map::IntoIter<String, String>, serde_json::error::Error, >::new(hashmap.into_iter()); Self::deserialize(iter) .change_context(errors::ParsingError::StructParseFailure("StreamData")) } }
crates/drainer/src/types.rs
drainer
full_file
null
null
null
254
null
null
null
null
null
null
null
// Struct: Archipel // File: crates/hyperswitch_connectors/src/connectors/archipel.rs // Module: hyperswitch_connectors // Implementations: 18 // Traits: api::PaymentAuthorize, api::PaymentSync, api::PaymentVoid, api::PaymentCapture, api::MandateSetup, api::ConnectorAccessToken, api::PaymentToken, api::PaymentSession, api::Refund, api::RefundExecute, api::RefundSync, api::Payment, api::PaymentIncrementalAuthorization, ConnectorCommon, ConnectorValidation, IncomingWebhook, ConnectorSpecifications pub struct Archipel
crates/hyperswitch_connectors/src/connectors/archipel.rs
hyperswitch_connectors
struct_definition
Archipel
18
[ "api::PaymentAuthorize", "api::PaymentSync", "api::PaymentVoid", "api::PaymentCapture", "api::MandateSetup", "api::ConnectorAccessToken", "api::PaymentToken", "api::PaymentSession", "api::Refund", "api::RefundExecute", "api::RefundSync", "api::Payment", "api::PaymentIncrementalAuthorization", "ConnectorCommon", "ConnectorValidation", "IncomingWebhook", "ConnectorSpecifications" ]
129
null
null
null
null
null
null
null
// Struct: ErrorResult // File: crates/api_models/src/analytics/payment_intents.rs // Module: api_models // Implementations: 0 pub struct ErrorResult
crates/api_models/src/analytics/payment_intents.rs
api_models
struct_definition
ErrorResult
0
[]
37
null
null
null
null
null
null
null
// Struct: CreateOrder // File: crates/hyperswitch_domain_models/src/router_flow_types/payments.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct CreateOrder
crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
hyperswitch_domain_models
struct_definition
CreateOrder
0
[]
43
null
null
null
null
null
null
null
// Implementation: impl SmtpServer // File: crates/external_services/src/email/smtp.rs // Module: external_services // Methods: 3 total (1 public) impl SmtpServer
crates/external_services/src/email/smtp.rs
external_services
impl_block
null
null
null
41
null
SmtpServer
null
3
1
null
null
// Implementation: impl Hash for for UserRole // File: crates/diesel_models/src/user_role.rs // Module: diesel_models // Methods: 1 total (0 public) impl Hash for for UserRole
crates/diesel_models/src/user_role.rs
diesel_models
impl_block
null
null
null
42
null
UserRole
Hash for
1
0
null
null
// Implementation: impl Responder // File: crates/router/src/analytics.rs // Module: router // Methods: 0 total (0 public) impl Responder
crates/router/src/analytics.rs
router
impl_block
null
null
null
35
null
Responder
null
0
0
null
null
// Function: new_token // File: crates/router/src/services/authentication.rs // Module: router pub fn new_token( user_id: String, merchant_id: id_type::MerchantId, settings: &Settings, org_id: id_type::OrganizationId, profile_id: id_type::ProfileId, tenant_id: Option<id_type::TenantId>, role_info: authorization::roles::RoleInfo, ) -> UserResult<String>
crates/router/src/services/authentication.rs
router
function_signature
null
null
null
98
new_token
null
null
null
null
null
null
// Struct: PaymentToFrmData // File: crates/router/src/core/fraud_check/types.rs // Module: router // Implementations: 0 pub struct PaymentToFrmData
crates/router/src/core/fraud_check/types.rs
router
struct_definition
PaymentToFrmData
0
[]
39
null
null
null
null
null
null
null
// Implementation: impl api::PaymentSession for for Itaubank // File: crates/hyperswitch_connectors/src/connectors/itaubank.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentSession for for Itaubank
crates/hyperswitch_connectors/src/connectors/itaubank.rs
hyperswitch_connectors
impl_block
null
null
null
61
null
Itaubank
api::PaymentSession for
0
0
null
null
// Function: update_target_count // File: crates/api_models/src/routing.rs // Module: api_models pub fn update_target_count(&mut self, new: &Self)
crates/api_models/src/routing.rs
api_models
function_signature
null
null
null
38
update_target_count
null
null
null
null
null
null
// Struct: DeleteTokenizeByTokenRequest // File: crates/api_models/src/payment_methods.rs // Module: api_models // Implementations: 0 pub struct DeleteTokenizeByTokenRequest
crates/api_models/src/payment_methods.rs
api_models
struct_definition
DeleteTokenizeByTokenRequest
0
[]
42
null
null
null
null
null
null
null
// Struct: DeutschebankReversalRequest // File: crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct DeutschebankReversalRequest
crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
hyperswitch_connectors
struct_definition
DeutschebankReversalRequest
0
[]
54
null
null
null
null
null
null
null
// File: crates/storage_impl/src/connection.rs // Module: storage_impl // Public functions: 3 use bb8::PooledConnection; use common_utils::errors; use diesel::PgConnection; use error_stack::ResultExt; pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>; pub type PgPooledConn = async_bb8_diesel::Connection<PgConnection>; /// Creates a Redis connection pool for the specified Redis settings /// # Panics /// /// Panics if failed to create a redis pool #[allow(clippy::expect_used)] pub async fn redis_connection( redis: &redis_interface::RedisSettings, ) -> redis_interface::RedisConnectionPool { redis_interface::RedisConnectionPool::new(redis) .await .expect("Failed to create Redis Connection Pool") } pub async fn pg_connection_read<T: crate::DatabaseStore>( store: &T, ) -> errors::CustomResult< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, crate::errors::StorageError, > { // If only OLAP is enabled get replica pool. #[cfg(all(feature = "olap", not(feature = "oltp")))] let pool = store.get_replica_pool(); // If either one of these are true we need to get master pool. // 1. Only OLTP is enabled. // 2. Both OLAP and OLTP is enabled. // 3. Both OLAP and OLTP is disabled. #[cfg(any( all(not(feature = "olap"), feature = "oltp"), all(feature = "olap", feature = "oltp"), all(not(feature = "olap"), not(feature = "oltp")) ))] let pool = store.get_master_pool(); pool.get() .await .change_context(crate::errors::StorageError::DatabaseConnectionError) } pub async fn pg_connection_write<T: crate::DatabaseStore>( store: &T, ) -> errors::CustomResult< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, crate::errors::StorageError, > { // Since all writes should happen to master DB only choose master DB. let pool = store.get_master_pool(); pool.get() .await .change_context(crate::errors::StorageError::DatabaseConnectionError) }
crates/storage_impl/src/connection.rs
storage_impl
full_file
null
null
null
520
null
null
null
null
null
null
null
// File: crates/diesel_models/src/address.rs // Module: diesel_models // Public functions: 1 // Public structs: 4 use common_utils::{crypto, encryption::Encryption}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums, schema::address}; #[derive(Clone, Debug, Insertable, Serialize, Deserialize, router_derive::DebugAsDisplay)] #[diesel(table_name = address)] pub struct AddressNew { pub address_id: String, pub city: Option<String>, pub country: Option<enums::CountryAlpha2>, pub line1: Option<Encryption>, pub line2: Option<Encryption>, pub line3: Option<Encryption>, pub state: Option<Encryption>, pub zip: Option<Encryption>, pub first_name: Option<Encryption>, pub last_name: Option<Encryption>, pub phone_number: Option<Encryption>, pub country_code: Option<String>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: Option<common_utils::id_type::PaymentId>, pub created_at: PrimitiveDateTime, pub modified_at: PrimitiveDateTime, pub updated_by: String, pub email: Option<Encryption>, pub origin_zip: Option<Encryption>, } #[derive(Clone, Debug, Queryable, Identifiable, Selectable, Serialize, Deserialize)] #[diesel(table_name = address, primary_key(address_id), check_for_backend(diesel::pg::Pg))] pub struct Address { pub address_id: String, pub city: Option<String>, pub country: Option<enums::CountryAlpha2>, pub line1: Option<Encryption>, pub line2: Option<Encryption>, pub line3: Option<Encryption>, pub state: Option<Encryption>, pub zip: Option<Encryption>, pub first_name: Option<Encryption>, pub last_name: Option<Encryption>, pub phone_number: Option<Encryption>, pub country_code: Option<String>, pub created_at: PrimitiveDateTime, pub modified_at: PrimitiveDateTime, pub customer_id: Option<common_utils::id_type::CustomerId>, pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: Option<common_utils::id_type::PaymentId>, pub updated_by: String, pub email: Option<Encryption>, pub origin_zip: Option<Encryption>, } #[derive(Clone)] // Intermediate struct to convert HashMap to Address pub struct EncryptableAddress { pub line1: crypto::OptionalEncryptableSecretString, pub line2: crypto::OptionalEncryptableSecretString, pub line3: crypto::OptionalEncryptableSecretString, pub state: crypto::OptionalEncryptableSecretString, pub zip: crypto::OptionalEncryptableSecretString, pub first_name: crypto::OptionalEncryptableSecretString, pub last_name: crypto::OptionalEncryptableSecretString, pub phone_number: crypto::OptionalEncryptableSecretString, pub email: crypto::OptionalEncryptableEmail, pub origin_zip: crypto::OptionalEncryptableSecretString, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = address)] pub struct AddressUpdateInternal { pub city: Option<String>, pub country: Option<enums::CountryAlpha2>, pub line1: Option<Encryption>, pub line2: Option<Encryption>, pub line3: Option<Encryption>, pub state: Option<Encryption>, pub zip: Option<Encryption>, pub first_name: Option<Encryption>, pub last_name: Option<Encryption>, pub phone_number: Option<Encryption>, pub country_code: Option<String>, pub modified_at: PrimitiveDateTime, pub updated_by: String, pub email: Option<Encryption>, pub origin_zip: Option<Encryption>, } impl AddressUpdateInternal { pub fn create_address(self, source: Address) -> Address { Address { city: self.city, country: self.country, line1: self.line1, line2: self.line2, line3: self.line3, state: self.state, zip: self.zip, first_name: self.first_name, last_name: self.last_name, phone_number: self.phone_number, country_code: self.country_code, modified_at: self.modified_at, updated_by: self.updated_by, origin_zip: self.origin_zip, ..source } } }
crates/diesel_models/src/address.rs
diesel_models
full_file
null
null
null
989
null
null
null
null
null
null
null
} // Verify the signature of the token fn verify_signature( &self, encrypted_data: &EncryptedData, ) -> CustomResult<(), errors::GooglePayDecryptionError> { // check the protocol version if encrypted_data.protocol_version != GooglePayProtocolVersion::EcProtocolVersion2 { return Err(errors::GooglePayDecryptionError::InvalidProtocolVersion.into()); } // verify the intermediate signing key self.verify_intermediate_signing_key(encrypted_data)?; // validate and fetch the signed key let signed_key = self.validate_signed_key(&encrypted_data.intermediate_signing_key)?; // verify the signature of the token self.verify_message_signature(encrypted_data, &signed_key) } // Verify the intermediate signing key fn verify_intermediate_signing_key( &self, encrypted_data: &EncryptedData, ) -> CustomResult<(), errors::GooglePayDecryptionError> { let mut signatrues: Vec<openssl::ecdsa::EcdsaSig> = Vec::new(); // decode and parse the signatures for signature in encrypted_data.intermediate_signing_key.signatures.iter() { let signature = BASE64_ENGINE .decode(signature.peek()) .change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?; let ecdsa_signature = openssl::ecdsa::EcdsaSig::from_der(&signature) .change_context(errors::GooglePayDecryptionError::EcdsaSignatureParsingFailed)?; signatrues.push(ecdsa_signature); } // get the sender id i.e. Google let sender_id = String::from_utf8(consts::SENDER_ID.to_vec()) .change_context(errors::GooglePayDecryptionError::DeserializationFailed)?; // construct the signed data let signed_data = self.construct_signed_data_for_intermediate_signing_key_verification( &sender_id, consts::PROTOCOL, encrypted_data.intermediate_signing_key.signed_key.peek(), )?; // check if any of the signatures are valid for any of the root signing keys for key in self.root_signing_keys.iter() { // decode and create public key let public_key = self .load_public_key(key.key_value.peek()) .change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?; // fetch the ec key from public key let ec_key = public_key .ec_key() .change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?; // hash the signed data let message_hash = openssl::sha::sha256(&signed_data); // verify if any of the signatures is valid against the given key for signature in signatrues.iter() { let result = signature.verify(&message_hash, &ec_key).change_context( errors::GooglePayDecryptionError::SignatureVerificationFailed, )?; if result { return Ok(()); } } } Err(errors::GooglePayDecryptionError::InvalidIntermediateSignature.into()) } // Construct signed data for intermediate signing key verification fn construct_signed_data_for_intermediate_signing_key_verification( &self, sender_id: &str, protocol_version: &str, signed_key: &str, ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> { let length_of_sender_id = u32::try_from(sender_id.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let length_of_protocol_version = u32::try_from(protocol_version.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let length_of_signed_key = u32::try_from(signed_key.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let mut signed_data: Vec<u8> = Vec::new(); signed_data.append(&mut get_little_endian_format(length_of_sender_id)); signed_data.append(&mut sender_id.as_bytes().to_vec()); signed_data.append(&mut get_little_endian_format(length_of_protocol_version)); signed_data.append(&mut protocol_version.as_bytes().to_vec()); signed_data.append(&mut get_little_endian_format(length_of_signed_key)); signed_data.append(&mut signed_key.as_bytes().to_vec()); Ok(signed_data) } // Validate and parse signed key fn validate_signed_key( &self, intermediate_signing_key: &IntermediateSigningKey, ) -> CustomResult<GooglePaySignedKey, errors::GooglePayDecryptionError> { let signed_key: GooglePaySignedKey = intermediate_signing_key .signed_key .clone() .expose() .parse_struct("GooglePaySignedKey") .change_context(errors::GooglePayDecryptionError::SignedKeyParsingFailure)?; if !matches!( check_expiration_date_is_valid(&signed_key.key_expiration), Ok(true) ) { return Err(errors::GooglePayDecryptionError::SignedKeyExpired)?; } Ok(signed_key) } // Verify the signed message fn verify_message_signature( &self, encrypted_data: &EncryptedData, signed_key: &GooglePaySignedKey, ) -> CustomResult<(), errors::GooglePayDecryptionError> { // create a public key from the intermediate signing key let public_key = self.load_public_key(signed_key.key_value.peek())?; // base64 decode the signature let signature = BASE64_ENGINE .decode(&encrypted_data.signature) .change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?; // parse the signature using ECDSA let ecdsa_signature = openssl::ecdsa::EcdsaSig::from_der(&signature) .change_context(errors::GooglePayDecryptionError::EcdsaSignatureFailed)?; // get the EC key from the public key let ec_key = public_key .ec_key() .change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?; // get the sender id i.e. Google let sender_id = String::from_utf8(consts::SENDER_ID.to_vec()) .change_context(errors::GooglePayDecryptionError::DeserializationFailed)?; // serialize the signed message to string let signed_message = serde_json::to_string(&encrypted_data.signed_message) .change_context(errors::GooglePayDecryptionError::SignedKeyParsingFailure)?; // construct the signed data let signed_data = self.construct_signed_data_for_signature_verification( &sender_id, consts::PROTOCOL, &signed_message, )?; // hash the signed data let message_hash = openssl::sha::sha256(&signed_data); // verify the signature let result = ecdsa_signature .verify(&message_hash, &ec_key) .change_context(errors::GooglePayDecryptionError::SignatureVerificationFailed)?; if result { Ok(()) } else { Err(errors::GooglePayDecryptionError::InvalidSignature)? } } // Fetch the public key fn load_public_key( &self, key: &str, ) -> CustomResult<PKey<openssl::pkey::Public>, errors::GooglePayDecryptionError> { // decode the base64 string let der_data = BASE64_ENGINE .decode(key) .change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?; // parse the DER-encoded data as an EC public key let ec_key = openssl::ec::EcKey::public_key_from_der(&der_data) .change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?; // wrap the EC key in a PKey (a more general-purpose public key type in OpenSSL) let public_key = PKey::from_ec_key(ec_key) .change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?; Ok(public_key) } // Construct signed data for signature verification fn construct_signed_data_for_signature_verification( &self, sender_id: &str, protocol_version: &str, signed_key: &str, ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> { let recipient_id = self.recipient_id.clone().expose(); let length_of_sender_id = u32::try_from(sender_id.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let length_of_recipient_id = u32::try_from(recipient_id.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let length_of_protocol_version = u32::try_from(protocol_version.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let length_of_signed_key = u32::try_from(signed_key.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let mut signed_data: Vec<u8> = Vec::new(); signed_data.append(&mut get_little_endian_format(length_of_sender_id)); signed_data.append(&mut sender_id.as_bytes().to_vec()); signed_data.append(&mut get_little_endian_format(length_of_recipient_id)); signed_data.append(&mut recipient_id.as_bytes().to_vec()); signed_data.append(&mut get_little_endian_format(length_of_protocol_version)); signed_data.append(&mut protocol_version.as_bytes().to_vec()); signed_data.append(&mut get_little_endian_format(length_of_signed_key)); signed_data.append(&mut signed_key.as_bytes().to_vec()); Ok(signed_data) } // Derive a shared key using ECDH fn get_shared_key( &self, ephemeral_public_key_bytes: &[u8], ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> { let group = openssl::ec::EcGroup::from_curve_name(openssl::nid::Nid::X9_62_PRIME256V1) .change_context(errors::GooglePayDecryptionError::DerivingEcGroupFailed)?; let mut big_num_context = openssl::bn::BigNumContext::new() .change_context(errors::GooglePayDecryptionError::BigNumAllocationFailed)?; let ec_key = openssl::ec::EcPoint::from_bytes( &group, ephemeral_public_key_bytes, &mut big_num_context, ) .change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?; // create an ephemeral public key from the given bytes let ephemeral_public_key = openssl::ec::EcKey::from_public_key(&group, &ec_key) .change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?; // wrap the public key in a PKey let ephemeral_pkey = PKey::from_ec_key(ephemeral_public_key) .change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?; // perform ECDH to derive the shared key let mut deriver = Deriver::new(&self.private_key) .change_context(errors::GooglePayDecryptionError::DerivingSharedSecretKeyFailed)?; deriver .set_peer(&ephemeral_pkey) .change_context(errors::GooglePayDecryptionError::DerivingSharedSecretKeyFailed)?; let shared_key = deriver .derive_to_vec() .change_context(errors::GooglePayDecryptionError::DerivingSharedSecretKeyFailed)?; Ok(shared_key) } // Derive symmetric key and MAC key using HKDF fn derive_key( &self, ephemeral_public_key_bytes: &[u8], shared_key: &[u8], ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> { // concatenate ephemeral public key and shared key let input_key_material = [ephemeral_public_key_bytes, shared_key].concat(); // initialize HKDF with SHA-256 as the hash function // Salt is not provided as per the Google Pay documentation // https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#encrypt-spec let hkdf: ::hkdf::Hkdf<sha2::Sha256> = ::hkdf::Hkdf::new(None, &input_key_material); // derive 64 bytes for the output key (symmetric encryption + MAC key) let mut output_key = vec![0u8; 64]; hkdf.expand(consts::SENDER_ID, &mut output_key) .map_err(|err| { logger::error!( "Failed to derive the shared ephemeral key for Google Pay decryption flow: {:?}", err ); report!(errors::GooglePayDecryptionError::DerivingSharedEphemeralKeyFailed) })?; Ok(output_key) } // Verify the Hmac key // https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#encrypt-spec fn verify_hmac( &self, mac_key: &[u8], tag: &[u8], encrypted_message: &[u8], ) -> CustomResult<(), errors::GooglePayDecryptionError> { let hmac_key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, mac_key); ring::hmac::verify(&hmac_key, encrypted_message, tag) .change_context(errors::GooglePayDecryptionError::HmacVerificationFailed) } // Method to decrypt the AES-GCM encrypted message fn decrypt_message( &self, symmetric_key: &[u8], encrypted_message: &[u8], ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> { //initialization vector IV is typically used in AES-GCM (Galois/Counter Mode) encryption for randomizing the encryption process. // zero iv is being passed as specified in Google Pay documentation // https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#decrypt-token let iv = [0u8; 16]; // extract the tag from the end of the encrypted message let tag = encrypted_message .get(encrypted_message.len() - 16..) .ok_or(errors::GooglePayDecryptionError::ParsingTagError)?; // decrypt the message using AES-256-CTR let cipher = Cipher::aes_256_ctr(); let decrypted_data = decrypt_aead( cipher, symmetric_key, Some(&iv), &[], encrypted_message, tag, ) .change_context(errors::GooglePayDecryptionError::DecryptionFailed)?; Ok(decrypted_data) } } pub fn decrypt_paze_token( paze_wallet_data: PazeWalletData, paze_private_key: masking::Secret<String>, paze_private_key_passphrase: masking::Secret<String>, ) -> CustomResult<serde_json::Value, errors::PazeDecryptionError> { let decoded_paze_private_key = BASE64_ENGINE .decode(paze_private_key.expose().as_bytes()) .change_context(errors::PazeDecryptionError::Base64DecodingFailed)?; let decrypted_private_key = openssl::rsa::Rsa::private_key_from_pem_passphrase( decoded_paze_private_key.as_slice(), paze_private_key_passphrase.expose().as_bytes(), ) .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?; let decrypted_private_key_pem = String::from_utf8( decrypted_private_key .private_key_to_pem() .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?, ) .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?; let decrypter = jwe::RSA_OAEP_256 .decrypter_from_pem(decrypted_private_key_pem) .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?; let paze_complete_response: Vec<&str> = paze_wallet_data .complete_response .peek() .split('.') .collect(); let encrypted_jwe_key = paze_complete_response .get(1) .ok_or(errors::PazeDecryptionError::DecryptionFailed)? .to_string(); let decoded_jwe_key = base64::engine::general_purpose::URL_SAFE_NO_PAD .decode(encrypted_jwe_key) .change_context(errors::PazeDecryptionError::Base64DecodingFailed)?; let jws_body: JwsBody = serde_json::from_slice(&decoded_jwe_key) .change_context(errors::PazeDecryptionError::DecryptionFailed)?; let (deserialized_payload, _deserialized_header) = jwe::deserialize_compact(jws_body.secured_payload.peek(), &decrypter) .change_context(errors::PazeDecryptionError::DecryptionFailed)?; let encoded_secured_payload_element = String::from_utf8(deserialized_payload) .change_context(errors::PazeDecryptionError::DecryptionFailed)? .split('.') .collect::<Vec<&str>>() .get(1) .ok_or(errors::PazeDecryptionError::DecryptionFailed)? .to_string(); let decoded_secured_payload_element = base64::engine::general_purpose::URL_SAFE_NO_PAD .decode(encoded_secured_payload_element) .change_context(errors::PazeDecryptionError::Base64DecodingFailed)?; let parsed_decrypted: serde_json::Value = serde_json::from_slice(&decoded_secured_payload_element) .change_context(errors::PazeDecryptionError::DecryptionFailed)?; Ok(parsed_decrypted) } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct JwsBody { pub payload_id: String, pub session_id: String, pub secured_payload: masking::Secret<String>, } pub fn get_key_params_for_surcharge_details( payment_method_data: &domain::PaymentMethodData, ) -> Option<( common_enums::PaymentMethod, common_enums::PaymentMethodType, Option<common_enums::CardNetwork>, )> { match payment_method_data { domain::PaymentMethodData::Card(card) => { // surcharge generated will always be same for credit as well as debit // since surcharge conditions cannot be defined on card_type Some(( common_enums::PaymentMethod::Card, common_enums::PaymentMethodType::Credit, card.card_network.clone(), )) } domain::PaymentMethodData::CardRedirect(card_redirect_data) => Some(( common_enums::PaymentMethod::CardRedirect, card_redirect_data.get_payment_method_type(), None, )), domain::PaymentMethodData::Wallet(wallet) => Some(( common_enums::PaymentMethod::Wallet, wallet.get_payment_method_type(), None, )), domain::PaymentMethodData::PayLater(pay_later) => Some(( common_enums::PaymentMethod::PayLater, pay_later.get_payment_method_type(), None, )), domain::PaymentMethodData::BankRedirect(bank_redirect) => Some(( common_enums::PaymentMethod::BankRedirect, bank_redirect.get_payment_method_type(), None, )), domain::PaymentMethodData::BankDebit(bank_debit) => Some(( common_enums::PaymentMethod::BankDebit, bank_debit.get_payment_method_type(), None, )), domain::PaymentMethodData::BankTransfer(bank_transfer) => Some(( common_enums::PaymentMethod::BankTransfer, bank_transfer.get_payment_method_type(), None, )), domain::PaymentMethodData::Crypto(crypto) => Some(( common_enums::PaymentMethod::Crypto, crypto.get_payment_method_type(), None, )), domain::PaymentMethodData::MandatePayment => None, domain::PaymentMethodData::Reward => None, domain::PaymentMethodData::RealTimePayment(real_time_payment) => Some(( common_enums::PaymentMethod::RealTimePayment, real_time_payment.get_payment_method_type(), None, )), domain::PaymentMethodData::Upi(upi_data) => Some(( common_enums::PaymentMethod::Upi, upi_data.get_payment_method_type(), None, )), domain::PaymentMethodData::Voucher(voucher) => Some(( common_enums::PaymentMethod::Voucher, voucher.get_payment_method_type(), None, )), domain::PaymentMethodData::GiftCard(gift_card) => Some(( common_enums::PaymentMethod::GiftCard, gift_card.get_payment_method_type(), None, )), domain::PaymentMethodData::OpenBanking(ob_data) => Some(( common_enums::PaymentMethod::OpenBanking, ob_data.get_payment_method_type(), None, )), domain::PaymentMethodData::MobilePayment(mobile_payment) => Some(( common_enums::PaymentMethod::MobilePayment, mobile_payment.get_payment_method_type(), None, )), domain::PaymentMethodData::CardToken(_) | domain::PaymentMethodData::NetworkToken(_) | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => None, } } pub fn validate_payment_link_request( request: &api::PaymentsRequest, ) -> Result<(), errors::ApiErrorResponse> { #[cfg(feature = "v1")] if request.confirm == Some(true) { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "cannot confirm a payment while creating a payment link".to_string(), }); } if request.return_url.is_none() { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "return_url must be sent while creating a payment link".to_string(), }); } Ok(()) } pub async fn get_gsm_record( state: &SessionState, error_code: Option<String>, error_message: Option<String>, connector_name: String, flow: String, ) -> Option<hyperswitch_domain_models::gsm::GatewayStatusMap> { let get_gsm = || async { state.store.find_gsm_rule( connector_name.clone(), flow.clone(), "sub_flow".to_string(), error_code.clone().unwrap_or_default(), // TODO: make changes in connector to get a mandatory code in case of success or error response error_message.clone().unwrap_or_default(), ) .await .map_err(|err| { if err.current_context().is_db_not_found() { logger::warn!( "GSM miss for connector - {}, flow - {}, error_code - {:?}, error_message - {:?}", connector_name, flow, error_code, error_message ); metrics::AUTO_RETRY_GSM_MISS_COUNT.add( 1, &[]); } else { metrics::AUTO_RETRY_GSM_FETCH_FAILURE_COUNT.add( 1, &[]); }; err.change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch decision from gsm") }) }; get_gsm() .await .inspect_err(|err| { // warn log should suffice here because we are not propagating this error logger::warn!(get_gsm_decision_fetch_error=?err, "error fetching gsm decision"); }) .ok() } pub async fn get_unified_translation( state: &SessionState, unified_code: String, unified_message: String, locale: String, ) -> Option<String> { let get_unified_translation = || async { state.store.find_translation( unified_code.clone(), unified_message.clone(), locale.clone(), ) .await .map_err(|err| { if err.current_context().is_db_not_found() { logger::warn!( "Translation missing for unified_code - {:?}, unified_message - {:?}, locale - {:?}", unified_code, unified_message, locale ); } err.change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch translation from unified_translations") }) }; get_unified_translation() .await .inspect_err(|err| { // warn log should suffice here because we are not propagating this error logger::warn!(get_translation_error=?err, "error fetching unified translations"); }) .ok() } pub fn validate_order_details_amount( order_details: Vec<api_models::payments::OrderDetailsWithAmount>, amount: MinorUnit, should_validate: bool, ) -> Result<(), errors::ApiErrorResponse> { if should_validate { let total_order_details_amount: MinorUnit = order_details .iter() .map(|order| order.amount * order.quantity) .sum(); if total_order_details_amount != amount { Err(errors::ApiErrorResponse::InvalidRequestData { message: "Total sum of order details doesn't match amount in payment request" .to_string(), }) } else { Ok(()) } } else { Ok(()) } } // This function validates the client secret expiry set by the merchant in the request pub fn validate_session_expiry(session_expiry: u32) -> Result<(), errors::ApiErrorResponse> { if !(consts::MIN_SESSION_EXPIRY..=consts::MAX_SESSION_EXPIRY).contains(&session_expiry) { Err(errors::ApiErrorResponse::InvalidRequestData { message: "session_expiry should be between 60(1 min) to 7890000(3 months).".to_string(), }) } else { Ok(()) } } pub fn get_recipient_id_for_open_banking( merchant_data: &AdditionalMerchantData, ) -> Result<Option<String>, errors::ApiErrorResponse> { match merchant_data { AdditionalMerchantData::OpenBankingRecipientData(data) => match data { MerchantRecipientData::ConnectorRecipientId(id) => Ok(Some(id.peek().clone())), MerchantRecipientData::AccountData(acc_data) => { let connector_recipient_id = match acc_data { MerchantAccountData::Bacs { connector_recipient_id, .. } | MerchantAccountData::Iban { connector_recipient_id, .. } | MerchantAccountData::FasterPayments { connector_recipient_id, .. } | MerchantAccountData::Sepa { connector_recipient_id, .. } | MerchantAccountData::SepaInstant { connector_recipient_id, .. } | MerchantAccountData::Elixir { connector_recipient_id, .. } | MerchantAccountData::Bankgiro { connector_recipient_id, .. } | MerchantAccountData::Plusgiro { connector_recipient_id, .. } => connector_recipient_id, }; match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Ok(Some(id.peek().clone())), Some(RecipientIdType::LockerId(id)) => Ok(Some(id.peek().clone())), _ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration { config: "recipient_id".to_string(), }), } } _ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration { config: "recipient_id".to_string(), }), }, } } // This function validates the intent fulfillment time expiry set by the merchant in the request pub fn validate_intent_fulfillment_expiry( intent_fulfillment_time: u32, ) -> Result<(), errors::ApiErrorResponse> { if !(consts::MIN_INTENT_FULFILLMENT_EXPIRY..=consts::MAX_INTENT_FULFILLMENT_EXPIRY) .contains(&intent_fulfillment_time) { Err(errors::ApiErrorResponse::InvalidRequestData { message: "intent_fulfillment_time should be between 60(1 min) to 1800(30 mins)." .to_string(), }) } else { Ok(()) } } pub fn add_connector_response_to_additional_payment_data( additional_payment_data: api_models::payments::AdditionalPaymentData, connector_response_payment_method_data: AdditionalPaymentMethodConnectorResponse, ) -> api_models::payments::AdditionalPaymentData { match ( &additional_payment_data, connector_response_payment_method_data, ) { ( api_models::payments::AdditionalPaymentData::Card(additional_card_data), AdditionalPaymentMethodConnectorResponse::Card { authentication_data, payment_checks, .. }, ) => api_models::payments::AdditionalPaymentData::Card(Box::new( api_models::payments::AdditionalCardInfo { payment_checks, authentication_data, ..*additional_card_data.clone() }, )), ( api_models::payments::AdditionalPaymentData::PayLater { .. }, AdditionalPaymentMethodConnectorResponse::PayLater { klarna_sdk: Some(KlarnaSdkResponse { payment_type }), }, ) => api_models::payments::AdditionalPaymentData::PayLater { klarna_sdk: Some(api_models::payments::KlarnaSdkPaymentMethod { payment_type }), }, _ => additional_payment_data, } } pub fn update_additional_payment_data_with_connector_response_pm_data( additional_payment_data: Option<serde_json::Value>, connector_response_pm_data: Option<AdditionalPaymentMethodConnectorResponse>, ) -> RouterResult<Option<serde_json::Value>> { let parsed_additional_payment_method_data = additional_payment_data .as_ref() .map(|payment_method_data| { payment_method_data .clone() .parse_value::<api_models::payments::AdditionalPaymentData>( "additional_payment_method_data", ) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to parse value into additional_payment_method_data")?; let additional_payment_method_data = parsed_additional_payment_method_data .zip(connector_response_pm_data) .map(|(additional_pm_data, connector_response_pm_data)| { add_connector_response_to_additional_payment_data( additional_pm_data, connector_response_pm_data, ) }); additional_payment_method_data .as_ref() .map(Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode additional pm data") } #[cfg(feature = "v2")] pub async fn get_payment_method_details_from_payment_token( state: &SessionState, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> { todo!() } #[cfg(feature = "v1")] pub async fn get_payment_method_details_from_payment_token( state: &SessionState, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> { let hyperswitch_token = if let Some(token) = payment_attempt.payment_token.clone() { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let key = format!( "pm_token_{}_{}_hyperswitch", token, payment_attempt .payment_method .to_owned() .get_required_value("payment_method")?, ); let token_data_string = redis_conn .get_key::<Option<String>>(&key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch the token from redis")? .ok_or(error_stack::Report::new( errors::ApiErrorResponse::UnprocessableEntity { message: "Token is invalid or expired".to_owned(), }, ))?; let token_data_result = token_data_string .clone() .parse_struct("PaymentTokenData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to deserialize hyperswitch token data"); let token_data = match token_data_result { Ok(data) => data, Err(e) => { // The purpose of this logic is backwards compatibility to support tokens // in redis that might be following the old format. if token_data_string.starts_with('{') { return Err(e); } else { storage::PaymentTokenData::temporary_generic(token_data_string) } } }; Some(token_data) } else { None }; let token = hyperswitch_token .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing hyperswitch_token")?; match token { storage::PaymentTokenData::TemporaryGeneric(generic_token) => { retrieve_payment_method_with_temporary_token( state, &generic_token.token, payment_intent, payment_attempt, key_store, None, ) .await } storage::PaymentTokenData::Temporary(generic_token) => { retrieve_payment_method_with_temporary_token( state, &generic_token.token, payment_intent, payment_attempt, key_store, None, ) .await } storage::PaymentTokenData::Permanent(card_token) => { retrieve_card_with_permanent_token_for_external_authentication( state, &card_token.token, payment_intent, None, key_store, storage_scheme, ) .await .map(|card| Some((card, enums::PaymentMethod::Card))) } storage::PaymentTokenData::PermanentCard(card_token) => { retrieve_card_with_permanent_token_for_external_authentication( state, &card_token.token, payment_intent, None, key_store, storage_scheme, ) .await .map(|card| Some((card, enums::PaymentMethod::Card))) } storage::PaymentTokenData::AuthBankDebit(auth_token) => { retrieve_payment_method_from_auth_service( state, key_store, &auth_token, payment_intent, &None, ) .await } storage::PaymentTokenData::WalletToken(_) => Ok(None), } } // This function validates the mandate_data with its setup_future_usage pub fn validate_mandate_data_and_future_usage( setup_future_usages: Option<api_enums::FutureUsage>, mandate_details_present: bool, ) -> Result<(), errors::ApiErrorResponse> { if mandate_details_present && (Some(api_enums::FutureUsage::OnSession) == setup_future_usages || setup_future_usages.is_none()) { Err(errors::ApiErrorResponse::PreconditionFailed { message: "`setup_future_usage` must be `off_session` for mandates".into(), }) } else { Ok(()) } } #[derive(Debug, Clone)] pub enum UnifiedAuthenticationServiceFlow { ClickToPayInitiate, ExternalAuthenticationInitiate { acquirer_details: Option<authentication::types::AcquirerDetails>, card: Box<hyperswitch_domain_models::payment_method_data::Card>, token: String, }, ExternalAuthenticationPostAuthenticate { authentication_id: id_type::AuthenticationId, }, } #[cfg(feature = "v1")] pub async fn decide_action_for_unified_authentication_service<F: Clone>( state: &SessionState, key_store: &domain::MerchantKeyStore, business_profile: &domain::Profile, payment_data: &mut PaymentData<F>, connector_call_type: &api::ConnectorCallType, mandate_type: Option<api_models::payments::MandateTransactionType>, ) -> RouterResult<Option<UnifiedAuthenticationServiceFlow>> { let external_authentication_flow = get_payment_external_authentication_flow_during_confirm( state, key_store, business_profile, payment_data, connector_call_type, mandate_type, ) .await?; Ok(match external_authentication_flow { Some(PaymentExternalAuthenticationFlow::PreAuthenticationFlow { acquirer_details, card, token, }) => Some( UnifiedAuthenticationServiceFlow::ExternalAuthenticationInitiate { acquirer_details, card, token, }, ), Some(PaymentExternalAuthenticationFlow::PostAuthenticationFlow { authentication_id }) => { Some( UnifiedAuthenticationServiceFlow::ExternalAuthenticationPostAuthenticate { authentication_id, }, ) } None => { if let Some(payment_method) = payment_data.payment_attempt.payment_method { if payment_method == storage_enums::PaymentMethod::Card && business_profile.is_click_to_pay_enabled && payment_data.service_details.is_some() { Some(UnifiedAuthenticationServiceFlow::ClickToPayInitiate) } else { None } } else { logger::info!( payment_method=?payment_data.payment_attempt.payment_method, click_to_pay_enabled=?business_profile.is_click_to_pay_enabled, "skipping unified authentication service call since payment conditions are not satisfied" ); None } } }) } pub enum PaymentExternalAuthenticationFlow { PreAuthenticationFlow { acquirer_details: Option<authentication::types::AcquirerDetails>, card: Box<hyperswitch_domain_models::payment_method_data::Card>, token: String, },
crates/router/src/core/payments/helpers.rs#chunk6
router
chunk
null
null
null
8,191
null
null
null
null
null
null
null
// Implementation: impl FilteredPaymentMethodsEnabled // File: crates/router/src/core/payments/payment_methods.rs // Module: router // Methods: 2 total (0 public) impl FilteredPaymentMethodsEnabled
crates/router/src/core/payments/payment_methods.rs
router
impl_block
null
null
null
44
null
FilteredPaymentMethodsEnabled
null
2
0
null
null
// Function: fetch_routing_algo // File: crates/router/src/core/routing.rs // Module: router pub fn fetch_routing_algo( merchant_id: &common_utils::id_type::MerchantId, algorithm_id: &common_utils::id_type::RoutingId, db: &dyn StorageInterface, ) -> RouterResult<Self>
crates/router/src/core/routing.rs
router
function_signature
null
null
null
72
fetch_routing_algo
null
null
null
null
null
null
// Struct: OrganizationId // File: crates/api_models/src/organization.rs // Module: api_models // Implementations: 0 pub struct OrganizationId
crates/api_models/src/organization.rs
api_models
struct_definition
OrganizationId
0
[]
34
null
null
null
null
null
null
null
// Implementation: impl ConnectorValidation for for Taxjar // File: crates/hyperswitch_connectors/src/connectors/taxjar.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl ConnectorValidation for for Taxjar
crates/hyperswitch_connectors/src/connectors/taxjar.rs
hyperswitch_connectors
impl_block
null
null
null
54
null
Taxjar
ConnectorValidation for
0
0
null
null
// File: crates/hyperswitch_connectors/src/connectors/wellsfargopayout.rs // Module: hyperswitch_connectors // Public functions: 1 // Public structs: 1 pub mod transformers; use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session, SetupMandate, Void, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, }, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, errors::ConnectorError, events::connector_api_logs::ConnectorEvent, types::{ PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, RefundExecuteType, RefundSyncType, Response, }, webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; use masking::{ExposeInterface, Mask as _, Maskable}; use self::transformers as wellsfargopayout; use crate::{constants::headers, types::ResponseRouterData, utils::convert_amount}; #[derive(Clone)] pub struct Wellsfargopayout { amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), } impl Wellsfargopayout { pub fn new() -> &'static Self { &Self { amount_converter: &StringMinorUnitForConnector, } } } impl api::Payment for Wellsfargopayout {} impl api::PaymentSession for Wellsfargopayout {} impl api::ConnectorAccessToken for Wellsfargopayout {} impl api::MandateSetup for Wellsfargopayout {} impl api::PaymentAuthorize for Wellsfargopayout {} impl api::PaymentSync for Wellsfargopayout {} impl api::PaymentCapture for Wellsfargopayout {} impl api::PaymentVoid for Wellsfargopayout {} impl api::Refund for Wellsfargopayout {} impl api::RefundExecute for Wellsfargopayout {} impl api::RefundSync for Wellsfargopayout {} impl api::PaymentToken for Wellsfargopayout {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Wellsfargopayout { // Not Implemented (R) } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Wellsfargopayout where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Wellsfargopayout { fn id(&self) -> &'static str { "wellsfargopayout" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Minor // todo!() // TODO! Check connector documentation, on which unit they are processing the currency. // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor, // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.wellsfargopayout.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let auth = wellsfargopayout::WellsfargopayoutAuthType::try_from(auth_type) .change_context(ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), auth.api_key.expose().into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { let response: wellsfargopayout::WellsfargopayoutErrorResponse = res .response .parse_struct("WellsfargopayoutErrorResponse") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: response.code, message: response.message, reason: response.reason, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl ConnectorValidation for Wellsfargopayout { //TODO: implement functions when support enabled } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Wellsfargopayout { //TODO: implement sessions flow } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Wellsfargopayout { } impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Wellsfargopayout { } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Wellsfargopayout { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Err(ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = wellsfargopayout::WellsfargopayoutRouterData::from((amount, req)); let connector_req = wellsfargopayout::WellsfargopayoutPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, ConnectorError> { let response: wellsfargopayout::WellsfargopayoutPaymentsResponse = res .response .parse_struct("Wellsfargopayout PaymentsAuthorizeResponse") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Wellsfargopayout { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsSyncRouterData, _connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Err(ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, ConnectorError> { let response: wellsfargopayout::WellsfargopayoutPaymentsResponse = res .response .parse_struct("wellsfargopayout PaymentsSyncResponse") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Wellsfargopayout { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Err(ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, ConnectorError> { Err(ConnectorError::NotImplemented("get_request_body method".to_string()).into()) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsCaptureType::get_headers(self, req, connectors)?) .set_body(PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, ConnectorError> { let response: wellsfargopayout::WellsfargopayoutPaymentsResponse = res .response .parse_struct("Wellsfargopayout PaymentsCaptureResponse") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Wellsfargopayout {} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Wellsfargopayout { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Err(ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, ConnectorError> { let refund_amount = convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = wellsfargopayout::WellsfargopayoutRouterData::from((refund_amount, req)); let connector_req = wellsfargopayout::WellsfargopayoutRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(RefundExecuteType::get_headers(self, req, connectors)?) .set_body(RefundExecuteType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, ConnectorError> { let response: wellsfargopayout::RefundResponse = res .response .parse_struct("wellsfargopayout RefundResponse") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Wellsfargopayout { fn get_headers( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundSyncRouterData, _connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Err(ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(RefundSyncType::get_headers(self, req, connectors)?) .set_body(RefundSyncType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, ConnectorError> { let response: wellsfargopayout::RefundResponse = res .response .parse_struct("wellsfargopayout RefundSyncResponse") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl IncomingWebhook for Wellsfargopayout { fn get_webhook_object_reference_id( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<ObjectReferenceId, ConnectorError> { Err(report!(ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { Err(report!(ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { Err(report!(ConnectorError::WebhooksNotImplemented)) } } static WELLSFARGOPAYOUTS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Wellsfargo Payout", description: "Wells Fargo Payouts streamlines secure domestic and international payments for businesses via online banking, supporting Bill Pay, Digital Wires, and Zelle", connector_type: common_enums::HyperswitchConnectorCategory::PayoutProcessor, integration_status: common_enums::ConnectorIntegrationStatus::Sandbox, }; impl ConnectorSpecifications for Wellsfargopayout { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&WELLSFARGOPAYOUTS_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { None } fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> { None } }
crates/hyperswitch_connectors/src/connectors/wellsfargopayout.rs
hyperswitch_connectors
full_file
null
null
null
4,618
null
null
null
null
null
null
null
// Implementation: impl ConnectorCommon for for Inespay // File: crates/hyperswitch_connectors/src/connectors/inespay.rs // Module: hyperswitch_connectors // Methods: 6 total (0 public) impl ConnectorCommon for for Inespay
crates/hyperswitch_connectors/src/connectors/inespay.rs
hyperswitch_connectors
impl_block
null
null
null
56
null
Inespay
ConnectorCommon for
6
0
null
null
// Struct: PayloadCaptureRequest // File: crates/hyperswitch_connectors/src/connectors/payload/requests.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PayloadCaptureRequest
crates/hyperswitch_connectors/src/connectors/payload/requests.rs
hyperswitch_connectors
struct_definition
PayloadCaptureRequest
0
[]
46
null
null
null
null
null
null
null
// Function: delete_by_theme_id // File: crates/diesel_models/src/query/user/theme.rs // Module: diesel_models pub fn delete_by_theme_id(conn: &PgPooledConn, theme_id: String) -> StorageResult<Self>
crates/diesel_models/src/query/user/theme.rs
diesel_models
function_signature
null
null
null
51
delete_by_theme_id
null
null
null
null
null
null
// Struct: NetworkTokenizationBuilder // File: crates/router/src/core/payment_methods/tokenize.rs // Module: router // Implementations: 0 pub struct NetworkTokenizationBuilder<'a, S: State>
crates/router/src/core/payment_methods/tokenize.rs
router
struct_definition
NetworkTokenizationBuilder
0
[]
46
null
null
null
null
null
null
null
// Struct: ThreeDsMethodData // File: crates/hyperswitch_domain_models/src/router_request_types/authentication.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct ThreeDsMethodData
crates/hyperswitch_domain_models/src/router_request_types/authentication.rs
hyperswitch_domain_models
struct_definition
ThreeDsMethodData
0
[]
46
null
null
null
null
null
null
null
// Function: set_time_range // File: crates/analytics/src/opensearch.rs // Module: analytics pub fn set_time_range(&mut self, time_range: OpensearchTimeRange) -> QueryResult<()>
crates/analytics/src/opensearch.rs
analytics
function_signature
null
null
null
46
set_time_range
null
null
null
null
null
null
// File: crates/euclid/src/frontend/ast.rs // Module: euclid // Public functions: 1 // Public structs: 9 pub mod lowering; #[cfg(feature = "ast_parser")] pub mod parser; use common_enums::RoutableConnectors; use common_utils::types::MinorUnit; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::types::{DataType, Metadata}; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] pub struct ConnectorChoice { pub connector: RoutableConnectors, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)] pub struct MetadataValue { pub key: String, pub value: String, } /// Represents a value in the DSL #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)] #[serde(tag = "type", content = "value", rename_all = "snake_case")] pub enum ValueType { /// Represents a number literal Number(MinorUnit), /// Represents an enum variant EnumVariant(String), /// Represents a Metadata variant MetadataVariant(MetadataValue), /// Represents a arbitrary String value StrValue(String), /// Represents an array of numbers. This is basically used for /// "one of the given numbers" operations /// eg: payment.method.amount = (1, 2, 3) NumberArray(Vec<MinorUnit>), /// Similar to NumberArray but for enum variants /// eg: payment.method.cardtype = (debit, credit) EnumVariantArray(Vec<String>), /// Like a number array but can include comparisons. Useful for /// conditions like "500 < amount < 1000" /// eg: payment.amount = (> 500, < 1000) NumberComparisonArray(Vec<NumberComparison>), } impl ValueType { pub fn get_type(&self) -> DataType { match self { Self::Number(_) => DataType::Number, Self::StrValue(_) => DataType::StrValue, Self::MetadataVariant(_) => DataType::MetadataValue, Self::EnumVariant(_) => DataType::EnumVariant, Self::NumberComparisonArray(_) => DataType::Number, Self::NumberArray(_) => DataType::Number, Self::EnumVariantArray(_) => DataType::EnumVariant, } } } /// Represents a number comparison for "NumberComparisonArrayValue" #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct NumberComparison { pub comparison_type: ComparisonType, pub number: MinorUnit, } /// Conditional comparison type #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ComparisonType { Equal, NotEqual, LessThan, LessThanEqual, GreaterThan, GreaterThanEqual, } /// Represents a single comparison condition. #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct Comparison { /// The left hand side which will always be a domain input identifier like "payment.method.cardtype" pub lhs: String, /// The comparison operator pub comparison: ComparisonType, /// The value to compare against pub value: ValueType, /// Additional metadata that the Static Analyzer and Backend does not touch. /// This can be used to store useful information for the frontend and is required for communication /// between the static analyzer and the frontend. #[schema(value_type=HashMap<String, serde_json::Value>)] pub metadata: Metadata, } /// Represents all the conditions of an IF statement /// eg: /// /// ```text /// payment.method = card & payment.method.cardtype = debit & payment.method.network = diners /// ``` pub type IfCondition = Vec<Comparison>; /// Represents an IF statement with conditions and optional nested IF statements /// /// ```text /// payment.method = card { /// payment.method.cardtype = (credit, debit) { /// payment.method.network = (amex, rupay, diners) /// } /// } /// ``` #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct IfStatement { #[schema(value_type=Vec<Comparison>)] pub condition: IfCondition, pub nested: Option<Vec<IfStatement>>, } /// Represents a rule /// /// ```text /// rule_name: [stripe, adyen, checkout] /// { /// payment.method = card { /// payment.method.cardtype = (credit, debit) { /// payment.method.network = (amex, rupay, diners) /// } /// /// payment.method.cardtype = credit /// } /// } /// ``` #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] #[aliases(RuleConnectorSelection = Rule<ConnectorSelection>)] pub struct Rule<O> { pub name: String, #[serde(alias = "routingOutput")] pub connector_selection: O, pub statements: Vec<IfStatement>, } /// The program, having a default connector selection and /// a bunch of rules. Also can hold arbitrary metadata. #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] #[aliases(ProgramConnectorSelection = Program<ConnectorSelection>)] pub struct Program<O> { pub default_selection: O, #[schema(value_type=RuleConnectorSelection)] pub rules: Vec<Rule<O>>, #[schema(value_type=HashMap<String, serde_json::Value>)] pub metadata: Metadata, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct RoutableConnectorChoice { #[serde(skip)] pub choice_kind: RoutableChoiceKind, pub connector: RoutableConnectors, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] pub enum RoutableChoiceKind { OnlyConnector, #[default] FullStruct, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct ConnectorVolumeSplit { pub connector: RoutableConnectorChoice, pub split: u8, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum ConnectorSelection { Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), }
crates/euclid/src/frontend/ast.rs
euclid
full_file
null
null
null
1,399
null
null
null
null
null
null
null
// Struct: AmountOfMoney // File: crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct AmountOfMoney
crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs
hyperswitch_connectors
struct_definition
AmountOfMoney
0
[]
47
null
null
null
null
null
null
null
// Struct: BlackhawknetworkAccessTokenRequest // File: crates/hyperswitch_connectors/src/connectors/blackhawknetwork/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct BlackhawknetworkAccessTokenRequest
crates/hyperswitch_connectors/src/connectors/blackhawknetwork/transformers.rs
hyperswitch_connectors
struct_definition
BlackhawknetworkAccessTokenRequest
0
[]
52
null
null
null
null
null
null
null
// Struct: AlipayInfo // File: crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct AlipayInfo
crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs
hyperswitch_connectors
struct_definition
AlipayInfo
0
[]
51
null
null
null
null
null
null
null
// Function: make_dsl_input_for_surcharge // File: crates/router/src/core/payments/routing.rs // Module: router pub fn make_dsl_input_for_surcharge( payment_attempt: &oss_storage::PaymentAttempt, payment_intent: &oss_storage::PaymentIntent, billing_address: Option<Address>, ) -> RoutingResult<dsl_inputs::BackendInput>
crates/router/src/core/payments/routing.rs
router
function_signature
null
null
null
79
make_dsl_input_for_surcharge
null
null
null
null
null
null
// Function: add_header // File: crates/common_utils/src/request.rs // Module: common_utils pub fn add_header(&mut self, header: &str, value: Maskable<String>)
crates/common_utils/src/request.rs
common_utils
function_signature
null
null
null
41
add_header
null
null
null
null
null
null
// Struct: MerchantConnectorAccountNew // File: crates/diesel_models/src/merchant_connector_account.rs // Module: diesel_models // Implementations: 0 pub struct MerchantConnectorAccountNew
crates/diesel_models/src/merchant_connector_account.rs
diesel_models
struct_definition
MerchantConnectorAccountNew
0
[]
41
null
null
null
null
null
null
null