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
// Implementation: impl MandateUpdateInternal // File: crates/diesel_models/src/mandate.rs // Module: diesel_models // Methods: 1 total (1 public) impl MandateUpdateInternal
crates/diesel_models/src/mandate.rs
diesel_models
impl_block
null
null
null
43
null
MandateUpdateInternal
null
1
1
null
null
// File: crates/hyperswitch_connectors/src/connectors/gpayments/gpayments_types.rs // Module: hyperswitch_connectors // Public structs: 10 use api_models::payments::ThreeDsCompletionIndicator; use cards::CardNumber; use common_utils::types; use masking::{Deserialize, Secret, Serialize}; #[derive(Debug, Serialize, Deserialize)] pub struct GpaymentsConnectorMetaData { pub authentication_url: String, pub three_ds_requestor_trans_id: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct GpaymentsPreAuthVersionCallRequest { pub acct_number: CardNumber, pub merchant_id: common_utils::id_type::MerchantId, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct GpaymentsPreAuthVersionCallResponse { pub enrolment_status: EnrollmentStatus, pub supported_message_versions: Option<Vec<types::SemanticVersion>>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum EnrollmentStatus { #[serde(rename = "00")] NotEnrolled, #[serde(rename = "01")] Enrolled, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct TDS2ApiError { pub error_code: String, pub error_component: Option<String>, pub error_description: String, pub error_detail: Option<String>, pub error_message_type: Option<String>, /// Always returns 'Error' to indicate that this message is an error. /// /// Example: "Error" pub message_type: String, pub message_version: Option<String>, #[serde(rename = "sdkTransID")] pub sdk_trans_id: Option<String>, #[serde(rename = "threeDSServerTransID")] pub three_ds_server_trans_id: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct GpaymentsPreAuthenticationRequest { pub acct_number: CardNumber, pub card_scheme: Option<CardScheme>, pub challenge_window_size: Option<ChallengeWindowSize>, /// URL where the 3DS requestor receives events during authentication. /// ActiveServer calls this URL through the iframe to notify events occurring during authentication. /// /// Example: "https://example.requestor.com/3ds-notify" /// Length: Maximum 2000 characters pub event_callback_url: String, /// Merchant identifier assigned by the acquirer. /// This may be the same value used in authorization requests sent on behalf of the 3DS Requestor. /// /// Example: "1234567890123456789012345678901234" /// Length: Maximum 35 characters pub merchant_id: common_utils::id_type::MerchantId, /// Optional boolean. If set to true, ActiveServer will not collect the browser information automatically. /// The requestor must have a backend implementation to collect browser information. pub skip_auto_browser_info_collect: Option<bool>, /// Universal unique transaction identifier assigned by the 3DS Requestor to identify a single transaction. /// /// Example: "6afa6072-9412-446b-9673-2f98b3ee98a2" /// Length: 36 characters #[serde(rename = "threeDSRequestorTransID")] pub three_ds_requestor_trans_id: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum ChallengeWindowSize { #[serde(rename = "01")] Size250x400, #[serde(rename = "02")] Size390x400, #[serde(rename = "03")] Size500x600, #[serde(rename = "04")] Size600x400, #[serde(rename = "05")] FullScreen, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "UPPERCASE")] pub enum CardScheme { Visa, MasterCard, AmericanExpress, JCB, Discover, UnionPay, Mir, Eftpos, BCard, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct GpaymentsPreAuthenticationResponse { pub auth_url: String, pub mon_url: Option<String>, pub resolved_card_scheme: Option<CardScheme>, #[serde(rename = "threeDSMethodAvailable")] pub three_ds_method_available: Option<bool>, #[serde(rename = "threeDSMethodUrl")] pub three_ds_method_url: Option<String>, #[serde(rename = "threeDSServerCallbackUrl")] pub three_ds_server_callback_url: Option<String>, #[serde(rename = "threeDSServerTransID")] pub three_ds_server_trans_id: String, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct GpaymentsAuthenticationRequest { pub acct_number: CardNumber, pub authentication_ind: String, pub browser_info_collected: BrowserInfoCollected, pub card_expiry_date: String, #[serde(rename = "notificationURL")] pub notification_url: String, pub merchant_id: common_utils::id_type::MerchantId, #[serde(rename = "threeDSCompInd")] pub three_ds_comp_ind: ThreeDsCompletionIndicator, pub message_category: String, pub purchase_amount: String, pub purchase_date: String, #[serde(rename = "threeDSServerTransID")] pub three_ds_server_trans_id: String, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct BrowserInfoCollected { pub browser_accept_header: Option<String>, pub browser_color_depth: Option<String>, #[serde(rename = "browserIP")] pub browser_ip: Option<Secret<String, common_utils::pii::IpAddress>>, pub browser_javascript_enabled: Option<bool>, pub browser_java_enabled: Option<bool>, pub browser_language: Option<String>, pub browser_screen_height: Option<String>, pub browser_screen_width: Option<String>, #[serde(rename = "browserTZ")] pub browser_tz: Option<String>, pub browser_user_agent: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum AuthenticationInd { #[serde(rename = "01")] PaymentTransaction, #[serde(rename = "02")] RecurringTransaction, #[serde(rename = "03")] InstalmentTransaction, #[serde(rename = "04")] AddCard, #[serde(rename = "05")] MaintainCard, #[serde(rename = "06")] CardholderVerification, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct GpaymentsAuthenticationSuccessResponse { #[serde(rename = "dsReferenceNumber")] pub ds_reference_number: String, #[serde(rename = "dsTransID")] pub ds_trans_id: String, #[serde(rename = "threeDSServerTransID")] pub three_ds_server_trans_id: String, #[serde(rename = "messageVersion")] pub message_version: String, #[serde(rename = "transStatus")] pub trans_status: AuthStatus, #[serde(rename = "acsTransID")] pub acs_trans_id: String, #[serde(rename = "challengeUrl")] pub acs_url: Option<url::Url>, #[serde(rename = "acsReferenceNumber")] pub acs_reference_number: String, pub authentication_value: Option<Secret<String>>, } #[derive(Deserialize, Debug, Clone, Serialize, PartialEq)] pub enum AuthStatus { /// Authentication/ Account Verification Successful Y, /// Not Authenticated /Account Not Verified; Transaction denied N, /// Authentication/ Account Verification Could Not Be Performed; Technical or other problem, as indicated in ARes or RReq U, /// Attempts Processing Performed; Not Authenticated/Verified , but a proof of attempted authentication/verification is provided A, /// Authentication/ Account Verification Rejected; Issuer is rejecting authentication/verification and request that authorisation not be attempted. R, /// Challenge required C, } impl From<AuthStatus> for common_enums::TransactionStatus { fn from(value: AuthStatus) -> Self { match value { AuthStatus::Y => Self::Success, AuthStatus::N => Self::Failure, AuthStatus::U => Self::VerificationNotPerformed, AuthStatus::A => Self::NotVerified, AuthStatus::R => Self::Rejected, AuthStatus::C => Self::ChallengeRequired, } } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GpaymentsPostAuthenticationResponse { pub authentication_value: Option<Secret<String>>, pub trans_status: AuthStatus, pub eci: Option<String>, }
crates/hyperswitch_connectors/src/connectors/gpayments/gpayments_types.rs
hyperswitch_connectors
full_file
null
null
null
1,965
null
null
null
null
null
null
null
// Function: save_migration_payment_method // File: crates/payment_methods/src/core/migration/payment_methods.rs // Module: payment_methods pub fn save_migration_payment_method( req: pm_api::PaymentMethodCreate, migration_status: &mut migration::RecordMigrationStatusBuilder, controller: &dyn PaymentMethodsController, ) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodResponse>, errors::ApiErrorResponse>
crates/payment_methods/src/core/migration/payment_methods.rs
payment_methods
function_signature
null
null
null
86
save_migration_payment_method
null
null
null
null
null
null
// Struct: NmiRouterData // File: crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct NmiRouterData<T>
crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
hyperswitch_connectors
struct_definition
NmiRouterData
0
[]
51
null
null
null
null
null
null
null
// Function: new // File: crates/hyperswitch_connectors/src/connectors/worldpay/response.rs // Module: hyperswitch_connectors pub fn new(risk_type: RiskType, risk: Risk) -> Self
crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
hyperswitch_connectors
function_signature
null
null
null
47
new
null
null
null
null
null
null
// Struct: Customers // File: crates/router/src/routes/app.rs // Module: router // Implementations: 2 pub struct Customers
crates/router/src/routes/app.rs
router
struct_definition
Customers
2
[]
30
null
null
null
null
null
null
null
// Struct: FiservemeaPaymentsRequest // File: crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct FiservemeaPaymentsRequest
crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs
hyperswitch_connectors
struct_definition
FiservemeaPaymentsRequest
0
[]
58
null
null
null
null
null
null
null
// Function: accept_invitations_pre_auth // File: crates/router/src/routes/user_role.rs // Module: router pub fn accept_invitations_pre_auth( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<user_role_api::AcceptInvitationsPreAuthRequest>, ) -> HttpResponse
crates/router/src/routes/user_role.rs
router
function_signature
null
null
null
69
accept_invitations_pre_auth
null
null
null
null
null
null
// Implementation: impl api::PaymentSession for for Multisafepay // File: crates/hyperswitch_connectors/src/connectors/multisafepay.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentSession for for Multisafepay
crates/hyperswitch_connectors/src/connectors/multisafepay.rs
hyperswitch_connectors
impl_block
null
null
null
67
null
Multisafepay
api::PaymentSession for
0
0
null
null
// Implementation: impl UserAuthenticationMethodNew // File: crates/diesel_models/src/query/user_authentication_method.rs // Module: diesel_models // Methods: 1 total (0 public) impl UserAuthenticationMethodNew
crates/diesel_models/src/query/user_authentication_method.rs
diesel_models
impl_block
null
null
null
44
null
UserAuthenticationMethodNew
null
1
0
null
null
// File: crates/router/tests/connectors/gocardless.rs // Module: router use masking::Secret; use router::types::{self, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct GocardlessTest; impl ConnectorActions for GocardlessTest {} impl utils::Connector for GocardlessTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Gocardless; utils::construct_connector_data_old( Box::new(Gocardless::new()), types::Connector::Gocardless, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .gocardless .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "gocardless".to_string() } } static CONNECTOR: GocardlessTest = GocardlessTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
crates/router/tests/connectors/gocardless.rs
router
full_file
null
null
null
2,941
null
null
null
null
null
null
null
// Implementation: impl api::PaymentsPreProcessing for for Nmi // File: crates/hyperswitch_connectors/src/connectors/nmi.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentsPreProcessing for for Nmi
crates/hyperswitch_connectors/src/connectors/nmi.rs
hyperswitch_connectors
impl_block
null
null
null
59
null
Nmi
api::PaymentsPreProcessing for
0
0
null
null
// Struct: BarclaycardAuthSetupRequest // File: crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct BarclaycardAuthSetupRequest
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
hyperswitch_connectors
struct_definition
BarclaycardAuthSetupRequest
0
[]
55
null
null
null
null
null
null
null
// Function: values_mut // File: crates/hyperswitch_constraint_graph/src/dense_map.rs // Module: hyperswitch_constraint_graph pub fn values_mut(&mut self) -> slice::IterMut<'_, V>
crates/hyperswitch_constraint_graph/src/dense_map.rs
hyperswitch_constraint_graph
function_signature
null
null
null
47
values_mut
null
null
null
null
null
null
// Struct: AuthenticationAuthenticateResponse // File: crates/api_models/src/authentication.rs // Module: api_models // Implementations: 1 // Traits: ApiEventMetric pub struct AuthenticationAuthenticateResponse
crates/api_models/src/authentication.rs
api_models
struct_definition
AuthenticationAuthenticateResponse
1
[ "ApiEventMetric" ]
42
null
null
null
null
null
null
null
// Struct: CardData // File: crates/router/src/types/payment_methods.rs // Module: router // Implementations: 0 pub struct CardData
crates/router/src/types/payment_methods.rs
router
struct_definition
CardData
0
[]
33
null
null
null
null
null
null
null
// Struct: ClickhouseConfig // File: crates/analytics/src/clickhouse.rs // Module: analytics // Implementations: 1 // Traits: Default pub struct ClickhouseConfig
crates/analytics/src/clickhouse.rs
analytics
struct_definition
ClickhouseConfig
1
[ "Default" ]
41
null
null
null
null
null
null
null
// Struct: Context // File: crates/hyperswitch_domain_models/src/merchant_context.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct Context
crates/hyperswitch_domain_models/src/merchant_context.rs
hyperswitch_domain_models
struct_definition
Context
0
[]
39
null
null
null
null
null
null
null
// Function: supports_vendor_disburse_account_create_for_payout // File: crates/common_enums/src/connector_enums.rs // Module: common_enums pub fn supports_vendor_disburse_account_create_for_payout(self) -> bool
crates/common_enums/src/connector_enums.rs
common_enums
function_signature
null
null
null
49
supports_vendor_disburse_account_create_for_payout
null
null
null
null
null
null
// Struct: ApiEventMetricsBucketIdentifier // File: crates/api_models/src/analytics/api_event.rs // Module: api_models // Implementations: 3 // Traits: Hash, PartialEq pub struct ApiEventMetricsBucketIdentifier
crates/api_models/src/analytics/api_event.rs
api_models
struct_definition
ApiEventMetricsBucketIdentifier
3
[ "Hash", "PartialEq" ]
49
null
null
null
null
null
null
null
// Struct: ItaubankErrorBody // File: crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ItaubankErrorBody
crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs
hyperswitch_connectors
struct_definition
ItaubankErrorBody
0
[]
53
null
null
null
null
null
null
null
// Struct: PaymentMethod // File: crates/hyperswitch_connectors/src/connectors/authipay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PaymentMethod
crates/hyperswitch_connectors/src/connectors/authipay/transformers.rs
hyperswitch_connectors
struct_definition
PaymentMethod
0
[]
45
null
null
null
null
null
null
null
// Struct: TransactionResponse // File: crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct TransactionResponse
crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs
hyperswitch_connectors
struct_definition
TransactionResponse
0
[]
45
null
null
null
null
null
null
null
// Implementation: impl api::RefundExecute for for CtpMastercard // File: crates/hyperswitch_connectors/src/connectors/ctp_mastercard.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::RefundExecute for for CtpMastercard
crates/hyperswitch_connectors/src/connectors/ctp_mastercard.rs
hyperswitch_connectors
impl_block
null
null
null
65
null
CtpMastercard
api::RefundExecute for
0
0
null
null
// Struct: GenericTokenData // File: crates/router/src/types/storage/payment_method.rs // Module: router // Implementations: 0 pub struct GenericTokenData
crates/router/src/types/storage/payment_method.rs
router
struct_definition
GenericTokenData
0
[]
36
null
null
null
null
null
null
null
// File: crates/router/tests/connectors/tesouro.rs // Module: router use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct TesouroTest; impl ConnectorActions for TesouroTest {} impl utils::Connector for TesouroTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Tesouro; utils::construct_connector_data_old( Box::new(Tesouro::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .tesouro .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "tesouro".to_string() } } static CONNECTOR: TesouroTest = TesouroTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
crates/router/tests/connectors/tesouro.rs
router
full_file
null
null
null
2,932
null
null
null
null
null
null
null
// Struct: Authentication // File: crates/hyperswitch_domain_models/src/router_flow_types/authentication.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct Authentication
crates/hyperswitch_domain_models/src/router_flow_types/authentication.rs
hyperswitch_domain_models
struct_definition
Authentication
0
[]
40
null
null
null
null
null
null
null
// Implementation: impl UserKeyStoreInterface for for KafkaStore // File: crates/router/src/db/kafka_store.rs // Module: router // Methods: 3 total (0 public) impl UserKeyStoreInterface for for KafkaStore
crates/router/src/db/kafka_store.rs
router
impl_block
null
null
null
49
null
KafkaStore
UserKeyStoreInterface for
3
0
null
null
web::resource("/{key_id}") .route(web::get().to(api_keys::api_key_retrieve)) .route(web::put().to(api_keys::api_key_update)) .route(web::delete().to(api_keys::api_key_revoke)), ) } } #[cfg(all(feature = "olap", feature = "v1"))] impl ApiKeys { pub fn server(state: AppState) -> Scope { web::scope("/api_keys/{merchant_id}") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(api_keys::api_key_create))) .service(web::resource("/list").route(web::get().to(api_keys::api_key_list))) .service( web::resource("/{key_id}") .route(web::get().to(api_keys::api_key_retrieve)) .route(web::post().to(api_keys::api_key_update)) .route(web::delete().to(api_keys::api_key_revoke)), ) } } pub struct Disputes; #[cfg(all(feature = "olap", feature = "v1"))] impl Disputes { pub fn server(state: AppState) -> Scope { web::scope("/disputes") .app_data(web::Data::new(state)) .service(web::resource("/list").route(web::get().to(disputes::retrieve_disputes_list))) .service( web::resource("/profile/list") .route(web::get().to(disputes::retrieve_disputes_list_profile)), ) .service(web::resource("/filter").route(web::get().to(disputes::get_disputes_filters))) .service( web::resource("/profile/filter") .route(web::get().to(disputes::get_disputes_filters_profile)), ) .service( web::resource("/accept/{dispute_id}") .route(web::post().to(disputes::accept_dispute)), ) .service( web::resource("/aggregate").route(web::get().to(disputes::get_disputes_aggregate)), ) .service( web::resource("/profile/aggregate") .route(web::get().to(disputes::get_disputes_aggregate_profile)), ) .service( web::resource("/evidence") .route(web::post().to(disputes::submit_dispute_evidence)) .route(web::put().to(disputes::attach_dispute_evidence)) .route(web::delete().to(disputes::delete_dispute_evidence)), ) .service( web::resource("/evidence/{dispute_id}") .route(web::get().to(disputes::retrieve_dispute_evidence)), ) .service( web::resource("/{dispute_id}").route(web::get().to(disputes::retrieve_dispute)), ) .service( web::resource("/{connector_id}/fetch") .route(web::get().to(disputes::fetch_disputes)), ) } } pub struct Cards; #[cfg(all(feature = "oltp", feature = "v1"))] impl Cards { pub fn server(state: AppState) -> Scope { web::scope("/cards") .app_data(web::Data::new(state)) .service(web::resource("/create").route(web::post().to(create_cards_info))) .service(web::resource("/update").route(web::post().to(update_cards_info))) .service(web::resource("/update-batch").route(web::post().to(migrate_cards_info))) .service(web::resource("/{bin}").route(web::get().to(card_iin_info))) } } pub struct Files; #[cfg(all(feature = "olap", feature = "v1"))] impl Files { pub fn server(state: AppState) -> Scope { web::scope("/files") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(files::files_create))) .service( web::resource("/{file_id}") .route(web::delete().to(files::files_delete)) .route(web::get().to(files::files_retrieve)), ) } } pub struct Cache; impl Cache { pub fn server(state: AppState) -> Scope { web::scope("/cache") .app_data(web::Data::new(state)) .service(web::resource("/invalidate/{key}").route(web::post().to(invalidate))) } } pub struct PaymentLink; #[cfg(all(feature = "olap", feature = "v1"))] impl PaymentLink { pub fn server(state: AppState) -> Scope { web::scope("/payment_link") .app_data(web::Data::new(state)) .service(web::resource("/list").route(web::post().to(payment_link::payments_link_list))) .service( web::resource("/{payment_link_id}") .route(web::get().to(payment_link::payment_link_retrieve)), ) .service( web::resource("{merchant_id}/{payment_id}") .route(web::get().to(payment_link::initiate_payment_link)), ) .service( web::resource("s/{merchant_id}/{payment_id}") .route(web::get().to(payment_link::initiate_secure_payment_link)), ) .service( web::resource("status/{merchant_id}/{payment_id}") .route(web::get().to(payment_link::payment_link_status)), ) } } #[cfg(feature = "payouts")] pub struct PayoutLink; #[cfg(all(feature = "payouts", feature = "v1"))] impl PayoutLink { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/payout_link").app_data(web::Data::new(state)); route = route.service( web::resource("/{merchant_id}/{payout_id}").route(web::get().to(render_payout_link)), ); route } } pub struct Profile; #[cfg(all(feature = "olap", feature = "v2"))] impl Profile { pub fn server(state: AppState) -> Scope { web::scope("/v2/profiles") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(profiles::profile_create))) .service( web::scope("/{profile_id}") .service( web::resource("") .route(web::get().to(profiles::profile_retrieve)) .route(web::put().to(profiles::profile_update)), ) .service( web::resource("/connector-accounts") .route(web::get().to(admin::connector_list)), ) .service( web::resource("/fallback-routing") .route(web::get().to(routing::routing_retrieve_default_config)) .route(web::patch().to(routing::routing_update_default_config)), ) .service( web::resource("/activate-routing-algorithm").route(web::patch().to( |state, req, path, payload| { routing::routing_link_config( state, req, path, payload, &TransactionType::Payment, ) }, )), ) .service( web::resource("/deactivate-routing-algorithm").route(web::patch().to( |state, req, path| { routing::routing_unlink_config( state, req, path, &TransactionType::Payment, ) }, )), ) .service(web::resource("/routing-algorithm").route(web::get().to( |state, req, query_params, path| { routing::routing_retrieve_linked_config( state, req, query_params, path, &TransactionType::Payment, ) }, ))) .service( web::resource("/decision") .route(web::put().to(routing::upsert_decision_manager_config)) .route(web::get().to(routing::retrieve_decision_manager_config)), ), ) } } #[cfg(all(feature = "olap", feature = "v1"))] impl Profile { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/account/{account_id}/business_profile") .app_data(web::Data::new(state)) .service( web::resource("") .route(web::post().to(profiles::profile_create)) .route(web::get().to(profiles::profiles_list)), ); #[cfg(feature = "dynamic_routing")] { route = route.service( web::scope("/{profile_id}/dynamic_routing") .service( web::scope("/success_based") .service( web::resource("/toggle") .route(web::post().to(routing::toggle_success_based_routing)), ) .service( web::resource("/create") .route(web::post().to(routing::create_success_based_routing)), ) .service(web::resource("/config/{algorithm_id}").route( web::patch().to(|state, req, path, payload| { routing::success_based_routing_update_configs( state, req, path, payload, ) }), )), ) .service( web::resource("/set_volume_split") .route(web::post().to(routing::set_dynamic_routing_volume_split)), ) .service( web::resource("/get_volume_split") .route(web::get().to(routing::get_dynamic_routing_volume_split)), ) .service( web::scope("/elimination") .service( web::resource("/toggle") .route(web::post().to(routing::toggle_elimination_routing)), ) .service( web::resource("/create") .route(web::post().to(routing::create_elimination_routing)), ) .service(web::resource("config/{algorithm_id}").route( web::patch().to(|state, req, path, payload| { routing::elimination_routing_update_configs( state, req, path, payload, ) }), )), ) .service( web::scope("/contracts") .service(web::resource("/toggle").route( web::post().to(routing::contract_based_routing_setup_config), )) .service(web::resource("/config/{algorithm_id}").route( web::patch().to(|state, req, path, payload| { routing::contract_based_routing_update_configs( state, req, path, payload, ) }), )), ), ); } route = route.service( web::scope("/{profile_id}") .service( web::resource("") .route(web::get().to(profiles::profile_retrieve)) .route(web::post().to(profiles::profile_update)) .route(web::delete().to(profiles::profile_delete)), ) .service( web::resource("/toggle_extended_card_info") .route(web::post().to(profiles::toggle_extended_card_info)), ) .service( web::resource("/toggle_connector_agnostic_mit") .route(web::post().to(profiles::toggle_connector_agnostic_mit)), ), ); route } } pub struct ProfileNew; #[cfg(feature = "olap")] impl ProfileNew { #[cfg(feature = "v1")] pub fn server(state: AppState) -> Scope { web::scope("/account/{account_id}/profile") .app_data(web::Data::new(state)) .service( web::resource("").route(web::get().to(profiles::profiles_list_at_profile_level)), ) .service( web::resource("/connectors").route(web::get().to(admin::connector_list_profile)), ) } #[cfg(feature = "v2")] pub fn server(state: AppState) -> Scope { web::scope("/account/{account_id}/profile").app_data(web::Data::new(state)) } } pub struct Gsm; #[cfg(all(feature = "v1", feature = "olap"))] impl Gsm { pub fn server(state: AppState) -> Scope { web::scope("/gsm") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(gsm::create_gsm_rule))) .service(web::resource("/get").route(web::post().to(gsm::get_gsm_rule))) .service(web::resource("/update").route(web::post().to(gsm::update_gsm_rule))) .service(web::resource("/delete").route(web::post().to(gsm::delete_gsm_rule))) } } #[cfg(all(feature = "v2", feature = "olap"))] impl Gsm { pub fn server(state: AppState) -> Scope { web::scope("/v2/gsm") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(gsm::create_gsm_rule))) .service(web::resource("/get").route(web::post().to(gsm::get_gsm_rule))) .service(web::resource("/update").route(web::post().to(gsm::update_gsm_rule))) .service(web::resource("/delete").route(web::post().to(gsm::delete_gsm_rule))) } } pub struct Chat; #[cfg(feature = "olap")] impl Chat { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/chat").app_data(web::Data::new(state.clone())); if state.conf.chat.get_inner().enabled { route = route.service( web::scope("/ai") .service( web::resource("/data") .route(web::post().to(chat::get_data_from_hyperswitch_ai_workflow)), ) .service( web::resource("/list").route(web::get().to(chat::get_all_conversations)), ), ); } route } } pub struct ThreeDsDecisionRule; #[cfg(feature = "oltp")] impl ThreeDsDecisionRule { pub fn server(state: AppState) -> Scope { web::scope("/three_ds_decision") .app_data(web::Data::new(state)) .service( web::resource("/execute") .route(web::post().to(three_ds_decision_rule::execute_decision_rule)), ) } } #[cfg(feature = "olap")] pub struct Verify; #[cfg(all(feature = "olap", feature = "v1"))] impl Verify { pub fn server(state: AppState) -> Scope { web::scope("/verify") .app_data(web::Data::new(state)) .service( web::resource("/apple_pay/{merchant_id}") .route(web::post().to(apple_pay_merchant_registration)), ) .service( web::resource("/applepay_verified_domains") .route(web::get().to(retrieve_apple_pay_verified_domains)), ) } } #[cfg(all(feature = "olap", feature = "v2"))] impl Verify { pub fn server(state: AppState) -> Scope { web::scope("/v2/verify") .app_data(web::Data::new(state)) .service( web::resource("/apple-pay/{merchant_id}") .route(web::post().to(apple_pay_merchant_registration)), ) .service( web::resource("/applepay-verified-domains") .route(web::get().to(retrieve_apple_pay_verified_domains)), ) } } pub struct UserDeprecated; #[cfg(all(feature = "olap", feature = "v2"))] impl UserDeprecated { pub fn server(state: AppState) -> Scope { // TODO: Deprecated. Remove this in favour of /v2/users let mut route = web::scope("/v2/user").app_data(web::Data::new(state)); route = route.service( web::resource("/create_merchant") .route(web::post().to(user::user_merchant_account_create)), ); route = route.service( web::scope("/list") .service( web::resource("/merchant") .route(web::get().to(user::list_merchants_for_user_in_org)), ) .service( web::resource("/profile") .route(web::get().to(user::list_profiles_for_user_in_org_and_merchant)), ), ); route = route.service( web::scope("/switch") .service( web::resource("/merchant") .route(web::post().to(user::switch_merchant_for_user_in_org)), ) .service( web::resource("/profile") .route(web::post().to(user::switch_profile_for_user_in_org_and_merchant)), ), ); route = route.service( web::resource("/data") .route(web::get().to(user::get_multiple_dashboard_metadata)) .route(web::post().to(user::set_dashboard_metadata)), ); route } } pub struct User; #[cfg(all(feature = "olap", feature = "v2"))] impl User { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/v2/users").app_data(web::Data::new(state)); route = route.service( web::resource("/create-merchant") .route(web::post().to(user::user_merchant_account_create)), ); route = route.service( web::scope("/list") .service( web::resource("/merchant") .route(web::get().to(user::list_merchants_for_user_in_org)), ) .service( web::resource("/profile") .route(web::get().to(user::list_profiles_for_user_in_org_and_merchant)), ), ); route = route.service( web::scope("/switch") .service( web::resource("/merchant") .route(web::post().to(user::switch_merchant_for_user_in_org)), ) .service( web::resource("/profile") .route(web::post().to(user::switch_profile_for_user_in_org_and_merchant)), ), ); route = route.service( web::resource("/data") .route(web::get().to(user::get_multiple_dashboard_metadata)) .route(web::post().to(user::set_dashboard_metadata)), ); route } } #[cfg(all(feature = "olap", feature = "v1"))] impl User { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/user").app_data(web::Data::new(state.clone())); route = route .service(web::resource("").route(web::get().to(user::get_user_details))) .service(web::resource("/signin").route(web::post().to(user::user_signin))) .service(web::resource("/v2/signin").route(web::post().to(user::user_signin))) // signin/signup with sso using openidconnect .service(web::resource("/oidc").route(web::post().to(user::sso_sign))) .service(web::resource("/signout").route(web::post().to(user::signout))) .service(web::resource("/rotate_password").route(web::post().to(user::rotate_password))) .service(web::resource("/change_password").route(web::post().to(user::change_password))) .service( web::resource("/internal_signup").route(web::post().to(user::internal_user_signup)), ) .service( web::resource("/tenant_signup").route(web::post().to(user::create_tenant_user)), ) .service(web::resource("/create_org").route(web::post().to(user::user_org_create))) .service( web::resource("/create_merchant") .route(web::post().to(user::user_merchant_account_create)), ) // TODO: To be deprecated .service( web::resource("/permission_info") .route(web::get().to(user_role::get_authorization_info)), ) // TODO: To be deprecated .service( web::resource("/module/list").route(web::get().to(user_role::get_role_information)), ) .service( web::resource("/parent/list") .route(web::get().to(user_role::get_parent_group_info)), ) .service( web::resource("/update").route(web::post().to(user::update_user_account_details)), ) .service( web::resource("/data") .route(web::get().to(user::get_multiple_dashboard_metadata)) .route(web::post().to(user::set_dashboard_metadata)), ); if state.conf.platform.enabled { route = route.service( web::resource("/create_platform").route(web::post().to(user::create_platform)), ) } route = route .service(web::scope("/key").service( web::resource("/transfer").route(web::post().to(user::transfer_user_key)), )); route = route.service( web::scope("/list") .service(web::resource("/org").route(web::get().to(user::list_orgs_for_user))) .service( web::resource("/merchant") .route(web::get().to(user::list_merchants_for_user_in_org)), ) .service( web::resource("/profile") .route(web::get().to(user::list_profiles_for_user_in_org_and_merchant)), ) .service( web::resource("/invitation") .route(web::get().to(user_role::list_invitations_for_user)), ), ); route = route.service( web::scope("/switch") .service(web::resource("/org").route(web::post().to(user::switch_org_for_user))) .service( web::resource("/merchant") .route(web::post().to(user::switch_merchant_for_user_in_org)), ) .service( web::resource("/profile") .route(web::post().to(user::switch_profile_for_user_in_org_and_merchant)), ), ); // Two factor auth routes route = route.service( web::scope("/2fa") // TODO: to be deprecated .service(web::resource("").route(web::get().to(user::check_two_factor_auth_status))) .service( web::resource("/v2") .route(web::get().to(user::check_two_factor_auth_status_with_attempts)), ) .service( web::scope("/totp") .service(web::resource("/begin").route(web::get().to(user::totp_begin))) .service(web::resource("/reset").route(web::get().to(user::totp_reset))) .service( web::resource("/verify") .route(web::post().to(user::totp_verify)) .route(web::put().to(user::totp_update)), ), ) .service( web::scope("/recovery_code") .service( web::resource("/verify") .route(web::post().to(user::verify_recovery_code)), ) .service( web::resource("/generate") .route(web::get().to(user::generate_recovery_codes)), ), ) .service( web::resource("/terminate") .route(web::get().to(user::terminate_two_factor_auth)), ), ); route = route.service( web::scope("/auth") .service( web::resource("") .route(web::post().to(user::create_user_authentication_method)) .route(web::put().to(user::update_user_authentication_method)), ) .service( web::resource("/list") .route(web::get().to(user::list_user_authentication_methods)), ) .service(web::resource("/url").route(web::get().to(user::get_sso_auth_url))) .service( web::resource("/select").route(web::post().to(user::terminate_auth_select)), ), ); #[cfg(feature = "email")] { route = route .service(web::resource("/from_email").route(web::post().to(user::user_from_email))) .service( web::resource("/connect_account") .route(web::post().to(user::user_connect_account)), ) .service( web::resource("/forgot_password").route(web::post().to(user::forgot_password)), ) .service( web::resource("/reset_password").route(web::post().to(user::reset_password)), ) .service( web::resource("/signup_with_merchant_id") .route(web::post().to(user::user_signup_with_merchant_id)), ) .service(web::resource("/verify_email").route(web::post().to(user::verify_email))) .service( web::resource("/v2/verify_email").route(web::post().to(user::verify_email)), ) .service( web::resource("/verify_email_request") .route(web::post().to(user::verify_email_request)), ) .service( web::resource("/user/resend_invite").route(web::post().to(user::resend_invite)), ) .service( web::resource("/accept_invite_from_email") .route(web::post().to(user::accept_invite_from_email)), ); } #[cfg(not(feature = "email"))] { route = route.service(web::resource("/signup").route(web::post().to(user::user_signup))) } // User management route = route.service( web::scope("/user") .service(web::resource("").route(web::post().to(user::list_user_roles_details))) // TODO: To be deprecated .service(web::resource("/v2").route(web::post().to(user::list_user_roles_details))) .service( web::resource("/list").route(web::get().to(user_role::list_users_in_lineage)), ) // TODO: To be deprecated .service( web::resource("/v2/list") .route(web::get().to(user_role::list_users_in_lineage)), ) .service( web::resource("/invite_multiple") .route(web::post().to(user::invite_multiple_user)), ) .service( web::scope("/invite/accept") .service( web::resource("") .route(web::post().to(user_role::accept_invitations_v2)), ) .service( web::resource("/pre_auth") .route(web::post().to(user_role::accept_invitations_pre_auth)), ) .service( web::scope("/v2") .service( web::resource("") .route(web::post().to(user_role::accept_invitations_v2)), ) .service( web::resource("/pre_auth").route( web::post().to(user_role::accept_invitations_pre_auth), ), ), ), ) .service( web::resource("/update_role") .route(web::post().to(user_role::update_user_role)), ) .service( web::resource("/delete").route(web::delete().to(user_role::delete_user_role)), ), ); if state.conf().clone_connector_allowlist.is_some() { route = route.service( web::resource("/clone_connector").route(web::post().to(user::clone_connector)), ); } // Role information route = route.service( web::scope("/role") .service( web::resource("") .route(web::get().to(user_role::get_role_from_token)) // TODO: To be deprecated .route(web::post().to(user_role::create_role)), ) .service( web::resource("/v2") .route(web::post().to(user_role::create_role_v2)) .route( web::get().to(user_role::get_groups_and_resources_for_role_from_token), ), ) // TODO: To be deprecated .service( web::resource("/v2/list").route(web::get().to(user_role::list_roles_with_info)), ) .service( web::scope("/list") .service( web::resource("").route(web::get().to(user_role::list_roles_with_info)), ) .service( web::resource("/invite").route( web::get().to(user_role::list_invitable_roles_at_entity_level), ), ) .service( web::resource("/update").route( web::get().to(user_role::list_updatable_roles_at_entity_level), ), ), ) .service( web::resource("/{role_id}") .route(web::get().to(user_role::get_role)) .route(web::put().to(user_role::update_role)), ) .service( web::resource("/{role_id}/v2") .route(web::get().to(user_role::get_parent_info_for_role)), ), ); #[cfg(feature = "dummy_connector")] { route = route.service( web::resource("/sample_data") .route(web::post().to(user::generate_sample_data)) .route(web::delete().to(user::delete_sample_data)), ) } // Admin Theme // TODO: To be deprecated route = route.service( web::scope("/admin/theme") .service( web::resource("") .route(web::get().to(user::theme::get_theme_using_lineage)) .route(web::post().to(user::theme::create_theme)), ) .service( web::resource("/{theme_id}") .route(web::get().to(user::theme::get_theme_using_theme_id)) .route(web::put().to(user::theme::update_theme)) .route(web::post().to(user::theme::upload_file_to_theme_storage)) .route(web::delete().to(user::theme::delete_theme)), ), ); // User Theme route = route.service( web::scope("/theme") .service( web::resource("") .route(web::post().to(user::theme::create_user_theme)) .route(web::get().to(user::theme::get_user_theme_using_lineage)), ) .service( web::resource("/list") .route(web::get().to(user::theme::list_all_themes_in_lineage)), ) .service( web::resource("/{theme_id}") .route(web::get().to(user::theme::get_user_theme_using_theme_id)) .route(web::put().to(user::theme::update_user_theme)) .route(web::post().to(user::theme::upload_file_to_user_theme_storage)) .route(web::delete().to(user::theme::delete_user_theme)), ), ); route } } pub struct ConnectorOnboarding; #[cfg(all(feature = "olap", feature = "v1"))] impl ConnectorOnboarding { pub fn server(state: AppState) -> Scope { web::scope("/connector_onboarding") .app_data(web::Data::new(state)) .service( web::resource("/action_url") .route(web::post().to(connector_onboarding::get_action_url)), ) .service( web::resource("/sync") .route(web::post().to(connector_onboarding::sync_onboarding_status)), ) .service( web::resource("/reset_tracking_id") .route(web::post().to(connector_onboarding::reset_tracking_id)), ) } } #[cfg(feature = "olap")] pub struct WebhookEvents; #[cfg(all(feature = "olap", feature = "v1"))] impl WebhookEvents { pub fn server(config: AppState) -> Scope { web::scope("/events") .app_data(web::Data::new(config)) .service(web::scope("/profile/list").service(web::resource("").route( web::post().to(webhook_events::list_initial_webhook_delivery_attempts_with_jwtauth), ))) .service( web::scope("/{merchant_id}") .service(web::resource("").route( web::post().to(webhook_events::list_initial_webhook_delivery_attempts), )) .service( web::scope("/{event_id}") .service(web::resource("attempts").route( web::get().to(webhook_events::list_webhook_delivery_attempts), )) .service(web::resource("retry").route( web::post().to(webhook_events::retry_webhook_delivery_attempt), )), ), ) } } #[cfg(feature = "olap")] pub struct FeatureMatrix; #[cfg(all(feature = "olap", feature = "v1"))] impl FeatureMatrix { pub fn server(state: AppState) -> Scope { web::scope("/feature_matrix") .app_data(web::Data::new(state)) .service(web::resource("").route(web::get().to(feature_matrix::fetch_feature_matrix))) } } #[cfg(feature = "olap")] pub struct ProcessTrackerDeprecated; #[cfg(all(feature = "olap", feature = "v2"))] impl ProcessTrackerDeprecated { pub fn server(state: AppState) -> Scope { use super::process_tracker::revenue_recovery; // TODO: Deprecated. Remove this in favour of /v2/process-trackers web::scope("/v2/process_tracker/revenue_recovery_workflow") .app_data(web::Data::new(state.clone())) .service( web::resource("/{revenue_recovery_id}") .route(web::get().to(revenue_recovery::revenue_recovery_pt_retrieve_api)), ) } } #[cfg(feature = "olap")] pub struct ProcessTracker; #[cfg(all(feature = "olap", feature = "v2"))] impl ProcessTracker { pub fn server(state: AppState) -> Scope { use super::process_tracker::revenue_recovery; web::scope("/v2/process-trackers/revenue-recovery-workflow") .app_data(web::Data::new(state.clone())) .service( web::scope("/{revenue_recovery_id}") .service( web::resource("").route( web::get().to(revenue_recovery::revenue_recovery_pt_retrieve_api), ), ) .service( web::resource("/resume") .route(web::post().to(revenue_recovery::revenue_recovery_resume_api)), ), ) } } pub struct Authentication; #[cfg(feature = "v1")] impl Authentication { pub fn server(state: AppState) -> Scope { web::scope("/authentication") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(authentication::authentication_create))) .service( web::resource("/{authentication_id}/eligibility") .route(web::post().to(authentication::authentication_eligibility)), ) .service( web::resource("/{authentication_id}/authenticate") .route(web::post().to(authentication::authentication_authenticate)), ) .service( web::resource("{merchant_id}/{authentication_id}/redirect") .route(web::post().to(authentication::authentication_sync_post_update)), ) .service( web::resource("{merchant_id}/{authentication_id}/sync") .route(web::post().to(authentication::authentication_sync)), ) } } #[cfg(feature = "olap")] pub struct ProfileAcquirer; #[cfg(all(feature = "olap", feature = "v1"))] impl ProfileAcquirer { pub fn server(state: AppState) -> Scope { web::scope("/profile_acquirer") .app_data(web::Data::new(state)) .service( web::resource("").route(web::post().to(profile_acquirer::create_profile_acquirer)), ) .service( web::resource("/{profile_id}/{profile_acquirer_id}") .route(web::post().to(profile_acquirer::profile_acquirer_update)), ) } } #[cfg(feature = "v2")] pub struct RecoveryDataBackfill; #[cfg(feature = "v2")] impl RecoveryDataBackfill { pub fn server(state: AppState) -> Scope { web::scope("/v2/recovery/data-backfill") .app_data(web::Data::new(state)) .service( web::resource("").route( web::post() .to(super::revenue_recovery_data_backfill::revenue_recovery_data_backfill), ), ) .service(web::resource("/status/{token_id}").route( web::post().to( super::revenue_recovery_data_backfill::revenue_recovery_data_backfill_status, ), )) } }
crates/router/src/routes/app.rs#chunk2
router
chunk
null
null
null
7,968
null
null
null
null
null
null
null
// Implementation: impl ConnectorCustomerMap // File: crates/common_types/src/customers.rs // Module: common_types // Methods: 1 total (1 public) impl ConnectorCustomerMap
crates/common_types/src/customers.rs
common_types
impl_block
null
null
null
39
null
ConnectorCustomerMap
null
1
1
null
null
// Function: to_currency_base_unit // File: crates/common_enums/src/enums.rs // Module: common_enums // Documentation: Convert the amount to its base denomination based on Currency and return String pub fn to_currency_base_unit(self, amount: i64) -> Result<String, TryFromIntError>
crates/common_enums/src/enums.rs
common_enums
function_signature
null
null
null
67
to_currency_base_unit
null
null
null
null
null
null
// Struct: PaymentUpdateMetadata // File: crates/router/src/core/payments/operations/payment_update_metadata.rs // Module: router // Implementations: 0 pub struct PaymentUpdateMetadata
crates/router/src/core/payments/operations/payment_update_metadata.rs
router
struct_definition
PaymentUpdateMetadata
0
[]
40
null
null
null
null
null
null
null
// Implementation: impl webhooks::IncomingWebhook for for Powertranz // File: crates/hyperswitch_connectors/src/connectors/powertranz.rs // Module: hyperswitch_connectors // Methods: 3 total (0 public) impl webhooks::IncomingWebhook for for Powertranz
crates/hyperswitch_connectors/src/connectors/powertranz.rs
hyperswitch_connectors
impl_block
null
null
null
64
null
Powertranz
webhooks::IncomingWebhook for
3
0
null
null
} else { None } .map(|data| { serde_json::to_value(types::AdditionalMerchantData::OpenBankingRecipientData( data, )) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize MerchantRecipientData")?; let encrypted_data = domain_types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), domain_types::CryptoOperation::BatchEncrypt( FromRequestEncryptableMerchantConnectorAccount::to_encryptable( FromRequestEncryptableMerchantConnectorAccount { connector_account_details: self.connector_account_details.ok_or( errors::ApiErrorResponse::MissingRequiredField { field_name: "connector_account_details", }, )?, connector_wallets_details: helpers::get_connector_wallets_details_with_apple_pay_certificates( &self.metadata, &self.connector_wallets_details, ) .await?, additional_merchant_data: merchant_recipient_data.map(Secret::new), }, ), ), identifier.clone(), key_store.key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details".to_string())?; let encrypted_data = FromRequestEncryptableMerchantConnectorAccount::from_encryptable(encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details")?; let feature_metadata = self .feature_metadata .as_ref() .map(ForeignTryFrom::foreign_try_from) .transpose()?; Ok(domain::MerchantConnectorAccount { merchant_id: business_profile.merchant_id.clone(), connector_type: self.connector_type, connector_name: self.connector_name, connector_account_details: encrypted_data.connector_account_details, payment_methods_enabled, disabled, metadata: self.metadata.clone(), frm_configs, connector_label: Some(connector_label.clone()), created_at: date_time::now(), modified_at: date_time::now(), id: common_utils::generate_merchant_connector_account_id_of_default_length(), connector_webhook_details: match self.connector_webhook_details { Some(connector_webhook_details) => { connector_webhook_details.encode_to_value( ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!("Failed to serialize api_models::admin::MerchantConnectorWebhookDetails for Merchant: {:?}", business_profile.merchant_id)) .map(Some)? .map(Secret::new) } None => None, }, profile_id: business_profile.get_id().to_owned(), applepay_verified_domains: None, pm_auth_config: self.pm_auth_config.clone(), status: connector_status, connector_wallets_details: encrypted_data.connector_wallets_details, additional_merchant_data: encrypted_data.additional_merchant_data, version: common_types::consts::API_VERSION, feature_metadata, }) } async fn validate_and_get_business_profile( self, merchant_context: &domain::MerchantContext, db: &dyn StorageInterface, key_manager_state: &KeyManagerState, ) -> RouterResult<domain::Profile> { let profile_id = self.profile_id; // Check whether this profile belongs to the merchant let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, merchant_context.get_merchant_key_store(), Some(&profile_id), merchant_context.get_merchant_account().get_id(), ) .await? .get_required_value("Profile") .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(business_profile) } } #[cfg(feature = "v1")] struct PaymentMethodsEnabled<'a> { payment_methods_enabled: &'a Option<Vec<api_models::admin::PaymentMethodsEnabled>>, } #[cfg(feature = "v1")] impl PaymentMethodsEnabled<'_> { fn get_payment_methods_enabled(&self) -> RouterResult<Option<Vec<pii::SecretSerdeValue>>> { let mut vec = Vec::new(); let payment_methods_enabled = match self.payment_methods_enabled.clone() { Some(val) => { for pm in val.into_iter() { let pm_value = pm .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed while encoding to serde_json::Value, PaymentMethod", )?; vec.push(Secret::new(pm_value)) } Some(vec) } None => None, }; Ok(payment_methods_enabled) } } #[cfg(all(feature = "v1", feature = "olap"))] #[async_trait::async_trait] impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { async fn create_domain_model_from_request( self, state: &SessionState, key_store: domain::MerchantKeyStore, business_profile: &domain::Profile, key_manager_state: &KeyManagerState, ) -> RouterResult<domain::MerchantConnectorAccount> { // If connector label is not passed in the request, generate one let connector_label = self .connector_label .clone() .or(core_utils::get_connector_label( self.business_country, self.business_label.as_ref(), self.business_sub_label.as_ref(), &self.connector_name.to_string(), )) .unwrap_or(format!( "{}_{}", self.connector_name, business_profile.profile_name )); let payment_methods_enabled = PaymentMethodsEnabled { payment_methods_enabled: &self.payment_methods_enabled, }; let payment_methods_enabled = payment_methods_enabled.get_payment_methods_enabled()?; let frm_configs = self.get_frm_config_as_secret(); // Validate Merchant api details and return error if not in correct format let auth = types::ConnectorAuthType::from_option_secret_value( self.connector_account_details.clone(), ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_account_details".to_string(), expected_format: "auth_type and api_key".to_string(), })?; let connector_auth_type_and_metadata_validation = ConnectorAuthTypeAndMetadataValidation { connector_name: &self.connector_name, auth_type: &auth, connector_meta_data: &self.metadata, }; connector_auth_type_and_metadata_validation.validate_auth_and_metadata_type()?; let connector_status_and_disabled_validation = ConnectorStatusAndDisabledValidation { status: &self.status, disabled: &self.disabled, auth: &auth, current_status: &api_enums::ConnectorStatus::Active, }; let (connector_status, disabled) = connector_status_and_disabled_validation.validate_status_and_disabled()?; let identifier = km_types::Identifier::Merchant(business_profile.merchant_id.clone()); let merchant_recipient_data = if let Some(data) = &self.additional_merchant_data { Some( process_open_banking_connectors( state, &business_profile.merchant_id, &auth, &self.connector_type, &self.connector_name, types::AdditionalMerchantData::foreign_from(data.clone()), &key_store, ) .await?, ) } else { None } .map(|data| { serde_json::to_value(types::AdditionalMerchantData::OpenBankingRecipientData( data, )) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize MerchantRecipientData")?; let encrypted_data = domain_types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), domain_types::CryptoOperation::BatchEncrypt( FromRequestEncryptableMerchantConnectorAccount::to_encryptable( FromRequestEncryptableMerchantConnectorAccount { connector_account_details: self.connector_account_details.ok_or( errors::ApiErrorResponse::MissingRequiredField { field_name: "connector_account_details", }, )?, connector_wallets_details: helpers::get_connector_wallets_details_with_apple_pay_certificates( &self.metadata, &self.connector_wallets_details, ) .await?, additional_merchant_data: merchant_recipient_data.map(Secret::new), }, ), ), identifier.clone(), key_store.key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details".to_string())?; let encrypted_data = FromRequestEncryptableMerchantConnectorAccount::from_encryptable(encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details")?; Ok(domain::MerchantConnectorAccount { merchant_id: business_profile.merchant_id.clone(), connector_type: self.connector_type, connector_name: self.connector_name.to_string(), merchant_connector_id: common_utils::generate_merchant_connector_account_id_of_default_length(), connector_account_details: encrypted_data.connector_account_details, payment_methods_enabled, disabled, metadata: self.metadata.clone(), frm_configs, connector_label: Some(connector_label.clone()), created_at: date_time::now(), modified_at: date_time::now(), connector_webhook_details: match self.connector_webhook_details { Some(connector_webhook_details) => { connector_webhook_details.encode_to_value( ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!("Failed to serialize api_models::admin::MerchantConnectorWebhookDetails for Merchant: {:?}", business_profile.merchant_id)) .map(Some)? .map(Secret::new) } None => None, }, profile_id: business_profile.get_id().to_owned(), applepay_verified_domains: None, pm_auth_config: self.pm_auth_config.clone(), status: connector_status, connector_wallets_details: encrypted_data.connector_wallets_details, test_mode: self.test_mode, business_country: self.business_country, business_label: self.business_label.clone(), business_sub_label: self.business_sub_label.clone(), additional_merchant_data: encrypted_data.additional_merchant_data, version: common_types::consts::API_VERSION, }) } /// If profile_id is not passed, use default profile if available, or /// If business_details (business_country and business_label) are passed, get the business_profile /// or return a `MissingRequiredField` error async fn validate_and_get_business_profile( self, merchant_context: &domain::MerchantContext, db: &dyn StorageInterface, key_manager_state: &KeyManagerState, ) -> RouterResult<domain::Profile> { match self.profile_id.or(merchant_context .get_merchant_account() .default_profile .clone()) { Some(profile_id) => { // Check whether this business profile belongs to the merchant let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, merchant_context.get_merchant_key_store(), Some(&profile_id), merchant_context.get_merchant_account().get_id(), ) .await? .get_required_value("Profile") .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(business_profile) } None => match self.business_country.zip(self.business_label) { Some((business_country, business_label)) => { let profile_name = format!("{business_country}_{business_label}"); let business_profile = db .find_business_profile_by_profile_name_merchant_id( key_manager_state, merchant_context.get_merchant_key_store(), &profile_name, merchant_context.get_merchant_account().get_id(), ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_name, })?; Ok(business_profile) } _ => Err(report!(errors::ApiErrorResponse::MissingRequiredField { field_name: "profile_id or business_country, business_label" })), }, } } } pub async fn create_connector( state: SessionState, req: api::MerchantConnectorCreate, merchant_context: domain::MerchantContext, auth_profile_id: Option<id_type::ProfileId>, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); #[cfg(feature = "dummy_connector")] fp_utils::when( req.connector_name .validate_dummy_connector_create(state.conf.dummy_connector.enabled), || { Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid connector name".to_string(), }) }, )?; let connector_metadata = ConnectorMetadata { connector_metadata: &req.metadata, }; let merchant_id = merchant_context.get_merchant_account().get_id(); connector_metadata.validate_apple_pay_certificates_in_mca_metadata()?; #[cfg(feature = "v1")] helpers::validate_business_details( req.business_country, req.business_label.as_ref(), &merchant_context, )?; let business_profile = req .clone() .validate_and_get_business_profile(&merchant_context, store, key_manager_state) .await?; #[cfg(feature = "v2")] if req.connector_type == common_enums::ConnectorType::BillingProcessor { let profile_wrapper = ProfileWrapper::new(business_profile.clone()); profile_wrapper .update_revenue_recovery_algorithm_under_profile( store, key_manager_state, merchant_context.get_merchant_key_store(), common_enums::RevenueRecoveryAlgorithmType::Monitoring, ) .await?; } core_utils::validate_profile_id_from_auth_layer(auth_profile_id, &business_profile)?; let pm_auth_config_validation = PMAuthConfigValidation { connector_type: &req.connector_type, pm_auth_config: &req.pm_auth_config, db: store, merchant_id, profile_id: business_profile.get_id(), key_store: merchant_context.get_merchant_key_store(), key_manager_state, }; pm_auth_config_validation.validate_pm_auth_config().await?; let connector_type_and_connector_enum = ConnectorTypeAndConnectorName { connector_type: &req.connector_type, connector_name: &req.connector_name, }; let routable_connector = connector_type_and_connector_enum.get_routable_connector()?; // The purpose of this merchant account update is just to update the // merchant account `modified_at` field for KGraph cache invalidation state .store .update_specific_fields_in_merchant( key_manager_state, merchant_id, storage::MerchantAccountUpdate::ModifiedAtUpdate, merchant_context.get_merchant_key_store(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error updating the merchant account when creating payment connector")?; let merchant_connector_account = req .clone() .create_domain_model_from_request( &state, merchant_context.get_merchant_key_store().clone(), &business_profile, key_manager_state, ) .await?; let mca = state .store .insert_merchant_connector_account( key_manager_state, merchant_connector_account.clone(), merchant_context.get_merchant_key_store(), ) .await .to_duplicate_response( errors::ApiErrorResponse::DuplicateMerchantConnectorAccount { profile_id: business_profile.get_id().get_string_repr().to_owned(), connector_label: merchant_connector_account .connector_label .unwrap_or_default(), }, )?; #[cfg(feature = "v1")] disputes::schedule_dispute_sync_task(&state, &business_profile, &mca).await?; #[cfg(feature = "v1")] //update merchant default config let merchant_default_config_update = MerchantDefaultConfigUpdate { routable_connector: &routable_connector, merchant_connector_id: &mca.get_id(), store, merchant_id, profile_id: business_profile.get_id(), transaction_type: &req.get_transaction_type(), }; #[cfg(feature = "v2")] //update merchant default config let merchant_default_config_update = DefaultFallbackRoutingConfigUpdate { routable_connector: &routable_connector, merchant_connector_id: &mca.get_id(), store, business_profile, key_store: merchant_context.get_merchant_key_store().to_owned(), key_manager_state, }; merchant_default_config_update .retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists() .await?; metrics::MCA_CREATE.add( 1, router_env::metric_attributes!( ("connector", req.connector_name.to_string()), ("merchant", merchant_id.clone()), ), ); let mca_response = mca.foreign_try_into()?; Ok(service_api::ApplicationResponse::Json(mca_response)) } #[cfg(feature = "v1")] async fn validate_pm_auth( val: pii::SecretSerdeValue, state: &SessionState, merchant_id: &id_type::MerchantId, merchant_context: domain::MerchantContext, profile_id: &id_type::ProfileId, ) -> RouterResponse<()> { let config = serde_json::from_value::<api_models::pm_auth::PaymentMethodAuthConfig>(val.expose()) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "invalid data received for payment method auth config".to_string(), }) .attach_printable("Failed to deserialize Payment Method Auth config")?; let all_mcas = state .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( &state.into(), merchant_id, true, merchant_context.get_merchant_key_store(), ) .await .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_context .get_merchant_account() .get_id() .get_string_repr() .to_owned(), })?; for conn_choice in config.enabled_payment_methods { let pm_auth_mca = all_mcas .iter() .find(|mca| mca.get_id() == conn_choice.mca_id) .ok_or(errors::ApiErrorResponse::GenericNotFoundError { message: "payment method auth connector account not found".to_string(), })?; if &pm_auth_mca.profile_id != profile_id { return Err(errors::ApiErrorResponse::GenericNotFoundError { message: "payment method auth profile_id differs from connector profile_id" .to_string(), } .into()); } } Ok(services::ApplicationResponse::StatusOk) } #[cfg(feature = "v1")] pub async fn retrieve_connector( state: SessionState, merchant_id: id_type::MerchantId, profile_id: Option<id_type::ProfileId>, merchant_connector_id: id_type::MerchantConnectorAccountId, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = store .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &store.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let _merchant_account = store .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let mca = store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, &merchant_id, &merchant_connector_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), })?; core_utils::validate_profile_id_from_auth_layer(profile_id, &mca)?; Ok(service_api::ApplicationResponse::Json( mca.foreign_try_into()?, )) } #[cfg(feature = "v2")] pub async fn retrieve_connector( state: SessionState, merchant_context: domain::MerchantContext, id: id_type::MerchantConnectorAccountId, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let mca = store .find_merchant_connector_account_by_id( key_manager_state, &id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: id.clone().get_string_repr().to_string(), })?; // Validate if the merchant_id sent in the request is valid if mca.merchant_id != *merchant_id { return Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Invalid merchant_id {} provided for merchant_connector_account {:?}", merchant_id.get_string_repr(), id ), } .into()); } Ok(service_api::ApplicationResponse::Json( mca.foreign_try_into()?, )) } #[cfg(all(feature = "olap", feature = "v2"))] pub async fn list_connectors_for_a_profile( state: SessionState, key_store: domain::MerchantKeyStore, profile_id: id_type::ProfileId, ) -> RouterResponse<Vec<api_models::admin::MerchantConnectorListResponse>> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_connector_accounts = store .list_connector_account_by_profile_id(key_manager_state, &profile_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; let mut response = vec![]; for mca in merchant_connector_accounts.into_iter() { response.push(mca.foreign_try_into()?); } Ok(service_api::ApplicationResponse::Json(response)) } pub async fn list_payment_connectors( state: SessionState, merchant_id: id_type::MerchantId, profile_id_list: Option<Vec<id_type::ProfileId>>, ) -> RouterResponse<Vec<api_models::admin::MerchantConnectorListResponse>> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = store .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &store.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; // Validate merchant account store .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_connector_accounts = store .find_merchant_connector_account_by_merchant_id_and_disabled_list( key_manager_state, &merchant_id, true, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; let merchant_connector_accounts = core_utils::filter_objects_based_on_profile_id_list( profile_id_list, merchant_connector_accounts, ); let mut response = vec![]; // The can be eliminated once [#79711](https://github.com/rust-lang/rust/issues/79711) is stabilized for mca in merchant_connector_accounts.into_iter() { response.push(mca.foreign_try_into()?); } Ok(service_api::ApplicationResponse::Json(response)) } pub async fn update_connector( state: SessionState, merchant_id: &id_type::MerchantId, profile_id: Option<id_type::ProfileId>, merchant_connector_id: &id_type::MerchantConnectorAccountId, req: api_models::admin::MerchantConnectorUpdate, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let mca = req .clone() .get_merchant_connector_account_from_id( db, merchant_id, merchant_connector_id, &key_store, key_manager_state, ) .await?; core_utils::validate_profile_id_from_auth_layer(profile_id, &mca)?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), key_store.clone(), ))); let payment_connector = req .clone() .create_domain_model_from_request(&state, &mca, key_manager_state, &merchant_context) .await?; // Profile id should always be present let profile_id = mca.profile_id.clone(); let request_connector_label = req.connector_label; let updated_mca = db .update_merchant_connector_account( key_manager_state, mca, payment_connector.into(), &key_store, ) .await .change_context( errors::ApiErrorResponse::DuplicateMerchantConnectorAccount { profile_id: profile_id.get_string_repr().to_owned(), connector_label: request_connector_label.unwrap_or_default(), }, ) .attach_printable_lazy(|| { format!( "Failed while updating MerchantConnectorAccount: id: {merchant_connector_id:?}", ) })?; let response = updated_mca.foreign_try_into()?; Ok(service_api::ApplicationResponse::Json(response)) } #[cfg(feature = "v1")] pub async fn delete_connector( state: SessionState, merchant_id: id_type::MerchantId, merchant_connector_id: id_type::MerchantConnectorAccountId, ) -> RouterResponse<api::MerchantConnectorDeleteResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let _merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, &merchant_id, &merchant_connector_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), })?; let is_deleted = db .delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &merchant_id, &merchant_connector_id, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), })?; // delete the mca from the config as well let merchant_default_config_delete = MerchantDefaultConfigUpdate { routable_connector: &Some( common_enums::RoutableConnectors::from_str(&mca.connector_name).map_err(|_| { errors::ApiErrorResponse::InvalidDataValue { field_name: "connector_name", } })?, ), merchant_connector_id: &mca.get_id(), store: db, merchant_id: &merchant_id, profile_id: &mca.profile_id, transaction_type: &mca.connector_type.into(), }; merchant_default_config_delete .retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists() .await?; let response = api::MerchantConnectorDeleteResponse { merchant_id, merchant_connector_id, deleted: is_deleted, }; Ok(service_api::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] pub async fn delete_connector( state: SessionState, merchant_context: domain::MerchantContext, id: id_type::MerchantConnectorAccountId, ) -> RouterResponse<api::MerchantConnectorDeleteResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let mca = db .find_merchant_connector_account_by_id( key_manager_state, &id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: id.clone().get_string_repr().to_string(), })?; // Validate if the merchant_id sent in the request is valid if mca.merchant_id != *merchant_id { return Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Invalid merchant_id {} provided for merchant_connector_account {:?}", merchant_id.get_string_repr(), id ), } .into()); } let is_deleted = db .delete_merchant_connector_account_by_id(&id) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: id.clone().get_string_repr().to_string(), })?; let business_profile = db .find_business_profile_by_profile_id( key_manager_state, merchant_context.get_merchant_key_store(), &mca.profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: mca.profile_id.get_string_repr().to_owned(), })?; let merchant_default_config_delete = DefaultFallbackRoutingConfigUpdate { routable_connector: &Some( common_enums::RoutableConnectors::from_str(&mca.connector_name.to_string()).map_err( |_| errors::ApiErrorResponse::InvalidDataValue { field_name: "connector_name", }, )?, ), merchant_connector_id: &mca.get_id(), store: db, business_profile, key_store: merchant_context.get_merchant_key_store().to_owned(), key_manager_state, }; merchant_default_config_delete .retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists() .await?; let response = api::MerchantConnectorDeleteResponse { merchant_id: merchant_id.clone(), id, deleted: is_deleted, }; Ok(service_api::ApplicationResponse::Json(response)) } pub async fn kv_for_merchant( state: SessionState, merchant_id: id_type::MerchantId, enable: bool, ) -> RouterResponse<api_models::admin::ToggleKVResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; // check if the merchant account exists let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let updated_merchant_account = match (enable, merchant_account.storage_scheme) { (true, MerchantStorageScheme::RedisKv) | (false, MerchantStorageScheme::PostgresOnly) => { Ok(merchant_account) } (true, MerchantStorageScheme::PostgresOnly) => { if state.conf.as_ref().is_kv_soft_kill_mode() { Err(errors::ApiErrorResponse::InvalidRequestData { message: "Kv cannot be enabled when application is in soft_kill_mode" .to_owned(), })? } db.update_merchant( key_manager_state, merchant_account, storage::MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme: MerchantStorageScheme::RedisKv, }, &key_store, ) .await } (false, MerchantStorageScheme::RedisKv) => { db.update_merchant( key_manager_state, merchant_account, storage::MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme: MerchantStorageScheme::PostgresOnly, }, &key_store, ) .await } } .map_err(|error| { error .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to switch merchant_storage_scheme") })?; let kv_status = matches!( updated_merchant_account.storage_scheme, MerchantStorageScheme::RedisKv ); Ok(service_api::ApplicationResponse::Json( api_models::admin::ToggleKVResponse { merchant_id: updated_merchant_account.get_id().to_owned(), kv_enabled: kv_status, }, )) } pub async fn toggle_kv_for_all_merchants( state: SessionState, enable: bool, ) -> RouterResponse<api_models::admin::ToggleAllKVResponse> { let db = state.store.as_ref(); let storage_scheme = if enable { MerchantStorageScheme::RedisKv } else { MerchantStorageScheme::PostgresOnly }; let total_update = db .update_all_merchant_account(storage::MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme, }) .await .map_err(|error| { error .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to switch merchant_storage_scheme for all merchants") })?; Ok(service_api::ApplicationResponse::Json( api_models::admin::ToggleAllKVResponse { total_updated: total_update, kv_enabled: enable, }, )) } pub async fn check_merchant_account_kv_status( state: SessionState, merchant_id: id_type::MerchantId, ) -> RouterResponse<api_models::admin::ToggleKVResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; // check if the merchant account exists let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let kv_status = matches!( merchant_account.storage_scheme, MerchantStorageScheme::RedisKv ); Ok(service_api::ApplicationResponse::Json( api_models::admin::ToggleKVResponse { merchant_id: merchant_account.get_id().to_owned(), kv_enabled: kv_status, }, )) } pub fn get_frm_config_as_secret( frm_configs: Option<Vec<api_models::admin::FrmConfigs>>, ) -> Option<Vec<Secret<serde_json::Value>>> { match frm_configs.as_ref() { Some(frm_value) => { let configs_for_frm_value: Vec<Secret<serde_json::Value>> = frm_value .iter() .map(|config| { config .encode_to_value() .change_context(errors::ApiErrorResponse::ConfigNotFound) .map(Secret::new) }) .collect::<Result<Vec<_>, _>>() .ok()?; Some(configs_for_frm_value) } None => None, } } #[cfg(feature = "v1")] pub async fn create_and_insert_business_profile( state: &SessionState, request: api::ProfileCreate, merchant_account: domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<domain::Profile> { let business_profile_new = admin::create_profile_from_merchant_account(state, merchant_account, request, key_store) .await?; let profile_name = business_profile_new.profile_name.clone(); state .store .insert_business_profile(&state.into(), key_store, business_profile_new) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: format!( "Business Profile with the profile_name {profile_name} already exists" ), }) .attach_printable("Failed to insert Business profile because of duplication error") } #[cfg(feature = "olap")] #[async_trait::async_trait]
crates/router/src/core/admin.rs#chunk2
router
chunk
null
null
null
8,191
null
null
null
null
null
null
null
// Struct: GocardlessRouterData // File: crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct GocardlessRouterData<T>
crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs
hyperswitch_connectors
struct_definition
GocardlessRouterData
0
[]
54
null
null
null
null
null
null
null
// Implementation: impl api::RefundExecute for for Authorizedotnet // File: crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::RefundExecute for for Authorizedotnet
crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs
hyperswitch_connectors
impl_block
null
null
null
63
null
Authorizedotnet
api::RefundExecute for
0
0
null
null
// Function: find_processes_to_clean // File: crates/diesel_models/src/query/process_tracker.rs // Module: diesel_models pub fn find_processes_to_clean( conn: &PgPooledConn, time_lower_limit: PrimitiveDateTime, time_upper_limit: PrimitiveDateTime, runner: &str, limit: usize, ) -> StorageResult<Vec<Self>>
crates/diesel_models/src/query/process_tracker.rs
diesel_models
function_signature
null
null
null
78
find_processes_to_clean
null
null
null
null
null
null
// Struct: CybersourceRedirectionAuthResponse // File: crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct CybersourceRedirectionAuthResponse
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
hyperswitch_connectors
struct_definition
CybersourceRedirectionAuthResponse
0
[]
57
null
null
null
null
null
null
null
// Implementation: impl api::MandateSetup for for Paybox // File: crates/hyperswitch_connectors/src/connectors/paybox.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::MandateSetup for for Paybox
crates/hyperswitch_connectors/src/connectors/paybox.rs
hyperswitch_connectors
impl_block
null
null
null
61
null
Paybox
api::MandateSetup for
0
0
null
null
// File: crates/router/src/services/authorization/permissions.rs // Module: router // Public functions: 2 use common_enums::{EntityType, PermissionScope, Resource}; use router_derive::generate_permissions; generate_permissions! { permissions: [ Payment: { scopes: [Read, Write], entities: [Profile, Merchant] }, Refund: { scopes: [Read, Write], entities: [Profile, Merchant] }, Dispute: { scopes: [Read, Write], entities: [Profile, Merchant] }, Mandate: { scopes: [Read, Write], entities: [Merchant] }, Customer: { scopes: [Read, Write], entities: [Merchant] }, Payout: { scopes: [Read], entities: [Profile, Merchant] }, ApiKey: { scopes: [Read, Write], entities: [Merchant] }, Account: { scopes: [Read, Write], entities: [Profile, Merchant, Organization, Tenant] }, Connector: { scopes: [Read, Write], entities: [Profile, Merchant] }, Routing: { scopes: [Read, Write], entities: [Profile, Merchant] }, Subscription: { scopes: [Read, Write], entities: [Profile, Merchant] }, ThreeDsDecisionManager: { scopes: [Read, Write], entities: [Merchant, Profile] }, SurchargeDecisionManager: { scopes: [Read, Write], entities: [Merchant] }, Analytics: { scopes: [Read], entities: [Profile, Merchant, Organization] }, Report: { scopes: [Read], entities: [Profile, Merchant, Organization] }, User: { scopes: [Read, Write], entities: [Profile, Merchant] }, WebhookEvent: { scopes: [Read, Write], entities: [Profile, Merchant] }, ReconToken: { scopes: [Read], entities: [Merchant] }, ReconFiles: { scopes: [Read, Write], entities: [Merchant] }, ReconAndSettlementAnalytics: { scopes: [Read], entities: [Merchant] }, ReconUpload: { scopes: [Read, Write], entities: [Merchant] }, ReconReports: { scopes: [Read, Write], entities: [Merchant] }, RunRecon: { scopes: [Read, Write], entities: [Merchant] }, ReconConfig: { scopes: [Read, Write], entities: [Merchant] }, RevenueRecovery: { scopes: [Read], entities: [Profile] }, InternalConnector: { scopes: [Write], entities: [Merchant] }, Theme: { scopes: [Read,Write], entities: [Organization] } ] } pub fn get_resource_name(resource: Resource, entity_type: EntityType) -> Option<&'static str> { match (resource, entity_type) { (Resource::Payment, _) => Some("Payments"), (Resource::Refund, _) => Some("Refunds"), (Resource::Dispute, _) => Some("Disputes"), (Resource::Mandate, _) => Some("Mandates"), (Resource::Customer, _) => Some("Customers"), (Resource::Payout, _) => Some("Payouts"), (Resource::ApiKey, _) => Some("Api Keys"), (Resource::Connector, _) => { Some("Payment Processors, Payout Processors, Fraud & Risk Managers") } (Resource::Routing, _) => Some("Routing"), (Resource::Subscription, _) => Some("Subscription"), (Resource::RevenueRecovery, _) => Some("Revenue Recovery"), (Resource::ThreeDsDecisionManager, _) => Some("3DS Decision Manager"), (Resource::SurchargeDecisionManager, _) => Some("Surcharge Decision Manager"), (Resource::Analytics, _) => Some("Analytics"), (Resource::Report, _) => Some("Operation Reports"), (Resource::User, _) => Some("Users"), (Resource::WebhookEvent, _) => Some("Webhook Events"), (Resource::ReconUpload, _) => Some("Reconciliation File Upload"), (Resource::RunRecon, _) => Some("Run Reconciliation Process"), (Resource::ReconConfig, _) => Some("Reconciliation Configurations"), (Resource::ReconToken, _) => Some("Generate & Verify Reconciliation Token"), (Resource::ReconFiles, _) => Some("Reconciliation Process Manager"), (Resource::ReconReports, _) => Some("Reconciliation Reports"), (Resource::ReconAndSettlementAnalytics, _) => Some("Reconciliation Analytics"), (Resource::Account, EntityType::Profile) => Some("Business Profile Account"), (Resource::Account, EntityType::Merchant) => Some("Merchant Account"), (Resource::Account, EntityType::Organization) => Some("Organization Account"), (Resource::Account, EntityType::Tenant) => Some("Tenant Account"), (Resource::Theme, _) => Some("Themes"), (Resource::InternalConnector, _) => None, } } pub fn get_scope_name(scope: PermissionScope) -> &'static str { match scope { PermissionScope::Read => "View", PermissionScope::Write => "View and Manage", } }
crates/router/src/services/authorization/permissions.rs
router
full_file
null
null
null
1,182
null
null
null
null
null
null
null
// Function: is_in_terminal_state // File: crates/common_enums/src/enums.rs // Module: common_enums // Documentation: Indicates whether the payment intent is in terminal state or not pub fn is_in_terminal_state(self) -> bool
crates/common_enums/src/enums.rs
common_enums
function_signature
null
null
null
52
is_in_terminal_state
null
null
null
null
null
null
// Struct: TemporaryVaultCvc // File: crates/router/src/core/payment_methods/vault.rs // Module: router // Implementations: 0 pub struct TemporaryVaultCvc
crates/router/src/core/payment_methods/vault.rs
router
struct_definition
TemporaryVaultCvc
0
[]
39
null
null
null
null
null
null
null
// File: crates/router/src/services/api/generic_link_response.rs // Module: router // Public functions: 6 use common_utils::errors::CustomResult; use error_stack::ResultExt; use hyperswitch_domain_models::api::{ GenericExpiredLinkData, GenericLinkFormData, GenericLinkStatusData, GenericLinksData, }; use tera::{Context, Tera}; use super::build_secure_payment_link_html; use crate::core::errors; pub mod context; pub fn build_generic_link_html( boxed_generic_link_data: GenericLinksData, locale: String, ) -> CustomResult<String, errors::ApiErrorResponse> { match boxed_generic_link_data { GenericLinksData::ExpiredLink(link_data) => build_generic_expired_link_html(&link_data), GenericLinksData::PaymentMethodCollect(pm_collect_data) => { build_pm_collect_link_html(&pm_collect_data) } GenericLinksData::PaymentMethodCollectStatus(pm_collect_data) => { build_pm_collect_link_status_html(&pm_collect_data) } GenericLinksData::PayoutLink(payout_link_data) => { build_payout_link_html(&payout_link_data, locale.as_str()) } GenericLinksData::PayoutLinkStatus(pm_collect_data) => { build_payout_link_status_html(&pm_collect_data, locale.as_str()) } GenericLinksData::SecurePaymentLink(payment_link_data) => { build_secure_payment_link_html(payment_link_data) } } } pub fn build_generic_expired_link_html( link_data: &GenericExpiredLinkData, ) -> CustomResult<String, errors::ApiErrorResponse> { let mut tera = Tera::default(); let mut context = Context::new(); // Build HTML let html_template = include_str!("../../core/generic_link/expired_link/index.html").to_string(); let _ = tera.add_raw_template("generic_expired_link", &html_template); context.insert("title", &link_data.title); context.insert("message", &link_data.message); context.insert("theme", &link_data.theme); tera.render("generic_expired_link", &context) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render expired link HTML template") } fn build_html_template( link_data: &GenericLinkFormData, document: &'static str, styles: &'static str, ) -> CustomResult<(Tera, Context), errors::ApiErrorResponse> { let mut tera: Tera = Tera::default(); let mut context = Context::new(); // Insert dynamic context in CSS let css_dynamic_context = "{{ color_scheme }}"; let css_template = styles.to_string(); let final_css = format!("{css_dynamic_context}\n{css_template}"); let _ = tera.add_raw_template("document_styles", &final_css); context.insert("color_scheme", &link_data.css_data); let css_style_tag = tera .render("document_styles", &context) .map(|css| format!("<style>{css}</style>")) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render CSS template")?; // Insert HTML context let html_template = document.to_string(); let _ = tera.add_raw_template("html_template", &html_template); context.insert("css_style_tag", &css_style_tag); Ok((tera, context)) } pub fn build_payout_link_html( link_data: &GenericLinkFormData, locale: &str, ) -> CustomResult<String, errors::ApiErrorResponse> { let document = include_str!("../../core/generic_link/payout_link/initiate/index.html"); let styles = include_str!("../../core/generic_link/payout_link/initiate/styles.css"); let (mut tera, mut context) = build_html_template(link_data, document, styles) .attach_printable("Failed to build context for payout link's HTML template")?; // Insert dynamic context in JS let script = include_str!("../../core/generic_link/payout_link/initiate/script.js"); let js_template = script.to_string(); let js_dynamic_context = "{{ script_data }}"; let final_js = format!("{js_dynamic_context}\n{js_template}"); let _ = tera.add_raw_template("document_scripts", &final_js); context.insert("script_data", &link_data.js_data); context::insert_locales_in_context_for_payout_link(&mut context, locale); let js_script_tag = tera .render("document_scripts", &context) .map(|js| format!("<script>{js}</script>")) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render JS template")?; context.insert("js_script_tag", &js_script_tag); context.insert( "hyper_sdk_loader_script_tag", &format!( r#"<script src="{}" onload="initializePayoutSDK()"></script>"#, link_data.sdk_url ), ); // Render HTML template tera.render("html_template", &context) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payout link's HTML template") } pub fn build_pm_collect_link_html( link_data: &GenericLinkFormData, ) -> CustomResult<String, errors::ApiErrorResponse> { let document = include_str!("../../core/generic_link/payment_method_collect/initiate/index.html"); let styles = include_str!("../../core/generic_link/payment_method_collect/initiate/styles.css"); let (mut tera, mut context) = build_html_template(link_data, document, styles) .attach_printable( "Failed to build context for payment method collect link's HTML template", )?; // Insert dynamic context in JS let script = include_str!("../../core/generic_link/payment_method_collect/initiate/script.js"); let js_template = script.to_string(); let js_dynamic_context = "{{ script_data }}"; let final_js = format!("{js_dynamic_context}\n{js_template}"); let _ = tera.add_raw_template("document_scripts", &final_js); context.insert("script_data", &link_data.js_data); let js_script_tag = tera .render("document_scripts", &context) .map(|js| format!("<script>{js}</script>")) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render JS template")?; context.insert("js_script_tag", &js_script_tag); context.insert( "hyper_sdk_loader_script_tag", &format!( r#"<script src="{}" onload="initializeCollectSDK()"></script>"#, link_data.sdk_url ), ); // Render HTML template tera.render("html_template", &context) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payment method collect link's HTML template") } pub fn build_payout_link_status_html( link_data: &GenericLinkStatusData, locale: &str, ) -> CustomResult<String, errors::ApiErrorResponse> { let mut tera = Tera::default(); let mut context = Context::new(); // Insert dynamic context in CSS let css_dynamic_context = "{{ color_scheme }}"; let css_template = include_str!("../../core/generic_link/payout_link/status/styles.css").to_string(); let final_css = format!("{css_dynamic_context}\n{css_template}"); let _ = tera.add_raw_template("payout_link_status_styles", &final_css); context.insert("color_scheme", &link_data.css_data); let css_style_tag = tera .render("payout_link_status_styles", &context) .map(|css| format!("<style>{css}</style>")) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payout link status CSS template")?; // Insert dynamic context in JS let js_dynamic_context = "{{ script_data }}"; let js_template = include_str!("../../core/generic_link/payout_link/status/script.js").to_string(); let final_js = format!("{js_dynamic_context}\n{js_template}"); let _ = tera.add_raw_template("payout_link_status_script", &final_js); context.insert("script_data", &link_data.js_data); context::insert_locales_in_context_for_payout_link_status(&mut context, locale); let js_script_tag = tera .render("payout_link_status_script", &context) .map(|js| format!("<script>{js}</script>")) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payout link status JS template")?; // Build HTML let html_template = include_str!("../../core/generic_link/payout_link/status/index.html").to_string(); let _ = tera.add_raw_template("payout_status_link", &html_template); context.insert("css_style_tag", &css_style_tag); context.insert("js_script_tag", &js_script_tag); tera.render("payout_status_link", &context) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payout link status HTML template") } pub fn build_pm_collect_link_status_html( link_data: &GenericLinkStatusData, ) -> CustomResult<String, errors::ApiErrorResponse> { let mut tera = Tera::default(); let mut context = Context::new(); // Insert dynamic context in CSS let css_dynamic_context = "{{ color_scheme }}"; let css_template = include_str!("../../core/generic_link/payment_method_collect/status/styles.css") .to_string(); let final_css = format!("{css_dynamic_context}\n{css_template}"); let _ = tera.add_raw_template("pm_collect_link_status_styles", &final_css); context.insert("color_scheme", &link_data.css_data); let css_style_tag = tera .render("pm_collect_link_status_styles", &context) .map(|css| format!("<style>{css}</style>")) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payment method collect link status CSS template")?; // Insert dynamic context in JS let js_dynamic_context = "{{ collect_link_status_context }}"; let js_template = include_str!("../../core/generic_link/payment_method_collect/status/script.js").to_string(); let final_js = format!("{js_dynamic_context}\n{js_template}"); let _ = tera.add_raw_template("pm_collect_link_status_script", &final_js); context.insert("collect_link_status_context", &link_data.js_data); let js_script_tag = tera .render("pm_collect_link_status_script", &context) .map(|js| format!("<script>{js}</script>")) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payment method collect link status JS template")?; // Build HTML let html_template = include_str!("../../core/generic_link/payment_method_collect/status/index.html") .to_string(); let _ = tera.add_raw_template("payment_method_collect_status_link", &html_template); context.insert("css_style_tag", &css_style_tag); context.insert("js_script_tag", &js_script_tag); tera.render("payment_method_collect_status_link", &context) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payment method collect link status HTML template") }
crates/router/src/services/api/generic_link_response.rs
router
full_file
null
null
null
2,491
null
null
null
null
null
null
null
// Function: payments_create // File: crates/router/src/routes/payments.rs // Module: router pub fn payments_create( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsRequest>, ) -> impl Responder
crates/router/src/routes/payments.rs
router
function_signature
null
null
null
66
payments_create
null
null
null
null
null
null
// Struct: ApplePayCertificatesMigration // File: crates/router/src/routes/app.rs // Module: router // Implementations: 1 pub struct ApplePayCertificatesMigration
crates/router/src/routes/app.rs
router
struct_definition
ApplePayCertificatesMigration
1
[]
36
null
null
null
null
null
null
null
// Implementation: impl behaviour::Conversion for for PaymentAddress // File: crates/router/src/types/domain/address.rs // Module: router // Methods: 3 total (0 public) impl behaviour::Conversion for for PaymentAddress
crates/router/src/types/domain/address.rs
router
impl_block
null
null
null
46
null
PaymentAddress
behaviour::Conversion for
3
0
null
null
// Implementation: impl ConnectorCommon for for Getnet // File: crates/hyperswitch_connectors/src/connectors/getnet.rs // Module: hyperswitch_connectors // Methods: 6 total (0 public) impl ConnectorCommon for for Getnet
crates/hyperswitch_connectors/src/connectors/getnet.rs
hyperswitch_connectors
impl_block
null
null
null
53
null
Getnet
ConnectorCommon for
6
0
null
null
// Struct: UpdateSuccessRateWindowEventRequest // File: crates/router/src/core/payments/routing/utils.rs // Module: router // Implementations: 0 pub struct UpdateSuccessRateWindowEventRequest
crates/router/src/core/payments/routing/utils.rs
router
struct_definition
UpdateSuccessRateWindowEventRequest
0
[]
44
null
null
null
null
null
null
null
// Function: list_users_in_lineage // File: crates/router/src/routes/user_role.rs // Module: router pub fn list_users_in_lineage( state: web::Data<AppState>, req: HttpRequest, query: web::Query<user_role_api::ListUsersInEntityRequest>, ) -> HttpResponse
crates/router/src/routes/user_role.rs
router
function_signature
null
null
null
67
list_users_in_lineage
null
null
null
null
null
null
// Function: new // File: crates/api_models/src/analytics/active_payments.rs // Module: api_models pub fn new(time_bucket: Option<String>) -> Self
crates/api_models/src/analytics/active_payments.rs
api_models
function_signature
null
null
null
36
new
null
null
null
null
null
null
// File: crates/redis_interface/src/types.rs // Module: redis_interface // Public functions: 10 // Public structs: 3 //! Data types and type conversions //! from `fred`'s internal data-types to custom data-types use common_utils::errors::CustomResult; use fred::types::RedisValue as FredRedisValue; use crate::{errors, RedisConnectionPool}; pub struct RedisValue { inner: FredRedisValue, } impl std::ops::Deref for RedisValue { type Target = FredRedisValue; fn deref(&self) -> &Self::Target { &self.inner } } impl RedisValue { pub fn new(value: FredRedisValue) -> Self { Self { inner: value } } pub fn into_inner(self) -> FredRedisValue { self.inner } pub fn from_bytes(val: Vec<u8>) -> Self { Self { inner: FredRedisValue::Bytes(val.into()), } } pub fn from_string(value: String) -> Self { Self { inner: FredRedisValue::String(value.into()), } } } impl From<RedisValue> for FredRedisValue { fn from(v: RedisValue) -> Self { v.inner } } #[derive(Debug, serde::Deserialize, Clone)] #[serde(default)] pub struct RedisSettings { pub host: String, pub port: u16, pub cluster_enabled: bool, pub cluster_urls: Vec<String>, pub use_legacy_version: bool, pub pool_size: usize, pub reconnect_max_attempts: u32, /// Reconnect delay in milliseconds pub reconnect_delay: u32, /// TTL in seconds pub default_ttl: u32, /// TTL for hash-tables in seconds pub default_hash_ttl: u32, pub stream_read_count: u64, pub auto_pipeline: bool, pub disable_auto_backpressure: bool, pub max_in_flight_commands: u64, pub default_command_timeout: u64, pub max_feed_count: u64, pub unresponsive_timeout: u64, } impl RedisSettings { /// Validates the Redis configuration provided. pub fn validate(&self) -> CustomResult<(), errors::RedisError> { use common_utils::{ext_traits::ConfigExt, fp_utils::when}; when(self.host.is_default_or_empty(), || { Err(errors::RedisError::InvalidConfiguration( "Redis `host` must be specified".into(), )) })?; when(self.cluster_enabled && self.cluster_urls.is_empty(), || { Err(errors::RedisError::InvalidConfiguration( "Redis `cluster_urls` must be specified if `cluster_enabled` is `true`".into(), )) })?; when( self.default_command_timeout < self.unresponsive_timeout, || { Err(errors::RedisError::InvalidConfiguration( "Unresponsive timeout cannot be greater than the command timeout".into(), ) .into()) }, ) } } impl Default for RedisSettings { fn default() -> Self { Self { host: "127.0.0.1".to_string(), port: 6379, cluster_enabled: false, cluster_urls: vec![], use_legacy_version: false, pool_size: 5, reconnect_max_attempts: 5, reconnect_delay: 5, default_ttl: 300, stream_read_count: 1, default_hash_ttl: 900, auto_pipeline: true, disable_auto_backpressure: false, max_in_flight_commands: 5000, default_command_timeout: 30, max_feed_count: 200, unresponsive_timeout: 10, } } } #[derive(Debug)] pub enum RedisEntryId { UserSpecifiedID { milliseconds: String, sequence_number: String, }, AutoGeneratedID, AfterLastID, /// Applicable only with consumer groups UndeliveredEntryID, } impl From<RedisEntryId> for fred::types::XID { fn from(id: RedisEntryId) -> Self { match id { RedisEntryId::UserSpecifiedID { milliseconds, sequence_number, } => Self::Manual(fred::bytes_utils::format_bytes!( "{milliseconds}-{sequence_number}" )), RedisEntryId::AutoGeneratedID => Self::Auto, RedisEntryId::AfterLastID => Self::Max, RedisEntryId::UndeliveredEntryID => Self::NewInGroup, } } } impl From<&RedisEntryId> for fred::types::XID { fn from(id: &RedisEntryId) -> Self { match id { RedisEntryId::UserSpecifiedID { milliseconds, sequence_number, } => Self::Manual(fred::bytes_utils::format_bytes!( "{milliseconds}-{sequence_number}" )), RedisEntryId::AutoGeneratedID => Self::Auto, RedisEntryId::AfterLastID => Self::Max, RedisEntryId::UndeliveredEntryID => Self::NewInGroup, } } } #[derive(Eq, PartialEq)] pub enum SetnxReply { KeySet, KeyNotSet, // Existing key } impl fred::types::FromRedis for SetnxReply { fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { match value { // Returns String ( "OK" ) in case of success fred::types::RedisValue::String(_) => Ok(Self::KeySet), // Return Null in case of failure fred::types::RedisValue::Null => Ok(Self::KeyNotSet), // Unexpected behaviour _ => Err(fred::error::RedisError::new( fred::error::RedisErrorKind::Unknown, "Unexpected SETNX command reply", )), } } } #[derive(Eq, PartialEq)] pub enum HsetnxReply { KeySet, KeyNotSet, // Existing key } impl fred::types::FromRedis for HsetnxReply { fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { match value { fred::types::RedisValue::Integer(1) => Ok(Self::KeySet), fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotSet), _ => Err(fred::error::RedisError::new( fred::error::RedisErrorKind::Unknown, "Unexpected HSETNX command reply", )), } } } #[derive(Eq, PartialEq)] pub enum MsetnxReply { KeysSet, KeysNotSet, // At least one existing key } impl fred::types::FromRedis for MsetnxReply { fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { match value { fred::types::RedisValue::Integer(1) => Ok(Self::KeysSet), fred::types::RedisValue::Integer(0) => Ok(Self::KeysNotSet), _ => Err(fred::error::RedisError::new( fred::error::RedisErrorKind::Unknown, "Unexpected MSETNX command reply", )), } } } #[derive(Debug)] pub enum StreamCapKind { MinID, MaxLen, } impl From<StreamCapKind> for fred::types::XCapKind { fn from(item: StreamCapKind) -> Self { match item { StreamCapKind::MaxLen => Self::MaxLen, StreamCapKind::MinID => Self::MinID, } } } #[derive(Debug)] pub enum StreamCapTrim { Exact, AlmostExact, } impl From<StreamCapTrim> for fred::types::XCapTrim { fn from(item: StreamCapTrim) -> Self { match item { StreamCapTrim::Exact => Self::Exact, StreamCapTrim::AlmostExact => Self::AlmostExact, } } } #[derive(Debug)] pub enum DelReply { KeyDeleted, KeyNotDeleted, // Key not found } impl DelReply { pub fn is_key_deleted(&self) -> bool { matches!(self, Self::KeyDeleted) } pub fn is_key_not_deleted(&self) -> bool { matches!(self, Self::KeyNotDeleted) } } impl fred::types::FromRedis for DelReply { fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { match value { fred::types::RedisValue::Integer(1) => Ok(Self::KeyDeleted), fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotDeleted), _ => Err(fred::error::RedisError::new( fred::error::RedisErrorKind::Unknown, "Unexpected del command reply", )), } } } #[derive(Debug)] pub enum SaddReply { KeySet, KeyNotSet, } impl fred::types::FromRedis for SaddReply { fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { match value { fred::types::RedisValue::Integer(1) => Ok(Self::KeySet), fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotSet), _ => Err(fred::error::RedisError::new( fred::error::RedisErrorKind::Unknown, "Unexpected sadd command reply", )), } } } #[derive(Debug)] pub enum SetGetReply<T> { ValueSet(T), // Value was set and this is the value that was set ValueExists(T), // Value already existed and this is the existing value } impl<T> SetGetReply<T> { pub fn get_value(&self) -> &T { match self { Self::ValueSet(value) => value, Self::ValueExists(value) => value, } } } #[derive(Debug)] pub struct RedisKey(String); impl RedisKey { pub fn tenant_aware_key(&self, pool: &RedisConnectionPool) -> String { pool.add_prefix(&self.0) } pub fn tenant_unaware_key(&self, _pool: &RedisConnectionPool) -> String { self.0.clone() } } impl<T: AsRef<str>> From<T> for RedisKey { fn from(value: T) -> Self { let value = value.as_ref(); Self(value.to_string()) } }
crates/redis_interface/src/types.rs
redis_interface
full_file
null
null
null
2,305
null
null
null
null
null
null
null
// Struct: AuthorizationIsoFields // File: crates/hyperswitch_connectors/src/connectors/silverflow/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct AuthorizationIsoFields
crates/hyperswitch_connectors/src/connectors/silverflow/transformers.rs
hyperswitch_connectors
struct_definition
AuthorizationIsoFields
0
[]
48
null
null
null
null
null
null
null
// Module Structure // File: crates/hyperswitch_connectors/src/connectors/nuvei.rs // Module: hyperswitch_connectors // Public submodules: pub mod transformers;
crates/hyperswitch_connectors/src/connectors/nuvei.rs
hyperswitch_connectors
module_structure
null
null
null
40
null
null
null
null
null
1
0
// Struct: HelcimVoidRequest // File: crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct HelcimVoidRequest
crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs
hyperswitch_connectors
struct_definition
HelcimVoidRequest
0
[]
53
null
null
null
null
null
null
null
// Function: get_skrill_account_id // File: crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs // Module: hyperswitch_connectors pub fn get_skrill_account_id( &self, currency: Currency, ) -> Result<Secret<String>, errors::ConnectorError>
crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
hyperswitch_connectors
function_signature
null
null
null
70
get_skrill_account_id
null
null
null
null
null
null
// Implementation: impl EmailData for for ProFeatureRequest // File: crates/router/src/services/email/types.rs // Module: router // Methods: 1 total (0 public) impl EmailData for for ProFeatureRequest
crates/router/src/services/email/types.rs
router
impl_block
null
null
null
46
null
ProFeatureRequest
EmailData for
1
0
null
null
// Function: retry_refund_sync_task // File: crates/router/src/core/refunds.rs // Module: router // Documentation: Schedule the task for refund retry Returns bool which indicates whether this was the last refund retry or not pub fn retry_refund_sync_task( db: &dyn db::StorageInterface, connector: String, merchant_id: common_utils::id_type::MerchantId, pt: storage::ProcessTracker, ) -> Result<bool, sch_errors::ProcessTrackerError>
crates/router/src/core/refunds.rs
router
function_signature
null
null
null
105
retry_refund_sync_task
null
null
null
null
null
null
// Struct: SearchData // File: crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct SearchData
crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
hyperswitch_connectors
struct_definition
SearchData
0
[]
46
null
null
null
null
null
null
null
// Struct: RetrieveCardResp // File: crates/router/src/core/payment_methods/transformers.rs // Module: router // Implementations: 0 pub struct RetrieveCardResp
crates/router/src/core/payment_methods/transformers.rs
router
struct_definition
RetrieveCardResp
0
[]
38
null
null
null
null
null
null
null
// Struct: RefundResponse // File: crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct RefundResponse
crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
hyperswitch_connectors
struct_definition
RefundResponse
0
[]
49
null
null
null
null
null
null
null
// Struct: DecisionManagerRecord // File: crates/api_models/src/conditional_configs.rs // Module: api_models // Implementations: 1 // Traits: events::ApiEventMetric pub struct DecisionManagerRecord
crates/api_models/src/conditional_configs.rs
api_models
struct_definition
DecisionManagerRecord
1
[ "events::ApiEventMetric" ]
46
null
null
null
null
null
null
null
// File: crates/router/src/core/fraud_check/operation/fraud_check_pre.rs // Module: router // Public structs: 1 use async_trait::async_trait; use common_enums::FrmSuggestion; use common_utils::ext_traits::Encode; use diesel_models::enums::FraudCheckLastStep; use router_env::{instrument, tracing}; use uuid::Uuid; use super::{Domain, FraudCheckOperation, GetTracker, UpdateTracker}; use crate::{ core::{ errors::RouterResult, fraud_check::{ self as frm_core, types::{FrmData, PaymentDetails, PaymentToFrmData}, ConnectorDetailsCore, }, payments, }, errors, routes::app::ReqState, types::{ api::fraud_check as frm_api, domain, fraud_check::{ FraudCheckCheckoutData, FraudCheckResponseData, FraudCheckTransactionData, FrmRequest, FrmResponse, FrmRouterData, }, storage::{ enums::{FraudCheckStatus, FraudCheckType}, fraud_check::{FraudCheckNew, FraudCheckUpdate}, }, ResponseId, }, SessionState, }; #[derive(Debug, Clone, Copy)] pub struct FraudCheckPre; impl<F, D> FraudCheckOperation<F, D> for &FraudCheckPre where F: Clone + Send, D: payments::OperationSessionGetters<F> + Send + Sync + Clone, { fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> { Ok(*self) } fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> { Ok(*self) } fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> { Ok(*self) } } impl<F, D> FraudCheckOperation<F, D> for FraudCheckPre where F: Clone + Send, D: payments::OperationSessionGetters<F> + Send + Sync + Clone, { fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> { Ok(self) } fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> { Ok(self) } fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> { Ok(self) } } #[async_trait] impl GetTracker<PaymentToFrmData> for FraudCheckPre { #[cfg(feature = "v2")] #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_data: PaymentToFrmData, frm_connector_details: ConnectorDetailsCore, ) -> RouterResult<Option<FrmData>> { todo!() } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_data: PaymentToFrmData, frm_connector_details: ConnectorDetailsCore, ) -> RouterResult<Option<FrmData>> { let db = &*state.store; let payment_details: Option<serde_json::Value> = PaymentDetails::from(payment_data.clone()) .encode_to_value() .ok(); let existing_fraud_check = db .find_fraud_check_by_payment_id_if_present( payment_data.payment_intent.get_id().to_owned(), payment_data.merchant_account.get_id().clone(), ) .await .ok(); let fraud_check = match existing_fraud_check { Some(Some(fraud_check)) => Ok(fraud_check), _ => { db.insert_fraud_check_response(FraudCheckNew { frm_id: Uuid::new_v4().simple().to_string(), payment_id: payment_data.payment_intent.get_id().to_owned(), merchant_id: payment_data.merchant_account.get_id().clone(), attempt_id: payment_data.payment_attempt.attempt_id.clone(), created_at: common_utils::date_time::now(), frm_name: frm_connector_details.connector_name, frm_transaction_id: None, frm_transaction_type: FraudCheckType::PreFrm, frm_status: FraudCheckStatus::Pending, frm_score: None, frm_reason: None, frm_error: None, payment_details, metadata: None, modified_at: common_utils::date_time::now(), last_step: FraudCheckLastStep::Processing, payment_capture_method: payment_data.payment_attempt.capture_method, }) .await } }; match fraud_check { Ok(fraud_check_value) => { let frm_data = FrmData { payment_intent: payment_data.payment_intent, payment_attempt: payment_data.payment_attempt, merchant_account: payment_data.merchant_account, address: payment_data.address, fraud_check: fraud_check_value, connector_details: payment_data.connector_details, order_details: payment_data.order_details, refund: None, frm_metadata: payment_data.frm_metadata, }; Ok(Some(frm_data)) } Err(error) => { router_env::logger::error!("inserting into fraud_check table failed {error:?}"); Ok(None) } } } } #[async_trait] impl<F, D> Domain<F, D> for FraudCheckPre where F: Clone + Send, D: payments::OperationSessionGetters<F> + Send + Sync + Clone, { #[cfg(feature = "v2")] #[instrument(skip_all)] async fn post_payment_frm<'a>( &'a self, _state: &'a SessionState, _req_state: ReqState, _payment_data: &mut D, _frm_data: &mut FrmData, _merchant_context: &domain::MerchantContext, _customer: &Option<domain::Customer>, ) -> RouterResult<Option<FrmRouterData>> { todo!() } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn post_payment_frm<'a>( &'a self, state: &'a SessionState, _req_state: ReqState, payment_data: &mut D, frm_data: &mut FrmData, merchant_context: &domain::MerchantContext, customer: &Option<domain::Customer>, ) -> RouterResult<Option<FrmRouterData>> { let router_data = frm_core::call_frm_service::<F, frm_api::Transaction, _, D>( state, payment_data, &mut frm_data.to_owned(), merchant_context, customer, ) .await?; frm_data.fraud_check.last_step = FraudCheckLastStep::TransactionOrRecordRefund; Ok(Some(FrmRouterData { merchant_id: router_data.merchant_id, connector: router_data.connector, payment_id: router_data.payment_id.clone(), attempt_id: router_data.attempt_id, request: FrmRequest::Transaction(FraudCheckTransactionData { amount: router_data.request.amount, order_details: router_data.request.order_details, currency: router_data.request.currency, payment_method: Some(router_data.payment_method), error_code: router_data.request.error_code, error_message: router_data.request.error_message, connector_transaction_id: router_data.request.connector_transaction_id, connector: router_data.request.connector, }), response: FrmResponse::Transaction(router_data.response), })) } async fn pre_payment_frm<'a>( &'a self, state: &'a SessionState, payment_data: &mut D, frm_data: &mut FrmData, merchant_context: &domain::MerchantContext, customer: &Option<domain::Customer>, ) -> RouterResult<FrmRouterData> { let router_data = frm_core::call_frm_service::<F, frm_api::Checkout, _, D>( state, payment_data, &mut frm_data.to_owned(), merchant_context, customer, ) .await?; frm_data.fraud_check.last_step = FraudCheckLastStep::CheckoutOrSale; Ok(FrmRouterData { merchant_id: router_data.merchant_id, connector: router_data.connector, payment_id: router_data.payment_id.clone(), attempt_id: router_data.attempt_id, request: FrmRequest::Checkout(Box::new(FraudCheckCheckoutData { amount: router_data.request.amount, order_details: router_data.request.order_details, currency: router_data.request.currency, browser_info: router_data.request.browser_info, payment_method_data: router_data.request.payment_method_data, email: router_data.request.email, gateway: router_data.request.gateway, })), response: FrmResponse::Checkout(router_data.response), }) } } #[async_trait] impl<F, D> UpdateTracker<FrmData, F, D> for FraudCheckPre where F: Clone + Send, D: payments::OperationSessionGetters<F> + Send + Sync + Clone, { async fn update_tracker<'b>( &'b self, state: &SessionState, _key_store: &domain::MerchantKeyStore, mut frm_data: FrmData, payment_data: &mut D, _frm_suggestion: Option<FrmSuggestion>, frm_router_data: FrmRouterData, ) -> RouterResult<FrmData> { let frm_check_update = match frm_router_data.response { FrmResponse::Checkout(response) => match response { Err(err) => Some(FraudCheckUpdate::ErrorUpdate { status: FraudCheckStatus::TransactionFailure, error_message: Some(Some(err.message)), }), Ok(payments_response) => match payments_response { FraudCheckResponseData::TransactionResponse { resource_id, connector_metadata, status, reason, score, } => { let connector_transaction_id = match resource_id { ResponseId::NoResponseId => None, ResponseId::ConnectorTransactionId(id) => Some(id), ResponseId::EncodedData(id) => Some(id), }; let fraud_check_update = FraudCheckUpdate::ResponseUpdate { frm_status: status, frm_transaction_id: connector_transaction_id, frm_reason: reason, frm_score: score, metadata: connector_metadata, modified_at: common_utils::date_time::now(), last_step: frm_data.fraud_check.last_step, payment_capture_method: frm_data.fraud_check.payment_capture_method, }; Some(fraud_check_update) } FraudCheckResponseData::FulfillmentResponse { order_id: _, shipment_ids: _, } => None, FraudCheckResponseData::RecordReturnResponse { resource_id: _, connector_metadata: _, return_id: _, } => Some(FraudCheckUpdate::ErrorUpdate { status: FraudCheckStatus::TransactionFailure, error_message: Some(Some( "Error: Got Record Return Response response in current Checkout flow" .to_string(), )), }), }, }, FrmResponse::Transaction(response) => match response { Err(err) => Some(FraudCheckUpdate::ErrorUpdate { status: FraudCheckStatus::TransactionFailure, error_message: Some(Some(err.message)), }), Ok(payments_response) => match payments_response { FraudCheckResponseData::TransactionResponse { resource_id, connector_metadata, status, reason, score, } => { let connector_transaction_id = match resource_id { ResponseId::NoResponseId => None, ResponseId::ConnectorTransactionId(id) => Some(id), ResponseId::EncodedData(id) => Some(id), }; let frm_status = payment_data .get_frm_message() .as_ref() .map_or(status, |frm_data| frm_data.frm_status); let fraud_check_update = FraudCheckUpdate::ResponseUpdate { frm_status, frm_transaction_id: connector_transaction_id, frm_reason: reason, frm_score: score, metadata: connector_metadata, modified_at: common_utils::date_time::now(), last_step: frm_data.fraud_check.last_step, payment_capture_method: None, }; Some(fraud_check_update) } FraudCheckResponseData::FulfillmentResponse { order_id: _, shipment_ids: _, } => None, FraudCheckResponseData::RecordReturnResponse { resource_id: _, connector_metadata: _, return_id: _, } => Some(FraudCheckUpdate::ErrorUpdate { status: FraudCheckStatus::TransactionFailure, error_message: Some(Some( "Error: Got Record Return Response response in current Checkout flow" .to_string(), )), }), }, }, FrmResponse::Sale(_response) | FrmResponse::Fulfillment(_response) | FrmResponse::RecordReturn(_response) => Some(FraudCheckUpdate::ErrorUpdate { status: FraudCheckStatus::TransactionFailure, error_message: Some(Some( "Error: Got Pre(Sale) flow response in current post flow".to_string(), )), }), }; let db = &*state.store; frm_data.fraud_check = match frm_check_update { Some(fraud_check_update) => db .update_fraud_check_response_with_attempt_id( frm_data.clone().fraud_check, fraud_check_update, ) .await .map_err(|error| error.change_context(errors::ApiErrorResponse::PaymentNotFound))?, None => frm_data.clone().fraud_check, }; Ok(frm_data) } }
crates/router/src/core/fraud_check/operation/fraud_check_pre.rs
router
full_file
null
null
null
2,944
null
null
null
null
null
null
null
// Function: set_three_d_s_comp_ind // File: crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs // Module: hyperswitch_connectors pub fn set_three_d_s_comp_ind(mut self, three_d_s_comp_ind: ThreeDSCompInd) -> Self
crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
hyperswitch_connectors
function_signature
null
null
null
62
set_three_d_s_comp_ind
null
null
null
null
null
null
// Struct: TrustpayWebhookResponse // File: crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct TrustpayWebhookResponse
crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
hyperswitch_connectors
struct_definition
TrustpayWebhookResponse
0
[]
52
null
null
null
null
null
null
null
// Implementation: impl Responder // File: crates/router/src/routes/payments.rs // Module: router // Methods: 0 total (0 public) impl Responder
crates/router/src/routes/payments.rs
router
impl_block
null
null
null
36
null
Responder
null
0
0
null
null
// File: crates/router/src/core/webhooks/incoming_v2.rs // Module: router // Public functions: 1 use std::{marker::PhantomData, str::FromStr, time::Instant}; use actix_web::FromRequest; use api_models::webhooks::{self, WebhookResponseTracker}; use common_utils::{ errors::ReportSwitchExt, events::ApiEventsType, types::keymanager::KeyManagerState, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payments::{HeaderPayload, PaymentStatusData}, router_request_types::VerifyWebhookSourceRequestData, router_response_types::{VerifyWebhookSourceResponseData, VerifyWebhookStatus}, }; use hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails; use router_env::{instrument, tracing, tracing_actix_web::RequestId}; use super::{types, utils, MERCHANT_ID}; #[cfg(feature = "revenue_recovery")] use crate::core::webhooks::recovery_incoming; use crate::{ core::{ api_locking, errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt}, metrics, payments::{ self, transformers::{GenerateResponse, ToResponse}, }, webhooks::{ create_event_and_trigger_outgoing_webhook, utils::construct_webhook_router_data, }, }, db::StorageInterface, events::api_logs::ApiEvent, logger, routes::{ app::{ReqState, SessionStateInfo}, lock_utils, SessionState, }, services::{ self, authentication as auth, connector_integration_interface::ConnectorEnum, ConnectorValidation, }, types::{ api::{self, ConnectorData, GetToken, IncomingWebhook}, domain, storage::enums, transformers::ForeignInto, }, }; #[allow(clippy::too_many_arguments)] pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>( flow: &impl router_env::types::FlowMetric, state: SessionState, req_state: ReqState, req: &actix_web::HttpRequest, merchant_context: domain::MerchantContext, profile: domain::Profile, connector_id: &common_utils::id_type::MerchantConnectorAccountId, body: actix_web::web::Bytes, is_relay_webhook: bool, ) -> RouterResponse<serde_json::Value> { let start_instant = Instant::now(); let (application_response, webhooks_response_tracker, serialized_req) = Box::pin(incoming_webhooks_core::<W>( state.clone(), req_state, req, merchant_context.clone(), profile, connector_id, body.clone(), is_relay_webhook, )) .await?; logger::info!(incoming_webhook_payload = ?serialized_req); let request_duration = Instant::now() .saturating_duration_since(start_instant) .as_millis(); let request_id = RequestId::extract(req) .await .attach_printable("Unable to extract request id from request") .change_context(errors::ApiErrorResponse::InternalServerError)?; let auth_type = auth::AuthenticationType::WebhookAuth { merchant_id: merchant_context.get_merchant_account().get_id().clone(), }; let status_code = 200; let api_event = ApiEventsType::Webhooks { connector: connector_id.clone(), payment_id: webhooks_response_tracker.get_payment_id(), }; let response_value = serde_json::to_value(&webhooks_response_tracker) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not convert webhook effect to string")?; let infra = state.infra_components.clone(); let api_event = ApiEvent::new( state.tenant.tenant_id.clone(), Some(merchant_context.get_merchant_account().get_id().clone()), flow, &request_id, request_duration, status_code, serialized_req, Some(response_value), None, auth_type, None, api_event, req, req.method(), infra, ); state.event_handler().log_event(&api_event); Ok(application_response) } #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( state: SessionState, req_state: ReqState, req: &actix_web::HttpRequest, merchant_context: domain::MerchantContext, profile: domain::Profile, connector_id: &common_utils::id_type::MerchantConnectorAccountId, body: actix_web::web::Bytes, _is_relay_webhook: bool, ) -> errors::RouterResult<( services::ApplicationResponse<serde_json::Value>, WebhookResponseTracker, serde_json::Value, )> { metrics::WEBHOOK_INCOMING_COUNT.add( 1, router_env::metric_attributes!(( MERCHANT_ID, merchant_context.get_merchant_account().get_id().clone() )), ); let mut request_details = IncomingWebhookRequestDetails { method: req.method().clone(), uri: req.uri().clone(), headers: req.headers(), query_params: req.query_string().to_string(), body: &body, }; // Fetch the merchant connector account to get the webhooks source secret // `webhooks source secret` is a secret shared between the merchant and connector // This is used for source verification and webhooks integrity let (merchant_connector_account, connector, connector_name) = fetch_mca_and_connector( &state, connector_id, merchant_context.get_merchant_key_store(), ) .await?; let decoded_body = connector .decode_webhook_body( &request_details, merchant_context.get_merchant_account().get_id(), merchant_connector_account.connector_webhook_details.clone(), connector_name.as_str(), ) .await .switch() .attach_printable("There was an error in incoming webhook body decoding")?; request_details.body = &decoded_body; let event_type = match connector .get_webhook_event_type(&request_details) .allow_webhook_event_type_not_found( state .clone() .conf .webhooks .ignore_error .event_type .unwrap_or(true), ) .switch() .attach_printable("Could not find event type in incoming webhook body")? { Some(event_type) => event_type, // Early return allows us to acknowledge the webhooks that we do not support None => { logger::error!( webhook_payload =? request_details.body, "Failed while identifying the event type", ); metrics::WEBHOOK_EVENT_TYPE_IDENTIFICATION_FAILURE_COUNT.add( 1, router_env::metric_attributes!( ( MERCHANT_ID, merchant_context.get_merchant_account().get_id().clone() ), ("connector", connector_name) ), ); let response = connector .get_webhook_api_response(&request_details, None) .switch() .attach_printable("Failed while early return in case of event type parsing")?; return Ok(( response, WebhookResponseTracker::NoEffect, serde_json::Value::Null, )); } }; logger::info!(event_type=?event_type); // if it is a setup webhook event, return ok status if event_type == webhooks::IncomingWebhookEvent::SetupWebhook { return Ok(( services::ApplicationResponse::StatusOk, WebhookResponseTracker::NoEffect, serde_json::Value::default(), )); } let is_webhook_event_supported = !matches!( event_type, webhooks::IncomingWebhookEvent::EventNotSupported ); let is_webhook_event_enabled = !utils::is_webhook_event_disabled( &*state.clone().store, connector_name.as_str(), merchant_context.get_merchant_account().get_id(), &event_type, ) .await; //process webhook further only if webhook event is enabled and is not event_not_supported let process_webhook_further = is_webhook_event_enabled && is_webhook_event_supported; logger::info!(process_webhook=?process_webhook_further); let flow_type: api::WebhookFlow = event_type.into(); let mut event_object: Box<dyn masking::ErasedMaskSerialize> = Box::new(serde_json::Value::Null); let webhook_effect = if process_webhook_further && !matches!(flow_type, api::WebhookFlow::ReturnResponse) { let object_ref_id = connector .get_webhook_object_reference_id(&request_details) .switch() .attach_printable("Could not find object reference id in incoming webhook body")?; let connector_enum = api_models::enums::Connector::from_str(&connector_name) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "connector", }) .attach_printable_lazy(|| { format!("unable to parse connector name {connector_name:?}") })?; let connectors_with_source_verification_call = &state.conf.webhook_source_verification_call; let source_verified = if connectors_with_source_verification_call .connectors_with_webhook_source_verification_call .contains(&connector_enum) { verify_webhook_source_verification_call( connector.clone(), &state, &merchant_context, merchant_connector_account.clone(), &connector_name, &request_details, ) .await .or_else(|error| match error.current_context() { errors::ConnectorError::WebhookSourceVerificationFailed => { logger::error!(?error, "Source Verification Failed"); Ok(false) } _ => Err(error), }) .switch() .attach_printable("There was an issue in incoming webhook source verification")? } else { connector .clone() .verify_webhook_source( &request_details, merchant_context.get_merchant_account().get_id(), merchant_connector_account.connector_webhook_details.clone(), merchant_connector_account.connector_account_details.clone(), connector_name.as_str(), ) .await .or_else(|error| match error.current_context() { errors::ConnectorError::WebhookSourceVerificationFailed => { logger::error!(?error, "Source Verification Failed"); Ok(false) } _ => Err(error), }) .switch() .attach_printable("There was an issue in incoming webhook source verification")? }; logger::info!(source_verified=?source_verified); if source_verified { metrics::WEBHOOK_SOURCE_VERIFIED_COUNT.add( 1, router_env::metric_attributes!(( MERCHANT_ID, merchant_context.get_merchant_account().get_id().clone() )), ); } // If source verification is mandatory and source is not verified, fail with webhook authentication error // else continue the flow match ( connector.is_webhook_source_verification_mandatory(), source_verified, ) { (true, false) => Err(errors::ApiErrorResponse::WebhookAuthenticationFailed)?, _ => { event_object = connector .get_webhook_resource_object(&request_details) .switch() .attach_printable("Could not find resource object in incoming webhook body")?; let webhook_details = api::IncomingWebhookDetails { object_reference_id: object_ref_id.clone(), resource_object: serde_json::to_vec(&event_object) .change_context(errors::ParsingError::EncodeError("byte-vec")) .attach_printable("Unable to convert webhook payload to a value") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "There was an issue when encoding the incoming webhook body to bytes", )?, }; match flow_type { api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow( state.clone(), req_state, merchant_context, profile, webhook_details, source_verified, )) .await .attach_printable("Incoming webhook flow for payments failed")?, api::WebhookFlow::Refund => todo!(), api::WebhookFlow::Dispute => todo!(), api::WebhookFlow::BankTransfer => todo!(), api::WebhookFlow::ReturnResponse => WebhookResponseTracker::NoEffect, api::WebhookFlow::Mandate => todo!(), api::WebhookFlow::ExternalAuthentication => todo!(), api::WebhookFlow::FraudCheck => todo!(), api::WebhookFlow::Setup => WebhookResponseTracker::NoEffect, #[cfg(feature = "payouts")] api::WebhookFlow::Payout => todo!(), api::WebhookFlow::Subscription => todo!(), #[cfg(all(feature = "revenue_recovery", feature = "v2"))] api::WebhookFlow::Recovery => { Box::pin(recovery_incoming::recovery_incoming_webhook_flow( state.clone(), merchant_context, profile, source_verified, &connector, merchant_connector_account, &connector_name, &request_details, event_type, req_state, &object_ref_id, )) .await .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("Failed to process recovery incoming webhook")? } } } } } else { metrics::WEBHOOK_INCOMING_FILTERED_COUNT.add( 1, router_env::metric_attributes!(( MERCHANT_ID, merchant_context.get_merchant_account().get_id().clone() )), ); WebhookResponseTracker::NoEffect }; let response = connector .get_webhook_api_response(&request_details, None) .switch() .attach_printable("Could not get incoming webhook api response from connector")?; let serialized_request = event_object .masked_serialize() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not convert webhook effect to string")?; Ok((response, webhook_effect, serialized_request)) } #[instrument(skip_all)] async fn payments_incoming_webhook_flow( state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, webhook_details: api::IncomingWebhookDetails, source_verified: bool, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { let consume_or_trigger_flow = if source_verified { payments::CallConnectorAction::HandleResponse(webhook_details.resource_object) } else { payments::CallConnectorAction::Trigger }; let key_manager_state = &(&state).into(); let payments_response = match webhook_details.object_reference_id { webhooks::ObjectReferenceId::PaymentId(id) => { let get_trackers_response = get_trackers_response_for_payment_get_operation( state.store.as_ref(), &id, profile.get_id(), key_manager_state, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await?; let payment_id = get_trackers_response.payment_data.get_payment_id(); let lock_action = api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::Payments, override_lock_retries: None, }, }; lock_action .clone() .perform_locking_action( &state, merchant_context.get_merchant_account().get_id().to_owned(), ) .await?; let ( payment_data, _req, customer, connector_http_status_code, external_latency, connector_response_data, ) = Box::pin(payments::payments_operation_core::< api::PSync, _, _, _, PaymentStatusData<api::PSync>, >( &state, req_state, merchant_context.clone(), &profile, payments::operations::PaymentGet, api::PaymentsRetrieveRequest { force_sync: true, expand_attempts: false, param: None, return_raw_connector_response: None, merchant_connector_details: None, }, get_trackers_response, consume_or_trigger_flow, HeaderPayload::default(), )) .await?; let response = payment_data.generate_response( &state, connector_http_status_code, external_latency, None, &merchant_context, &profile, Some(connector_response_data), ); lock_action .free_lock_action( &state, merchant_context.get_merchant_account().get_id().to_owned(), ) .await?; match response { Ok(value) => value, Err(err) if matches!( err.current_context(), &errors::ApiErrorResponse::PaymentNotFound ) && state .clone() .conf .webhooks .ignore_error .payment_not_found .unwrap_or(true) => { metrics::WEBHOOK_PAYMENT_NOT_FOUND.add( 1, router_env::metric_attributes!(( "merchant_id", merchant_context.get_merchant_account().get_id().clone() )), ); return Ok(WebhookResponseTracker::NoEffect); } error @ Err(_) => error?, } } _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable( "Did not get payment id as object reference id in webhook payments flow", )?, }; match payments_response { services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => { let payment_id = payments_response.id.clone(); let status = payments_response.status; let event_type: Option<enums::EventType> = payments_response.status.into(); // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook if let Some(outgoing_event_type) = event_type { let primary_object_created_at = payments_response.created; // TODO: trigger an outgoing webhook to merchant Box::pin(create_event_and_trigger_outgoing_webhook( state, profile, merchant_context.get_merchant_key_store(), outgoing_event_type, enums::EventClass::Payments, payment_id.get_string_repr().to_owned(), enums::EventObjectType::PaymentDetails, api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)), primary_object_created_at, )) .await?; }; let response = WebhookResponseTracker::Payment { payment_id, status }; Ok(response) } _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("received non-json response from payments core")?, } } async fn get_trackers_response_for_payment_get_operation<F>( db: &dyn StorageInterface, payment_id: &api::PaymentIdType, profile_id: &common_utils::id_type::ProfileId, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> errors::RouterResult<payments::operations::GetTrackerResponse<PaymentStatusData<F>>> where F: Clone, { let (payment_intent, payment_attempt) = match payment_id { api_models::payments::PaymentIdType::PaymentIntentId(ref id) => { let payment_intent = db .find_payment_intent_by_id( key_manager_state, id, merchant_key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_attempt = db .find_payment_attempt_by_id( key_manager_state, merchant_key_store, &payment_intent .active_attempt_id .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("active_attempt_id not present in payment_attempt")?, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; (payment_intent, payment_attempt) } api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => { let payment_attempt = db .find_payment_attempt_by_profile_id_connector_transaction_id( key_manager_state, merchant_key_store, profile_id, id, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_intent = db .find_payment_intent_by_id( key_manager_state, &payment_attempt.payment_id, merchant_key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; (payment_intent, payment_attempt) } api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => { let global_attempt_id = common_utils::id_type::GlobalAttemptId::try_from( std::borrow::Cow::Owned(id.to_owned()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while getting GlobalAttemptId")?; let payment_attempt = db .find_payment_attempt_by_id( key_manager_state, merchant_key_store, &global_attempt_id, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_intent = db .find_payment_intent_by_id( key_manager_state, &payment_attempt.payment_id, merchant_key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; (payment_intent, payment_attempt) } api_models::payments::PaymentIdType::PreprocessingId(ref _id) => todo!(), }; // We need the address here to send it in the response // In case we need to send an outgoing webhook, we might have to send the billing address and shipping address let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new( payment_intent .shipping_address .clone() .map(|address| address.into_inner()), payment_intent .billing_address .clone() .map(|address| address.into_inner()), payment_attempt .payment_method_billing_address .clone() .map(|address| address.into_inner()), Some(true), ); Ok(payments::operations::GetTrackerResponse { payment_data: PaymentStatusData { flow: PhantomData, payment_intent, payment_attempt, attempts: None, should_sync_with_connector: true, payment_address, merchant_connector_details: None, }, }) } #[inline] async fn verify_webhook_source_verification_call( connector: ConnectorEnum, state: &SessionState, merchant_context: &domain::MerchantContext, merchant_connector_account: domain::MerchantConnectorAccount, connector_name: &str, request_details: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<bool, errors::ConnectorError> { let connector_data = ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, GetToken::Connector, None, ) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) .attach_printable("invalid connector name received in payment attempt")?; let connector_integration: services::BoxedWebhookSourceVerificationConnectorIntegrationInterface< hyperswitch_domain_models::router_flow_types::VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, > = connector_data.connector.get_connector_integration(); let connector_webhook_secrets = connector .get_webhook_source_verification_merchant_secret( merchant_context.get_merchant_account().get_id(), connector_name, merchant_connector_account.connector_webhook_details.clone(), ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let router_data = construct_webhook_router_data( state, connector_name, merchant_connector_account, merchant_context, &connector_webhook_secrets, request_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) .attach_printable("Failed while constructing webhook router data")?; let response = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await?; let verification_result = response .response .map(|response| response.verify_webhook_status); match verification_result { Ok(VerifyWebhookStatus::SourceVerified) => Ok(true), _ => Ok(false), } } fn get_connector_by_connector_name( state: &SessionState, connector_name: &str, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, ) -> CustomResult<(ConnectorEnum, String), errors::ApiErrorResponse> { let authentication_connector = api_models::enums::convert_authentication_connector(connector_name); #[cfg(feature = "frm")] { let frm_connector = api_models::enums::convert_frm_connector(connector_name); if frm_connector.is_some() { let frm_connector_data = api::FraudCheckConnectorData::get_connector_by_name(connector_name)?; return Ok(( frm_connector_data.connector, frm_connector_data.connector_name.to_string(), )); } } let (connector, connector_name) = if authentication_connector.is_some() { let authentication_connector_data = api::AuthenticationConnectorData::get_connector_by_name(connector_name)?; ( authentication_connector_data.connector, authentication_connector_data.connector_name.to_string(), ) } else { let connector_data = ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, GetToken::Connector, merchant_connector_id, ) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "invalid connector name received".to_string(), }) .attach_printable("Failed construction of ConnectorData")?; ( connector_data.connector, connector_data.connector_name.to_string(), ) }; Ok((connector, connector_name)) } /// This function fetches the merchant connector account and connector details async fn fetch_mca_and_connector( state: &SessionState, connector_id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<(domain::MerchantConnectorAccount, ConnectorEnum, String), errors::ApiErrorResponse> { let db = &state.store; let mca = db .find_merchant_connector_account_by_id(&state.into(), connector_id, key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: connector_id.get_string_repr().to_owned(), }) .attach_printable("error while fetching merchant_connector_account from connector_id")?; let (connector, connector_name) = get_connector_by_connector_name( state, &mca.connector_name.to_string(), Some(mca.get_id()), )?; Ok((mca, connector, connector_name)) }
crates/router/src/core/webhooks/incoming_v2.rs
router
full_file
null
null
null
5,878
null
null
null
null
null
null
null
// Function: validate // File: crates/router/src/configs/validations.rs // Module: router pub fn validate(&self) -> Result<(), ApplicationError>
crates/router/src/configs/validations.rs
router
function_signature
null
null
null
35
validate
null
null
null
null
null
null
// Struct: ProphetpayRefundResponse // File: crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ProphetpayRefundResponse
crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs
hyperswitch_connectors
struct_definition
ProphetpayRefundResponse
0
[]
52
null
null
null
null
null
null
null
// File: crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs // Module: hyperswitch_connectors // Public functions: 1 // Public structs: 33 use common_enums::{enums, AttemptStatus, BankNames}; use common_utils::{ errors::ParsingError, pii::{Email, IpAddress}, request::Method, types::{FloatMajorUnit, MinorUnit}, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{BankRedirectData, PayLaterData, PaymentMethodData, WalletData}, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, }, types::{self}, }; use hyperswitch_interfaces::{ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, errors, }; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use url::Url; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ self, AddressDetailsData, CardData as _, PaymentsAuthorizeRequestData, RouterData as _, }, }; #[derive(Debug, Serialize)] pub struct MultisafepayRouterData<T> { amount: MinorUnit, router_data: T, } impl<T> From<(MinorUnit, T)> for MultisafepayRouterData<T> { fn from((amount, item): (MinorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum Type { Direct, Redirect, } #[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum Gateway { Amex, CreditCard, Discover, Maestro, MasterCard, Visa, Klarna, Googlepay, Paypal, Ideal, Giropay, Trustly, Alipay, #[serde(rename = "WECHAT")] WeChatPay, Eps, MbWay, #[serde(rename = "DIRECTBANK")] Sofort, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct Coupons { pub allow: Option<Vec<Secret<String>>>, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct Mistercash { pub mobile_pay_button_position: Option<String>, pub disable_mobile_pay_button: Option<String>, pub qr_only: Option<String>, pub qr_size: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "UPPERCASE")] pub struct Gateways { pub mistercash: Option<Mistercash>, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct Settings { pub coupons: Option<Coupons>, pub gateways: Option<Gateways>, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct PaymentOptions { pub notification_url: Option<String>, pub notification_method: Option<String>, pub redirect_url: String, pub cancel_url: String, pub close_window: Option<bool>, pub settings: Option<Settings>, pub template_id: Option<String>, pub allowed_countries: Option<Vec<String>>, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct Browser { pub javascript_enabled: Option<bool>, pub java_enabled: Option<bool>, pub cookies_enabled: Option<bool>, pub language: Option<String>, pub screen_color_depth: Option<i32>, pub screen_height: Option<i32>, pub screen_width: Option<i32>, pub time_zone: Option<i32>, pub user_agent: Option<String>, pub platform: Option<String>, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct Customer { pub browser: Option<Browser>, pub locale: Option<String>, pub ip_address: Option<Secret<String, IpAddress>>, pub forward_ip: Option<Secret<String, IpAddress>>, pub first_name: Option<Secret<String>>, pub last_name: Option<Secret<String>>, pub gender: Option<Secret<String>>, pub birthday: Option<Secret<String>>, pub address1: Option<Secret<String>>, pub address2: Option<Secret<String>>, pub house_number: Option<Secret<String>>, pub zip_code: Option<Secret<String>>, pub city: Option<String>, pub state: Option<String>, pub country: Option<String>, pub phone: Option<Secret<String>>, pub email: Option<Email>, pub user_agent: Option<String>, pub referrer: Option<String>, pub reference: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct CardInfo { pub card_number: Option<cards::CardNumber>, pub card_holder_name: Option<Secret<String>>, pub card_expiry_date: Option<Secret<i32>>, pub card_cvc: Option<Secret<String>>, pub flexible_3d: Option<bool>, pub moto: Option<bool>, pub term_url: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct GpayInfo { pub payment_token: Option<Secret<String>>, } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct PayLaterInfo { pub email: Option<Email>, } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum GatewayInfo { Card(CardInfo), Wallet(WalletInfo), PayLater(PayLaterInfo), BankRedirect(BankRedirectInfo), } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum WalletInfo { GooglePay(GpayInfo), Alipay(AlipayInfo), WeChatPay(WeChatPayInfo), MbWay(MbWayInfo), } #[derive(Debug, Clone, Serialize, Eq, PartialEq)] pub struct MbWayInfo {} #[derive(Debug, Clone, Serialize, Eq, PartialEq)] pub struct WeChatPayInfo {} #[derive(Debug, Clone, Serialize, Eq, PartialEq)] pub struct AlipayInfo {} #[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum BankRedirectInfo { Ideal(IdealInfo), Trustly(TrustlyInfo), Eps(EpsInfo), Sofort(SofortInfo), } #[derive(Debug, Clone, Serialize, Eq, PartialEq)] pub struct SofortInfo {} #[derive(Debug, Clone, Serialize, Eq, PartialEq)] pub struct EpsInfo {} #[derive(Debug, Clone, Serialize, Eq, PartialEq)] pub struct TrustlyInfo {} #[derive(Debug, Clone, Serialize, Eq, PartialEq)] pub struct IdealInfo { pub issuer_id: MultisafepayBankNames, } #[derive(Debug, Clone, Serialize, Eq, PartialEq)] pub enum MultisafepayBankNames { #[serde(rename = "0031")] AbnAmro, #[serde(rename = "0761")] AsnBank, #[serde(rename = "4371")] Bunq, #[serde(rename = "0721")] Ing, #[serde(rename = "0801")] Knab, #[serde(rename = "9926")] N26, #[serde(rename = "9927")] NationaleNederlanden, #[serde(rename = "0021")] Rabobank, #[serde(rename = "0771")] Regiobank, #[serde(rename = "1099")] Revolut, #[serde(rename = "0751")] SnsBank, #[serde(rename = "0511")] TriodosBank, #[serde(rename = "0161")] VanLanschot, #[serde(rename = "0806")] Yoursafe, #[serde(rename = "1235")] Handelsbanken, } impl TryFrom<&BankNames> for MultisafepayBankNames { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(bank: &BankNames) -> Result<Self, Self::Error> { match bank { BankNames::AbnAmro => Ok(Self::AbnAmro), BankNames::AsnBank => Ok(Self::AsnBank), BankNames::Bunq => Ok(Self::Bunq), BankNames::Ing => Ok(Self::Ing), BankNames::Knab => Ok(Self::Knab), BankNames::N26 => Ok(Self::N26), BankNames::NationaleNederlanden => Ok(Self::NationaleNederlanden), BankNames::Rabobank => Ok(Self::Rabobank), BankNames::Regiobank => Ok(Self::Regiobank), BankNames::Revolut => Ok(Self::Revolut), BankNames::SnsBank => Ok(Self::SnsBank), BankNames::TriodosBank => Ok(Self::TriodosBank), BankNames::VanLanschot => Ok(Self::VanLanschot), BankNames::Yoursafe => Ok(Self::Yoursafe), BankNames::Handelsbanken => Ok(Self::Handelsbanken), BankNames::AmericanExpress | BankNames::AffinBank | BankNames::AgroBank | BankNames::AllianceBank | BankNames::AmBank | BankNames::BankOfAmerica | BankNames::BankOfChina | BankNames::BankIslam | BankNames::BankMuamalat | BankNames::BankRakyat | BankNames::BankSimpananNasional | BankNames::Barclays | BankNames::BlikPSP | BankNames::CapitalOne | BankNames::Chase | BankNames::Citi | BankNames::CimbBank | BankNames::Discover | BankNames::NavyFederalCreditUnion | BankNames::PentagonFederalCreditUnion | BankNames::SynchronyBank | BankNames::WellsFargo | BankNames::HongLeongBank | BankNames::HsbcBank | BankNames::KuwaitFinanceHouse | BankNames::Moneyou | BankNames::ArzteUndApothekerBank | BankNames::AustrianAnadiBankAg | BankNames::BankAustria | BankNames::Bank99Ag | BankNames::BankhausCarlSpangler | BankNames::BankhausSchelhammerUndSchatteraAg | BankNames::BankMillennium | BankNames::BankPEKAOSA | BankNames::BawagPskAg | BankNames::BksBankAg | BankNames::BrullKallmusBankAg | BankNames::BtvVierLanderBank | BankNames::CapitalBankGraweGruppeAg | BankNames::CeskaSporitelna | BankNames::Dolomitenbank | BankNames::EasybankAg | BankNames::EPlatbyVUB | BankNames::ErsteBankUndSparkassen | BankNames::FrieslandBank | BankNames::HypoAlpeadriabankInternationalAg | BankNames::HypoNoeLbFurNiederosterreichUWien | BankNames::HypoOberosterreichSalzburgSteiermark | BankNames::HypoTirolBankAg | BankNames::HypoVorarlbergBankAg | BankNames::HypoBankBurgenlandAktiengesellschaft | BankNames::KomercniBanka | BankNames::MBank | BankNames::MarchfelderBank | BankNames::Maybank | BankNames::OberbankAg | BankNames::OsterreichischeArzteUndApothekerbank | BankNames::OcbcBank | BankNames::PayWithING | BankNames::PlaceZIPKO | BankNames::PlatnoscOnlineKartaPlatnicza | BankNames::PosojilnicaBankEGen | BankNames::PostovaBanka | BankNames::PublicBank | BankNames::RaiffeisenBankengruppeOsterreich | BankNames::RhbBank | BankNames::SchelhammerCapitalBankAg | BankNames::StandardCharteredBank | BankNames::SchoellerbankAg | BankNames::SpardaBankWien | BankNames::SporoPay | BankNames::SantanderPrzelew24 | BankNames::TatraPay | BankNames::Viamo | BankNames::VolksbankGruppe | BankNames::VolkskreditbankAg | BankNames::VrBankBraunau | BankNames::UobBank | BankNames::PayWithAliorBank | BankNames::BankiSpoldzielcze | BankNames::PayWithInteligo | BankNames::BNPParibasPoland | BankNames::BankNowySA | BankNames::CreditAgricole | BankNames::PayWithBOS | BankNames::PayWithCitiHandlowy | BankNames::PayWithPlusBank | BankNames::ToyotaBank | BankNames::VeloBank | BankNames::ETransferPocztowy24 | BankNames::PlusBank | BankNames::EtransferPocztowy24 | BankNames::BankiSpbdzielcze | BankNames::BankNowyBfgSa | BankNames::GetinBank | BankNames::Blik | BankNames::NoblePay | BankNames::IdeaBank | BankNames::EnveloBank | BankNames::NestPrzelew | BankNames::MbankMtransfer | BankNames::Inteligo | BankNames::PbacZIpko | BankNames::BnpParibas | BankNames::BankPekaoSa | BankNames::VolkswagenBank | BankNames::AliorBank | BankNames::Boz | BankNames::BangkokBank | BankNames::KrungsriBank | BankNames::KrungThaiBank | BankNames::TheSiamCommercialBank | BankNames::KasikornBank | BankNames::OpenBankSuccess | BankNames::OpenBankFailure | BankNames::OpenBankCancelled | BankNames::Aib | BankNames::BankOfScotland | BankNames::DanskeBank | BankNames::FirstDirect | BankNames::FirstTrust | BankNames::Halifax | BankNames::Lloyds | BankNames::Monzo | BankNames::NatWest | BankNames::NationwideBank | BankNames::RoyalBankOfScotland | BankNames::Starling | BankNames::TsbBank | BankNames::TescoBank | BankNames::UlsterBank => Err(Into::into(errors::ConnectorError::NotSupported { message: String::from("BankRedirect"), connector: "Multisafepay", })), } } } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct DeliveryObject { first_name: Secret<String>, last_name: Secret<String>, address1: Secret<String>, house_number: Secret<String>, zip_code: Secret<String>, city: String, country: api_models::enums::CountryAlpha2, } #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct DefaultObject { shipping_taxed: bool, rate: f64, } #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct TaxObject { pub default: DefaultObject, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct CheckoutOptions { pub validate_cart: Option<bool>, pub tax_tables: TaxObject, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct Item { pub name: String, pub unit_price: FloatMajorUnit, pub description: Option<String>, pub quantity: i64, } #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct ShoppingCart { pub items: Vec<Item>, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, PartialEq, Serialize)] pub struct MultisafepayPaymentsRequest { #[serde(rename = "type")] pub payment_type: Type, pub gateway: Option<Gateway>, pub order_id: String, pub currency: String, pub amount: MinorUnit, pub description: String, pub payment_options: Option<PaymentOptions>, pub customer: Option<Customer>, pub gateway_info: Option<GatewayInfo>, pub delivery: Option<DeliveryObject>, pub checkout_options: Option<CheckoutOptions>, pub shopping_cart: Option<ShoppingCart>, pub items: Option<String>, pub recurring_model: Option<MandateType>, pub recurring_id: Option<Secret<String>>, pub capture: Option<String>, pub days_active: Option<i32>, pub seconds_active: Option<i32>, pub var1: Option<String>, pub var2: Option<String>, pub var3: Option<String>, } impl TryFrom<utils::CardIssuer> for Gateway { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(issuer: utils::CardIssuer) -> Result<Self, Self::Error> { match issuer { utils::CardIssuer::AmericanExpress => Ok(Self::Amex), utils::CardIssuer::Master => Ok(Self::MasterCard), utils::CardIssuer::Maestro => Ok(Self::Maestro), utils::CardIssuer::Discover => Ok(Self::Discover), utils::CardIssuer::Visa => Ok(Self::Visa), utils::CardIssuer::DinersClub | utils::CardIssuer::JCB | utils::CardIssuer::CarteBlanche | utils::CardIssuer::UnionPay | utils::CardIssuer::CartesBancaires => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Multisafe pay"), ) .into()), } } } impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> for MultisafepayPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let payment_type = match item.router_data.request.payment_method_data { PaymentMethodData::Card(ref _ccard) => Type::Direct, PaymentMethodData::MandatePayment => Type::Direct, PaymentMethodData::Wallet(ref wallet_data) => match wallet_data { WalletData::GooglePay(_) => Type::Direct, WalletData::PaypalRedirect(_) => Type::Redirect, WalletData::AliPayRedirect(_) => Type::Redirect, WalletData::WeChatPayRedirect(_) => Type::Redirect, WalletData::MbWayRedirect(_) => Type::Redirect, WalletData::AliPayQr(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPay(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::BluecodeRedirect {} | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::ApplePay(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::Mifinity(_) | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))?, }, PaymentMethodData::BankRedirect(ref bank_data) => match bank_data { BankRedirectData::Giropay { .. } => Type::Redirect, BankRedirectData::Ideal { .. } => Type::Direct, BankRedirectData::Trustly { .. } => Type::Redirect, BankRedirectData::Eps { .. } => Type::Redirect, BankRedirectData::Sofort { .. } => Type::Redirect, BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum { .. } | BankRedirectData::Blik { .. } | BankRedirectData::Eft { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } | BankRedirectData::OnlineBankingPoland { .. } | BankRedirectData::OnlineBankingSlovakia { .. } | BankRedirectData::OpenBankingUk { .. } | BankRedirectData::Przelewy24 { .. } | BankRedirectData::OnlineBankingFpx { .. } | BankRedirectData::OnlineBankingThailand { .. } | BankRedirectData::LocalBankRedirect {} => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))? } }, PaymentMethodData::PayLater(ref _paylater) => Type::Redirect, _ => Type::Redirect, }; let gateway = match item.router_data.request.payment_method_data { PaymentMethodData::Card(ref ccard) => { Some(Gateway::try_from(ccard.get_card_issuer()?)?) } PaymentMethodData::Wallet(ref wallet_data) => Some(match wallet_data { WalletData::GooglePay(_) => Gateway::Googlepay, WalletData::PaypalRedirect(_) => Gateway::Paypal, WalletData::AliPayRedirect(_) => Gateway::Alipay, WalletData::WeChatPayRedirect(_) => Gateway::WeChatPay, WalletData::MbWayRedirect(_) => Gateway::MbWay, WalletData::AliPayQr(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPay(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::BluecodeRedirect {} | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::ApplePay(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::Mifinity(_) | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))?, }), PaymentMethodData::BankRedirect(ref bank_data) => Some(match bank_data { BankRedirectData::Giropay { .. } => Gateway::Giropay, BankRedirectData::Ideal { .. } => Gateway::Ideal, BankRedirectData::Trustly { .. } => Gateway::Trustly, BankRedirectData::Eps { .. } => Gateway::Eps, BankRedirectData::Sofort { .. } => Gateway::Sofort, BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum { .. } | BankRedirectData::Blik { .. } | BankRedirectData::Eft { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } | BankRedirectData::OnlineBankingPoland { .. } | BankRedirectData::OnlineBankingSlovakia { .. } | BankRedirectData::OpenBankingUk { .. } | BankRedirectData::Przelewy24 { .. } | BankRedirectData::OnlineBankingFpx { .. } | BankRedirectData::OnlineBankingThailand { .. } | BankRedirectData::LocalBankRedirect {} => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))? } }), PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect {}) => Some(Gateway::Klarna), PaymentMethodData::MandatePayment => None, PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | 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("multisafepay"), ))? } }; let description = item.router_data.get_description()?; let payment_options = PaymentOptions { notification_url: None, redirect_url: item.router_data.request.get_router_return_url()?, cancel_url: item.router_data.request.get_router_return_url()?, close_window: None, notification_method: None, settings: None, template_id: None, allowed_countries: None, }; let customer = Customer { browser: None, locale: None, ip_address: None, forward_ip: None, first_name: None, last_name: None, gender: None, birthday: None, address1: None, address2: None, house_number: None, zip_code: None, city: None, state: None, country: None, phone: None, email: item.router_data.request.email.clone(), user_agent: None, referrer: None, reference: Some(item.router_data.connector_request_reference_id.clone()), }; let billing_address = item .router_data .get_billing()? .address .as_ref() .ok_or_else(utils::missing_field_err("billing.address"))?; let first_name = billing_address.get_first_name()?; let delivery = DeliveryObject { first_name: first_name.clone(), last_name: billing_address .get_last_name() .unwrap_or(first_name) .clone(), address1: billing_address.get_line1()?.to_owned(), house_number: billing_address.get_line2()?.to_owned(), zip_code: billing_address.get_zip()?.to_owned(), city: billing_address.get_city()?.to_owned(), country: billing_address.get_country()?.to_owned(), }; let gateway_info = match item.router_data.request.payment_method_data { PaymentMethodData::Card(ref ccard) => Some(GatewayInfo::Card(CardInfo { card_number: Some(ccard.card_number.clone()), card_expiry_date: Some(Secret::new( (format!( "{}{}", ccard.get_card_expiry_year_2_digit()?.expose(), ccard.card_exp_month.clone().expose() )) .parse::<i32>() .unwrap_or_default(), )), card_cvc: Some(ccard.card_cvc.clone()), card_holder_name: None, flexible_3d: None, moto: None, term_url: None, })), PaymentMethodData::Wallet(ref wallet_data) => match wallet_data { WalletData::GooglePay(ref google_pay) => { Some(GatewayInfo::Wallet(WalletInfo::GooglePay({ GpayInfo { payment_token: Some(Secret::new( google_pay .tokenization_data .get_encrypted_google_pay_token() .change_context(errors::ConnectorError::MissingRequiredField { field_name: "google_pay_token", })? .clone(), )), } }))) } WalletData::AliPayRedirect(_) => { Some(GatewayInfo::Wallet(WalletInfo::Alipay(AlipayInfo {}))) } WalletData::PaypalRedirect(_) => None, WalletData::WeChatPayRedirect(_) => { Some(GatewayInfo::Wallet(WalletInfo::WeChatPay(WeChatPayInfo {}))) } WalletData::MbWayRedirect(_) => { Some(GatewayInfo::Wallet(WalletInfo::MbWay(MbWayInfo {}))) } WalletData::AliPayQr(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPay(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::BluecodeRedirect {} | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::ApplePay(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::Mifinity(_) | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))?, }, PaymentMethodData::PayLater(ref paylater) => { Some(GatewayInfo::PayLater(PayLaterInfo { email: Some(match paylater { PayLaterData::KlarnaRedirect {} => item.router_data.get_billing_email()?, PayLaterData::KlarnaSdk { token: _ } | PayLaterData::AffirmRedirect {} | PayLaterData::FlexitiRedirect {} | PayLaterData::AfterpayClearpayRedirect {} | PayLaterData::PayBrightRedirect {} | PayLaterData::WalleyRedirect {} | PayLaterData::AlmaRedirect {} | PayLaterData::AtomeRedirect {} | PayLaterData::BreadpayRedirect {} => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message( "multisafepay", ), ))? } }), })) } PaymentMethodData::BankRedirect(ref bank_redirect_data) => match bank_redirect_data { BankRedirectData::Ideal { bank_name, .. } => Some(GatewayInfo::BankRedirect( BankRedirectInfo::Ideal(IdealInfo { issuer_id: MultisafepayBankNames::try_from(&bank_name.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "ideal.bank_name", }, )?)?, }), )), BankRedirectData::Trustly { .. } => Some(GatewayInfo::BankRedirect( BankRedirectInfo::Trustly(TrustlyInfo {}), )), BankRedirectData::Eps { .. } => { Some(GatewayInfo::BankRedirect(BankRedirectInfo::Eps(EpsInfo {}))) } BankRedirectData::Sofort { .. } => Some(GatewayInfo::BankRedirect( BankRedirectInfo::Sofort(SofortInfo {}), )), BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum { .. } | BankRedirectData::Blik { .. } | BankRedirectData::Eft { .. } | BankRedirectData::Giropay { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } | BankRedirectData::OnlineBankingPoland { .. } | BankRedirectData::OnlineBankingSlovakia { .. } | BankRedirectData::OpenBankingUk { .. } | BankRedirectData::Przelewy24 { .. } | BankRedirectData::OnlineBankingFpx { .. } | BankRedirectData::OnlineBankingThailand { .. } | BankRedirectData::LocalBankRedirect {} => None, }, PaymentMethodData::MandatePayment => None, PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))? } }; Ok(Self { payment_type, gateway, order_id: item.router_data.connector_request_reference_id.to_string(), currency: item.router_data.request.currency.to_string(), amount: item.amount, description, payment_options: Some(payment_options), customer: Some(customer), delivery: Some(delivery), gateway_info, checkout_options: None, shopping_cart: None, capture: None, items: None, recurring_model: if item.router_data.request.is_mandate_payment() { Some(MandateType::Unscheduled) } else { None }, recurring_id: item .router_data .request .mandate_id .clone() .and_then(|mandate_ids| match mandate_ids.mandate_reference_id { Some(api_models::payments::MandateReferenceId::ConnectorMandateId( connector_mandate_ids, )) => connector_mandate_ids .get_connector_mandate_id() .map(Secret::new), _ => None, }),
crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs#chunk0
hyperswitch_connectors
chunk
null
null
null
8,189
null
null
null
null
null
null
null
// Struct: PayoutData // File: crates/router/src/core/payouts.rs // Module: router // Implementations: 0 pub struct PayoutData
crates/router/src/core/payouts.rs
router
struct_definition
PayoutData
0
[]
36
null
null
null
null
null
null
null
// Implementation: impl Parse for for TryGetEnumMeta // File: crates/router_derive/src/macros/try_get_enum.rs // Module: router_derive // Methods: 1 total (0 public) impl Parse for for TryGetEnumMeta
crates/router_derive/src/macros/try_get_enum.rs
router_derive
impl_block
null
null
null
53
null
TryGetEnumMeta
Parse for
1
0
null
null
// Implementation: impl api::PaymentToken for for Mpgs // File: crates/hyperswitch_connectors/src/connectors/mpgs.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentToken for for Mpgs
crates/hyperswitch_connectors/src/connectors/mpgs.rs
hyperswitch_connectors
impl_block
null
null
null
59
null
Mpgs
api::PaymentToken for
0
0
null
null
// Struct: PaymentRequestBankRedirect // File: crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PaymentRequestBankRedirect
crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
hyperswitch_connectors
struct_definition
PaymentRequestBankRedirect
0
[]
50
null
null
null
null
null
null
null
// Implementation: impl DatabaseStore for for Store // File: crates/storage_impl/src/database/store.rs // Module: storage_impl // Methods: 5 total (0 public) impl DatabaseStore for for Store
crates/storage_impl/src/database/store.rs
storage_impl
impl_block
null
null
null
43
null
Store
DatabaseStore for
5
0
null
null
// Implementation: impl api::RefundExecute for for Klarna // File: crates/hyperswitch_connectors/src/connectors/klarna.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::RefundExecute for for Klarna
crates/hyperswitch_connectors/src/connectors/klarna.rs
hyperswitch_connectors
impl_block
null
null
null
60
null
Klarna
api::RefundExecute for
0
0
null
null
// Struct: PeachpaymentsPaymentsRequest // File: crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PeachpaymentsPaymentsRequest
crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs
hyperswitch_connectors
struct_definition
PeachpaymentsPaymentsRequest
0
[]
51
null
null
null
null
null
null
null
// Struct: ClientSecretTypeNew // File: crates/diesel_models/src/ephemeral_key.rs // Module: diesel_models // Implementations: 0 pub struct ClientSecretTypeNew
crates/diesel_models/src/ephemeral_key.rs
diesel_models
struct_definition
ClientSecretTypeNew
0
[]
42
null
null
null
null
null
null
null
// Struct: MerchantConnectorAccountFeatureMetadata // File: crates/api_models/src/admin.rs // Module: api_models // Implementations: 0 // Documentation: Feature metadata for merchant connector account pub struct MerchantConnectorAccountFeatureMetadata
crates/api_models/src/admin.rs
api_models
struct_definition
MerchantConnectorAccountFeatureMetadata
0
[]
49
null
null
null
null
null
null
null
// Struct: ErrorResponse // File: crates/hyperswitch_domain_models/src/router_data.rs // Module: hyperswitch_domain_models // Implementations: 2 // Traits: Default pub struct ErrorResponse
crates/hyperswitch_domain_models/src/router_data.rs
hyperswitch_domain_models
struct_definition
ErrorResponse
2
[ "Default" ]
43
null
null
null
null
null
null
null
// Function: validate_payout_list_request // File: crates/router/src/core/payouts/validator.rs // Module: router pub fn validate_payout_list_request( req: &payouts::PayoutListConstraints, ) -> CustomResult<(), errors::ApiErrorResponse>
crates/router/src/core/payouts/validator.rs
router
function_signature
null
null
null
59
validate_payout_list_request
null
null
null
null
null
null
// Implementation: impl Parse for for Derives // File: crates/router_derive/src/macros/operation.rs // Module: router_derive // Methods: 1 total (0 public) impl Parse for for Derives
crates/router_derive/src/macros/operation.rs
router_derive
impl_block
null
null
null
47
null
Derives
Parse for
1
0
null
null
// File: crates/diesel_models/src/payment_method.rs // Module: diesel_models // Public functions: 10 // Public structs: 15 use std::collections::HashMap; use common_enums::MerchantStorageScheme; use common_utils::{ encryption::Encryption, errors::{CustomResult, ParsingError}, pii, }; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use error_stack::ResultExt; #[cfg(feature = "v1")] use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; #[cfg(feature = "v1")] use crate::{enums as storage_enums, schema::payment_methods}; #[cfg(feature = "v2")] use crate::{enums as storage_enums, schema_v2::payment_methods}; #[cfg(feature = "v1")] #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, )] #[diesel(table_name = payment_methods, primary_key(payment_method_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentMethod { pub customer_id: common_utils::id_type::CustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub payment_method_id: String, #[diesel(deserialize_as = super::OptionalDieselArray<storage_enums::Currency>)] pub accepted_currency: Option<Vec<storage_enums::Currency>>, pub scheme: Option<String>, pub token: Option<String>, pub cardholder_name: Option<Secret<String>>, pub issuer_name: Option<String>, pub issuer_country: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub payer_country: Option<Vec<String>>, pub is_stored: Option<bool>, pub swift_code: Option<String>, pub direct_debit_token: Option<String>, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub payment_method: Option<storage_enums::PaymentMethod>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub payment_method_issuer: Option<String>, pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>, pub metadata: Option<pii::SecretSerdeValue>, pub payment_method_data: Option<Encryption>, pub locker_id: Option<String>, pub last_used_at: PrimitiveDateTime, pub connector_mandate_details: Option<serde_json::Value>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, pub network_transaction_id: Option<String>, pub client_secret: Option<String>, pub payment_method_billing_address: Option<Encryption>, pub updated_by: Option<String>, pub version: common_enums::ApiVersion, pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, pub network_token_payment_method_data: Option<Encryption>, pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>, pub vault_type: Option<storage_enums::VaultType>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Identifiable, Queryable, Selectable, Serialize, Deserialize)] #[diesel(table_name = payment_methods, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct PaymentMethod { pub customer_id: common_utils::id_type::GlobalCustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub payment_method_data: Option<Encryption>, pub locker_id: Option<String>, pub last_used_at: PrimitiveDateTime, pub connector_mandate_details: Option<CommonMandateReference>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, pub network_transaction_id: Option<String>, pub client_secret: Option<String>, pub payment_method_billing_address: Option<Encryption>, pub updated_by: Option<String>, pub version: common_enums::ApiVersion, pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, pub network_token_payment_method_data: Option<Encryption>, pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>, pub vault_type: Option<storage_enums::VaultType>, pub locker_fingerprint_id: Option<String>, pub payment_method_type_v2: Option<storage_enums::PaymentMethod>, pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, pub id: common_utils::id_type::GlobalPaymentMethodId, pub external_vault_token_data: Option<Encryption>, } impl PaymentMethod { #[cfg(feature = "v1")] pub fn get_id(&self) -> &String { &self.payment_method_id } #[cfg(feature = "v2")] pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId { &self.id } } #[cfg(feature = "v1")] #[derive( Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] #[diesel(table_name = payment_methods)] pub struct PaymentMethodNew { pub customer_id: common_utils::id_type::CustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub payment_method_id: String, pub payment_method: Option<storage_enums::PaymentMethod>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub payment_method_issuer: Option<String>, pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>, pub accepted_currency: Option<Vec<storage_enums::Currency>>, pub scheme: Option<String>, pub token: Option<String>, pub cardholder_name: Option<Secret<String>>, pub issuer_name: Option<String>, pub issuer_country: Option<String>, pub payer_country: Option<Vec<String>>, pub is_stored: Option<bool>, pub swift_code: Option<String>, pub direct_debit_token: Option<String>, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub metadata: Option<pii::SecretSerdeValue>, pub payment_method_data: Option<Encryption>, pub locker_id: Option<String>, pub last_used_at: PrimitiveDateTime, pub connector_mandate_details: Option<serde_json::Value>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, pub network_transaction_id: Option<String>, pub client_secret: Option<String>, pub payment_method_billing_address: Option<Encryption>, pub updated_by: Option<String>, pub version: common_enums::ApiVersion, pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, pub network_token_payment_method_data: Option<Encryption>, pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>, pub vault_type: Option<storage_enums::VaultType>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_methods)] pub struct PaymentMethodNew { pub customer_id: common_utils::id_type::GlobalCustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub payment_method_data: Option<Encryption>, pub locker_id: Option<String>, pub last_used_at: PrimitiveDateTime, pub connector_mandate_details: Option<CommonMandateReference>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, pub network_transaction_id: Option<String>, pub client_secret: Option<String>, pub payment_method_billing_address: Option<Encryption>, pub updated_by: Option<String>, pub version: common_enums::ApiVersion, pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, pub network_token_payment_method_data: Option<Encryption>, pub external_vault_token_data: Option<Encryption>, pub locker_fingerprint_id: Option<String>, pub payment_method_type_v2: Option<storage_enums::PaymentMethod>, pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, pub id: common_utils::id_type::GlobalPaymentMethodId, pub vault_type: Option<storage_enums::VaultType>, } impl PaymentMethodNew { pub fn update_storage_scheme(&mut self, storage_scheme: MerchantStorageScheme) { self.updated_by = Some(storage_scheme.to_string()); } #[cfg(feature = "v1")] pub fn get_id(&self) -> &String { &self.payment_method_id } #[cfg(feature = "v2")] pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId { &self.id } } #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct TokenizeCoreWorkflow { pub lookup_key: String, pub pm: storage_enums::PaymentMethod, } #[cfg(feature = "v1")] #[derive(Debug, Serialize, Deserialize)] pub enum PaymentMethodUpdate { MetadataUpdateAndLastUsed { metadata: Option<serde_json::Value>, last_used_at: PrimitiveDateTime, }, UpdatePaymentMethodDataAndLastUsed { payment_method_data: Option<Encryption>, scheme: Option<String>, last_used_at: PrimitiveDateTime, }, PaymentMethodDataUpdate { payment_method_data: Option<Encryption>, }, LastUsedUpdate { last_used_at: PrimitiveDateTime, }, NetworkTransactionIdAndStatusUpdate { network_transaction_id: Option<String>, status: Option<storage_enums::PaymentMethodStatus>, }, StatusUpdate { status: Option<storage_enums::PaymentMethodStatus>, }, AdditionalDataUpdate { payment_method_data: Option<Encryption>, status: Option<storage_enums::PaymentMethodStatus>, locker_id: Option<String>, payment_method: Option<storage_enums::PaymentMethod>, payment_method_type: Option<storage_enums::PaymentMethodType>, payment_method_issuer: Option<String>, network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: Option<Encryption>, }, ConnectorMandateDetailsUpdate { connector_mandate_details: Option<serde_json::Value>, }, NetworkTokenDataUpdate { network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: Option<Encryption>, }, ConnectorNetworkTransactionIdAndMandateDetailsUpdate { connector_mandate_details: Option<pii::SecretSerdeValue>, network_transaction_id: Option<Secret<String>>, }, ConnectorNetworkTransactionIdStatusAndMandateDetailsUpdate { connector_mandate_details: Option<pii::SecretSerdeValue>, network_transaction_id: Option<String>, status: Option<storage_enums::PaymentMethodStatus>, }, } #[cfg(feature = "v2")] #[derive(Debug, Serialize, Deserialize)] pub enum PaymentMethodUpdate { UpdatePaymentMethodDataAndLastUsed { payment_method_data: Option<Encryption>, scheme: Option<String>, last_used_at: PrimitiveDateTime, }, PaymentMethodDataUpdate { payment_method_data: Option<Encryption>, }, LastUsedUpdate { last_used_at: PrimitiveDateTime, }, NetworkTransactionIdAndStatusUpdate { network_transaction_id: Option<String>, status: Option<storage_enums::PaymentMethodStatus>, }, StatusUpdate { status: Option<storage_enums::PaymentMethodStatus>, }, GenericUpdate { payment_method_data: Option<Encryption>, status: Option<storage_enums::PaymentMethodStatus>, locker_id: Option<String>, payment_method_type_v2: Option<storage_enums::PaymentMethod>, payment_method_subtype: Option<storage_enums::PaymentMethodType>, network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: Option<Encryption>, locker_fingerprint_id: Option<String>, connector_mandate_details: Option<CommonMandateReference>, external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>, }, ConnectorMandateDetailsUpdate { connector_mandate_details: Option<CommonMandateReference>, }, } impl PaymentMethodUpdate { pub fn convert_to_payment_method_update( self, storage_scheme: MerchantStorageScheme, ) -> PaymentMethodUpdateInternal { let mut update_internal: PaymentMethodUpdateInternal = self.into(); update_internal.updated_by = Some(storage_scheme.to_string()); update_internal } } #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_methods)] pub struct PaymentMethodUpdateInternal { payment_method_data: Option<Encryption>, last_used_at: Option<PrimitiveDateTime>, network_transaction_id: Option<String>, status: Option<storage_enums::PaymentMethodStatus>, locker_id: Option<String>, payment_method_type_v2: Option<storage_enums::PaymentMethod>, connector_mandate_details: Option<CommonMandateReference>, updated_by: Option<String>, payment_method_subtype: Option<storage_enums::PaymentMethodType>, last_modified: PrimitiveDateTime, network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: Option<Encryption>, locker_fingerprint_id: Option<String>, external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v2")] impl PaymentMethodUpdateInternal { pub fn apply_changeset(self, source: PaymentMethod) -> PaymentMethod { let Self { payment_method_data, last_used_at, network_transaction_id, status, locker_id, payment_method_type_v2, connector_mandate_details, updated_by, payment_method_subtype, last_modified, network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, locker_fingerprint_id, external_vault_source, } = self; PaymentMethod { customer_id: source.customer_id, merchant_id: source.merchant_id, created_at: source.created_at, last_modified, payment_method_data: payment_method_data.or(source.payment_method_data), locker_id: locker_id.or(source.locker_id), last_used_at: last_used_at.unwrap_or(source.last_used_at), connector_mandate_details: connector_mandate_details .or(source.connector_mandate_details), customer_acceptance: source.customer_acceptance, status: status.unwrap_or(source.status), network_transaction_id: network_transaction_id.or(source.network_transaction_id), client_secret: source.client_secret, payment_method_billing_address: source.payment_method_billing_address, updated_by: updated_by.or(source.updated_by), locker_fingerprint_id: locker_fingerprint_id.or(source.locker_fingerprint_id), payment_method_type_v2: payment_method_type_v2.or(source.payment_method_type_v2), payment_method_subtype: payment_method_subtype.or(source.payment_method_subtype), id: source.id, version: source.version, network_token_requestor_reference_id: network_token_requestor_reference_id .or(source.network_token_requestor_reference_id), network_token_locker_id: network_token_locker_id.or(source.network_token_locker_id), network_token_payment_method_data: network_token_payment_method_data .or(source.network_token_payment_method_data), external_vault_source: external_vault_source.or(source.external_vault_source), external_vault_token_data: source.external_vault_token_data, vault_type: source.vault_type, } } } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_methods)] pub struct PaymentMethodUpdateInternal { metadata: Option<serde_json::Value>, payment_method_data: Option<Encryption>, last_used_at: Option<PrimitiveDateTime>, network_transaction_id: Option<String>, status: Option<storage_enums::PaymentMethodStatus>, locker_id: Option<String>, network_token_requestor_reference_id: Option<String>, payment_method: Option<storage_enums::PaymentMethod>, connector_mandate_details: Option<serde_json::Value>, updated_by: Option<String>, payment_method_type: Option<storage_enums::PaymentMethodType>, payment_method_issuer: Option<String>, last_modified: PrimitiveDateTime, network_token_locker_id: Option<String>, network_token_payment_method_data: Option<Encryption>, scheme: Option<String>, } #[cfg(feature = "v1")] impl PaymentMethodUpdateInternal { pub fn apply_changeset(self, source: PaymentMethod) -> PaymentMethod { let Self { metadata, payment_method_data, last_used_at, network_transaction_id, status, locker_id, network_token_requestor_reference_id, payment_method, connector_mandate_details, updated_by, payment_method_type, payment_method_issuer, last_modified, network_token_locker_id, network_token_payment_method_data, scheme, } = self; PaymentMethod { customer_id: source.customer_id, merchant_id: source.merchant_id, payment_method_id: source.payment_method_id, accepted_currency: source.accepted_currency, scheme: scheme.or(source.scheme), token: source.token, cardholder_name: source.cardholder_name, issuer_name: source.issuer_name, issuer_country: source.issuer_country, payer_country: source.payer_country, is_stored: source.is_stored, swift_code: source.swift_code, direct_debit_token: source.direct_debit_token, created_at: source.created_at, last_modified, payment_method: payment_method.or(source.payment_method), payment_method_type: payment_method_type.or(source.payment_method_type), payment_method_issuer: payment_method_issuer.or(source.payment_method_issuer), payment_method_issuer_code: source.payment_method_issuer_code, metadata: metadata.map_or(source.metadata, |v| Some(v.into())), payment_method_data: payment_method_data.or(source.payment_method_data), locker_id: locker_id.or(source.locker_id), last_used_at: last_used_at.unwrap_or(source.last_used_at), connector_mandate_details: connector_mandate_details .or(source.connector_mandate_details), customer_acceptance: source.customer_acceptance, status: status.unwrap_or(source.status), network_transaction_id: network_transaction_id.or(source.network_transaction_id), client_secret: source.client_secret, payment_method_billing_address: source.payment_method_billing_address, updated_by: updated_by.or(source.updated_by), version: source.version, network_token_requestor_reference_id: network_token_requestor_reference_id .or(source.network_token_requestor_reference_id), network_token_locker_id: network_token_locker_id.or(source.network_token_locker_id), network_token_payment_method_data: network_token_payment_method_data .or(source.network_token_payment_method_data), external_vault_source: source.external_vault_source, vault_type: source.vault_type, } } } #[cfg(feature = "v1")] impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { fn from(payment_method_update: PaymentMethodUpdate) -> Self { match payment_method_update { PaymentMethodUpdate::MetadataUpdateAndLastUsed { metadata, last_used_at, } => Self { metadata, payment_method_data: None, last_used_at: Some(last_used_at), network_transaction_id: None, status: None, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data, } => Self { metadata: None, payment_method_data, last_used_at: None, network_transaction_id: None, status: None, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self { metadata: None, payment_method_data: None, last_used_at: Some(last_used_at), network_transaction_id: None, status: None, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed { payment_method_data, scheme, last_used_at, } => Self { metadata: None, payment_method_data, last_used_at: Some(last_used_at), network_transaction_id: None, status: None, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme, }, PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate { network_transaction_id, status, } => Self { metadata: None, payment_method_data: None, last_used_at: None, network_transaction_id, status, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::StatusUpdate { status } => Self { metadata: None, payment_method_data: None, last_used_at: None, network_transaction_id: None, status, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::AdditionalDataUpdate { payment_method_data, status, locker_id, network_token_requestor_reference_id, payment_method, payment_method_type, payment_method_issuer, network_token_locker_id, network_token_payment_method_data, } => Self { metadata: None, payment_method_data, last_used_at: None, network_transaction_id: None, status, locker_id, network_token_requestor_reference_id, payment_method, connector_mandate_details: None, updated_by: None, payment_method_issuer, payment_method_type, last_modified: common_utils::date_time::now(), network_token_locker_id, network_token_payment_method_data, scheme: None, }, PaymentMethodUpdate::ConnectorMandateDetailsUpdate { connector_mandate_details, } => Self { metadata: None, payment_method_data: None, last_used_at: None, status: None, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details, network_transaction_id: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::NetworkTokenDataUpdate { network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, } => Self { metadata: None, payment_method_data: None, last_used_at: None, status: None, locker_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_transaction_id: None, network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, scheme: None, }, PaymentMethodUpdate::ConnectorNetworkTransactionIdAndMandateDetailsUpdate { connector_mandate_details, network_transaction_id, } => Self { connector_mandate_details: connector_mandate_details .map(|mandate_details| mandate_details.expose()), network_transaction_id: network_transaction_id.map(|txn_id| txn_id.expose()), last_modified: common_utils::date_time::now(), status: None, metadata: None, payment_method_data: None, last_used_at: None, locker_id: None, payment_method: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, network_token_requestor_reference_id: None, network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::ConnectorNetworkTransactionIdStatusAndMandateDetailsUpdate { connector_mandate_details, network_transaction_id, status, } => Self { metadata: None, payment_method_data: None, last_used_at: None, status, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: connector_mandate_details .map(|mandate_details| mandate_details.expose()), network_transaction_id, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, } } } #[cfg(feature = "v2")] impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { fn from(payment_method_update: PaymentMethodUpdate) -> Self { match payment_method_update { PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data, } => Self { payment_method_data, last_used_at: None, network_transaction_id: None, status: None, locker_id: None, payment_method_type_v2: None, connector_mandate_details: None, updated_by: None, payment_method_subtype: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, locker_fingerprint_id: None, external_vault_source: None, }, PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self { payment_method_data: None, last_used_at: Some(last_used_at), network_transaction_id: None, status: None, locker_id: None, payment_method_type_v2: None, connector_mandate_details: None, updated_by: None, payment_method_subtype: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, locker_fingerprint_id: None, external_vault_source: None, }, PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed { payment_method_data, last_used_at, .. } => Self { payment_method_data, last_used_at: Some(last_used_at), network_transaction_id: None, status: None, locker_id: None, payment_method_type_v2: None, connector_mandate_details: None, updated_by: None, payment_method_subtype: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, locker_fingerprint_id: None, external_vault_source: None, }, PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate { network_transaction_id, status, } => Self { payment_method_data: None, last_used_at: None, network_transaction_id, status, locker_id: None, payment_method_type_v2: None, connector_mandate_details: None, updated_by: None, payment_method_subtype: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, locker_fingerprint_id: None, external_vault_source: None, }, PaymentMethodUpdate::StatusUpdate { status } => Self { payment_method_data: None, last_used_at: None, network_transaction_id: None, status, locker_id: None, payment_method_type_v2: None, connector_mandate_details: None, updated_by: None, payment_method_subtype: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, locker_fingerprint_id: None, external_vault_source: None, }, PaymentMethodUpdate::GenericUpdate { payment_method_data, status, locker_id, payment_method_type_v2, payment_method_subtype, network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, locker_fingerprint_id, connector_mandate_details, external_vault_source, } => Self { payment_method_data, last_used_at: None, network_transaction_id: None, status, locker_id, payment_method_type_v2, connector_mandate_details, updated_by: None, payment_method_subtype, last_modified: common_utils::date_time::now(), network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, locker_fingerprint_id, external_vault_source, }, PaymentMethodUpdate::ConnectorMandateDetailsUpdate { connector_mandate_details, } => Self { payment_method_data: None, last_used_at: None, status: None, locker_id: None, payment_method_type_v2: None, connector_mandate_details, network_transaction_id: None, updated_by: None, payment_method_subtype: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, locker_fingerprint_id: None, external_vault_source: None, }, } } } #[cfg(feature = "v1")] impl From<&PaymentMethodNew> for PaymentMethod { fn from(payment_method_new: &PaymentMethodNew) -> Self { Self { customer_id: payment_method_new.customer_id.clone(), merchant_id: payment_method_new.merchant_id.clone(), payment_method_id: payment_method_new.payment_method_id.clone(), locker_id: payment_method_new.locker_id.clone(), network_token_requestor_reference_id: payment_method_new .network_token_requestor_reference_id .clone(), accepted_currency: payment_method_new.accepted_currency.clone(), scheme: payment_method_new.scheme.clone(), token: payment_method_new.token.clone(), cardholder_name: payment_method_new.cardholder_name.clone(), issuer_name: payment_method_new.issuer_name.clone(), issuer_country: payment_method_new.issuer_country.clone(), payer_country: payment_method_new.payer_country.clone(), is_stored: payment_method_new.is_stored, swift_code: payment_method_new.swift_code.clone(), direct_debit_token: payment_method_new.direct_debit_token.clone(), created_at: payment_method_new.created_at, last_modified: payment_method_new.last_modified, payment_method: payment_method_new.payment_method, payment_method_type: payment_method_new.payment_method_type, payment_method_issuer: payment_method_new.payment_method_issuer.clone(), payment_method_issuer_code: payment_method_new.payment_method_issuer_code, metadata: payment_method_new.metadata.clone(), payment_method_data: payment_method_new.payment_method_data.clone(), last_used_at: payment_method_new.last_used_at, connector_mandate_details: payment_method_new.connector_mandate_details.clone(), customer_acceptance: payment_method_new.customer_acceptance.clone(), status: payment_method_new.status, network_transaction_id: payment_method_new.network_transaction_id.clone(), client_secret: payment_method_new.client_secret.clone(), updated_by: payment_method_new.updated_by.clone(), payment_method_billing_address: payment_method_new .payment_method_billing_address .clone(), version: payment_method_new.version, network_token_locker_id: payment_method_new.network_token_locker_id.clone(), network_token_payment_method_data: payment_method_new .network_token_payment_method_data .clone(), external_vault_source: payment_method_new.external_vault_source.clone(), vault_type: payment_method_new.vault_type, } } } #[cfg(feature = "v2")] impl From<&PaymentMethodNew> for PaymentMethod { fn from(payment_method_new: &PaymentMethodNew) -> Self { Self { customer_id: payment_method_new.customer_id.clone(), merchant_id: payment_method_new.merchant_id.clone(), locker_id: payment_method_new.locker_id.clone(), created_at: payment_method_new.created_at, last_modified: payment_method_new.last_modified, payment_method_data: payment_method_new.payment_method_data.clone(), last_used_at: payment_method_new.last_used_at, connector_mandate_details: payment_method_new.connector_mandate_details.clone(), customer_acceptance: payment_method_new.customer_acceptance.clone(), status: payment_method_new.status, network_transaction_id: payment_method_new.network_transaction_id.clone(), client_secret: payment_method_new.client_secret.clone(), updated_by: payment_method_new.updated_by.clone(), payment_method_billing_address: payment_method_new .payment_method_billing_address .clone(), locker_fingerprint_id: payment_method_new.locker_fingerprint_id.clone(), payment_method_type_v2: payment_method_new.payment_method_type_v2, payment_method_subtype: payment_method_new.payment_method_subtype, id: payment_method_new.id.clone(), version: payment_method_new.version, network_token_requestor_reference_id: payment_method_new .network_token_requestor_reference_id .clone(), network_token_locker_id: payment_method_new.network_token_locker_id.clone(), network_token_payment_method_data: payment_method_new .network_token_payment_method_data .clone(), external_vault_source: None, external_vault_token_data: payment_method_new.external_vault_token_data.clone(), vault_type: payment_method_new.vault_type, } } } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentsMandateReferenceRecord { pub connector_mandate_id: String, pub payment_method_type: Option<common_enums::PaymentMethodType>, pub original_payment_authorized_amount: Option<i64>, pub original_payment_authorized_currency: Option<common_enums::Currency>, pub mandate_metadata: Option<pii::SecretSerdeValue>, pub connector_mandate_status: Option<common_enums::ConnectorMandateStatus>, pub connector_mandate_request_reference_id: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ConnectorTokenReferenceRecord { pub connector_token: String, pub payment_method_subtype: Option<common_enums::PaymentMethodType>, pub original_payment_authorized_amount: Option<common_utils::types::MinorUnit>, pub original_payment_authorized_currency: Option<common_enums::Currency>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_token_status: common_enums::ConnectorTokenStatus,
crates/diesel_models/src/payment_method.rs#chunk0
diesel_models
chunk
null
null
null
8,182
null
null
null
null
null
null
null
// File: crates/router_env/src/logger/formatter.rs // Module: router_env // Public functions: 3 // Public structs: 1 //! Formatting [layer](https://docs.rs/tracing-subscriber/0.3.15/tracing_subscriber/layer/trait.Layer.html) for Router. use std::{ collections::{HashMap, HashSet}, fmt, io::Write, sync::LazyLock, }; use config::ConfigError; use serde::ser::{SerializeMap, Serializer}; use serde_json::{ser::Formatter, Value}; // use time::format_description::well_known::Rfc3339; use time::format_description::well_known::Iso8601; use tracing::{Event, Metadata, Subscriber}; use tracing_subscriber::{ fmt::MakeWriter, layer::Context, registry::{LookupSpan, SpanRef}, Layer, }; use crate::Storage; // TODO: Documentation coverage for this crate // Implicit keys const MESSAGE: &str = "message"; const HOSTNAME: &str = "hostname"; const PID: &str = "pid"; const ENV: &str = "env"; const VERSION: &str = "version"; const BUILD: &str = "build"; const LEVEL: &str = "level"; const TARGET: &str = "target"; const SERVICE: &str = "service"; const LINE: &str = "line"; const FILE: &str = "file"; const FN: &str = "fn"; const FULL_NAME: &str = "full_name"; const TIME: &str = "time"; // Extra implicit keys. Keys that are provided during runtime but should be treated as // implicit in the logs const FLOW: &str = "flow"; const MERCHANT_AUTH: &str = "merchant_authentication"; const MERCHANT_ID: &str = "merchant_id"; const REQUEST_METHOD: &str = "request_method"; const REQUEST_URL_PATH: &str = "request_url_path"; const REQUEST_ID: &str = "request_id"; const WORKFLOW_ID: &str = "workflow_id"; const GLOBAL_ID: &str = "global_id"; const SESSION_ID: &str = "session_id"; /// Set of predefined implicit keys. pub static IMPLICIT_KEYS: LazyLock<rustc_hash::FxHashSet<&str>> = LazyLock::new(|| { let mut set = rustc_hash::FxHashSet::default(); set.insert(HOSTNAME); set.insert(PID); set.insert(ENV); set.insert(VERSION); set.insert(BUILD); set.insert(LEVEL); set.insert(TARGET); set.insert(SERVICE); set.insert(LINE); set.insert(FILE); set.insert(FN); set.insert(FULL_NAME); set.insert(TIME); set }); /// Extra implicit keys. Keys that are not purely implicit but need to be logged alongside /// other implicit keys in the log json. pub static EXTRA_IMPLICIT_KEYS: LazyLock<rustc_hash::FxHashSet<&str>> = LazyLock::new(|| { let mut set = rustc_hash::FxHashSet::default(); set.insert(MESSAGE); set.insert(FLOW); set.insert(MERCHANT_AUTH); set.insert(MERCHANT_ID); set.insert(REQUEST_METHOD); set.insert(REQUEST_URL_PATH); set.insert(REQUEST_ID); set.insert(GLOBAL_ID); set.insert(SESSION_ID); set.insert(WORKFLOW_ID); set }); /// Describe type of record: entering a span, exiting a span, an event. #[derive(Clone, Debug)] pub enum RecordType { /// Entering a span. EnterSpan, /// Exiting a span. ExitSpan, /// Event. Event, } impl fmt::Display for RecordType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let repr = match self { Self::EnterSpan => "START", Self::ExitSpan => "END", Self::Event => "EVENT", }; write!(f, "{repr}") } } /// Format log records. /// `FormattingLayer` relies on the `tracing_bunyan_formatter::JsonStorageLayer` which is storage of entries. #[derive(Debug)] pub struct FormattingLayer<W, F> where W: for<'a> MakeWriter<'a> + 'static, F: Formatter + Clone, { dst_writer: W, pid: u32, hostname: String, env: String, service: String, #[cfg(feature = "vergen")] version: String, #[cfg(feature = "vergen")] build: String, default_fields: HashMap<String, Value>, formatter: F, } impl<W, F> FormattingLayer<W, F> where W: for<'a> MakeWriter<'a> + 'static, F: Formatter + Clone, { /// Constructor of `FormattingLayer`. /// /// A `name` will be attached to all records during formatting. /// A `dst_writer` to forward all records. /// /// ## Example /// ```rust /// let formatting_layer = router_env::FormattingLayer::new("my_service", std::io::stdout, serde_json::ser::CompactFormatter); /// ``` pub fn new( service: &str, dst_writer: W, formatter: F, ) -> error_stack::Result<Self, ConfigError> { Self::new_with_implicit_entries(service, dst_writer, HashMap::new(), formatter) } /// Construct of `FormattingLayer with implicit default entries. pub fn new_with_implicit_entries( service: &str, dst_writer: W, default_fields: HashMap<String, Value>, formatter: F, ) -> error_stack::Result<Self, ConfigError> { let pid = std::process::id(); let hostname = gethostname::gethostname().to_string_lossy().into_owned(); let service = service.to_string(); #[cfg(feature = "vergen")] let version = crate::version!().to_string(); #[cfg(feature = "vergen")] let build = crate::build!().to_string(); let env = crate::env::which().to_string(); for key in default_fields.keys() { if IMPLICIT_KEYS.contains(key.as_str()) { return Err(ConfigError::Message(format!( "A reserved key `{key}` was included in `default_fields` in the log formatting layer" )) .into()); } } Ok(Self { dst_writer, pid, hostname, env, service, #[cfg(feature = "vergen")] version, #[cfg(feature = "vergen")] build, default_fields, formatter, }) } /// Serialize common for both span and event entries. fn common_serialize<S>( &self, map_serializer: &mut impl SerializeMap<Error = serde_json::Error>, metadata: &Metadata<'_>, span: Option<&SpanRef<'_, S>>, storage: &Storage<'_>, name: &str, ) -> Result<(), std::io::Error> where S: Subscriber + for<'a> LookupSpan<'a>, { let is_extra = |s: &str| !IMPLICIT_KEYS.contains(s); let is_extra_implicit = |s: &str| is_extra(s) && EXTRA_IMPLICIT_KEYS.contains(s); map_serializer.serialize_entry(HOSTNAME, &self.hostname)?; map_serializer.serialize_entry(PID, &self.pid)?; map_serializer.serialize_entry(ENV, &self.env)?; #[cfg(feature = "vergen")] map_serializer.serialize_entry(VERSION, &self.version)?; #[cfg(feature = "vergen")] map_serializer.serialize_entry(BUILD, &self.build)?; map_serializer.serialize_entry(LEVEL, &format_args!("{}", metadata.level()))?; map_serializer.serialize_entry(TARGET, metadata.target())?; map_serializer.serialize_entry(SERVICE, &self.service)?; map_serializer.serialize_entry(LINE, &metadata.line())?; map_serializer.serialize_entry(FILE, &metadata.file())?; map_serializer.serialize_entry(FN, name)?; map_serializer .serialize_entry(FULL_NAME, &format_args!("{}::{}", metadata.target(), name))?; if let Ok(time) = &time::OffsetDateTime::now_utc().format(&Iso8601::DEFAULT) { map_serializer.serialize_entry(TIME, time)?; } // Write down implicit default entries. for (key, value) in self.default_fields.iter() { map_serializer.serialize_entry(key, value)?; } #[cfg(feature = "log_custom_entries_to_extra")] let mut extra = serde_json::Map::default(); let mut explicit_entries_set: HashSet<&str> = HashSet::default(); // Write down explicit event's entries. for (key, value) in storage.values.iter() { if is_extra_implicit(key) { #[cfg(feature = "log_extra_implicit_fields")] map_serializer.serialize_entry(key, value)?; explicit_entries_set.insert(key); } else if is_extra(key) { #[cfg(feature = "log_custom_entries_to_extra")] extra.insert(key.to_string(), value.clone()); #[cfg(not(feature = "log_custom_entries_to_extra"))] map_serializer.serialize_entry(key, value)?; explicit_entries_set.insert(key); } else { tracing::warn!( ?key, ?value, "Attempting to log a reserved entry. It won't be added to the logs" ); } } // Write down entries from the span, if it exists. if let Some(span) = &span { let extensions = span.extensions(); if let Some(visitor) = extensions.get::<Storage<'_>>() { for (key, value) in &visitor.values { if is_extra_implicit(key) && !explicit_entries_set.contains(key) { #[cfg(feature = "log_extra_implicit_fields")] map_serializer.serialize_entry(key, value)?; } else if is_extra(key) && !explicit_entries_set.contains(key) { #[cfg(feature = "log_custom_entries_to_extra")] extra.insert(key.to_string(), value.clone()); #[cfg(not(feature = "log_custom_entries_to_extra"))] map_serializer.serialize_entry(key, value)?; } else { tracing::warn!( ?key, ?value, "Attempting to log a reserved entry. It won't be added to the logs" ); } } } } #[cfg(feature = "log_custom_entries_to_extra")] map_serializer.serialize_entry("extra", &extra)?; Ok(()) } /// Flush memory buffer into an output stream trailing it with next line. /// /// Should be done by single `write_all` call to avoid fragmentation of log because of mutlithreading. fn flush(&self, mut buffer: Vec<u8>) -> Result<(), std::io::Error> { buffer.write_all(b"\n")?; self.dst_writer.make_writer().write_all(&buffer) } /// Serialize entries of span. fn span_serialize<S>( &self, span: &SpanRef<'_, S>, ty: RecordType, ) -> Result<Vec<u8>, std::io::Error> where S: Subscriber + for<'a> LookupSpan<'a>, { let mut buffer = Vec::new(); let mut serializer = serde_json::Serializer::with_formatter(&mut buffer, self.formatter.clone()); let mut map_serializer = serializer.serialize_map(None)?; let message = Self::span_message(span, ty); let mut storage = Storage::default(); storage.record_value("message", message.into()); self.common_serialize( &mut map_serializer, span.metadata(), Some(span), &storage, span.name(), )?; map_serializer.end()?; Ok(buffer) } /// Serialize event into a buffer of bytes using parent span. pub fn event_serialize<S>( &self, span: Option<&SpanRef<'_, S>>, event: &Event<'_>, ) -> std::io::Result<Vec<u8>> where S: Subscriber + for<'a> LookupSpan<'a>, { let mut buffer = Vec::new(); let mut serializer = serde_json::Serializer::with_formatter(&mut buffer, self.formatter.clone()); let mut map_serializer = serializer.serialize_map(None)?; let mut storage = Storage::default(); event.record(&mut storage); let name = span.map_or("?", SpanRef::name); Self::event_message(span, event, &mut storage); self.common_serialize(&mut map_serializer, event.metadata(), span, &storage, name)?; map_serializer.end()?; Ok(buffer) } /// Format message of a span. /// /// Example: "[FN_WITHOUT_COLON - START]" fn span_message<S>(span: &SpanRef<'_, S>, ty: RecordType) -> String where S: Subscriber + for<'a> LookupSpan<'a>, { format!("[{} - {}]", span.metadata().name().to_uppercase(), ty) } /// Format message of an event. /// /// Examples: "[FN_WITHOUT_COLON - EVENT] Message" fn event_message<S>(span: Option<&SpanRef<'_, S>>, event: &Event<'_>, storage: &mut Storage<'_>) where S: Subscriber + for<'a> LookupSpan<'a>, { // Get value of kept "message" or "target" if does not exist. let message = storage .values .entry("message") .or_insert_with(|| event.metadata().target().into()); // Prepend the span name to the message if span exists. if let (Some(span), Value::String(a)) = (span, message) { *a = format!("{} {}", Self::span_message(span, RecordType::Event), a,); } } } #[allow(clippy::expect_used)] impl<S, W, F> Layer<S> for FormattingLayer<W, F> where S: Subscriber + for<'a> LookupSpan<'a>, W: for<'a> MakeWriter<'a> + 'static, F: Formatter + Clone + 'static, { fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) { // Event could have no span. let span = ctx.lookup_current(); let result: std::io::Result<Vec<u8>> = self.event_serialize(span.as_ref(), event); if let Ok(formatted) = result { let _ = self.flush(formatted); } } #[cfg(feature = "log_active_span_json")] fn on_enter(&self, id: &tracing::Id, ctx: Context<'_, S>) { let span = ctx.span(id).expect("No span"); if let Ok(serialized) = self.span_serialize(&span, RecordType::EnterSpan) { let _ = self.flush(serialized); } } #[cfg(not(feature = "log_active_span_json"))] fn on_close(&self, id: tracing::Id, ctx: Context<'_, S>) { let span = ctx.span(&id).expect("No span"); if span.parent().is_none() { if let Ok(serialized) = self.span_serialize(&span, RecordType::ExitSpan) { let _ = self.flush(serialized); } } } #[cfg(feature = "log_active_span_json")] fn on_close(&self, id: tracing::Id, ctx: Context<'_, S>) { let span = ctx.span(&id).expect("No span"); if let Ok(serialized) = self.span_serialize(&span, RecordType::ExitSpan) { let _ = self.flush(serialized); } } }
crates/router_env/src/logger/formatter.rs
router_env
full_file
null
null
null
3,401
null
null
null
null
null
null
null
// Implementation: impl ConnectorCommon for for Affirm // File: crates/hyperswitch_connectors/src/connectors/affirm.rs // Module: hyperswitch_connectors // Methods: 6 total (0 public) impl ConnectorCommon for for Affirm
crates/hyperswitch_connectors/src/connectors/affirm.rs
hyperswitch_connectors
impl_block
null
null
null
54
null
Affirm
ConnectorCommon for
6
0
null
null
// Struct: MandateRevokedResponse // File: crates/api_models/src/mandates.rs // Module: api_models // Implementations: 0 pub struct MandateRevokedResponse
crates/api_models/src/mandates.rs
api_models
struct_definition
MandateRevokedResponse
0
[]
41
null
null
null
null
null
null
null
// Struct: PaymentMethodAuth // File: crates/payment_methods/src/configs/settings.rs // Module: payment_methods // Implementations: 1 // Traits: SecretsHandler pub struct PaymentMethodAuth
crates/payment_methods/src/configs/settings.rs
payment_methods
struct_definition
PaymentMethodAuth
1
[ "SecretsHandler" ]
43
null
null
null
null
null
null
null
// Struct: GlobepayPaymentsRequest // File: crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct GlobepayPaymentsRequest
crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
hyperswitch_connectors
struct_definition
GlobepayPaymentsRequest
0
[]
53
null
null
null
null
null
null
null
// Struct: ApplicationInformation // File: crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ApplicationInformation
crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
hyperswitch_connectors
struct_definition
ApplicationInformation
0
[]
47
null
null
null
null
null
null
null
// Struct: BamboraapacMeta // File: crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct BamboraapacMeta
crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs
hyperswitch_connectors
struct_definition
BamboraapacMeta
0
[]
56
null
null
null
null
null
null
null
// Struct: JpmorganPSyncResponse // File: crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct JpmorganPSyncResponse
crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs
hyperswitch_connectors
struct_definition
JpmorganPSyncResponse
0
[]
54
null
null
null
null
null
null
null
// Function: generate_newman_command_for_users // File: crates/test_utils/src/newman_runner.rs // Module: test_utils pub fn generate_newman_command_for_users() -> Result<ReturnArgs>
crates/test_utils/src/newman_runner.rs
test_utils
function_signature
null
null
null
43
generate_newman_command_for_users
null
null
null
null
null
null
// File: crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs // Module: hyperswitch_connectors // Public functions: 3 // Public structs: 55 use common_enums::enums; use common_utils::{ errors::ParsingError, pii::{Email, IpAddress}, request::Method, types::{MinorUnit, StringMajorUnit}, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{ BankRedirectData, BankTransferData, PayLaterData, PaymentMethodData, WalletData, }, router_data::{AccessToken, ConnectorAuthType, RouterData}, router_flow_types::{ refunds::{Execute, RSync}, PSync, }, router_request_types::{PaymentsSyncData, ResponseId}, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types, }; use hyperswitch_interfaces::errors; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use url::Url; use uuid::Uuid; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ self, BrowserInformationData, CardData as _, ForeignTryFrom, PaymentsAuthorizeRequestData, PhoneDetailsData, RouterData as _, }, }; pub struct AirwallexAuthType { pub x_api_key: Secret<String>, pub x_client_id: Secret<String>, } impl TryFrom<&ConnectorAuthType> for AirwallexAuthType { 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 { x_api_key: api_key.clone(), x_client_id: key1.clone(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? } } } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct ReferrerData { #[serde(rename = "type")] r_type: String, version: String, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct AirwallexIntentRequest { // Unique ID to be sent for each transaction/operation request to the connector request_id: String, amount: StringMajorUnit, currency: enums::Currency, //ID created in merchant's order system that corresponds to this PaymentIntent. merchant_order_id: String, // This data is required to whitelist Hyperswitch at Airwallex. referrer_data: ReferrerData, order: Option<AirwallexOrderData>, } impl TryFrom<&AirwallexRouterData<&types::PaymentsPreProcessingRouterData>> for AirwallexIntentRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &AirwallexRouterData<&types::PaymentsPreProcessingRouterData>, ) -> Result<Self, Self::Error> { let referrer_data = ReferrerData { r_type: "hyperswitch".to_string(), version: "1.0.0".to_string(), }; let amount = item.amount.clone(); let currency = item.router_data.request.currency.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "currency", }, )?; let order = match item.router_data.request.payment_method_data { Some(PaymentMethodData::PayLater(_)) => Some( item.router_data .request .order_details .as_ref() .map(|order_data| AirwallexOrderData { products: order_data .iter() .map(|product| AirwallexProductData { name: product.product_name.clone(), quantity: product.quantity, unit_price: product.amount, }) .collect(), shipping: Some(AirwallexShippingData { first_name: item.router_data.get_optional_shipping_first_name(), last_name: item.router_data.get_optional_shipping_last_name(), phone_number: item.router_data.get_optional_shipping_phone_number(), address: AirwallexPLShippingAddress { country_code: item.router_data.get_optional_shipping_country(), city: item.router_data.get_optional_shipping_city(), street: item.router_data.get_optional_shipping_line1(), postcode: item.router_data.get_optional_shipping_zip(), }, }), }) .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "order_details", })?, ), _ => None, }; Ok(Self { request_id: Uuid::new_v4().to_string(), amount, currency, merchant_order_id: item.router_data.connector_request_reference_id.clone(), referrer_data, order, }) } } #[derive(Debug, Serialize)] pub struct AirwallexRouterData<T> { pub amount: StringMajorUnit, pub router_data: T, } impl<T> TryFrom<(StringMajorUnit, T)> for AirwallexRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from((amount, router_data): (StringMajorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data, }) } } #[derive(Debug, Serialize)] pub struct AirwallexPaymentsRequest { // Unique ID to be sent for each transaction/operation request to the connector request_id: String, payment_method: AirwallexPaymentMethod, payment_method_options: Option<AirwallexPaymentOptions>, return_url: Option<String>, device_data: DeviceData, } #[derive(Debug, Serialize, Eq, PartialEq, Default)] pub struct AirwallexOrderData { products: Vec<AirwallexProductData>, shipping: Option<AirwallexShippingData>, } #[derive(Debug, Serialize, Eq, PartialEq)] pub struct AirwallexProductData { name: String, quantity: u16, unit_price: MinorUnit, } #[derive(Debug, Serialize, Eq, PartialEq)] pub struct AirwallexShippingData { first_name: Option<Secret<String>>, last_name: Option<Secret<String>>, phone_number: Option<Secret<String>>, address: AirwallexPLShippingAddress, } #[derive(Debug, Serialize, Eq, PartialEq)] pub struct AirwallexPLShippingAddress { country_code: Option<enums::CountryAlpha2>, city: Option<String>, street: Option<Secret<String>>, postcode: Option<Secret<String>>, } #[derive(Debug, Serialize)] pub struct DeviceData { accept_header: String, browser: Browser, ip_address: Secret<String, IpAddress>, language: String, mobile: Option<Mobile>, screen_color_depth: u8, screen_height: u32, screen_width: u32, timezone: String, } #[derive(Debug, Serialize)] pub struct Browser { java_enabled: bool, javascript_enabled: bool, user_agent: String, } #[derive(Debug, Serialize)] pub struct Mobile { device_model: Option<String>, os_type: Option<String>, os_version: Option<String>, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum AirwallexPaymentMethod { Card(AirwallexCard), Wallets(AirwallexWalletData), PayLater(AirwallexPayLaterData), BankRedirect(AirwallexBankRedirectData), BankTransfer(AirwallexBankTransferData), } #[derive(Debug, Serialize)] pub struct AirwallexCard { card: AirwallexCardDetails, #[serde(rename = "type")] payment_method_type: AirwallexPaymentType, } #[derive(Debug, Serialize)] pub struct AirwallexCardDetails { expiry_month: Secret<String>, expiry_year: Secret<String>, number: cards::CardNumber, cvc: Secret<String>, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum AirwallexWalletData { GooglePay(GooglePayData), Paypal(PaypalData), Skrill(SkrillData), } #[derive(Debug, Serialize)] pub struct GooglePayData { googlepay: GooglePayDetails, #[serde(rename = "type")] payment_method_type: AirwallexPaymentType, } #[derive(Debug, Serialize)] pub struct PaypalData { paypal: PaypalDetails, #[serde(rename = "type")] payment_method_type: AirwallexPaymentType, } #[derive(Debug, Serialize)] pub struct SkrillData { skrill: SkrillDetails, #[serde(rename = "type")] payment_method_type: AirwallexPaymentType, } #[derive(Debug, Serialize)] pub struct GooglePayDetails { encrypted_payment_token: Secret<String>, payment_data_type: GpayPaymentDataType, } #[derive(Debug, Serialize)] pub struct PaypalDetails { shopper_name: Secret<String>, country_code: enums::CountryAlpha2, } #[derive(Debug, Serialize)] pub struct SkrillDetails { shopper_name: Secret<String>, shopper_email: Email, country_code: enums::CountryAlpha2, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum AirwallexPayLaterData { Klarna(Box<KlarnaData>), Atome(AtomeData), } #[derive(Debug, Serialize)] pub struct KlarnaData { klarna: KlarnaDetails, #[serde(rename = "type")] payment_method_type: AirwallexPaymentType, } #[derive(Debug, Serialize)] pub struct KlarnaDetails { country_code: enums::CountryAlpha2, billing: Option<Billing>, } #[derive(Debug, Serialize)] pub struct Billing { date_of_birth: Option<Secret<String>>, email: Option<Email>, first_name: Option<Secret<String>>, last_name: Option<Secret<String>>, phone_number: Option<Secret<String>>, address: Option<AddressAirwallex>, } #[derive(Debug, Serialize)] pub struct AddressAirwallex { country_code: Option<enums::CountryAlpha2>, city: Option<String>, street: Option<Secret<String>>, postcode: Option<Secret<String>>, } #[derive(Debug, Serialize)] pub struct AtomeData { atome: AtomeDetails, #[serde(rename = "type")] payment_method_type: AirwallexPaymentType, } #[derive(Debug, Serialize)] pub struct AtomeDetails { shopper_phone: Secret<String>, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum AirwallexBankTransferData { IndonesianBankTransfer(IndonesianBankTransferData), } #[derive(Debug, Serialize)] pub struct IndonesianBankTransferData { bank_transfer: IndonesianBankTransferDetails, #[serde(rename = "type")] payment_method_type: AirwallexPaymentType, } #[derive(Debug, Serialize)] pub struct IndonesianBankTransferDetails { shopper_name: Secret<String>, shopper_email: Email, bank_name: common_enums::BankNames, country_code: enums::CountryAlpha2, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum AirwallexBankRedirectData { Trustly(TrustlyData), Blik(BlikData), Ideal(IdealData), } #[derive(Debug, Serialize)] pub struct TrustlyData { trustly: TrustlyDetails, #[serde(rename = "type")] payment_method_type: AirwallexPaymentType, } #[derive(Debug, Serialize)] pub struct TrustlyDetails { shopper_name: Secret<String>, country_code: enums::CountryAlpha2, } #[derive(Debug, Serialize)] pub struct BlikData { blik: BlikDetails, #[serde(rename = "type")] payment_method_type: AirwallexPaymentType, } #[derive(Debug, Serialize)] pub struct BlikDetails { shopper_name: Secret<String>, } #[derive(Debug, Serialize)] pub struct IdealData { ideal: IdealDetails, #[serde(rename = "type")] payment_method_type: AirwallexPaymentType, } #[derive(Debug, Serialize)] pub struct IdealDetails { bank_name: Option<common_enums::BankNames>, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub enum AirwallexPaymentType { Card, Googlepay, Paypal, Klarna, Atome, Trustly, Blik, Ideal, Skrill, BankTransfer, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub enum GpayPaymentDataType { EncryptedPaymentToken, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub enum AirwallexPaymentOptions { Card(AirwallexCardPaymentOptions), Klarna(AirwallexPayLaterPaymentOptions), Atome(AirwallexPayLaterPaymentOptions), } #[derive(Debug, Serialize)] pub struct AirwallexCardPaymentOptions { auto_capture: bool, } #[derive(Debug, Serialize)] pub struct AirwallexPayLaterPaymentOptions { auto_capture: bool, } impl TryFrom<&AirwallexRouterData<&types::PaymentsAuthorizeRouterData>> for AirwallexPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &AirwallexRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let mut payment_method_options = None; let request = &item.router_data.request; let payment_method = match request.payment_method_data.clone() { PaymentMethodData::Card(ccard) => { payment_method_options = Some(AirwallexPaymentOptions::Card(AirwallexCardPaymentOptions { auto_capture: matches!( request.capture_method, Some(enums::CaptureMethod::Automatic) | Some(enums::CaptureMethod::SequentialAutomatic) | None ), })); Ok(AirwallexPaymentMethod::Card(AirwallexCard { card: AirwallexCardDetails { number: ccard.card_number.clone(), expiry_month: ccard.card_exp_month.clone(), expiry_year: ccard.get_expiry_year_4_digit(), cvc: ccard.card_cvc, }, payment_method_type: AirwallexPaymentType::Card, })) } PaymentMethodData::Wallet(ref wallet_data) => get_wallet_details(wallet_data, item), PaymentMethodData::PayLater(ref paylater_data) => { let paylater_options = AirwallexPayLaterPaymentOptions { auto_capture: item.router_data.request.is_auto_capture()?, }; payment_method_options = match paylater_data { PayLaterData::KlarnaRedirect { .. } => { Some(AirwallexPaymentOptions::Klarna(paylater_options)) } PayLaterData::AtomeRedirect { .. } => { Some(AirwallexPaymentOptions::Atome(paylater_options)) } _ => None, }; get_paylater_details(paylater_data, item) } PaymentMethodData::BankTransfer(ref banktransfer_data) => { get_banktransfer_details(banktransfer_data, item) } PaymentMethodData::BankRedirect(ref bankredirect_data) => { get_bankredirect_details(bankredirect_data, item) } PaymentMethodData::BankDebit(_) | PaymentMethodData::CardRedirect(_) | 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("airwallex"), )) } }?; let device_data = get_device_data(item.router_data)?; let return_url = match &request.payment_method_data { PaymentMethodData::Wallet(wallet_data) => match wallet_data { WalletData::PaypalRedirect(_paypal_details) => { item.router_data.request.router_return_url.clone() } WalletData::Skrill(_) => item.router_data.request.router_return_url.clone(), _ => request.complete_authorize_url.clone(), }, PaymentMethodData::BankRedirect(_bankredirect_data) => { item.router_data.request.router_return_url.clone() } PaymentMethodData::PayLater(_paylater_data) => { item.router_data.request.router_return_url.clone() } _ => request.complete_authorize_url.clone(), }; Ok(Self { request_id: Uuid::new_v4().to_string(), payment_method, payment_method_options, return_url, device_data, }) } } fn get_device_data( item: &types::PaymentsAuthorizeRouterData, ) -> Result<DeviceData, error_stack::Report<errors::ConnectorError>> { let info = item.request.get_browser_info()?; let browser = Browser { java_enabled: info.get_java_enabled()?, javascript_enabled: info.get_java_script_enabled()?, user_agent: info.get_user_agent()?, }; let mobile = { let device_model = info.get_device_model().ok(); let os_type = info.get_os_type().ok(); let os_version = info.get_os_version().ok(); if device_model.is_some() || os_type.is_some() || os_version.is_some() { Some(Mobile { device_model, os_type, os_version, }) } else { None } }; Ok(DeviceData { accept_header: info.get_accept_header()?, browser, ip_address: info.get_ip_address()?, mobile, screen_color_depth: info.get_color_depth()?, screen_height: info.get_screen_height()?, screen_width: info.get_screen_width()?, timezone: info.get_time_zone()?.to_string(), language: info.get_language()?, }) } fn get_banktransfer_details( banktransfer_data: &BankTransferData, item: &AirwallexRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<AirwallexPaymentMethod, errors::ConnectorError> { let _bank_transfer_details = match banktransfer_data { BankTransferData::IndonesianBankTransfer { bank_name } => { AirwallexPaymentMethod::BankTransfer(AirwallexBankTransferData::IndonesianBankTransfer( IndonesianBankTransferData { bank_transfer: IndonesianBankTransferDetails { shopper_name: item.router_data.get_billing_full_name().map_err(|_| { errors::ConnectorError::MissingRequiredField { field_name: "shopper_name", } })?, shopper_email: item.router_data.get_billing_email().map_err(|_| { errors::ConnectorError::MissingRequiredField { field_name: "shopper_email", } })?, bank_name: bank_name.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "bank_name", }, )?, country_code: item.router_data.get_billing_country().map_err(|_| { errors::ConnectorError::MissingRequiredField { field_name: "country_code", } })?, }, payment_method_type: AirwallexPaymentType::BankTransfer, }, )) } _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("airwallex"), ))?, }; let not_implemented = Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("airwallex"), ))?; Ok(not_implemented) } fn get_paylater_details( paylater_data: &PayLaterData, item: &AirwallexRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<AirwallexPaymentMethod, errors::ConnectorError> { let paylater_details = match paylater_data { PayLaterData::KlarnaRedirect {} => { AirwallexPaymentMethod::PayLater(AirwallexPayLaterData::Klarna(Box::new(KlarnaData { klarna: KlarnaDetails { country_code: item.router_data.get_billing_country().map_err(|_| { errors::ConnectorError::MissingRequiredField { field_name: "country_code", } })?, billing: Some(Billing { date_of_birth: None, first_name: item.router_data.get_optional_billing_first_name(), last_name: item.router_data.get_optional_billing_last_name(), email: item.router_data.get_optional_billing_email(), phone_number: item.router_data.get_optional_billing_phone_number(), address: Some(AddressAirwallex { country_code: item.router_data.get_optional_billing_country(), city: item.router_data.get_optional_billing_city(), street: item.router_data.get_optional_billing_line1(), postcode: item.router_data.get_optional_billing_zip(), }), }), }, payment_method_type: AirwallexPaymentType::Klarna, }))) } PayLaterData::AtomeRedirect {} => { AirwallexPaymentMethod::PayLater(AirwallexPayLaterData::Atome(AtomeData { atome: AtomeDetails { shopper_phone: item .router_data .get_billing_phone() .map_err(|_| errors::ConnectorError::MissingRequiredField { field_name: "shopper_phone", })? .get_number_with_country_code() .map_err(|_| errors::ConnectorError::MissingRequiredField { field_name: "country_code", })?, }, payment_method_type: AirwallexPaymentType::Atome, })) } _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("airwallex"), ))?, }; Ok(paylater_details) } fn get_bankredirect_details( bankredirect_data: &BankRedirectData, item: &AirwallexRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<AirwallexPaymentMethod, errors::ConnectorError> { let bank_redirect_details = match bankredirect_data { BankRedirectData::Trustly { .. } => { AirwallexPaymentMethod::BankRedirect(AirwallexBankRedirectData::Trustly(TrustlyData { trustly: TrustlyDetails { shopper_name: item.router_data.get_billing_full_name().map_err(|_| { errors::ConnectorError::MissingRequiredField { field_name: "shopper_name", } })?, country_code: item.router_data.get_billing_country().map_err(|_| { errors::ConnectorError::MissingRequiredField { field_name: "country_code", } })?, }, payment_method_type: AirwallexPaymentType::Trustly, })) } BankRedirectData::Blik { .. } => { AirwallexPaymentMethod::BankRedirect(AirwallexBankRedirectData::Blik(BlikData { blik: BlikDetails { shopper_name: item.router_data.get_billing_full_name().map_err(|_| { errors::ConnectorError::MissingRequiredField { field_name: "shopper_name", } })?, }, payment_method_type: AirwallexPaymentType::Blik, })) } BankRedirectData::Ideal { .. } => { AirwallexPaymentMethod::BankRedirect(AirwallexBankRedirectData::Ideal(IdealData { ideal: IdealDetails { bank_name: None }, payment_method_type: AirwallexPaymentType::Ideal, })) } _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("airwallex"), ))?, }; Ok(bank_redirect_details) } fn get_wallet_details( wallet_data: &WalletData, item: &AirwallexRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<AirwallexPaymentMethod, errors::ConnectorError> { let wallet_details: AirwallexPaymentMethod = match wallet_data { WalletData::GooglePay(gpay_details) => { let token = gpay_details .tokenization_data .get_encrypted_google_pay_token() .attach_printable("Failed to get gpay wallet token") .map_err(|_| errors::ConnectorError::MissingRequiredField { field_name: "gpay wallet_token", })?; AirwallexPaymentMethod::Wallets(AirwallexWalletData::GooglePay(GooglePayData { googlepay: GooglePayDetails { encrypted_payment_token: Secret::new(token.clone()), payment_data_type: GpayPaymentDataType::EncryptedPaymentToken, }, payment_method_type: AirwallexPaymentType::Googlepay, })) } WalletData::PaypalRedirect(_paypal_details) => { AirwallexPaymentMethod::Wallets(AirwallexWalletData::Paypal(PaypalData { paypal: PaypalDetails { shopper_name: item .router_data .request .customer_name .as_ref() .cloned() .or_else(|| item.router_data.get_billing_full_name().ok()) .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "shopper_name", })?, country_code: item.router_data.get_billing_country().map_err(|_| { errors::ConnectorError::MissingRequiredField { field_name: "country_code", } })?, }, payment_method_type: AirwallexPaymentType::Paypal, })) } WalletData::Skrill(_skrill_details) => { AirwallexPaymentMethod::Wallets(AirwallexWalletData::Skrill(SkrillData { skrill: SkrillDetails { shopper_name: item .router_data .request .customer_name .as_ref() .cloned() .or_else(|| item.router_data.get_billing_full_name().ok()) .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "shopper_name", })?, shopper_email: item.router_data.get_billing_email().map_err(|_| { errors::ConnectorError::MissingRequiredField { field_name: "shopper_email", } })?, country_code: item.router_data.get_billing_country().map_err(|_| { errors::ConnectorError::MissingRequiredField { field_name: "country_code", } })?, }, payment_method_type: AirwallexPaymentType::Skrill, })) } WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::AmazonPay(_) | WalletData::ApplePay(_) | WalletData::BluecodeRedirect {} | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MbWayRedirect(_) | WalletData::MobilePayRedirect(_) | 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("airwallex"), ))?, }; Ok(wallet_details) } #[derive(Deserialize, Debug, Serialize)] pub struct AirwallexAuthUpdateResponse { #[serde(with = "common_utils::custom_serde::iso8601")] expires_at: PrimitiveDateTime, token: Secret<String>, } impl<F, T> TryFrom<ResponseRouterData<F, AirwallexAuthUpdateResponse, T, AccessToken>> for RouterData<F, T, AccessToken> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, AirwallexAuthUpdateResponse, T, AccessToken>, ) -> Result<Self, Self::Error> { let expires = (item.response.expires_at - common_utils::date_time::now()).whole_seconds(); Ok(Self { response: Ok(AccessToken { token: item.response.token, expires, }), ..item.data }) } } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct AirwallexCompleteRequest { request_id: String, three_ds: AirwallexThreeDsData, #[serde(rename = "type")] three_ds_type: AirwallexThreeDsType, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct AirwallexThreeDsData { acs_response: Option<Secret<String>>, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub enum AirwallexThreeDsType { #[default] #[serde(rename = "3ds_continue")] ThreeDSContinue, } impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for AirwallexCompleteRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> { Ok(Self { request_id: Uuid::new_v4().to_string(), three_ds: AirwallexThreeDsData { acs_response: item .request .redirect_response .as_ref() .map(|f| f.payload.to_owned()) .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "redirect_response.payload", })? .as_ref() .map(|data| serde_json::to_string(data.peek())) .transpose() .change_context(errors::ConnectorError::ResponseDeserializationFailed)? .map(Secret::new), }, three_ds_type: AirwallexThreeDsType::ThreeDSContinue, }) } } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct AirwallexPaymentsCaptureRequest { // Unique ID to be sent for each transaction/operation request to the connector request_id: String, amount: Option<String>, } impl TryFrom<&types::PaymentsCaptureRouterData> for AirwallexPaymentsCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { Ok(Self { request_id: Uuid::new_v4().to_string(), amount: Some(utils::to_currency_base_unit( item.request.amount_to_capture, item.request.currency, )?), }) } } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct AirwallexPaymentsCancelRequest { // Unique ID to be sent for each transaction/operation request to the connector request_id: String, cancellation_reason: Option<String>, } impl TryFrom<&types::PaymentsCancelRouterData> for AirwallexPaymentsCancelRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { Ok(Self { request_id: Uuid::new_v4().to_string(), cancellation_reason: item.request.cancellation_reason.clone(), }) } } // PaymentsResponse #[derive(Debug, Clone, Default, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum AirwallexPaymentStatus { Succeeded, Failed, #[default] Pending, RequiresPaymentMethod, RequiresCustomerAction, RequiresCapture, Cancelled, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum AirwallexNextAction { Payments(AirwallexPaymentsNextAction), Redirect(AirwallexRedirectNextAction), } fn get_payment_status( status: &AirwallexPaymentStatus, next_action: &Option<AirwallexNextAction>, ) -> enums::AttemptStatus { match status.clone() { AirwallexPaymentStatus::Succeeded => enums::AttemptStatus::Charged, AirwallexPaymentStatus::Failed => enums::AttemptStatus::Failure, AirwallexPaymentStatus::Pending => enums::AttemptStatus::Pending, AirwallexPaymentStatus::RequiresPaymentMethod => enums::AttemptStatus::PaymentMethodAwaited, AirwallexPaymentStatus::RequiresCustomerAction => next_action.as_ref().map_or( enums::AttemptStatus::AuthenticationPending, |next_action| match next_action { AirwallexNextAction::Payments(payments_next_action) => { match payments_next_action.stage { AirwallexNextActionStage::WaitingDeviceDataCollection => { enums::AttemptStatus::DeviceDataCollectionPending } AirwallexNextActionStage::WaitingUserInfoInput => { enums::AttemptStatus::AuthenticationPending } } } AirwallexNextAction::Redirect(_) => enums::AttemptStatus::AuthenticationPending, }, ), AirwallexPaymentStatus::RequiresCapture => enums::AttemptStatus::Authorized, AirwallexPaymentStatus::Cancelled => enums::AttemptStatus::Voided, } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum AirwallexNextActionStage { WaitingDeviceDataCollection, WaitingUserInfoInput, } #[derive(Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct AirwallexRedirectFormData { #[serde(rename = "JWT")] jwt: Option<Secret<String>>, #[serde(rename = "threeDSMethodData")] three_ds_method_data: Option<Secret<String>>, token: Option<Secret<String>>, provider: Option<String>, version: Option<String>, } #[derive(Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct AirwallexPaymentsNextAction { url: Url, method: Method, data: AirwallexRedirectFormData, stage: AirwallexNextActionStage, } #[derive(Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct AirwallexRedirectNextAction { url: Url, method: Method, } #[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct AirwallexPaymentsResponse { status: AirwallexPaymentStatus, //Unique identifier for the PaymentIntent id: String, amount: Option<f32>, //ID of the PaymentConsent related to this PaymentIntent payment_consent_id: Option<Secret<String>>, next_action: Option<AirwallexPaymentsNextAction>, } #[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct AirwallexRedirectResponse { status: AirwallexPaymentStatus, id: String, amount: Option<f32>, payment_consent_id: Option<Secret<String>>, next_action: Option<AirwallexRedirectNextAction>, } #[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct AirwallexPaymentsSyncResponse { status: AirwallexPaymentStatus, //Unique identifier for the PaymentIntent id: String, amount: Option<f32>, //ID of the PaymentConsent related to this PaymentIntent payment_consent_id: Option<Secret<String>>, next_action: Option<AirwallexPaymentsNextAction>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(untagged)] pub enum AirwallexAuthorizeResponse { AirwallexPaymentsResponse(AirwallexPaymentsResponse), AirwallexRedirectResponse(AirwallexRedirectResponse), } fn get_redirection_form(response_url_data: AirwallexPaymentsNextAction) -> Option<RedirectForm> { Some(RedirectForm::Form { endpoint: response_url_data.url.to_string(), method: response_url_data.method, form_fields: std::collections::HashMap::from([ //Some form fields might be empty based on the authentication type by the connector ( "JWT".to_string(), response_url_data .data .jwt .map(|jwt| jwt.expose()) .unwrap_or_default(), ), ( "threeDSMethodData".to_string(), response_url_data .data .three_ds_method_data .map(|three_ds_method_data| three_ds_method_data.expose()) .unwrap_or_default(), ), ( "token".to_string(), response_url_data .data .token .map(|token: Secret<String>| token.expose()) .unwrap_or_default(), ), ( "provider".to_string(), response_url_data.data.provider.unwrap_or_default(), ), ( "version".to_string(),
crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs#chunk0
hyperswitch_connectors
chunk
null
null
null
8,188
null
null
null
null
null
null
null
// Struct: RefundRequest // File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct RefundRequest
crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs
hyperswitch_connectors
struct_definition
RefundRequest
0
[]
49
null
null
null
null
null
null
null
// Trait: DynamicRoutingAlgoAccessor // File: crates/api_models/src/routing.rs // Module: api_models pub trait DynamicRoutingAlgoAccessor
crates/api_models/src/routing.rs
api_models
trait_definition
null
null
null
33
null
null
DynamicRoutingAlgoAccessor
null
null
null
null
// File: crates/diesel_models/src/organization.rs // Module: diesel_models // Public functions: 6 // Public structs: 6 use common_utils::{id_type, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; #[cfg(feature = "v1")] use crate::schema::organization; #[cfg(feature = "v2")] use crate::schema_v2::organization; pub trait OrganizationBridge { fn get_organization_id(&self) -> id_type::OrganizationId; fn get_organization_name(&self) -> Option<String>; fn set_organization_name(&mut self, organization_name: String); } #[cfg(feature = "v1")] #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel( table_name = organization, primary_key(org_id), check_for_backend(diesel::pg::Pg) )] pub struct Organization { org_id: id_type::OrganizationId, org_name: Option<String>, pub organization_details: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, #[allow(dead_code)] id: Option<id_type::OrganizationId>, #[allow(dead_code)] organization_name: Option<String>, pub version: common_enums::ApiVersion, pub organization_type: Option<common_enums::OrganizationType>, pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel( table_name = organization, primary_key(id), check_for_backend(diesel::pg::Pg) )] pub struct Organization { pub organization_details: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, id: id_type::OrganizationId, organization_name: Option<String>, pub version: common_enums::ApiVersion, pub organization_type: Option<common_enums::OrganizationType>, pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v1")] impl Organization { pub fn new(org_new: OrganizationNew) -> Self { let OrganizationNew { org_id, org_name, organization_details, metadata, created_at, modified_at, id: _, organization_name: _, version, organization_type, platform_merchant_id, } = org_new; Self { id: Some(org_id.clone()), organization_name: org_name.clone(), org_id, org_name, organization_details, metadata, created_at, modified_at, version, organization_type: Some(organization_type), platform_merchant_id, } } pub fn get_organization_type(&self) -> common_enums::OrganizationType { self.organization_type.unwrap_or_default() } } #[cfg(feature = "v2")] impl Organization { pub fn new(org_new: OrganizationNew) -> Self { let OrganizationNew { id, organization_name, organization_details, metadata, created_at, modified_at, version, organization_type, platform_merchant_id, } = org_new; Self { id, organization_name, organization_details, metadata, created_at, modified_at, version, organization_type: Some(organization_type), platform_merchant_id, } } pub fn get_organization_type(&self) -> common_enums::OrganizationType { self.organization_type.unwrap_or_default() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, Insertable)] #[diesel(table_name = organization, primary_key(org_id))] pub struct OrganizationNew { org_id: id_type::OrganizationId, org_name: Option<String>, id: id_type::OrganizationId, organization_name: Option<String>, pub organization_details: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub version: common_enums::ApiVersion, pub organization_type: common_enums::OrganizationType, pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Insertable)] #[diesel(table_name = organization, primary_key(id))] pub struct OrganizationNew { id: id_type::OrganizationId, organization_name: Option<String>, pub organization_details: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub version: common_enums::ApiVersion, pub organization_type: common_enums::OrganizationType, pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v1")] impl OrganizationNew { pub fn new( id: id_type::OrganizationId, organization_type: common_enums::OrganizationType, organization_name: Option<String>, ) -> Self { Self { org_id: id.clone(), org_name: organization_name.clone(), id, organization_name, organization_details: None, metadata: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), version: common_types::consts::API_VERSION, organization_type, platform_merchant_id: None, } } } #[cfg(feature = "v2")] impl OrganizationNew { pub fn new( id: id_type::OrganizationId, organization_type: common_enums::OrganizationType, organization_name: Option<String>, ) -> Self { Self { id, organization_name, organization_details: None, metadata: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), version: common_types::consts::API_VERSION, organization_type, platform_merchant_id: None, } } } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset)] #[diesel(table_name = organization)] pub struct OrganizationUpdateInternal { org_name: Option<String>, organization_name: Option<String>, organization_details: Option<pii::SecretSerdeValue>, metadata: Option<pii::SecretSerdeValue>, modified_at: time::PrimitiveDateTime, platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset)] #[diesel(table_name = organization)] pub struct OrganizationUpdateInternal { organization_name: Option<String>, organization_details: Option<pii::SecretSerdeValue>, metadata: Option<pii::SecretSerdeValue>, modified_at: time::PrimitiveDateTime, platform_merchant_id: Option<id_type::MerchantId>, } pub enum OrganizationUpdate { Update { organization_name: Option<String>, organization_details: Option<pii::SecretSerdeValue>, metadata: Option<pii::SecretSerdeValue>, platform_merchant_id: Option<id_type::MerchantId>, }, } #[cfg(feature = "v1")] impl From<OrganizationUpdate> for OrganizationUpdateInternal { fn from(value: OrganizationUpdate) -> Self { match value { OrganizationUpdate::Update { organization_name, organization_details, metadata, platform_merchant_id, } => Self { org_name: organization_name.clone(), organization_name, organization_details, metadata, modified_at: common_utils::date_time::now(), platform_merchant_id, }, } } } #[cfg(feature = "v2")] impl From<OrganizationUpdate> for OrganizationUpdateInternal { fn from(value: OrganizationUpdate) -> Self { match value { OrganizationUpdate::Update { organization_name, organization_details, metadata, platform_merchant_id, } => Self { organization_name, organization_details, metadata, modified_at: common_utils::date_time::now(), platform_merchant_id, }, } } } #[cfg(feature = "v1")] impl OrganizationBridge for Organization { fn get_organization_id(&self) -> id_type::OrganizationId { self.org_id.clone() } fn get_organization_name(&self) -> Option<String> { self.org_name.clone() } fn set_organization_name(&mut self, organization_name: String) { self.org_name = Some(organization_name); } } #[cfg(feature = "v1")] impl OrganizationBridge for OrganizationNew { fn get_organization_id(&self) -> id_type::OrganizationId { self.org_id.clone() } fn get_organization_name(&self) -> Option<String> { self.org_name.clone() } fn set_organization_name(&mut self, organization_name: String) { self.org_name = Some(organization_name); } } #[cfg(feature = "v2")] impl OrganizationBridge for Organization { fn get_organization_id(&self) -> id_type::OrganizationId { self.id.clone() } fn get_organization_name(&self) -> Option<String> { self.organization_name.clone() } fn set_organization_name(&mut self, organization_name: String) { self.organization_name = Some(organization_name); } } #[cfg(feature = "v2")] impl OrganizationBridge for OrganizationNew { fn get_organization_id(&self) -> id_type::OrganizationId { self.id.clone() } fn get_organization_name(&self) -> Option<String> { self.organization_name.clone() } fn set_organization_name(&mut self, organization_name: String) { self.organization_name = Some(organization_name); } }
crates/diesel_models/src/organization.rs
diesel_models
full_file
null
null
null
2,143
null
null
null
null
null
null
null
// Struct: SplitRefundInput // File: crates/router/src/core/utils/refunds_transformers.rs // Module: router // Implementations: 0 pub struct SplitRefundInput
crates/router/src/core/utils/refunds_transformers.rs
router
struct_definition
SplitRefundInput
0
[]
40
null
null
null
null
null
null
null
// Struct: BuyerDetails // File: crates/hyperswitch_connectors/src/connectors/amazonpay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct BuyerDetails
crates/hyperswitch_connectors/src/connectors/amazonpay/transformers.rs
hyperswitch_connectors
struct_definition
BuyerDetails
0
[]
46
null
null
null
null
null
null
null
// Struct: ProducerSettings // File: crates/scheduler/src/settings.rs // Module: scheduler // Implementations: 2 // Traits: Default pub struct ProducerSettings
crates/scheduler/src/settings.rs
scheduler
struct_definition
ProducerSettings
2
[ "Default" ]
37
null
null
null
null
null
null
null
// Function: setup_intents_create // File: crates/router/src/compatibility/stripe/setup_intents.rs // Module: router pub fn setup_intents_create( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, ) -> HttpResponse
crates/router/src/compatibility/stripe/setup_intents.rs
router
function_signature
null
null
null
76
setup_intents_create
null
null
null
null
null
null
// Implementation: impl PaymentData // File: crates/router/src/core/payments.rs // Module: router // Methods: 2 total (0 public) impl PaymentData
crates/router/src/core/payments.rs
router
impl_block
null
null
null
36
null
PaymentData
null
2
0
null
null