text
stringlengths
65
57.3k
file_path
stringlengths
22
92
module
stringclasses
38 values
type
stringclasses
7 values
struct_name
stringlengths
3
60
impl_count
int64
0
60
traits
listlengths
0
59
tokens
int64
16
8.19k
function_name
stringlengths
3
85
type_name
stringlengths
1
67
trait_name
stringclasses
573 values
method_count
int64
0
31
public_method_count
int64
0
19
submodule_count
int64
0
56
export_count
int64
0
9
// Struct: CybersourceRsyncResponse // File: crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct CybersourceRsyncResponse
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
hyperswitch_connectors
struct_definition
CybersourceRsyncResponse
0
[]
55
null
null
null
null
null
null
null
// Struct: OrganizationResponse // File: crates/api_models/src/organization.rs // Module: api_models // Implementations: 0 pub struct OrganizationResponse
crates/api_models/src/organization.rs
api_models
struct_definition
OrganizationResponse
0
[]
34
null
null
null
null
null
null
null
// File: crates/router/tests/connectors/bankofamerica.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 BankofamericaTest; impl ConnectorActions for BankofamericaTest {} impl utils::Connector for BankofamericaTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Bankofamerica; utils::construct_connector_data_old( Box::new(Bankofamerica::new()), // Remove `dummy_connector` feature gate from module in `main.rs` when updating this to use actual connector variant types::Connector::DummyConnector1, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .bankofamerica .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "bankofamerica".to_string() } } static CONNECTOR: BankofamericaTest = BankofamericaTest {}; 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/bankofamerica.rs
router
full_file
null
null
null
2,978
null
null
null
null
null
null
null
// Implementation: impl api::RefundSync for for Worldline // File: crates/hyperswitch_connectors/src/connectors/worldline.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::RefundSync for for Worldline
crates/hyperswitch_connectors/src/connectors/worldline.rs
hyperswitch_connectors
impl_block
null
null
null
59
null
Worldline
api::RefundSync for
0
0
null
null
// Function: get_metadata_as_secret // File: crates/api_models/src/admin.rs // Module: api_models pub fn get_metadata_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError>
crates/api_models/src/admin.rs
api_models
function_signature
null
null
null
54
get_metadata_as_secret
null
null
null
null
null
null
// Struct: GpayEcryptedTokenizationData // File: crates/common_types/src/payments.rs // Module: common_types // Implementations: 0 // Documentation: This struct represents the encrypted Gpay payment data pub struct GpayEcryptedTokenizationData
crates/common_types/src/payments.rs
common_types
struct_definition
GpayEcryptedTokenizationData
0
[]
57
null
null
null
null
null
null
null
// File: crates/hyperswitch_connectors/src/connectors/paybox.rs // Module: hyperswitch_connectors // Public functions: 1 // Public structs: 1 pub mod transformers; use std::sync::LazyLock; use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; use common_enums::{enums, CallConnectorAction, PaymentAction}; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, CompleteAuthorize, }, router_request_types::{ AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, types::{self, Response}, webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; use masking::{ExposeInterface, Mask}; use transformers as paybox; use crate::{ constants::headers, types::ResponseRouterData, utils::{convert_amount, is_mandate_supported, PaymentMethodDataType, RouterData as _}, }; #[derive(Clone)] pub struct Paybox { amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), } impl Paybox { pub fn new() -> &'static Self { &Self { amount_converter: &MinorUnitForConnector, } } } impl api::Payment for Paybox {} impl api::PaymentSession for Paybox {} impl api::ConnectorAccessToken for Paybox {} impl api::MandateSetup for Paybox {} impl api::PaymentAuthorize for Paybox {} impl api::PaymentSync for Paybox {} impl api::PaymentCapture for Paybox {} impl api::PaymentVoid for Paybox {} impl api::Refund for Paybox {} impl api::RefundExecute for Paybox {} impl api::RefundSync for Paybox {} impl api::PaymentToken for Paybox {} impl api::PaymentsCompleteAuthorize for Paybox {} impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Paybox { fn build_request( &self, _req: &PaymentsCancelRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("Cancel/Void flow".to_string()).into()) } } impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Paybox { } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Paybox where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, _req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; Ok(header) } } impl ConnectorCommon for Paybox { fn id(&self) -> &'static str { "paybox" } fn common_get_content_type(&self) -> &'static str { "application/x-www-form-urlencoded" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.paybox.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = paybox::PayboxAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), auth.cle.expose().into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: paybox::PayboxErrorResponse = res .response .parse_struct("PayboxErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: response.code, message: response.message, reason: response.reason, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl ConnectorValidation for Paybox { fn validate_mandate_payment( &self, pm_type: Option<enums::PaymentMethodType>, pm_data: PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { let mandate_supported_pmd = std::collections::HashSet::from([PaymentMethodDataType::Card]); is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) } } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Paybox {} impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Paybox {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Paybox {} impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Paybox { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { if req.is_three_ds() { Ok(format!( "{}cgi/RemoteMPI.cgi", connectors.paybox.secondary_base_url )) } else { Ok(self.base_url(connectors).to_string()) } } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = paybox::PayboxRouterData::from((amount, req)); let connector_req = paybox::PayboxPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .set_body(types::PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: paybox::PayboxResponse = paybox::parse_paybox_response(res.response, data.is_three_ds())?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Paybox { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_request_body( &self, req: &PaymentsSyncRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = paybox::PayboxPSyncRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn get_url( &self, _req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_string()) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .set_body(types::PaymentsSyncType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: paybox::PayboxSyncResponse = paybox::parse_url_encoded_to_struct(res.response)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Paybox { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_string()) } fn get_request_body( &self, req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount_to_capture, req.request.currency, )?; let connector_router_data = paybox::PayboxRouterData::from((amount, req)); let connector_req = paybox::PayboxCaptureRequest::try_from(&connector_router_data)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .set_body(types::PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: paybox::PayboxCaptureResponse = paybox::parse_url_encoded_to_struct(res.response)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Paybox { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_string()) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let refund_amount = convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = paybox::PayboxRouterData::from((refund_amount, req)); let connector_req = paybox::PayboxRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .set_body(types::RefundExecuteType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: paybox::TransactionResponse = paybox::parse_url_encoded_to_struct(res.response)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Paybox { fn get_headers( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_string()) } fn get_request_body( &self, req: &RefundSyncRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = paybox::PayboxRsyncRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .set_body(types::RefundSyncType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: paybox::PayboxSyncResponse = paybox::parse_url_encoded_to_struct(res.response)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl IncomingWebhook for Paybox { fn get_webhook_object_reference_id( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> for Paybox { fn get_headers( &self, req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_string()) } fn get_request_body( &self, req: &PaymentsCompleteAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = paybox::PayboxRouterData::from((amount, req)); let connector_req = paybox::PaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsCompleteAuthorizeType::get_url( self, req, connectors, )?) .headers(types::PaymentsCompleteAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsCompleteAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCompleteAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: paybox::TransactionResponse = paybox::parse_url_encoded_to_struct(res.response)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorRedirectResponse for Paybox { fn get_flow_type( &self, _query_params: &str, _json_payload: Option<serde_json::Value>, action: PaymentAction, ) -> CustomResult<CallConnectorAction, errors::ConnectorError> { match action { PaymentAction::PSync | PaymentAction::CompleteAuthorize | PaymentAction::PaymentAuthenticateCompleteAuthorize => { Ok(CallConnectorAction::Trigger) } } } } static PAYBOX_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, enums::CaptureMethod::SequentialAutomatic, ]; let supported_card_network = vec![ common_enums::CardNetwork::Visa, common_enums::CardNetwork::Mastercard, common_enums::CardNetwork::Interac, common_enums::CardNetwork::AmericanExpress, common_enums::CardNetwork::JCB, common_enums::CardNetwork::DinersClub, common_enums::CardNetwork::Discover, common_enums::CardNetwork::CartesBancaires, common_enums::CardNetwork::UnionPay, ]; let mut paybox_supported_payment_methods = SupportedPaymentMethods::new(); paybox_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Debit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::Supported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); paybox_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Credit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::Supported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); paybox_supported_payment_methods }); static PAYBOX_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Paybox", description: "Paybox is a payment gateway that enables businesses to process online transactions securely ", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Sandbox, }; static PAYBOX_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; impl ConnectorSpecifications for Paybox { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&PAYBOX_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*PAYBOX_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&PAYBOX_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/paybox.rs
hyperswitch_connectors
full_file
null
null
null
5,834
null
null
null
null
null
null
null
// Struct: MandateRequest // File: crates/hyperswitch_connectors/src/connectors/payme/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct MandateRequest
crates/hyperswitch_connectors/src/connectors/payme/transformers.rs
hyperswitch_connectors
struct_definition
MandateRequest
0
[]
47
null
null
null
null
null
null
null
// Implementation: impl VaultingDataInterface for for PaymentMethodVaultingData // File: crates/hyperswitch_domain_models/src/vault.rs // Module: hyperswitch_domain_models // Methods: 1 total (0 public) impl VaultingDataInterface for for PaymentMethodVaultingData
crates/hyperswitch_domain_models/src/vault.rs
hyperswitch_domain_models
impl_block
null
null
null
61
null
PaymentMethodVaultingData
VaultingDataInterface for
1
0
null
null
// Function: get_theme_lineage_from_user_token // File: crates/router/src/utils/user/theme.rs // Module: router pub fn get_theme_lineage_from_user_token( user_from_token: &UserFromToken, state: &SessionState, request_entity_type: &EntityType, ) -> UserResult<ThemeLineage>
crates/router/src/utils/user/theme.rs
router
function_signature
null
null
null
71
get_theme_lineage_from_user_token
null
null
null
null
null
null
// Struct: RedsysAuthType // File: crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct RedsysAuthType
crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
hyperswitch_connectors
struct_definition
RedsysAuthType
0
[]
49
null
null
null
null
null
null
null
// Function: parse_routing_algorithm // File: crates/api_models/src/admin.rs // Module: api_models pub fn parse_routing_algorithm(&self) -> CustomResult<(), errors::ParsingError>
crates/api_models/src/admin.rs
api_models
function_signature
null
null
null
40
parse_routing_algorithm
null
null
null
null
null
null
// Struct: PaymentsResponse // File: crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PaymentsResponse
crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
hyperswitch_connectors
struct_definition
PaymentsResponse
0
[]
47
null
null
null
null
null
null
null
// Function: update_merchant // File: crates/router/src/routes/recon.rs // Module: router pub fn update_merchant( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, json_payload: web::Json<recon_api::ReconUpdateMerchantRequest>, ) -> HttpResponse
crates/router/src/routes/recon.rs
router
function_signature
null
null
null
80
update_merchant
null
null
null
null
null
null
// Struct: RsyncApplicationInformation // File: crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct RsyncApplicationInformation
crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
hyperswitch_connectors
struct_definition
RsyncApplicationInformation
0
[]
51
null
null
null
null
null
null
null
// Function: get_co_badged_card_data // File: crates/hyperswitch_domain_models/src/payment_method_data.rs // Module: hyperswitch_domain_models pub fn get_co_badged_card_data(&self) -> Option<payment_methods::CoBadgedCardData>
crates/hyperswitch_domain_models/src/payment_method_data.rs
hyperswitch_domain_models
function_signature
null
null
null
57
get_co_badged_card_data
null
null
null
null
null
null
// Struct: OrderInformationWithBill // File: crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct OrderInformationWithBill
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
hyperswitch_connectors
struct_definition
OrderInformationWithBill
0
[]
51
null
null
null
null
null
null
null
// Struct: AuthEventFiltersResponse // File: crates/api_models/src/analytics.rs // Module: api_models // Implementations: 0 pub struct AuthEventFiltersResponse
crates/api_models/src/analytics.rs
api_models
struct_definition
AuthEventFiltersResponse
0
[]
38
null
null
null
null
null
null
null
// Struct: RevenueRecoveryAttempt // File: crates/router/src/core/webhooks/recovery_incoming.rs // Module: router // Implementations: 1 pub struct RevenueRecoveryAttempt
crates/router/src/core/webhooks/recovery_incoming.rs
router
struct_definition
RevenueRecoveryAttempt
1
[]
41
null
null
null
null
null
null
null
// Function: get_id // File: crates/hyperswitch_domain_models/src/payments.rs // Module: hyperswitch_domain_models pub fn get_id(&self) -> &id_type::GlobalPaymentId
crates/hyperswitch_domain_models/src/payments.rs
hyperswitch_domain_models
function_signature
null
null
null
44
get_id
null
null
null
null
null
null
// Struct: PaymentAttempts // File: crates/api_models/src/analytics/sdk_events.rs // Module: api_models // Implementations: 0 pub struct PaymentAttempts
crates/api_models/src/analytics/sdk_events.rs
api_models
struct_definition
PaymentAttempts
0
[]
36
null
null
null
null
null
null
null
// Struct: WellsfargopayoutRouterData // File: crates/hyperswitch_connectors/src/connectors/wellsfargopayout/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct WellsfargopayoutRouterData<T>
crates/hyperswitch_connectors/src/connectors/wellsfargopayout/transformers.rs
hyperswitch_connectors
struct_definition
WellsfargopayoutRouterData
0
[]
61
null
null
null
null
null
null
null
// Struct: PaymentInformationResponse // File: crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PaymentInformationResponse
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
hyperswitch_connectors
struct_definition
PaymentInformationResponse
0
[]
49
null
null
null
null
null
null
null
// File: crates/test_utils/tests/connectors/multisafepay_ui.rs // Module: test_utils use serial_test::serial; use thirtyfour::{prelude::*, WebDriver}; use crate::{selenium::*, tester}; struct MultisafepaySeleniumTest; impl SeleniumTest for MultisafepaySeleniumTest { fn get_connector_name(&self) -> String { "multisafepay".to_string() } } async fn should_make_multisafepay_3ds_payment_success( web_driver: WebDriver, ) -> Result<(), WebDriverError> { let conn = MultisafepaySeleniumTest {}; conn.make_redirection_payment( web_driver, vec![ Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/207"))), Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), Event::Assert(Assert::IsPresent("succeeded")), ], ) .await?; Ok(()) } async fn should_make_multisafepay_3ds_payment_failed( web_driver: WebDriver, ) -> Result<(), WebDriverError> { let conn = MultisafepaySeleniumTest {}; conn.make_redirection_payment( web_driver, vec![ Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/93"))), Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), Event::Assert(Assert::IsPresent("failed")), ], ) .await?; Ok(()) } async fn should_make_gpay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> { let conn = MultisafepaySeleniumTest {}; conn.make_redirection_payment( web_driver, vec![ Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/153"))), Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), Event::Trigger(Trigger::Click(By::Css("button[class='btn btn-default']"))), Event::Assert(Assert::IsPresent("succeeded")), ], ) .await?; Ok(()) } async fn should_make_paypal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> { let conn = MultisafepaySeleniumTest {}; conn.make_redirection_payment( web_driver, vec![ Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/154"))), Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), Event::Trigger(Trigger::Click(By::Css( "button[class='btn btn-msp-success btn-block']", ))), Event::Assert(Assert::IsPresent("succeeded")), ], ) .await?; Ok(()) } #[test] #[serial] fn should_make_multisafepay_3ds_payment_success_test() { tester!(should_make_multisafepay_3ds_payment_success); } #[test] #[serial] fn should_make_multisafepay_3ds_payment_failed_test() { tester!(should_make_multisafepay_3ds_payment_failed); } #[test] #[serial] #[ignore] fn should_make_gpay_payment_test() { tester!(should_make_gpay_payment); } #[test] #[serial] fn should_make_paypal_payment_test() { tester!(should_make_paypal_payment); }
crates/test_utils/tests/connectors/multisafepay_ui.rs
test_utils
full_file
null
null
null
748
null
null
null
null
null
null
null
// Struct: LoonioTransactionSyncResponse // File: crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct LoonioTransactionSyncResponse
crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs
hyperswitch_connectors
struct_definition
LoonioTransactionSyncResponse
0
[]
52
null
null
null
null
null
null
null
// Implementation: impl IncomingWebhook for for Bluesnap // File: crates/hyperswitch_connectors/src/connectors/bluesnap.rs // Module: hyperswitch_connectors // Methods: 7 total (0 public) impl IncomingWebhook for for Bluesnap
crates/hyperswitch_connectors/src/connectors/bluesnap.rs
hyperswitch_connectors
impl_block
null
null
null
56
null
Bluesnap
IncomingWebhook for
7
0
null
null
// Struct: BarclaycardRsyncResponse // File: crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct BarclaycardRsyncResponse
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
hyperswitch_connectors
struct_definition
BarclaycardRsyncResponse
0
[]
55
null
null
null
null
null
null
null
// Implementation: impl Responder // File: crates/router/src/analytics.rs // Module: router // Methods: 0 total (0 public) impl Responder
crates/router/src/analytics.rs
router
impl_block
null
null
null
35
null
Responder
null
0
0
null
null
// Function: resend_invite // File: crates/router/src/core/user.rs // Module: router pub fn resend_invite( state: SessionState, user_from_token: auth::UserFromToken, request: user_api::ReInviteUserRequest, auth_id: Option<String>, ) -> UserResponse<()>
crates/router/src/core/user.rs
router
function_signature
null
null
null
66
resend_invite
null
null
null
null
null
null
// Struct: EbanxPayoutResponse // File: crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct EbanxPayoutResponse
crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs
hyperswitch_connectors
struct_definition
EbanxPayoutResponse
0
[]
55
null
null
null
null
null
null
null
// Implementation: impl ConnectorPreAuthentication for for Netcetera // File: crates/hyperswitch_connectors/src/connectors/netcetera.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl ConnectorPreAuthentication for for Netcetera
crates/hyperswitch_connectors/src/connectors/netcetera.rs
hyperswitch_connectors
impl_block
null
null
null
61
null
Netcetera
ConnectorPreAuthentication for
0
0
null
null
} fn get_routing_config_cache_key(self) -> storage_impl::redis::cache::CacheKind<'static> { let merchant_id = self.profile.merchant_id.clone(); let profile_id = self.profile.get_id().to_owned(); storage_impl::redis::cache::CacheKind::Routing( format!( "routing_config_{}_{}", merchant_id.get_string_repr(), profile_id.get_string_repr() ) .into(), ) } pub async fn update_profile_and_invalidate_routing_config_for_active_algorithm_id_update( self, db: &dyn StorageInterface, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, algorithm_id: id_type::RoutingId, transaction_type: &storage::enums::TransactionType, ) -> RouterResult<()> { let routing_cache_key = self.clone().get_routing_config_cache_key(); let (routing_algorithm_id, payout_routing_algorithm_id) = match transaction_type { storage::enums::TransactionType::Payment => (Some(algorithm_id), None), #[cfg(feature = "payouts")] storage::enums::TransactionType::Payout => (None, Some(algorithm_id)), //TODO: Handle ThreeDsAuthentication Transaction Type for Three DS Decision Rule Algorithm configuration storage::enums::TransactionType::ThreeDsAuthentication => todo!(), }; let profile_update = domain::ProfileUpdate::RoutingAlgorithmUpdate { routing_algorithm_id, payout_routing_algorithm_id, }; let profile = self.profile; db.update_profile_by_profile_id( key_manager_state, merchant_key_store, profile, profile_update, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref in business profile")?; storage_impl::redis::cache::redact_from_redis_and_publish( db.get_cache_store().as_ref(), [routing_cache_key], ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to invalidate routing cache")?; Ok(()) } pub fn get_routing_algorithm_id<'a>( &'a self, transaction_data: &'a routing::TransactionData<'_>, ) -> Option<id_type::RoutingId> { match transaction_data { routing::TransactionData::Payment(_) => self.profile.routing_algorithm_id.clone(), #[cfg(feature = "payouts")] routing::TransactionData::Payout(_) => self.profile.payout_routing_algorithm_id.clone(), } } pub fn get_default_fallback_list_of_connector_under_profile( &self, ) -> RouterResult<Vec<routing_types::RoutableConnectorChoice>> { let fallback_connectors = if let Some(default_fallback_routing) = self.profile.default_fallback_routing.clone() { default_fallback_routing .expose() .parse_value::<Vec<routing_types::RoutableConnectorChoice>>( "Vec<RoutableConnectorChoice>", ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Business Profile default config has invalid structure")? } else { Vec::new() }; Ok(fallback_connectors) } pub fn get_default_routing_configs_from_profile( &self, ) -> RouterResult<routing_types::ProfileDefaultRoutingConfig> { let profile_id = self.profile.get_id().to_owned(); let connectors = self.get_default_fallback_list_of_connector_under_profile()?; Ok(routing_types::ProfileDefaultRoutingConfig { profile_id, connectors, }) } pub async fn update_default_fallback_routing_of_connectors_under_profile( self, db: &dyn StorageInterface, updated_config: &Vec<routing_types::RoutableConnectorChoice>, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, ) -> RouterResult<()> { let default_fallback_routing = Secret::from( updated_config .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert routing ref to value")?, ); let profile_update = domain::ProfileUpdate::DefaultRoutingFallbackUpdate { default_fallback_routing: Some(default_fallback_routing), }; db.update_profile_by_profile_id( key_manager_state, merchant_key_store, self.profile, profile_update, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref in business profile")?; Ok(()) } pub async fn update_revenue_recovery_algorithm_under_profile( self, db: &dyn StorageInterface, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, revenue_recovery_retry_algorithm_type: common_enums::RevenueRecoveryAlgorithmType, ) -> RouterResult<()> { let recovery_algorithm_data = diesel_models::business_profile::RevenueRecoveryAlgorithmData { monitoring_configured_timestamp: date_time::now(), }; let profile_update = domain::ProfileUpdate::RevenueRecoveryAlgorithmUpdate { revenue_recovery_retry_algorithm_type, revenue_recovery_retry_algorithm_data: Some(recovery_algorithm_data), }; db.update_profile_by_profile_id( key_manager_state, merchant_key_store, self.profile, profile_update, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to update revenue recovery retry algorithm in business profile", )?; Ok(()) } } pub async fn extended_card_info_toggle( state: SessionState, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, ext_card_info_choice: admin_types::ExtendedCardInfoChoice, ) -> RouterResponse<admin_types::ExtendedCardInfoChoice> { 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, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) .attach_printable("Error while fetching the key store by merchant_id")?; let business_profile = db .find_business_profile_by_profile_id(key_manager_state, &key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; if business_profile.is_extended_card_info_enabled.is_none() || business_profile .is_extended_card_info_enabled .is_some_and(|existing_config| existing_config != ext_card_info_choice.enabled) { let profile_update = domain::ProfileUpdate::ExtendedCardInfoUpdate { is_extended_card_info_enabled: ext_card_info_choice.enabled, }; db.update_profile_by_profile_id( key_manager_state, &key_store, business_profile, profile_update, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; } Ok(service_api::ApplicationResponse::Json(ext_card_info_choice)) } pub async fn connector_agnostic_mit_toggle( state: SessionState, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, connector_agnostic_mit_choice: admin_types::ConnectorAgnosticMitChoice, ) -> RouterResponse<admin_types::ConnectorAgnosticMitChoice> { 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, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) .attach_printable("Error while fetching the key store by merchant_id")?; let business_profile = db .find_business_profile_by_profile_id(key_manager_state, &key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; if business_profile.merchant_id != *merchant_id { Err(errors::ApiErrorResponse::AccessForbidden { resource: profile_id.get_string_repr().to_owned(), })? } if business_profile.is_connector_agnostic_mit_enabled != Some(connector_agnostic_mit_choice.enabled) { let profile_update = domain::ProfileUpdate::ConnectorAgnosticMitUpdate { is_connector_agnostic_mit_enabled: connector_agnostic_mit_choice.enabled, }; db.update_profile_by_profile_id( key_manager_state, &key_store, business_profile, profile_update, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; } Ok(service_api::ApplicationResponse::Json( connector_agnostic_mit_choice, )) } pub async fn transfer_key_store_to_key_manager( state: SessionState, req: admin_types::MerchantKeyTransferRequest, ) -> RouterResponse<admin_types::TransferKeyResponse> { let resp = transfer_encryption_key(&state, req).await?; Ok(service_api::ApplicationResponse::Json( admin_types::TransferKeyResponse { total_transferred: resp, }, )) } async fn process_open_banking_connectors( state: &SessionState, merchant_id: &id_type::MerchantId, auth: &types::ConnectorAuthType, connector_type: &api_enums::ConnectorType, connector: &api_enums::Connector, additional_merchant_data: types::AdditionalMerchantData, key_store: &domain::MerchantKeyStore, ) -> RouterResult<types::MerchantRecipientData> { let new_merchant_data = match additional_merchant_data { types::AdditionalMerchantData::OpenBankingRecipientData(merchant_data) => { if connector_type != &api_enums::ConnectorType::PaymentProcessor { return Err(errors::ApiErrorResponse::InvalidConnectorConfiguration { config: "OpenBanking connector for Payment Initiation should be a payment processor" .to_string(), } .into()); } match &merchant_data { types::MerchantRecipientData::AccountData(acc_data) => { core_utils::validate_bank_account_data(acc_data)?; let connector_name = api_enums::Connector::to_string(connector); let recipient_creation_not_supported = state .conf .locker_based_open_banking_connectors .connector_list .contains(connector_name.as_str()); let recipient_id = if recipient_creation_not_supported { locker_recipient_create_call(state, merchant_id, acc_data, key_store).await } else { connector_recipient_create_call( state, merchant_id, connector_name, auth, acc_data, ) .await } .attach_printable("failed to get recipient_id")?; let conn_recipient_id = if recipient_creation_not_supported { Some(types::RecipientIdType::LockerId(Secret::new(recipient_id))) } else { Some(types::RecipientIdType::ConnectorId(Secret::new( recipient_id, ))) }; let account_data = match &acc_data { types::MerchantAccountData::Iban { iban, name, .. } => { types::MerchantAccountData::Iban { iban: iban.clone(), name: name.clone(), connector_recipient_id: conn_recipient_id.clone(), } } types::MerchantAccountData::Bacs { account_number, sort_code, name, .. } => types::MerchantAccountData::Bacs { account_number: account_number.clone(), sort_code: sort_code.clone(), name: name.clone(), connector_recipient_id: conn_recipient_id.clone(), }, types::MerchantAccountData::FasterPayments { account_number, sort_code, name, .. } => types::MerchantAccountData::FasterPayments { account_number: account_number.clone(), sort_code: sort_code.clone(), name: name.clone(), connector_recipient_id: conn_recipient_id.clone(), }, types::MerchantAccountData::Sepa { iban, name, .. } => { types::MerchantAccountData::Sepa { iban: iban.clone(), name: name.clone(), connector_recipient_id: conn_recipient_id.clone(), } } types::MerchantAccountData::SepaInstant { iban, name, .. } => { types::MerchantAccountData::SepaInstant { iban: iban.clone(), name: name.clone(), connector_recipient_id: conn_recipient_id.clone(), } } types::MerchantAccountData::Elixir { account_number, iban, name, .. } => types::MerchantAccountData::Elixir { account_number: account_number.clone(), iban: iban.clone(), name: name.clone(), connector_recipient_id: conn_recipient_id.clone(), }, types::MerchantAccountData::Bankgiro { number, name, .. } => { types::MerchantAccountData::Bankgiro { number: number.clone(), name: name.clone(), connector_recipient_id: conn_recipient_id.clone(), } } types::MerchantAccountData::Plusgiro { number, name, .. } => { types::MerchantAccountData::Plusgiro { number: number.clone(), name: name.clone(), connector_recipient_id: conn_recipient_id.clone(), } } }; types::MerchantRecipientData::AccountData(account_data) } _ => merchant_data.clone(), } } }; Ok(new_merchant_data) } async fn connector_recipient_create_call( state: &SessionState, merchant_id: &id_type::MerchantId, connector_name: String, auth: &types::ConnectorAuthType, data: &types::MerchantAccountData, ) -> RouterResult<String> { let connector = pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name( connector_name.as_str(), )?; let auth = pm_auth_types::ConnectorAuthType::foreign_try_from(auth.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while converting ConnectorAuthType")?; let connector_integration: pm_auth_types::api::BoxedConnectorIntegration< '_, pm_auth_types::api::auth_service::RecipientCreate, pm_auth_types::RecipientCreateRequest, pm_auth_types::RecipientCreateResponse, > = connector.connector.get_connector_integration(); let req = pm_auth_types::RecipientCreateRequest::from(data); let router_data = pm_auth_types::RecipientCreateRouterData { flow: std::marker::PhantomData, merchant_id: Some(merchant_id.to_owned()), connector: Some(connector_name), request: req, response: Err(pm_auth_types::ErrorResponse { status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(), code: consts::NO_ERROR_CODE.to_string(), message: consts::UNSUPPORTED_ERROR_MESSAGE.to_string(), reason: None, }), connector_http_status_code: None, connector_auth_type: auth, }; let resp = payment_initiation_service::execute_connector_processing_step( state, connector_integration, &router_data, &connector.connector_name, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while calling recipient create connector api")?; let recipient_create_resp = resp.response .map_err(|err| errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: connector.connector_name.to_string(), status_code: err.status_code, reason: err.reason, })?; let recipient_id = recipient_create_resp.recipient_id; Ok(recipient_id) } async fn locker_recipient_create_call( state: &SessionState, merchant_id: &id_type::MerchantId, data: &types::MerchantAccountData, key_store: &domain::MerchantKeyStore, ) -> RouterResult<String> { let key_manager_state = &state.into(); let key = key_store.key.get_inner().peek(); let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone()); let data_json = serde_json::to_string(data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize MerchantAccountData to JSON")?; let encrypted_data = domain_types::crypto_operation( key_manager_state, type_name!(payment_method::PaymentMethod), domain_types::CryptoOperation::Encrypt(Secret::<String, masking::WithType>::new(data_json)), identifier, key, ) .await .and_then(|val| val.try_into_operation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encrypt merchant account data")?; let enc_data = hex::encode(encrypted_data.into_encrypted().expose()); let merchant_id_string = merchant_id.get_string_repr().to_owned(); let cust_id = id_type::CustomerId::try_from(std::borrow::Cow::from(merchant_id_string)) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert to CustomerId")?; let payload = transformers::StoreLockerReq::LockerGeneric(transformers::StoreGenericReq { merchant_id: merchant_id.to_owned(), merchant_customer_id: cust_id.clone(), enc_data, ttl: state.conf.locker.ttl_for_storage_in_secs, }); let store_resp = cards::add_card_to_hs_locker( state, &payload, &cust_id, api_enums::LockerChoice::HyperswitchCardVault, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encrypt merchant bank account data")?; Ok(store_resp.card_reference) } pub async fn enable_platform_account( state: SessionState, merchant_id: id_type::MerchantId, ) -> RouterResponse<()> { 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)?; db.update_merchant( key_manager_state, merchant_account, storage::MerchantAccountUpdate::ToPlatformAccount, &key_store, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while enabling platform merchant account") .map(|_| services::ApplicationResponse::StatusOk) } impl From<&types::MerchantAccountData> for pm_auth_types::RecipientCreateRequest { fn from(data: &types::MerchantAccountData) -> Self { let (name, account_data) = match data { types::MerchantAccountData::Iban { iban, name, .. } => ( name.clone(), pm_auth_types::RecipientAccountData::Iban(iban.clone()), ), types::MerchantAccountData::Bacs { account_number, sort_code, name, .. } => ( name.clone(), pm_auth_types::RecipientAccountData::Bacs { sort_code: sort_code.clone(), account_number: account_number.clone(), }, ), types::MerchantAccountData::FasterPayments { account_number, sort_code, name, .. } => ( name.clone(), pm_auth_types::RecipientAccountData::FasterPayments { sort_code: sort_code.clone(), account_number: account_number.clone(), }, ), types::MerchantAccountData::Sepa { iban, name, .. } => ( name.clone(), pm_auth_types::RecipientAccountData::Sepa(iban.clone()), ), types::MerchantAccountData::SepaInstant { iban, name, .. } => ( name.clone(), pm_auth_types::RecipientAccountData::SepaInstant(iban.clone()), ), types::MerchantAccountData::Elixir { account_number, iban, name, .. } => ( name.clone(), pm_auth_types::RecipientAccountData::Elixir { account_number: account_number.clone(), iban: iban.clone(), }, ), types::MerchantAccountData::Bankgiro { number, name, .. } => ( name.clone(), pm_auth_types::RecipientAccountData::Bankgiro(number.clone()), ), types::MerchantAccountData::Plusgiro { number, name, .. } => ( name.clone(), pm_auth_types::RecipientAccountData::Plusgiro(number.clone()), ), }; Self { name, account_data, address: None, } } }
crates/router/src/core/admin.rs#chunk4
router
chunk
null
null
null
4,704
null
null
null
null
null
null
null
// Implementation: impl AcceptDispute for for Adyen // File: crates/hyperswitch_connectors/src/connectors/adyen.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl AcceptDispute for for Adyen
crates/hyperswitch_connectors/src/connectors/adyen.rs
hyperswitch_connectors
impl_block
null
null
null
56
null
Adyen
AcceptDispute for
0
0
null
null
// Function: get_profile_id // File: crates/hyperswitch_domain_models/src/payments/payment_intent.rs // Module: hyperswitch_domain_models pub fn get_profile_id(&self) -> Option<id_type::ProfileId>
crates/hyperswitch_domain_models/src/payments/payment_intent.rs
hyperswitch_domain_models
function_signature
null
null
null
49
get_profile_id
null
null
null
null
null
null
// Function: insert // File: crates/diesel_models/src/query/dashboard_metadata.rs // Module: diesel_models pub fn insert(self, conn: &PgPooledConn) -> StorageResult<DashboardMetadata>
crates/diesel_models/src/query/dashboard_metadata.rs
diesel_models
function_signature
null
null
null
44
insert
null
null
null
null
null
null
// Implementation: impl api::PaymentCapture for for Paysafe // File: crates/hyperswitch_connectors/src/connectors/paysafe.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentCapture for for Paysafe
crates/hyperswitch_connectors/src/connectors/paysafe.rs
hyperswitch_connectors
impl_block
null
null
null
58
null
Paysafe
api::PaymentCapture for
0
0
null
null
// Function: from_input // File: crates/euclid/src/backend/vir_interpreter/types.rs // Module: euclid pub fn from_input(input: BackendInput) -> Self
crates/euclid/src/backend/vir_interpreter/types.rs
euclid
function_signature
null
null
null
39
from_input
null
null
null
null
null
null
// Function: get_not_implemented // File: crates/hyperswitch_domain_models/src/router_data.rs // Module: hyperswitch_domain_models pub fn get_not_implemented() -> Self
crates/hyperswitch_domain_models/src/router_data.rs
hyperswitch_domain_models
function_signature
null
null
null
40
get_not_implemented
null
null
null
null
null
null
// Struct: SuccessfulTransactionData // File: crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct SuccessfulTransactionData
crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs
hyperswitch_connectors
struct_definition
SuccessfulTransactionData
0
[]
49
null
null
null
null
null
null
null
// Struct: BillingConnectorInvoiceSyncFlowData // File: crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct BillingConnectorInvoiceSyncFlowData
crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
hyperswitch_domain_models
struct_definition
BillingConnectorInvoiceSyncFlowData
0
[]
54
null
null
null
null
null
null
null
// Function: generate_digest // File: crates/hyperswitch_connectors/src/connectors/nordea.rs // Module: hyperswitch_connectors pub fn generate_digest(&self, payload: &[u8]) -> String
crates/hyperswitch_connectors/src/connectors/nordea.rs
hyperswitch_connectors
function_signature
null
null
null
47
generate_digest
null
null
null
null
null
null
// Trait: IntoInjectorResponse // File: crates/injector/src/types.rs // Module: injector pub trait IntoInjectorResponse
crates/injector/src/types.rs
injector
trait_definition
null
null
null
28
null
null
IntoInjectorResponse
null
null
null
null
// Function: get_id // File: crates/hyperswitch_domain_models/src/payments/payment_attempt.rs // Module: hyperswitch_domain_models pub fn get_id(&self) -> &str
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
hyperswitch_domain_models
function_signature
null
null
null
41
get_id
null
null
null
null
null
null
// Function: get_payout_routing_algorithm // File: crates/hyperswitch_domain_models/src/business_profile.rs // Module: hyperswitch_domain_models pub fn get_payout_routing_algorithm( &self, ) -> CustomResult< Option<api_models::routing::RoutingAlgorithmRef>, api_error_response::ApiErrorResponse, >
crates/hyperswitch_domain_models/src/business_profile.rs
hyperswitch_domain_models
function_signature
null
null
null
72
get_payout_routing_algorithm
null
null
null
null
null
null
// Struct: AdditionalErrorDetails // File: crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct AdditionalErrorDetails
crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
hyperswitch_connectors
struct_definition
AdditionalErrorDetails
0
[]
48
null
null
null
null
null
null
null
// Function: server // File: crates/router/src/routes/app.rs // Module: router pub fn server(config: AppState) -> Scope
crates/router/src/routes/app.rs
router
function_signature
null
null
null
29
server
null
null
null
null
null
null
// Struct: ToggleDynamicRoutingQuery // File: crates/api_models/src/routing.rs // Module: api_models // Implementations: 0 pub struct ToggleDynamicRoutingQuery
crates/api_models/src/routing.rs
api_models
struct_definition
ToggleDynamicRoutingQuery
0
[]
38
null
null
null
null
null
null
null
// Struct: OrgAuthenticationMethodUpdateInternal // File: crates/diesel_models/src/user_authentication_method.rs // Module: diesel_models // Implementations: 0 pub struct OrgAuthenticationMethodUpdateInternal
crates/diesel_models/src/user_authentication_method.rs
diesel_models
struct_definition
OrgAuthenticationMethodUpdateInternal
0
[]
42
null
null
null
null
null
null
null
// Struct: SiftRouterData // File: crates/hyperswitch_connectors/src/connectors/sift/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct SiftRouterData<T>
crates/hyperswitch_connectors/src/connectors/sift/transformers.rs
hyperswitch_connectors
struct_definition
SiftRouterData
0
[]
51
null
null
null
null
null
null
null
// Function: get_all_keys // File: crates/euclid_wasm/src/lib.rs // Module: euclid_wasm pub fn get_all_keys() -> JsResult
crates/euclid_wasm/src/lib.rs
euclid_wasm
function_signature
null
null
null
37
get_all_keys
null
null
null
null
null
null
// Implementation: impl api::RefundSync for for Moneris // File: crates/hyperswitch_connectors/src/connectors/moneris.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::RefundSync for for Moneris
crates/hyperswitch_connectors/src/connectors/moneris.rs
hyperswitch_connectors
impl_block
null
null
null
63
null
Moneris
api::RefundSync for
0
0
null
null
// File: crates/analytics/src/payments/metrics/sessionized_metrics/payments_distribution.rs // Module: analytics use std::collections::HashSet; use api_models::analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::PaymentMetricRow; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(crate) struct PaymentsDistribution; #[async_trait::async_trait] impl<T> super::PaymentMetric<T> for PaymentsDistribution where T: AnalyticsDataSource + super::PaymentMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::PaymentSessionized); let mut dimensions = dimensions.to_vec(); dimensions.push(PaymentDimensions::PaymentStatus); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(Aggregate::Count { field: None, alias: Some("count"), }) .switch()?; query_builder.add_select_column("first_attempt").switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; auth.set_filter_clause(&mut query_builder).switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; for dim in dimensions.iter() { query_builder .add_group_by_clause(dim) .attach_printable("Error grouping by dimensions") .switch()?; } query_builder .add_group_by_clause("first_attempt") .attach_printable("Error grouping by first_attempt") .switch()?; if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } query_builder .execute_query::<PaymentMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( PaymentMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), None, i.connector.clone(), i.authentication_type.as_ref().map(|i| i.0), i.payment_method.clone(), i.payment_method_type.clone(), i.client_source.clone(), i.client_version.clone(), i.profile_id.clone(), i.card_network.clone(), i.merchant_id.clone(), i.card_last_4.clone(), i.card_issuer.clone(), i.error_reason.clone(), i.routing_approach.as_ref().map(|i| i.0.clone()), i.signature_network.clone(), i.is_issuer_regulated, i.is_debit_routed, TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result< HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/payments/metrics/sessionized_metrics/payments_distribution.rs
analytics
full_file
null
null
null
1,003
null
null
null
null
null
null
null
// Implementation: impl webhooks::IncomingWebhook for for Authorizedotnet // File: crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs // Module: hyperswitch_connectors // Methods: 6 total (0 public) impl webhooks::IncomingWebhook for for Authorizedotnet
crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs
hyperswitch_connectors
impl_block
null
null
null
65
null
Authorizedotnet
webhooks::IncomingWebhook for
6
0
null
null
// File: crates/router/src/core/subscription.rs // Module: router // Public functions: 11 // Public structs: 4 use std::str::FromStr; use api_models::{ enums as api_enums, subscription::{self as subscription_types, CreateSubscriptionResponse, SubscriptionStatus}, }; use common_utils::{ext_traits::ValueExt, id_type::GenerateId, pii}; use diesel_models::subscription::SubscriptionNew; use error_stack::ResultExt; use hyperswitch_domain_models::{ api::ApplicationResponse, merchant_context::MerchantContext, router_data_v2::flow_common_types::{SubscriptionCreateData, SubscriptionCustomerData}, router_request_types::{subscriptions as subscription_request_types, ConnectorCustomerData}, router_response_types::{ subscriptions as subscription_response_types, ConnectorCustomerResponseData, PaymentsResponseData, }, }; use masking::Secret; use super::errors::{self, RouterResponse}; use crate::{ core::payments as payments_core, routes::SessionState, services, types::api as api_types, }; pub const SUBSCRIPTION_CONNECTOR_ID: &str = "DefaultSubscriptionConnectorId"; pub const SUBSCRIPTION_PAYMENT_ID: &str = "DefaultSubscriptionPaymentId"; pub async fn create_subscription( state: SessionState, merchant_context: MerchantContext, profile_id: String, request: subscription_types::CreateSubscriptionRequest, ) -> RouterResponse<CreateSubscriptionResponse> { let store = state.store.clone(); let db = store.as_ref(); let id = common_utils::id_type::SubscriptionId::generate(); let profile_id = common_utils::id_type::ProfileId::from_str(&profile_id).change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "X-Profile-Id", }, )?; let mut subscription = SubscriptionNew::new( id, SubscriptionStatus::Created.to_string(), None, None, None, None, None, merchant_context.get_merchant_account().get_id().clone(), request.customer_id.clone(), None, profile_id, request.merchant_reference_id, ); subscription.generate_and_set_client_secret(); let subscription_response = db .insert_subscription_entry(subscription) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("subscriptions: unable to insert subscription entry to database")?; let response = CreateSubscriptionResponse::new( subscription_response.id.clone(), subscription_response.merchant_reference_id, SubscriptionStatus::from_str(&subscription_response.status) .unwrap_or(SubscriptionStatus::Created), None, subscription_response.profile_id, subscription_response.merchant_id, subscription_response.client_secret.map(Secret::new), request.customer_id, ); Ok(ApplicationResponse::Json(response)) } pub async fn confirm_subscription( state: SessionState, merchant_context: MerchantContext, profile_id: String, request: subscription_types::ConfirmSubscriptionRequest, subscription_id: common_utils::id_type::SubscriptionId, ) -> RouterResponse<subscription_types::ConfirmSubscriptionResponse> { let profile_id = common_utils::id_type::ProfileId::from_str(&profile_id).change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "X-Profile-Id", }, )?; let key_manager_state = &(&state).into(); let merchant_key_store = merchant_context.get_merchant_key_store(); let profile = state .store .find_business_profile_by_profile_id(key_manager_state, merchant_key_store, &profile_id) .await .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_string(), })?; let customer = state .store .find_customer_by_customer_id_merchant_id( key_manager_state, &request.customer_id, merchant_context.get_merchant_account().get_id(), merchant_key_store, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::CustomerNotFound) .attach_printable("subscriptions: unable to fetch customer from database")?; let handler = SubscriptionHandler::new(state, merchant_context, request, profile); let mut subscription_entry = handler .find_subscription(subscription_id.get_string_repr().to_string()) .await?; let billing_handler = subscription_entry.get_billing_handler(customer).await?; let invoice_handler = subscription_entry.get_invoice_handler().await?; let _customer_create_response = billing_handler .create_customer_on_connector(&handler.state) .await?; let subscription_create_response = billing_handler .create_subscription_on_connector(&handler.state) .await?; // let payment_response = invoice_handler.create_cit_payment().await?; let invoice_entry = invoice_handler .create_invoice_entry( &handler.state, subscription_entry.profile.get_billing_processor_id()?, None, billing_handler.request.amount, billing_handler.request.currency.to_string(), common_enums::connector_enums::InvoiceStatus::InvoiceCreated, billing_handler.connector_data.connector_name, None, ) .await?; // invoice_entry // .create_invoice_record_back_job(&payment_response) // .await?; subscription_entry .update_subscription_status( SubscriptionStatus::from(subscription_create_response.status).to_string(), ) .await?; let response = subscription_entry .generate_response(&invoice_entry, subscription_create_response.status)?; Ok(ApplicationResponse::Json(response)) } pub struct SubscriptionHandler { state: SessionState, merchant_context: MerchantContext, request: subscription_types::ConfirmSubscriptionRequest, profile: hyperswitch_domain_models::business_profile::Profile, } impl SubscriptionHandler { pub fn new( state: SessionState, merchant_context: MerchantContext, request: subscription_types::ConfirmSubscriptionRequest, profile: hyperswitch_domain_models::business_profile::Profile, ) -> Self { Self { state, merchant_context, request, profile, } } pub async fn find_subscription( &self, subscription_id: String, ) -> errors::RouterResult<SubscriptionWithHandler<'_>> { let subscription = self .state .store .find_by_merchant_id_subscription_id( self.merchant_context.get_merchant_account().get_id(), subscription_id.clone(), ) .await .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: format!("subscription not found for id: {subscription_id}"), })?; Ok(SubscriptionWithHandler { handler: self, subscription, profile: self.profile.clone(), }) } } pub struct SubscriptionWithHandler<'a> { handler: &'a SubscriptionHandler, subscription: diesel_models::subscription::Subscription, profile: hyperswitch_domain_models::business_profile::Profile, } impl<'a> SubscriptionWithHandler<'a> { fn generate_response( &self, invoice: &diesel_models::invoice::Invoice, // _payment_response: &subscription_types::PaymentResponseData, status: subscription_response_types::SubscriptionStatus, ) -> errors::RouterResult<subscription_types::ConfirmSubscriptionResponse> { Ok(subscription_types::ConfirmSubscriptionResponse { id: self.subscription.id.clone(), merchant_reference_id: self.subscription.merchant_reference_id.clone(), status: SubscriptionStatus::from(status), plan_id: None, profile_id: self.subscription.profile_id.to_owned(), payment: None, customer_id: Some(self.subscription.customer_id.clone()), price_id: None, coupon: None, invoice: Some(subscription_types::Invoice { id: invoice.id.clone(), subscription_id: invoice.subscription_id.clone(), merchant_id: invoice.merchant_id.clone(), profile_id: invoice.profile_id.clone(), merchant_connector_id: invoice.merchant_connector_id.clone(), payment_intent_id: invoice.payment_intent_id.clone(), payment_method_id: invoice.payment_method_id.clone(), customer_id: invoice.customer_id.clone(), amount: invoice.amount, currency: api_enums::Currency::from_str(invoice.currency.as_str()) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "currency", }) .attach_printable(format!( "unable to parse currency name {currency:?}", currency = invoice.currency ))?, status: invoice.status.clone(), }), }) } async fn update_subscription_status(&mut self, status: String) -> errors::RouterResult<()> { let db = self.handler.state.store.as_ref(); let updated_subscription = db .update_subscription_entry( self.handler .merchant_context .get_merchant_account() .get_id(), self.subscription.id.get_string_repr().to_string(), diesel_models::subscription::SubscriptionUpdate::new(None, Some(status)), ) .await .change_context(errors::ApiErrorResponse::SubscriptionError { operation: "Subscription Update".to_string(), }) .attach_printable("subscriptions: unable to update subscription entry in database")?; self.subscription = updated_subscription; Ok(()) } pub async fn get_billing_handler( &self, customer: hyperswitch_domain_models::customer::Customer, ) -> errors::RouterResult<BillingHandler> { let mca_id = self.profile.get_billing_processor_id()?; let billing_processor_mca = self .handler .state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( &(&self.handler.state).into(), self.handler .merchant_context .get_merchant_account() .get_id(), &mca_id, self.handler.merchant_context.get_merchant_key_store(), ) .await .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: mca_id.get_string_repr().to_string(), })?; let connector_name = billing_processor_mca.connector_name.clone(); let auth_type: hyperswitch_domain_models::router_data::ConnectorAuthType = payments_core::helpers::MerchantConnectorAccountType::DbVal(Box::new( billing_processor_mca.clone(), )) .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_account_details".to_string(), expected_format: "auth_type and api_key".to_string(), })?; let connector_data = api_types::ConnectorData::get_connector_by_name( &self.handler.state.conf.connectors, &connector_name, api_types::GetToken::Connector, Some(billing_processor_mca.get_id()), ) .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven) .attach_printable( "invalid connector name received in billing merchant connector account", )?; let connector_enum = common_enums::connector_enums::Connector::from_str(connector_name.as_str()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!("unable to parse connector name {connector_name:?}"))?; let connector_params = hyperswitch_domain_models::connector_endpoints::Connectors::get_connector_params( &self.handler.state.conf.connectors, connector_enum, ) .change_context(errors::ApiErrorResponse::ConfigNotFound) .attach_printable(format!( "cannot find connector params for this connector {connector_name} in this flow", ))?; Ok(BillingHandler { subscription: self.subscription.clone(), auth_type, connector_data, connector_params, request: self.handler.request.clone(), connector_metadata: billing_processor_mca.metadata.clone(), customer, }) } pub async fn get_invoice_handler(&self) -> errors::RouterResult<InvoiceHandler> { Ok(InvoiceHandler { subscription: self.subscription.clone(), }) } } pub struct BillingHandler { subscription: diesel_models::subscription::Subscription, auth_type: hyperswitch_domain_models::router_data::ConnectorAuthType, connector_data: api_types::ConnectorData, connector_params: hyperswitch_domain_models::connector_endpoints::ConnectorParams, connector_metadata: Option<pii::SecretSerdeValue>, customer: hyperswitch_domain_models::customer::Customer, request: subscription_types::ConfirmSubscriptionRequest, } pub struct InvoiceHandler { subscription: diesel_models::subscription::Subscription, } #[allow(clippy::todo)] impl InvoiceHandler { #[allow(clippy::too_many_arguments)] pub async fn create_invoice_entry( self, state: &SessionState, merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, payment_intent_id: Option<common_utils::id_type::PaymentId>, amount: common_utils::types::MinorUnit, currency: String, status: common_enums::connector_enums::InvoiceStatus, provider_name: common_enums::connector_enums::Connector, metadata: Option<pii::SecretSerdeValue>, ) -> errors::RouterResult<diesel_models::invoice::Invoice> { let invoice_new = diesel_models::invoice::InvoiceNew::new( self.subscription.id.to_owned(), self.subscription.merchant_id.to_owned(), self.subscription.profile_id.to_owned(), merchant_connector_id, payment_intent_id, self.subscription.payment_method_id.clone(), self.subscription.customer_id.to_owned(), amount, currency, status, provider_name, metadata, ); let invoice = state .store .insert_invoice_entry(invoice_new) .await .change_context(errors::ApiErrorResponse::SubscriptionError { operation: "Subscription Confirm".to_string(), }) .attach_printable("invoices: unable to insert invoice entry to database")?; Ok(invoice) } pub async fn create_cit_payment( &self, ) -> errors::RouterResult<subscription_types::PaymentResponseData> { // Create a CIT payment for the invoice todo!("Create a CIT payment for the invoice") } pub async fn create_invoice_record_back_job( &self, // _invoice: &subscription_types::Invoice, _payment_response: &subscription_types::PaymentResponseData, ) -> errors::RouterResult<()> { // Create an invoice job entry based on payment status todo!("Create an invoice job entry based on payment status") } } #[allow(clippy::todo)] impl BillingHandler { pub async fn create_customer_on_connector( &self, state: &SessionState, ) -> errors::RouterResult<ConnectorCustomerResponseData> { let customer_req = ConnectorCustomerData { email: self.customer.email.clone().map(pii::Email::from), payment_method_data: self .request .payment_details .payment_method_data .payment_method_data .clone() .map(|pmd| pmd.into()), description: None, phone: None, name: None, preprocessing_id: None, split_payments: None, setup_future_usage: None, customer_acceptance: None, customer_id: Some(self.subscription.customer_id.to_owned()), billing_address: self .request .billing_address .as_ref() .and_then(|add| add.address.clone()) .and_then(|addr| addr.into()), }; let router_data = self.build_router_data( state, customer_req, SubscriptionCustomerData { connector_meta_data: self.connector_metadata.clone(), }, )?; let connector_integration = self.connector_data.connector.get_connector_integration(); let response = Box::pin(self.call_connector( state, router_data, "create customer on connector", connector_integration, )) .await?; match response { Ok(response_data) => match response_data { PaymentsResponseData::ConnectorCustomerResponse(customer_response) => { Ok(customer_response) } _ => Err(errors::ApiErrorResponse::SubscriptionError { operation: "Subscription Customer Create".to_string(), } .into()), }, Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: self.connector_data.connector_name.to_string(), status_code: err.status_code, reason: err.reason, } .into()), } } pub async fn create_subscription_on_connector( &self, state: &SessionState, ) -> errors::RouterResult<subscription_response_types::SubscriptionCreateResponse> { let subscription_item = subscription_request_types::SubscriptionItem { item_price_id: self.request.get_item_price_id().change_context( errors::ApiErrorResponse::MissingRequiredField { field_name: "item_price_id", }, )?, quantity: Some(1), }; let subscription_req = subscription_request_types::SubscriptionCreateRequest { subscription_id: self.subscription.id.to_owned(), customer_id: self.subscription.customer_id.to_owned(), subscription_items: vec![subscription_item], billing_address: self.request.get_billing_address().change_context( errors::ApiErrorResponse::MissingRequiredField { field_name: "billing_address", }, )?, auto_collection: subscription_request_types::SubscriptionAutoCollection::Off, connector_params: self.connector_params.clone(), }; let router_data = self.build_router_data( state, subscription_req, SubscriptionCreateData { connector_meta_data: self.connector_metadata.clone(), }, )?; let connector_integration = self.connector_data.connector.get_connector_integration(); let response = self .call_connector( state, router_data, "create subscription on connector", connector_integration, ) .await?; match response { Ok(response_data) => Ok(response_data), Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: self.connector_data.connector_name.to_string(), status_code: err.status_code, reason: err.reason, } .into()), } } async fn call_connector<F, ResourceCommonData, Req, Resp>( &self, state: &SessionState, router_data: hyperswitch_domain_models::router_data_v2::RouterDataV2< F, ResourceCommonData, Req, Resp, >, operation_name: &str, connector_integration: hyperswitch_interfaces::connector_integration_interface::BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>, ) -> errors::RouterResult<Result<Resp, hyperswitch_domain_models::router_data::ErrorResponse>> where F: Clone + std::fmt::Debug + 'static, Req: Clone + std::fmt::Debug + 'static, Resp: Clone + std::fmt::Debug + 'static, ResourceCommonData: hyperswitch_interfaces::connector_integration_interface::RouterDataConversion< F, Req, Resp, > + Clone + 'static, { let old_router_data = ResourceCommonData::to_old_router_data(router_data).change_context( errors::ApiErrorResponse::SubscriptionError { operation: { operation_name.to_string() }, }, )?; let router_resp = services::execute_connector_processing_step( state, connector_integration, &old_router_data, payments_core::CallConnectorAction::Trigger, None, None, ) .await .change_context(errors::ApiErrorResponse::SubscriptionError { operation: operation_name.to_string(), }) .attach_printable(format!( "Failed while in subscription operation: {operation_name}" ))?; Ok(router_resp.response) } fn build_router_data<F, ResourceCommonData, Req, Resp>( &self, state: &SessionState, req: Req, resource_common_data: ResourceCommonData, ) -> errors::RouterResult< hyperswitch_domain_models::router_data_v2::RouterDataV2<F, ResourceCommonData, Req, Resp>, > { Ok(hyperswitch_domain_models::router_data_v2::RouterDataV2 { flow: std::marker::PhantomData, connector_auth_type: self.auth_type.clone(), resource_common_data, tenant_id: state.tenant.tenant_id.clone(), request: req, response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), }) } }
crates/router/src/core/subscription.rs
router
full_file
null
null
null
4,354
null
null
null
null
null
null
null
// File: crates/hyperswitch_domain_models/src/cards_info.rs // Module: hyperswitch_domain_models use common_utils::errors; use diesel_models::cards_info; #[async_trait::async_trait] pub trait CardsInfoInterface { type Error; async fn get_card_info( &self, _card_iin: &str, ) -> errors::CustomResult<Option<cards_info::CardInfo>, Self::Error>; async fn add_card_info( &self, data: cards_info::CardInfo, ) -> errors::CustomResult<cards_info::CardInfo, Self::Error>; async fn update_card_info( &self, card_iin: String, data: cards_info::UpdateCardInfo, ) -> errors::CustomResult<cards_info::CardInfo, Self::Error>; }
crates/hyperswitch_domain_models/src/cards_info.rs
hyperswitch_domain_models
full_file
null
null
null
177
null
null
null
null
null
null
null
// Trait: DomainType // File: crates/storage_impl/src/kv_router_store.rs // Module: storage_impl pub trait DomainType: Debug + Sync + Conversion
crates/storage_impl/src/kv_router_store.rs
storage_impl
trait_definition
null
null
null
35
null
null
DomainType
null
null
null
null
// Implementation: impl super::disputes::filters::DisputeFilterAnalytics for for ClickhouseClient // File: crates/analytics/src/clickhouse.rs // Module: analytics // Methods: 0 total (0 public) impl super::disputes::filters::DisputeFilterAnalytics for for ClickhouseClient
crates/analytics/src/clickhouse.rs
analytics
impl_block
null
null
null
67
null
ClickhouseClient
super::disputes::filters::DisputeFilterAnalytics for
0
0
null
null
// Struct: CardDetailUpdate // File: crates/api_models/src/payment_methods.rs // Module: api_models // Implementations: 2 pub struct CardDetailUpdate
crates/api_models/src/payment_methods.rs
api_models
struct_definition
CardDetailUpdate
2
[]
36
null
null
null
null
null
null
null
// Implementation: impl Default for for Memoization // File: crates/hyperswitch_constraint_graph/src/types.rs // Module: hyperswitch_constraint_graph // Methods: 1 total (0 public) impl Default for for Memoization
crates/hyperswitch_constraint_graph/src/types.rs
hyperswitch_constraint_graph
impl_block
null
null
null
48
null
Memoization
Default for
1
0
null
null
// Implementation: impl Serialize for for StrongSecret // File: crates/masking/src/serde.rs // Module: masking // Methods: 1 total (0 public) impl Serialize for for StrongSecret
crates/masking/src/serde.rs
masking
impl_block
null
null
null
42
null
StrongSecret
Serialize for
1
0
null
null
// File: crates/router/tests/connectors/tokenex.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 TokenexTest; impl ConnectorActions for TokenexTest {} impl utils::Connector for TokenexTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Tokenex; utils::construct_connector_data_old( Box::new(&Tokenex), types::Connector::Tokenex, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .tokenex .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "tokenex".to_string() } } static CONNECTOR: TokenexTest = TokenexTest {}; 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/tokenex.rs
router
full_file
null
null
null
2,929
null
null
null
null
null
null
null
// Function: generate_network_token // File: crates/router/src/core/payment_methods/network_tokenization.rs // Module: router pub fn generate_network_token( state: &routes::SessionState, payload_bytes: &[u8], customer_id: id_type::GlobalCustomerId, tokenization_service: &settings::NetworkTokenizationService, ) -> CustomResult< (pm_types::GenerateNetworkTokenResponsePayload, String), errors::NetworkTokenizationError, >
crates/router/src/core/payment_methods/network_tokenization.rs
router
function_signature
null
null
null
99
generate_network_token
null
null
null
null
null
null
// Struct: Airwallex // File: crates/hyperswitch_connectors/src/connectors/airwallex.rs // Module: hyperswitch_connectors // Implementations: 20 // Traits: ConnectorCommon, ConnectorValidation, api::Payment, api::PaymentsPreProcessing, api::PaymentsCompleteAuthorize, api::MandateSetup, api::PaymentToken, api::ConnectorAccessToken, api::PaymentAuthorize, api::PaymentSync, api::PaymentCapture, api::PaymentSession, api::PaymentVoid, api::Refund, api::RefundExecute, api::RefundSync, IncomingWebhook, ConnectorRedirectResponse, ConnectorSpecifications pub struct Airwallex
crates/hyperswitch_connectors/src/connectors/airwallex.rs
hyperswitch_connectors
struct_definition
Airwallex
20
[ "ConnectorCommon", "ConnectorValidation", "api::Payment", "api::PaymentsPreProcessing", "api::PaymentsCompleteAuthorize", "api::MandateSetup", "api::PaymentToken", "api::ConnectorAccessToken", "api::PaymentAuthorize", "api::PaymentSync", "api::PaymentCapture", "api::PaymentSession", "api::PaymentVoid", "api::Refund", "api::RefundExecute", "api::RefundSync", "IncomingWebhook", "ConnectorRedirectResponse", "ConnectorSpecifications" ]
142
null
null
null
null
null
null
null
// Struct: RefundResponse // File: crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct RefundResponse
crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
hyperswitch_connectors
struct_definition
RefundResponse
0
[]
48
null
null
null
null
null
null
null
// Struct: WebhookResponseData // File: crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct WebhookResponseData
crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs
hyperswitch_connectors
struct_definition
WebhookResponseData
0
[]
49
null
null
null
null
null
null
null
// Implementation: impl ApiEventMetric for for FrmFilterValue // File: crates/api_models/src/analytics.rs // Module: api_models // Methods: 0 total (0 public) impl ApiEventMetric for for FrmFilterValue
crates/api_models/src/analytics.rs
api_models
impl_block
null
null
null
49
null
FrmFilterValue
ApiEventMetric for
0
0
null
null
// Implementation: impl Fiuu // File: crates/hyperswitch_connectors/src/connectors/fiuu.rs // Module: hyperswitch_connectors // Methods: 1 total (1 public) impl Fiuu
crates/hyperswitch_connectors/src/connectors/fiuu.rs
hyperswitch_connectors
impl_block
null
null
null
48
null
Fiuu
null
1
1
null
null
// File: crates/router/src/core/payment_methods/tokenize.rs // Module: router // Public functions: 3 // Public structs: 4 use actix_multipart::form::{bytes::Bytes, text::Text, MultipartForm}; use api_models::{enums as api_enums, payment_methods as payment_methods_api}; use cards::CardNumber; use common_utils::{ crypto::Encryptable, id_type, transformers::{ForeignFrom, ForeignTryFrom}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::router_request_types as domain_request_types; use masking::{ExposeInterface, Secret}; use router_env::logger; use crate::{ core::payment_methods::{ cards::{add_card_to_hs_locker, create_encrypted_data, tokenize_card_flow}, network_tokenization, transformers as pm_transformers, }, errors::{self, RouterResult}, services, types::{api, domain, payment_methods as pm_types}, SessionState, }; pub mod card_executor; pub mod payment_method_executor; pub use card_executor::*; pub use payment_method_executor::*; use rdkafka::message::ToBytes; #[derive(Debug, MultipartForm)] pub struct CardNetworkTokenizeForm { #[multipart(limit = "1MB")] pub file: Bytes, pub merchant_id: Text<id_type::MerchantId>, } pub fn parse_csv( merchant_id: &id_type::MerchantId, data: &[u8], ) -> csv::Result<Vec<payment_methods_api::CardNetworkTokenizeRequest>> { let mut csv_reader = csv::ReaderBuilder::new() .has_headers(true) .from_reader(data); let mut records = Vec::new(); let mut id_counter = 0; for (i, result) in csv_reader .deserialize::<domain::CardNetworkTokenizeRecord>() .enumerate() { match result { Ok(mut record) => { logger::info!("Parsed Record (line {}): {:?}", i + 1, record); id_counter += 1; record.line_number = Some(id_counter); record.merchant_id = Some(merchant_id.clone()); match payment_methods_api::CardNetworkTokenizeRequest::foreign_try_from(record) { Ok(record) => { records.push(record); } Err(err) => { logger::error!("Error parsing line {}: {}", i + 1, err.to_string()); } } } Err(e) => logger::error!("Error parsing line {}: {}", i + 1, e), } } Ok(records) } pub fn get_tokenize_card_form_records( form: CardNetworkTokenizeForm, ) -> Result< ( id_type::MerchantId, Vec<payment_methods_api::CardNetworkTokenizeRequest>, ), errors::ApiErrorResponse, > { match parse_csv(&form.merchant_id, form.file.data.to_bytes()) { Ok(records) => { logger::info!("Parsed a total of {} records", records.len()); Ok((form.merchant_id.0, records)) } Err(e) => { logger::error!("Failed to parse CSV: {:?}", e); Err(errors::ApiErrorResponse::PreconditionFailed { message: e.to_string(), }) } } } pub async fn tokenize_cards( state: &SessionState, records: Vec<payment_methods_api::CardNetworkTokenizeRequest>, merchant_context: &domain::MerchantContext, ) -> errors::RouterResponse<Vec<payment_methods_api::CardNetworkTokenizeResponse>> { use futures::stream::StreamExt; // Process all records in parallel let responses = futures::stream::iter(records.into_iter()) .map(|record| async move { let tokenize_request = record.data.clone(); let customer = record.customer.clone(); Box::pin(tokenize_card_flow( state, domain::CardNetworkTokenizeRequest::foreign_from(record), merchant_context, )) .await .unwrap_or_else(|e| { let err = e.current_context(); payment_methods_api::CardNetworkTokenizeResponse { tokenization_data: Some(tokenize_request), error_code: Some(err.error_code()), error_message: Some(err.error_message()), card_tokenized: false, payment_method_response: None, customer: Some(customer), } }) }) .buffer_unordered(10) .collect() .await; // Return the final response Ok(services::ApplicationResponse::Json(responses)) } // Data types type NetworkTokenizationResponse = (pm_types::CardNetworkTokenResponsePayload, Option<String>); pub struct StoreLockerResponse { pub store_card_resp: pm_transformers::StoreCardRespPayload, pub store_token_resp: pm_transformers::StoreCardRespPayload, } // Builder pub struct NetworkTokenizationBuilder<'a, S: State> { /// Current state state: std::marker::PhantomData<S>, /// Customer details pub customer: Option<&'a api::CustomerDetails>, /// Card details pub card: Option<domain::CardDetail>, /// CVC pub card_cvc: Option<Secret<String>>, /// Network token details pub network_token: Option<&'a pm_types::CardNetworkTokenResponsePayload>, /// Stored card details pub stored_card: Option<&'a pm_transformers::StoreCardRespPayload>, /// Stored token details pub stored_token: Option<&'a pm_transformers::StoreCardRespPayload>, /// Payment method response pub payment_method_response: Option<api::PaymentMethodResponse>, /// Card network tokenization status pub card_tokenized: bool, /// Error code pub error_code: Option<&'a String>, /// Error message pub error_message: Option<&'a String>, } // Async executor pub struct CardNetworkTokenizeExecutor<'a, D> { pub state: &'a SessionState, pub merchant_account: &'a domain::MerchantAccount, key_store: &'a domain::MerchantKeyStore, data: &'a D, customer: &'a domain_request_types::CustomerDetails, } // State machine pub trait State {} pub trait TransitionTo<S: State> {} // Trait for network tokenization #[async_trait::async_trait] pub trait NetworkTokenizationProcess<'a, D> { fn new( state: &'a SessionState, merchant_context: &'a domain::MerchantContext, data: &'a D, customer: &'a domain_request_types::CustomerDetails, ) -> Self; async fn encrypt_card( &self, card_details: &domain::CardDetail, saved_to_locker: bool, ) -> RouterResult<Encryptable<Secret<serde_json::Value>>>; async fn encrypt_network_token( &self, network_token_details: &NetworkTokenizationResponse, card_details: &domain::CardDetail, saved_to_locker: bool, ) -> RouterResult<Encryptable<Secret<serde_json::Value>>>; async fn fetch_bin_details_and_validate_card_network( &self, card_number: CardNumber, card_issuer: Option<&String>, card_network: Option<&api_enums::CardNetwork>, card_type: Option<&api_models::payment_methods::CardType>, card_issuing_country: Option<&String>, ) -> RouterResult<Option<diesel_models::CardInfo>>; fn validate_card_network( &self, optional_card_network: Option<&api_enums::CardNetwork>, ) -> RouterResult<()>; async fn tokenize_card( &self, customer_id: &id_type::CustomerId, card: &domain::CardDetail, optional_cvc: Option<Secret<String>>, ) -> RouterResult<NetworkTokenizationResponse>; async fn store_network_token_in_locker( &self, network_token: &NetworkTokenizationResponse, customer_id: &id_type::CustomerId, card_holder_name: Option<Secret<String>>, nick_name: Option<Secret<String>>, ) -> RouterResult<pm_transformers::StoreCardRespPayload>; } // Generic implementation #[async_trait::async_trait] impl<'a, D> NetworkTokenizationProcess<'a, D> for CardNetworkTokenizeExecutor<'a, D> where D: Send + Sync + 'static, { fn new( state: &'a SessionState, merchant_context: &'a domain::MerchantContext, data: &'a D, customer: &'a domain_request_types::CustomerDetails, ) -> Self { Self { data, customer, state, merchant_account: merchant_context.get_merchant_account(), key_store: merchant_context.get_merchant_key_store(), } } async fn encrypt_card( &self, card_details: &domain::CardDetail, saved_to_locker: bool, ) -> RouterResult<Encryptable<Secret<serde_json::Value>>> { let pm_data = api::PaymentMethodsData::Card(api::CardDetailsPaymentMethod { last4_digits: Some(card_details.card_number.get_last4()), expiry_month: Some(card_details.card_exp_month.clone()), expiry_year: Some(card_details.card_exp_year.clone()), card_isin: Some(card_details.card_number.get_card_isin()), nick_name: card_details.nick_name.clone(), card_holder_name: card_details.card_holder_name.clone(), issuer_country: card_details.card_issuing_country.clone(), card_issuer: card_details.card_issuer.clone(), card_network: card_details.card_network.clone(), card_type: card_details.card_type.clone(), saved_to_locker, co_badged_card_data: card_details .co_badged_card_data .as_ref() .map(|data| data.into()), }); create_encrypted_data(&self.state.into(), self.key_store, pm_data) .await .inspect_err(|err| logger::info!("Error encrypting payment method data: {:?}", err)) .change_context(errors::ApiErrorResponse::InternalServerError) } async fn encrypt_network_token( &self, network_token_details: &NetworkTokenizationResponse, card_details: &domain::CardDetail, saved_to_locker: bool, ) -> RouterResult<Encryptable<Secret<serde_json::Value>>> { let network_token = &network_token_details.0; let token_data = api::PaymentMethodsData::Card(api::CardDetailsPaymentMethod { last4_digits: Some(network_token.token_last_four.clone()), expiry_month: Some(network_token.token_expiry_month.clone()), expiry_year: Some(network_token.token_expiry_year.clone()), card_isin: Some(network_token.token_isin.clone()), nick_name: card_details.nick_name.clone(), card_holder_name: card_details.card_holder_name.clone(), issuer_country: card_details.card_issuing_country.clone(), card_issuer: card_details.card_issuer.clone(), card_network: card_details.card_network.clone(), card_type: card_details.card_type.clone(), saved_to_locker, co_badged_card_data: None, }); create_encrypted_data(&self.state.into(), self.key_store, token_data) .await .inspect_err(|err| logger::info!("Error encrypting network token data: {:?}", err)) .change_context(errors::ApiErrorResponse::InternalServerError) } async fn fetch_bin_details_and_validate_card_network( &self, card_number: CardNumber, card_issuer: Option<&String>, card_network: Option<&api_enums::CardNetwork>, card_type: Option<&api_models::payment_methods::CardType>, card_issuing_country: Option<&String>, ) -> RouterResult<Option<diesel_models::CardInfo>> { let db = &*self.state.store; if card_issuer.is_some() && card_network.is_some() && card_type.is_some() && card_issuing_country.is_some() { self.validate_card_network(card_network)?; return Ok(None); } db.get_card_info(&card_number.get_card_isin()) .await .attach_printable("Failed to perform BIN lookup") .change_context(errors::ApiErrorResponse::InternalServerError)? .map(|card_info| { self.validate_card_network(card_info.card_network.as_ref())?; Ok(card_info) }) .transpose() } async fn tokenize_card( &self, customer_id: &id_type::CustomerId, card: &domain::CardDetail, optional_cvc: Option<Secret<String>>, ) -> RouterResult<NetworkTokenizationResponse> { network_tokenization::make_card_network_tokenization_request( self.state, card, optional_cvc, customer_id, ) .await .map_err(|err| { logger::error!("Failed to tokenize card with the network: {:?}", err); report!(errors::ApiErrorResponse::InternalServerError) }) } fn validate_card_network( &self, optional_card_network: Option<&api_enums::CardNetwork>, ) -> RouterResult<()> { optional_card_network.map_or( Err(report!(errors::ApiErrorResponse::NotSupported { message: "Unknown card network".to_string() })), |card_network| { if self .state .conf .network_tokenization_supported_card_networks .card_networks .contains(card_network) { Ok(()) } else { Err(report!(errors::ApiErrorResponse::NotSupported { message: format!( "Network tokenization for {card_network} is not supported", ) })) } }, ) } async fn store_network_token_in_locker( &self, network_token: &NetworkTokenizationResponse, customer_id: &id_type::CustomerId, card_holder_name: Option<Secret<String>>, nick_name: Option<Secret<String>>, ) -> RouterResult<pm_transformers::StoreCardRespPayload> { let network_token = &network_token.0; let merchant_id = self.merchant_account.get_id(); let locker_req = pm_transformers::StoreLockerReq::LockerCard(pm_transformers::StoreCardReq { merchant_id: merchant_id.clone(), merchant_customer_id: customer_id.clone(), card: payment_methods_api::Card { card_number: network_token.token.clone(), card_exp_month: network_token.token_expiry_month.clone(), card_exp_year: network_token.token_expiry_year.clone(), card_brand: Some(network_token.card_brand.to_string()), card_isin: Some(network_token.token_isin.clone()), name_on_card: card_holder_name, nick_name: nick_name.map(|nick_name| nick_name.expose()), }, requestor_card_reference: None, ttl: self.state.conf.locker.ttl_for_storage_in_secs, }); let stored_resp = add_card_to_hs_locker( self.state, &locker_req, customer_id, api_enums::LockerChoice::HyperswitchCardVault, ) .await .inspect_err(|err| logger::info!("Error adding card in locker: {:?}", err)) .change_context(errors::ApiErrorResponse::InternalServerError)?; Ok(stored_resp) } }
crates/router/src/core/payment_methods/tokenize.rs
router
full_file
null
null
null
3,279
null
null
null
null
null
null
null
// Struct: PayuErrorResponse // File: crates/hyperswitch_connectors/src/connectors/payu/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PayuErrorResponse
crates/hyperswitch_connectors/src/connectors/payu/transformers.rs
hyperswitch_connectors
struct_definition
PayuErrorResponse
0
[]
47
null
null
null
null
null
null
null
// Struct: MerchantAccountUpdate // File: crates/api_models/src/admin.rs // Module: api_models // Implementations: 2 pub struct MerchantAccountUpdate
crates/api_models/src/admin.rs
api_models
struct_definition
MerchantAccountUpdate
2
[]
35
null
null
null
null
null
null
null
// Struct: ChargebeeWebhookBody // File: crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs // Module: hyperswitch_connectors // Implementations: 1 pub struct ChargebeeWebhookBody
crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs
hyperswitch_connectors
struct_definition
ChargebeeWebhookBody
1
[]
52
null
null
null
null
null
null
null
// File: crates/hyperswitch_connectors/src/connectors/worldpayxml/transformers.rs // Module: hyperswitch_connectors // Public structs: 6 use common_enums::enums; use common_utils::types::StringMinorUnit; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{Card, PaymentMethodData}, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::{ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData, ResponseId, }, router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{consts, errors}; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ self as connector_utils, CardData, PaymentsAuthorizeRequestData, PaymentsSyncRequestData, RouterData as _, }, }; pub struct WorldpayxmlRouterData<T> { pub amount: StringMinorUnit, pub router_data: T, } impl<T> From<(StringMinorUnit, T)> for WorldpayxmlRouterData<T> { fn from((amount, item): (StringMinorUnit, T)) -> Self { Self { amount, router_data: item, } } } pub mod worldpayxml_constants { pub const WORLDPAYXML_VERSION: &str = "1.4"; pub const XML_VERSION: &str = "1.0"; pub const XML_ENCODING: &str = "UTF-8"; pub const WORLDPAYXML_DOC_TYPE: &str = r#"paymentService PUBLIC "-//Worldpay//DTD Worldpay PaymentService v1//EN" "http://dtd.worldpay.com/paymentService_v1.dtd""#; } #[derive(Debug, Serialize, Deserialize)] #[serde(rename = "paymentService")] pub struct PaymentService { #[serde(rename = "@version")] version: String, #[serde(rename = "@merchantCode")] merchant_code: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] submit: Option<Submit>, #[serde(skip_serializing_if = "Option::is_none")] pub reply: Option<Reply>, #[serde(skip_serializing_if = "Option::is_none")] inquiry: Option<Inquiry>, #[serde(skip_serializing_if = "Option::is_none")] modify: Option<Modify>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct Modify { order_modification: OrderModification, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct OrderModification { #[serde(rename = "@orderCode")] order_code: String, #[serde(skip_serializing_if = "Option::is_none")] capture: Option<CaptureRequest>, #[serde(skip_serializing_if = "Option::is_none")] cancel: Option<CancelRequest>, #[serde(skip_serializing_if = "Option::is_none")] refund: Option<RefundRequest>, } #[derive(Debug, Serialize, Deserialize)] struct RefundRequest { amount: WorldpayXmlAmount, } #[derive(Debug, Serialize, Deserialize)] struct CancelRequest {} #[derive(Debug, Serialize, Deserialize)] struct CaptureRequest { amount: WorldpayXmlAmount, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct Inquiry { order_inquiry: OrderInquiry, } #[derive(Debug, Serialize, Deserialize)] struct OrderInquiry { #[serde(rename = "@orderCode")] order_code: String, } #[derive(Debug, Serialize, Deserialize)] struct Submit { order: Order, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct Reply { order_status: Option<OrderStatus>, pub error: Option<WorldpayXmlErrorResponse>, ok: Option<OkResponse>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] struct OkResponse { capture_received: Option<ModifyRequestReceived>, cancel_received: Option<ModifyRequestReceived>, refund_received: Option<ModifyRequestReceived>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] struct ModifyRequestReceived { #[serde(rename = "@orderCode")] order_code: String, amount: Option<WorldpayXmlAmount>, } #[derive(Debug, Deserialize, Serialize)] pub struct WorldpayXmlErrorResponse { #[serde(rename = "@code")] pub code: String, #[serde(rename = "$value")] pub message: String, } #[derive(Debug, Deserialize, Serialize)] struct OrderStatus { #[serde(rename = "@orderCode")] order_code: String, payment: Option<Payment>, error: Option<WorldpayXmlErrorResponse>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] struct Payment { payment_method: String, amount: WorldpayXmlAmount, last_event: LastEvent, #[serde(rename = "AuthorisationId")] authorisation_id: Option<AuthorisationId>, scheme_response: Option<SchemeResponse>, payment_method_detail: Option<PaymentMethodDetail>, #[serde(rename = "CVCResultCode")] cvc_result_code: Option<ResultCode>, #[serde(rename = "AVSResultCode")] avs_result_code: Option<ResultCode>, #[serde(rename = "AAVAddressResultCode")] aav_address_result_code: Option<ResultCode>, #[serde(rename = "AAVPostcodeResultCode")] aav_postcode_result_code: Option<ResultCode>, #[serde(rename = "AAVCardholderNameResultCode")] aav_cardholder_name_result_code: Option<ResultCode>, #[serde(rename = "AAVTelephoneResultCode")] aav_telephone_result_code: Option<ResultCode>, #[serde(rename = "AAVEmailResultCode")] aav_email_result_code: Option<ResultCode>, issuer_country_code: Option<String>, issuer_name: Option<String>, balance: Option<Vec<Balance>>, card_holder_name: Option<String>, #[serde(rename = "ISO8583ReturnCode")] return_code: Option<ReturnCode>, } #[derive(Debug, Deserialize, Serialize)] struct ReturnCode { #[serde(rename = "@description")] description: String, #[serde(rename = "@code")] code: String, } #[derive(Debug, Deserialize, Serialize)] struct ResultCode { #[serde(rename = "@description")] description: String, } #[derive(Debug, Deserialize, Serialize)] struct Balance { #[serde(rename = "@accountType")] account_type: String, amount: WorldpayXmlAmount, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] struct PaymentMethodDetail { card: CardResponse, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] struct CardResponse { #[serde(rename = "@number")] number: Option<Secret<String>>, #[serde(rename = "@type")] card_type: String, expiry_date: Option<ExpiryDate>, } #[derive(Debug, Deserialize, Serialize)] struct AuthorisationId { #[serde(rename = "@id")] id: Secret<String>, } #[derive(Debug, Clone, Copy, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] enum LastEvent { Authorised, Refused, Cancelled, Captured, Settled, SentForAuthorisation, SentForRefund, Refunded, RefundRequested, RefundFailed, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] struct SchemeResponse { transaction_identifier: String, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct Order { #[serde(rename = "@orderCode")] order_code: String, #[serde(rename = "@captureDelay")] capture_delay: AutoCapture, description: String, amount: WorldpayXmlAmount, payment_details: PaymentDetails, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] enum AutoCapture { Off, #[serde(rename = "0")] On, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct WorldpayXmlAmount { #[serde(rename = "@value")] value: StringMinorUnit, #[serde(rename = "@currencyCode")] currency_code: api_models::enums::Currency, #[serde(rename = "@exponent")] exponent: String, } #[derive(Debug, Serialize, Deserialize)] struct PaymentDetails { #[serde(rename = "CARD-SSL")] card_ssl: CardSSL, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] struct CardSSL { card_number: cards::CardNumber, expiry_date: ExpiryDate, card_holder_name: Option<Secret<String>>, cvc: Secret<String>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename = "expiryDate")] struct ExpiryDate { date: Date, } #[derive(Debug, Deserialize, Serialize)] struct Date { #[serde(rename = "@month")] month: Secret<String>, #[serde(rename = "@year")] year: Secret<String>, } impl TryFrom<&Card> for PaymentDetails { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(card_data: &Card) -> Result<Self, Self::Error> { Ok(Self { card_ssl: CardSSL { card_number: card_data.card_number.clone(), expiry_date: ExpiryDate { date: Date { month: card_data.get_card_expiry_month_2_digit()?, year: card_data.get_expiry_year_4_digit(), }, }, card_holder_name: card_data.card_holder_name.to_owned(), cvc: card_data.card_cvc.to_owned(), }, }) } } impl TryFrom<(&WorldpayxmlRouterData<&PaymentsAuthorizeRouterData>, &Card)> for PaymentService { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: (&WorldpayxmlRouterData<&PaymentsAuthorizeRouterData>, &Card), ) -> Result<Self, Self::Error> { let authorize_data = item.0; let card_data = item.1; let auth = WorldpayxmlAuthType::try_from(&authorize_data.router_data.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let order_code = authorize_data .router_data .connector_request_reference_id .to_owned(); let capture_delay = if authorize_data.router_data.request.is_auto_capture()? { AutoCapture::On } else { AutoCapture::Off }; let description = authorize_data.router_data.description.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "description", }, )?; let exponent = authorize_data .router_data .request .currency .number_of_digits_after_decimal_point() .to_string(); let amount = WorldpayXmlAmount { currency_code: authorize_data.router_data.request.currency.to_owned(), exponent, value: authorize_data.amount.to_owned(), }; let payment_details = PaymentDetails::try_from(card_data)?; let submit = Some(Submit { order: Order { order_code, capture_delay, description, amount, payment_details, }, }); Ok(Self { version: worldpayxml_constants::WORLDPAYXML_VERSION.to_string(), merchant_code: auth.merchant_code.clone(), submit, reply: None, inquiry: None, modify: None, }) } } impl TryFrom<&WorldpayxmlRouterData<&PaymentsAuthorizeRouterData>> for PaymentService { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &WorldpayxmlRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { if item.router_data.is_three_ds() { Err(errors::ConnectorError::NotSupported { message: "Card 3DS".to_string(), connector: "Worldpayxml", })? }; match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(req_card) => Self::try_from((item, &req_card)), _ => Err(errors::ConnectorError::NotImplemented( connector_utils::get_unimplemented_payment_method_error_message("Worldpayxml"), ))?, } } } impl TryFrom<&WorldpayxmlRouterData<&PaymentsCaptureRouterData>> for PaymentService { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &WorldpayxmlRouterData<&PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { let auth = WorldpayxmlAuthType::try_from(&item.router_data.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let modify = Some(Modify { order_modification: OrderModification { order_code: item.router_data.request.connector_transaction_id.clone(), capture: Some(CaptureRequest { amount: WorldpayXmlAmount { currency_code: item.router_data.request.currency.to_owned(), exponent: item .router_data .request .currency .number_of_digits_after_decimal_point() .to_string(), value: item.amount.to_owned(), }, }), cancel: None, refund: None, }, }); Ok(Self { version: worldpayxml_constants::WORLDPAYXML_VERSION.to_string(), merchant_code: auth.merchant_code.clone(), submit: None, reply: None, inquiry: None, modify, }) } } impl TryFrom<&PaymentsCancelRouterData> for PaymentService { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { let auth = WorldpayxmlAuthType::try_from(&item.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let modify = Some(Modify { order_modification: OrderModification { order_code: item.request.connector_transaction_id.clone(), capture: None, cancel: Some(CancelRequest {}), refund: None, }, }); Ok(Self { version: worldpayxml_constants::WORLDPAYXML_VERSION.to_string(), merchant_code: auth.merchant_code.clone(), submit: None, reply: None, inquiry: None, modify, }) } } impl<F> TryFrom<&WorldpayxmlRouterData<&RefundsRouterData<F>>> for PaymentService { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &WorldpayxmlRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { let auth = WorldpayxmlAuthType::try_from(&item.router_data.connector_auth_type)?; let modify = Some(Modify { order_modification: OrderModification { order_code: item.router_data.request.connector_transaction_id.clone(), capture: None, cancel: None, refund: Some(RefundRequest { amount: WorldpayXmlAmount { currency_code: item.router_data.request.currency.to_owned(), exponent: item .router_data .request .currency .number_of_digits_after_decimal_point() .to_string(), value: item.amount.to_owned(), }, }), }, }); Ok(Self { version: worldpayxml_constants::WORLDPAYXML_VERSION.to_string(), merchant_code: auth.merchant_code.clone(), submit: None, reply: None, inquiry: None, modify, }) } } impl TryFrom<RefundsResponseRouterData<Execute, PaymentService>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, PaymentService>, ) -> Result<Self, Self::Error> { let reply = item .response .reply .ok_or(errors::ConnectorError::UnexpectedResponseError( bytes::Bytes::from("Missing reply data".to_string()), ))?; if let Some(refund_received) = reply.ok.and_then(|ok| ok.refund_received) { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: refund_received.order_code, refund_status: enums::RefundStatus::Pending, }), ..item.data }) } else { let error = reply .error .ok_or(errors::ConnectorError::UnexpectedResponseError( bytes::Bytes::from( "Either refund_received or error must be present in the response" .to_string(), ), ))?; Ok(Self { response: Err(ErrorResponse { code: error.code, message: error.message.clone(), reason: Some(error.message.clone()), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } } } pub struct WorldpayxmlAuthType { pub(super) api_username: Secret<String>, pub(super) api_password: Secret<String>, pub(super) merchant_code: Secret<String>, } impl TryFrom<&ConnectorAuthType> for WorldpayxmlAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Ok(Self { api_username: api_key.to_owned(), api_password: key1.to_owned(), merchant_code: api_secret.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum WorldpayxmlPaymentStatus { Succeeded, Failed, #[default] Processing, } fn get_attempt_status( is_auto_capture: bool, last_event: LastEvent, previous_status: Option<&common_enums::AttemptStatus>, ) -> Result<common_enums::AttemptStatus, errors::ConnectorError> { match last_event { LastEvent::Authorised => { if is_auto_capture { Ok(common_enums::AttemptStatus::Pending) } else if previous_status == Some(&common_enums::AttemptStatus::CaptureInitiated) && !is_auto_capture { Ok(common_enums::AttemptStatus::CaptureInitiated) } else if previous_status == Some(&common_enums::AttemptStatus::VoidInitiated) && !is_auto_capture { Ok(common_enums::AttemptStatus::VoidInitiated) } else { Ok(common_enums::AttemptStatus::Authorized) } } LastEvent::Refused => Ok(common_enums::AttemptStatus::Failure), LastEvent::Cancelled => Ok(common_enums::AttemptStatus::Voided), LastEvent::Captured | LastEvent::Settled => Ok(common_enums::AttemptStatus::Charged), LastEvent::SentForAuthorisation => Ok(common_enums::AttemptStatus::Authorizing), LastEvent::Refunded | LastEvent::SentForRefund | LastEvent::RefundRequested | LastEvent::RefundFailed => Err(errors::ConnectorError::UnexpectedResponseError( bytes::Bytes::from("Invalid LastEvent".to_string()), )), } } fn get_refund_status(last_event: LastEvent) -> Result<enums::RefundStatus, errors::ConnectorError> { match last_event { LastEvent::Refunded => Ok(enums::RefundStatus::Success), LastEvent::SentForRefund | LastEvent::RefundRequested => Ok(enums::RefundStatus::Pending), LastEvent::RefundFailed => Ok(enums::RefundStatus::Failure), LastEvent::Captured | LastEvent::Settled => Ok(enums::RefundStatus::Pending), LastEvent::Authorised | LastEvent::Refused | LastEvent::Cancelled | LastEvent::SentForAuthorisation => Err(errors::ConnectorError::UnexpectedResponseError( bytes::Bytes::from("Invalid LastEvent".to_string()), )), } } impl<F> TryFrom<ResponseRouterData<F, PaymentService, PaymentsSyncData, PaymentsResponseData>> for RouterData<F, PaymentsSyncData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PaymentService, PaymentsSyncData, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let is_auto_capture = item.data.request.is_auto_capture()?; let reply = item .response .reply .ok_or(errors::ConnectorError::UnexpectedResponseError( bytes::Bytes::from("Missing reply data".to_string()), ))?; validate_reply(&reply)?; if let Some(order_status) = reply.order_status { validate_order_status(&order_status)?; if let Some(payment_data) = order_status.payment { let status = get_attempt_status( is_auto_capture, payment_data.last_event, Some(&item.data.status), )?; let response = process_payment_response( status, &payment_data, item.http_code, order_status.order_code.clone(), ) .map_err(|err| *err); Ok(Self { status, response, ..item.data }) } else { order_status.error .ok_or(errors::ConnectorError::UnexpectedResponseError( bytes::Bytes::from("Either order_status.payment or order_status.error must be present in the response".to_string()), ))?; // Handle API errors unrelated to the payment to prevent failing the payment. Ok(Self { status: item.data.status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( order_status.order_code.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(order_status.order_code.clone()), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } else { // Handle API errors unrelated to the payment to prevent failing the payment Ok(Self { status: item.data.status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: item.data.request.connector_transaction_id.clone(), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } } impl TryFrom<&PaymentsSyncRouterData> for PaymentService { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> { let auth = WorldpayxmlAuthType::try_from(&item.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let order_code = item .request .connector_transaction_id .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; let inquiry = Some(Inquiry { order_inquiry: OrderInquiry { order_code }, }); Ok(Self { version: worldpayxml_constants::WORLDPAYXML_VERSION.to_string(), merchant_code: auth.merchant_code.clone(), submit: None, reply: None, inquiry, modify: None, }) } } impl<F> TryFrom<ResponseRouterData<F, PaymentService, PaymentsAuthorizeData, PaymentsResponseData>> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PaymentService, PaymentsAuthorizeData, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let is_auto_capture = item.data.request.is_auto_capture()?; let reply = item .response .reply .ok_or(errors::ConnectorError::UnexpectedResponseError( bytes::Bytes::from("Missing reply data".to_string()), ))?; validate_reply(&reply)?; if let Some(order_status) = reply.order_status { validate_order_status(&order_status)?; if let Some(payment_data) = order_status.payment { let status = get_attempt_status(is_auto_capture, payment_data.last_event, None)?; let response = process_payment_response( status, &payment_data, item.http_code, order_status.order_code.clone(), ) .map_err(|err| *err); Ok(Self { status, response, ..item.data }) } else { let error = order_status.error .ok_or(errors::ConnectorError::UnexpectedResponseError( bytes::Bytes::from("Either order_status.payment or order_status.error must be present in the response".to_string()), ))?; Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(ErrorResponse { code: error.code, message: error.message.clone(), reason: Some(error.message.clone()), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(order_status.order_code), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } } else { let error = reply .error .ok_or(errors::ConnectorError::UnexpectedResponseError( bytes::Bytes::from("Missing reply.error".to_string()), ))?; Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(ErrorResponse { code: error.code, message: error.message.clone(), reason: Some(error.message.clone()), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } } } impl<F> TryFrom<ResponseRouterData<F, PaymentService, PaymentsCaptureData, PaymentsResponseData>> for RouterData<F, PaymentsCaptureData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PaymentService, PaymentsCaptureData, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let reply = item .response .reply .ok_or(errors::ConnectorError::UnexpectedResponseError( bytes::Bytes::from("Missing reply data".to_string()), ))?; if let Some(capture_received) = reply.ok.and_then(|ok| ok.capture_received) { Ok(Self { // Capture status will be updated via Psync status: common_enums::AttemptStatus::CaptureInitiated, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( capture_received.order_code.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(capture_received.order_code.clone()), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } else { let error = reply .error .ok_or(errors::ConnectorError::UnexpectedResponseError( bytes::Bytes::from( "Either capture_received or error must be present in the response" .to_string(), ), ))?; Ok(Self { status: common_enums::AttemptStatus::CaptureFailed, response: Err(ErrorResponse { code: error.code, message: error.message.clone(), reason: Some(error.message.clone()), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } } } impl<F> TryFrom<ResponseRouterData<F, PaymentService, PaymentsCancelData, PaymentsResponseData>> for RouterData<F, PaymentsCancelData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PaymentService, PaymentsCancelData, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let reply = item .response .reply .ok_or(errors::ConnectorError::UnexpectedResponseError( bytes::Bytes::from("Missing reply data".to_string()), ))?; if let Some(cancel_received) = reply.ok.and_then(|ok| ok.cancel_received) { Ok(Self { // Cancel status will be updated via Psync status: common_enums::AttemptStatus::VoidInitiated, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( cancel_received.order_code.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(cancel_received.order_code.clone()), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } else { let error = reply .error .ok_or(errors::ConnectorError::UnexpectedResponseError( bytes::Bytes::from( "Either cancel_received or error must be present in the response" .to_string(), ), ))?; Ok(Self { status: common_enums::AttemptStatus::VoidFailed, response: Err(ErrorResponse { code: error.code, message: error.message.clone(), reason: Some(error.message.clone()), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } } } #[derive(Default, Debug, Serialize)] pub struct WorldpayxmlRefundRequest { pub amount: StringMinorUnit, } impl TryFrom<RefundsResponseRouterData<RSync, PaymentService>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, PaymentService>, ) -> Result<Self, Self::Error> { let reply = item .response .reply .ok_or(errors::ConnectorError::UnexpectedResponseError( bytes::Bytes::from("Missing reply data".to_string()), ))?; validate_reply(&reply)?; if let Some(order_status) = reply.order_status { validate_order_status(&order_status)?; if let Some(payment_data) = order_status.payment { let status = get_refund_status(payment_data.last_event)?; let response = if connector_utils::is_refund_failure(status) { let error_code = payment_data .return_code .as_ref() .map(|code| code.code.clone()); let error_message = payment_data .return_code .as_ref() .map(|code| code.description.clone()); Err(ErrorResponse { code: error_code.unwrap_or(consts::NO_ERROR_CODE.to_string()), message: error_message .clone() .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), reason: error_message.clone(), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { Ok(RefundsResponseData { connector_refund_id: order_status.order_code, refund_status: status, }) }; Ok(Self { response, ..item.data }) } else { order_status.error .ok_or(errors::ConnectorError::UnexpectedResponseError( bytes::Bytes::from("Either order_status.payment or order_status.error must be present in the response".to_string()), ))?; // Return TransactionResponse for API errors unrelated to the payment to prevent failing the payment. let response = Ok(RefundsResponseData { connector_refund_id: order_status.order_code, refund_status: enums::RefundStatus::Pending, }); Ok(Self { response, ..item.data }) } } else { // Return TransactionResponse for API errors unrelated to the payment to prevent failing the payment let response = Ok(RefundsResponseData { connector_refund_id: item.data.request.connector_transaction_id.clone(), refund_status: enums::RefundStatus::Pending, }); Ok(Self { response, ..item.data }) } } } impl TryFrom<&RefundSyncRouterData> for PaymentService { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &RefundSyncRouterData) -> Result<Self, Self::Error> { let auth = WorldpayxmlAuthType::try_from(&item.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let order_code = item.request.connector_transaction_id.clone(); let inquiry = Some(Inquiry { order_inquiry: OrderInquiry { order_code }, }); Ok(Self { version: worldpayxml_constants::WORLDPAYXML_VERSION.to_string(), merchant_code: auth.merchant_code.clone(), submit: None, reply: None, inquiry, modify: None, }) } } fn validate_reply(reply: &Reply) -> Result<(), errors::ConnectorError> { if (reply.error.is_some() && reply.order_status.is_some()) || (reply.error.is_none() && reply.order_status.is_none()) { Err(errors::ConnectorError::UnexpectedResponseError( bytes::Bytes::from( "Either reply.error_data or reply.order_data must be present in the response" .to_string(), ), )) } else { Ok(()) } } fn validate_order_status(order_status: &OrderStatus) -> Result<(), errors::ConnectorError> { if (order_status.payment.is_some() && order_status.error.is_some()) || (order_status.payment.is_none() && order_status.error.is_none()) { Err(errors::ConnectorError::UnexpectedResponseError( bytes::Bytes::from( "Either order_status.payment or order_status.error must be present in the response" .to_string(), ), )) } else { Ok(()) } } fn process_payment_response( status: common_enums::AttemptStatus, payment_data: &Payment, http_code: u16, order_code: String, ) -> Result<PaymentsResponseData, Box<ErrorResponse>> { if connector_utils::is_payment_failure(status) { let error_code = payment_data .return_code .as_ref() .map(|code| code.code.clone()); let error_message = payment_data .return_code .as_ref() .map(|code| code.description.clone()); Err(Box::new(ErrorResponse { code: error_code.unwrap_or(consts::NO_ERROR_CODE.to_string()), message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), reason: None, status_code: http_code, attempt_status: None, connector_transaction_id: Some(order_code.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, })) } else { Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(order_code.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(order_code.clone()), incremental_authorization_allowed: None, charges: None, }) } }
crates/hyperswitch_connectors/src/connectors/worldpayxml/transformers.rs
hyperswitch_connectors
full_file
null
null
null
8,040
null
null
null
null
null
null
null
// Struct: EdgeData // File: crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct EdgeData
crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
hyperswitch_connectors
struct_definition
EdgeData
0
[]
46
null
null
null
null
null
null
null
// Module Structure // File: crates/hyperswitch_connectors/src/connectors/nmi.rs // Module: hyperswitch_connectors // Public submodules: pub mod transformers;
crates/hyperswitch_connectors/src/connectors/nmi.rs
hyperswitch_connectors
module_structure
null
null
null
38
null
null
null
null
null
1
0
// Struct: WorldpayvantivAuthType // File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct WorldpayvantivAuthType
crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs
hyperswitch_connectors
struct_definition
WorldpayvantivAuthType
0
[]
55
null
null
null
null
null
null
null
// Function: get_organization // File: crates/router/src/core/admin.rs // Module: router pub fn get_organization( state: SessionState, org_id: api::OrganizationId, ) -> RouterResponse<api::OrganizationResponse>
crates/router/src/core/admin.rs
router
function_signature
null
null
null
51
get_organization
null
null
null
null
null
null
// Implementation: impl DynamicAlgorithmWithTimestamp // File: crates/api_models/src/routing.rs // Module: api_models // Methods: 1 total (1 public) impl DynamicAlgorithmWithTimestamp
crates/api_models/src/routing.rs
api_models
impl_block
null
null
null
41
null
DynamicAlgorithmWithTimestamp
null
1
1
null
null
// Function: string_str // File: crates/euclid/src/frontend/ast/parser.rs // Module: euclid pub fn string_str(input: &str) -> ParseResult<&str, String>
crates/euclid/src/frontend/ast/parser.rs
euclid
function_signature
null
null
null
43
string_str
null
null
null
null
null
null
// Implementation: impl api::ConnectorAccessToken for for Getnet // File: crates/hyperswitch_connectors/src/connectors/getnet.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::ConnectorAccessToken for for Getnet
crates/hyperswitch_connectors/src/connectors/getnet.rs
hyperswitch_connectors
impl_block
null
null
null
57
null
Getnet
api::ConnectorAccessToken for
0
0
null
null
// Implementation: impl ConnectorSpecifications for for Flexiti // File: crates/hyperswitch_connectors/src/connectors/flexiti.rs // Module: hyperswitch_connectors // Methods: 3 total (0 public) impl ConnectorSpecifications for for Flexiti
crates/hyperswitch_connectors/src/connectors/flexiti.rs
hyperswitch_connectors
impl_block
null
null
null
54
null
Flexiti
ConnectorSpecifications for
3
0
null
null
// Function: get_payment_filters // File: crates/router/src/core/payments.rs // Module: router pub fn get_payment_filters( state: SessionState, merchant_context: domain::MerchantContext, profile_id_list: Option<Vec<id_type::ProfileId>>, ) -> RouterResponse<api::PaymentListFiltersV2>
crates/router/src/core/payments.rs
router
function_signature
null
null
null
71
get_payment_filters
null
null
null
null
null
null
// Module Structure // File: crates/hyperswitch_connectors/src/connectors/silverflow.rs // Module: hyperswitch_connectors // Public submodules: pub mod transformers;
crates/hyperswitch_connectors/src/connectors/silverflow.rs
hyperswitch_connectors
module_structure
null
null
null
39
null
null
null
null
null
1
0
// Implementation: impl PaymentIntentMetricAccumulator for for ProcessedAmountAccumulator // File: crates/analytics/src/payment_intents/accumulator.rs // Module: analytics // Methods: 2 total (0 public) impl PaymentIntentMetricAccumulator for for ProcessedAmountAccumulator
crates/analytics/src/payment_intents/accumulator.rs
analytics
impl_block
null
null
null
63
null
ProcessedAmountAccumulator
PaymentIntentMetricAccumulator for
2
0
null
null
RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::BillingAddressLine2.to_tuple(), RequiredField::BillingPhone.to_tuple(), RequiredField::BillingPhoneCountryCode.to_tuple(), RequiredField::BillingEmail.to_tuple(), ]) } pub fn get_shipping_required_fields() -> HashMap<String, RequiredFieldInfo> { HashMap::from([ RequiredField::ShippingFirstName.to_tuple(), RequiredField::ShippingLastName.to_tuple(), RequiredField::ShippingAddressCity.to_tuple(), RequiredField::ShippingAddressState.to_tuple(), RequiredField::ShippingAddressZip.to_tuple(), RequiredField::ShippingAddressCountries(vec!["ALL"]).to_tuple(), RequiredField::ShippingAddressLine1.to_tuple(), RequiredField::ShippingPhone.to_tuple(), RequiredField::ShippingPhoneCountryCode.to_tuple(), RequiredField::ShippingEmail.to_tuple(), ]) } #[cfg(feature = "v1")] impl RequiredFields { pub fn new(bank_config: &BankRedirectConfig) -> Self { let cards_required_fields = get_cards_required_fields(); let mut debit_required_fields = cards_required_fields.clone(); debit_required_fields.extend(HashMap::from([ ( Connector::Bankofamerica, fields( vec![], vec![], [card_basic(), email(), full_name(), billing_address()].concat(), ), ), ( Connector::Getnet, fields( vec![], vec![], [card_basic(), vec![RequiredField::CardNetwork]].concat(), ), ), ])); Self(HashMap::from([ ( enums::PaymentMethod::Card, PaymentMethodType(HashMap::from([ ( enums::PaymentMethodType::Debit, ConnectorFields { fields: cards_required_fields.clone(), }, ), ( enums::PaymentMethodType::Credit, ConnectorFields { fields: debit_required_fields.clone(), }, ), ])), ), ( enums::PaymentMethod::BankRedirect, PaymentMethodType(get_bank_redirect_required_fields(bank_config)), ), ( enums::PaymentMethod::Wallet, PaymentMethodType(get_wallet_required_fields()), ), ( enums::PaymentMethod::PayLater, PaymentMethodType(get_pay_later_required_fields()), ), ( enums::PaymentMethod::Crypto, PaymentMethodType(HashMap::from([( enums::PaymentMethodType::CryptoCurrency, connectors(vec![( Connector::Cryptopay, fields( vec![], vec![ RequiredField::CyptoPayCurrency(vec![ "BTC", "LTC", "ETH", "XRP", "XLM", "BCH", "ADA", "SOL", "SHIB", "TRX", "DOGE", "BNB", "USDT", "USDC", "DAI", ]), RequiredField::CryptoNetwork, ], vec![], ), )]), )])), ), ( enums::PaymentMethod::Voucher, PaymentMethodType(get_voucher_required_fields()), ), ( enums::PaymentMethod::Upi, PaymentMethodType(HashMap::from([( enums::PaymentMethodType::UpiCollect, connectors(vec![ ( Connector::Razorpay, fields( vec![], vec![], vec![ RequiredField::UpiCollectVpaId, RequiredField::BillingEmail, RequiredField::BillingPhone, RequiredField::BillingPhoneCountryCode, ], ), ), ( Connector::Phonepe, fields( vec![], vec![], vec![ RequiredField::UpiCollectVpaId, RequiredField::BillingEmail, RequiredField::BillingPhone, RequiredField::BillingPhoneCountryCode, ], ), ), ( Connector::Paytm, fields( vec![], vec![], vec![ RequiredField::UpiCollectVpaId, RequiredField::BillingEmail, RequiredField::BillingPhone, RequiredField::BillingPhoneCountryCode, ], ), ), ]), )])), ), ( enums::PaymentMethod::BankDebit, PaymentMethodType(get_bank_debit_required_fields()), ), ( enums::PaymentMethod::BankTransfer, PaymentMethodType(get_bank_transfer_required_fields()), ), ( enums::PaymentMethod::GiftCard, PaymentMethodType(HashMap::from([ ( enums::PaymentMethodType::PaySafeCard, connectors(vec![(Connector::Adyen, fields(vec![], vec![], vec![]))]), ), ( enums::PaymentMethodType::Givex, connectors(vec![( Connector::Adyen, fields( vec![], vec![RequiredField::GiftCardNumber, RequiredField::GiftCardCvc], vec![], ), )]), ), ])), ), ( enums::PaymentMethod::CardRedirect, PaymentMethodType(HashMap::from([ ( enums::PaymentMethodType::Benefit, connectors(vec![( Connector::Adyen, fields( vec![], vec![ RequiredField::BillingFirstName( "first_name", FieldType::UserFullName, ), RequiredField::BillingLastName( "last_name", FieldType::UserFullName, ), RequiredField::BillingEmail, RequiredField::BillingPhone, RequiredField::BillingPhoneCountryCode, ], vec![], ), )]), ), ( enums::PaymentMethodType::Knet, connectors(vec![( Connector::Adyen, fields( vec![], vec![ RequiredField::BillingFirstName( "first_name", FieldType::UserFullName, ), RequiredField::BillingLastName( "last_name", FieldType::UserFullName, ), RequiredField::BillingEmail, RequiredField::BillingPhone, RequiredField::BillingPhoneCountryCode, ], vec![], ), )]), ), ( enums::PaymentMethodType::MomoAtm, connectors(vec![( Connector::Adyen, fields( vec![], vec![ RequiredField::BillingEmail, RequiredField::BillingPhone, RequiredField::BillingPhoneCountryCode, ], vec![], ), )]), ), ])), ), ( enums::PaymentMethod::MobilePayment, PaymentMethodType(HashMap::from([( enums::PaymentMethodType::DirectCarrierBilling, connectors(vec![( Connector::Digitalvirgo, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::DcbMsisdn.to_tuple(), RequiredField::DcbClientUid.to_tuple(), RequiredField::OrderDetailsProductName.to_tuple(), ]), }, )]), )])), ), ])) } } #[cfg(feature = "v1")] impl Default for RequiredFields { fn default() -> Self { Self::new(&BankRedirectConfig::default()) } } #[cfg(feature = "v1")] fn get_cards_required_fields() -> HashMap<Connector, RequiredFieldFinal> { HashMap::from([ (Connector::Aci, fields(vec![], vec![], card_with_name())), (Connector::Authipay, fields(vec![], vec![], card_basic())), (Connector::Adyen, fields(vec![], vec![], card_with_name())), (Connector::Airwallex, fields(vec![], card_basic(), vec![])), ( Connector::Authorizedotnet, fields(vec![], vec![], card_basic()), ), ( Connector::Bambora, fields(vec![], [card_with_name(), billing_email()].concat(), vec![]), ), ( Connector::Bankofamerica, fields( vec![], vec![], [card_basic(), email(), full_name(), billing_address()].concat(), ), ), ( Connector::Barclaycard, fields( vec![], vec![], [card_basic(), email(), full_name(), billing_address()].concat(), ), ), (Connector::Billwerk, fields(vec![], vec![], card_basic())), ( Connector::Bluesnap, fields( vec![], [card_basic(), email(), full_name()].concat(), vec![], ), ), (Connector::Boku, fields(vec![], vec![], card_basic())), (Connector::Braintree, fields(vec![], vec![], card_basic())), (Connector::Celero, fields(vec![], vec![], card_basic())), (Connector::Checkout, fields(vec![], card_basic(), vec![])), ( Connector::Coinbase, fields(vec![], vec![RequiredField::BillingUserFirstName], vec![]), ), ( Connector::Cybersource, fields( vec![], vec![], [card_with_name(), billing_email(), billing_address()].concat(), ), ), ( Connector::Datatrans, fields(vec![], vec![], [billing_email(), card_with_name()].concat()), ), ( Connector::Deutschebank, fields( vec![], [ card_basic(), email(), billing_address(), vec![ RequiredField::BillingFirstName("first_name", FieldType::UserFullName), RequiredField::BillingLastName("last_name", FieldType::UserFullName), ], ] .concat(), vec![], ), ), ( Connector::Dlocal, fields( vec![], [ card_with_name(), vec![RequiredField::BillingAddressCountries(vec!["ALL"])], ] .concat(), vec![], ), ), #[cfg(feature = "dummy_connector")] ( Connector::DummyConnector1, fields(vec![], vec![], card_basic()), ), #[cfg(feature = "dummy_connector")] ( Connector::DummyConnector2, fields(vec![], vec![], card_basic()), ), #[cfg(feature = "dummy_connector")] ( Connector::DummyConnector3, fields(vec![], vec![], card_basic()), ), #[cfg(feature = "dummy_connector")] ( Connector::DummyConnector4, fields(vec![], vec![], card_basic()), ), #[cfg(feature = "dummy_connector")] ( Connector::DummyConnector5, fields(vec![], vec![], card_basic()), ), #[cfg(feature = "dummy_connector")] ( Connector::DummyConnector6, fields(vec![], vec![], card_basic()), ), #[cfg(feature = "dummy_connector")] ( Connector::DummyConnector7, fields(vec![], vec![], card_basic()), ), ( Connector::Elavon, fields(vec![], [card_basic(), billing_email()].concat(), vec![]), ), (Connector::Fiserv, fields(vec![], card_basic(), vec![])), ( Connector::Fiuu, fields( vec![ RequiredField::BillingEmail, RequiredField::BillingUserFirstName, ], vec![], card_basic(), ), ), (Connector::Forte, fields(vec![], card_with_name(), vec![])), (Connector::Globalpay, fields(vec![], vec![], card_basic())), ( Connector::Hipay, fields( vec![], vec![], [ vec![RequiredField::BillingEmail], billing_address(), card_with_name(), ] .concat(), ), ), ( Connector::Helcim, fields( vec![], [ card_with_name(), vec![ RequiredField::BillingAddressZip, RequiredField::BillingAddressLine1, ], ] .concat(), vec![], ), ), (Connector::Iatapay, fields(vec![], vec![], vec![])), (Connector::Mollie, fields(vec![], card_with_name(), vec![])), (Connector::Moneris, fields(vec![], card_basic(), vec![])), ( Connector::Multisafepay, fields( vec![], vec![], [ card_with_name(), vec![ RequiredField::BillingAddressLine1, RequiredField::BillingAddressLine2, RequiredField::BillingAddressCity, RequiredField::BillingAddressZip, RequiredField::BillingAddressCountries(vec!["ALL"]), ], ] .concat(), ), ), (Connector::Nexinets, fields(vec![], vec![], card_basic())), ( Connector::Nexixpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::CardNumber.to_tuple(), RequiredField::CardExpMonth.to_tuple(), RequiredField::CardExpYear.to_tuple(), RequiredField::BillingFirstName("first_name", FieldType::UserFullName) .to_tuple(), RequiredField::BillingLastName("last_name", FieldType::UserFullName).to_tuple(), ]), }, ), ( Connector::Nmi, fields( vec![], [card_with_name(), vec![RequiredField::BillingAddressZip]].concat(), vec![], ), ), (Connector::Noon, fields(vec![], vec![], card_with_name())), ( Connector::Novalnet, fields( vec![], vec![], [ vec![ RequiredField::BillingFirstName("first_name", FieldType::UserFullName), RequiredField::BillingLastName("last_name", FieldType::UserFullName), ], billing_email(), ] .concat(), ), ), ( Connector::Nuvei, fields( vec![], vec![], [ card_basic(), vec![ RequiredField::BillingEmail, RequiredField::BillingCountries(vec!["ALL"]), RequiredField::BillingFirstName("first_name", FieldType::UserFullName), RequiredField::BillingLastName("last_name", FieldType::UserFullName), ], ] .concat(), ), ), ( Connector::Paybox, fields( vec![], vec![], [ email(), card_with_name(), vec![ RequiredField::BillingAddressLine1, RequiredField::BillingAddressCity, RequiredField::BillingAddressZip, RequiredField::BillingAddressCountries(vec!["ALL"]), ], ] .concat(), ), ), ( Connector::Payload, fields( vec![], vec![], [ email(), card_with_name(), vec![ RequiredField::BillingAddressLine1, RequiredField::BillingAddressCity, RequiredField::BillingAddressZip, RequiredField::BillingAddressState, RequiredField::BillingAddressCountries(vec!["ALL"]), ], ] .concat(), ), ), ( Connector::Payme, fields(vec![], vec![], [email(), card_with_name()].concat()), ), (Connector::Paypal, fields(vec![], card_basic(), vec![])), (Connector::Payu, fields(vec![], card_basic(), vec![])), ( Connector::Peachpayments, fields(vec![], vec![], card_with_name()), ), ( Connector::Powertranz, fields(vec![], card_with_name(), vec![]), ), (Connector::Rapyd, fields(vec![], card_with_name(), vec![])), (Connector::Redsys, fields(vec![], card_basic(), vec![])), (Connector::Shift4, fields(vec![], card_basic(), vec![])), (Connector::Silverflow, fields(vec![], vec![], card_basic())), (Connector::Square, fields(vec![], vec![], card_basic())), (Connector::Stax, fields(vec![], card_with_name(), vec![])), (Connector::Stripe, fields(vec![], vec![], card_basic())), ( Connector::Trustpay, fields( vec![], [ card_with_name(), vec![ RequiredField::BillingAddressLine1, RequiredField::BillingAddressCity, RequiredField::BillingAddressZip, RequiredField::BillingAddressCountries(vec!["ALL"]), ], ] .concat(), vec![], ), ), ( Connector::Trustpayments, fields(vec![], vec![], card_basic()), ), (Connector::Tsys, fields(vec![], card_basic(), vec![])), ( Connector::Wellsfargo, fields( vec![], vec![], [card_with_name(), email(), billing_address()].concat(), ), ), ( Connector::Worldline, fields( vec![], [ card_basic(), vec![RequiredField::BillingAddressCountries(vec!["ALL"])], ] .concat(), vec![], ), ), ( Connector::Worldpay, fields( vec![], vec![], vec![ RequiredField::CardNumber, RequiredField::CardExpMonth, RequiredField::CardExpYear, RequiredField::BillingUserFirstName, ], ), ), ( Connector::Worldpayvantiv, fields(vec![], card_basic(), vec![]), ), ( Connector::Xendit, fields( vec![], vec![], [ card_basic(), vec![ RequiredField::BillingEmail, RequiredField::BillingPhone, RequiredField::BillingPhoneCountryCode, RequiredField::BillingUserFirstName, RequiredField::BillingUserLastName, RequiredField::BillingAddressCountries(vec!["ID,PH"]), ], ] .concat(), ), ), ( Connector::Zen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::CardNumber.to_tuple(), RequiredField::CardExpMonth.to_tuple(), RequiredField::CardExpYear.to_tuple(), RequiredField::Email.to_tuple(), ]), common: HashMap::new(), }, ), ]) } #[cfg(feature = "v1")] fn get_bank_redirect_required_fields( bank_config: &BankRedirectConfig, ) -> HashMap<enums::PaymentMethodType, ConnectorFields> { HashMap::from([ ( enums::PaymentMethodType::OpenBankingUk, connectors(vec![ (Connector::Volt, fields(vec![], billing_name(), vec![])), ( Connector::Adyen, fields(vec![], vec![RequiredField::OpenBankingUkIssuer], vec![]), ), ]), ), ( enums::PaymentMethodType::Trustly, connectors(vec![ (Connector::Adyen, fields(vec![], vec![], vec![])), ( Connector::Airwallex, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingUserFirstName.to_tuple(), RequiredField::BillingUserLastName.to_tuple(), RequiredField::BillingAddressCountries(vec![ "DE", "DK", "EE", "ES", "FI", "GB", "LV", "LT", "NL", "PL", "PT", "SE", "SK", ]) .to_tuple(), ]), common: HashMap::new(), }, ), ]), ), ( enums::PaymentMethodType::OnlineBankingCzechRepublic, connectors(vec![( Connector::Adyen, fields( vec![], vec![RequiredField::OpenBankingCzechRepublicIssuer], vec![], ), )]), ), ( enums::PaymentMethodType::OnlineBankingFinland, connectors(vec![( Connector::Adyen, fields(vec![], vec![RequiredField::BillingEmail], vec![]), )]), ), ( enums::PaymentMethodType::OnlineBankingPoland, connectors(vec![( Connector::Adyen, fields( vec![], vec![ RequiredField::OpenBankingPolandIssuer, RequiredField::BillingEmail, ], vec![], ), )]), ), ( enums::PaymentMethodType::OnlineBankingSlovakia, connectors(vec![( Connector::Adyen, fields( vec![], vec![RequiredField::OpenBankingSlovakiaIssuer], vec![], ), )]), ), ( enums::PaymentMethodType::OnlineBankingFpx, connectors(vec![( Connector::Adyen, fields(vec![], vec![RequiredField::OpenBankingFpxIssuer], vec![]), )]), ), ( enums::PaymentMethodType::OnlineBankingThailand, connectors(vec![( Connector::Adyen, fields( vec![], vec![RequiredField::OpenBankingThailandIssuer], vec![], ), )]), ), ( enums::PaymentMethodType::Bizum, connectors(vec![(Connector::Adyen, fields(vec![], vec![], vec![]))]), ), ( enums::PaymentMethodType::Przelewy24, connectors(vec![( Connector::Stripe, fields(vec![], vec![RequiredField::BillingEmail], vec![]), )]), ), ( enums::PaymentMethodType::BancontactCard, connectors(vec![ (Connector::Mollie, fields(vec![], vec![], vec![])), ( Connector::Stripe, fields( vec![RequiredField::BillingEmail], vec![], vec![ RequiredField::BillingFirstName( "billing_name", FieldType::UserFullName, ), RequiredField::BillingLastName("billing_name", FieldType::UserFullName), ], ), ), ( Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BanContactCardNumber.to_tuple(), RequiredField::BanContactCardExpMonth.to_tuple(), RequiredField::BanContactCardExpYear.to_tuple(), RequiredField::BillingUserFirstName.to_tuple(), RequiredField::BillingUserLastName.to_tuple(), ]), }, ), ]), ), ( enums::PaymentMethodType::Giropay, connectors(vec![ ( Connector::Aci, fields( vec![], vec![RequiredField::BillingCountries(vec!["DE"])], vec![], ), ), (Connector::Adyen, fields(vec![], vec![], vec![])), ( Connector::Globalpay, fields( vec![], vec![], vec![RequiredField::BillingAddressCountries(vec!["DE"])], ), ), (Connector::Mollie, fields(vec![], vec![], vec![])), ( Connector::Nuvei, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::Email.to_tuple(), RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressCountries(vec!["DE"]).to_tuple(), ]), common: HashMap::new(), }, ), ( Connector::Paypal, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingCountries(vec!["DE"]).to_tuple(), RequiredField::BillingFirstName( "billing_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_name", FieldType::UserBillingName, ) .to_tuple(), ]), common: HashMap::new(), }, ), ( Connector::Stripe, fields( vec![], vec![ RequiredField::BillingFirstName( "billing_name", FieldType::UserBillingName, ), RequiredField::BillingLastName( "billing_name", FieldType::UserBillingName, ), ], vec![], ), ), (Connector::Shift4, fields(vec![], vec![], vec![])), ( Connector::Trustpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["DE"]).to_tuple(), ]), common: HashMap::new(), }, ), ]), ), ( enums::PaymentMethodType::Ideal, connectors(vec![ ( Connector::Aci, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::IdealBankName.to_tuple(), RequiredField::BillingCountries(vec!["NL"]).to_tuple(), ]), common: HashMap::new(), }, ), ( Connector::Adyen, fields(vec![], vec![], vec![RequiredField::IdealBankName]), ), (Connector::Globalpay, fields(vec![], vec![], vec![])), (Connector::Mollie, fields(vec![], vec![], vec![])), (Connector::Nexinets, fields(vec![], vec![], vec![])), (Connector::Airwallex, fields(vec![], vec![], vec![])), ( Connector::Nuvei, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::Email.to_tuple(), RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressCountries(vec!["NL"]).to_tuple(), ]), common: HashMap::new(), }, ), ( Connector::Shift4, fields( vec![], vec![RequiredField::BillingCountries(vec!["NL"])], vec![], ), ), ( Connector::Paypal, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingFirstName( "billing_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingCountries(vec!["NL"]).to_tuple(), ]), common: HashMap::new(), }, ), ( Connector::Stripe, RequiredFieldFinal { mandate: HashMap::from([ RequiredField::BillingFirstName( "billing_name", FieldType::UserFullName, ) .to_tuple(), RequiredField::BillingLastName("billing_name", FieldType::UserFullName) .to_tuple(), RequiredField::BillingEmail.to_tuple(), ]), non_mandate: HashMap::new(), common: HashMap::new(), }, ), ( Connector::Trustpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["NL"]).to_tuple(), ]), common: HashMap::new(), }, ), ]), ), ( enums::PaymentMethodType::Sofort, connectors(vec![ ( Connector::Aci, fields( vec![], vec![RequiredField::BillingCountries(vec![ "ES", "GB", "SE", "AT", "NL", "DE", "CH", "BE", "FR", "FI", "IT", "PL", ])], vec![], ), ), (Connector::Adyen, fields(vec![], vec![], vec![])), ( Connector::Globalpay, fields( vec![], vec![], vec![RequiredField::BillingAddressCountries(vec![ "AT", "BE", "DE", "ES", "IT", "NL", ])], ), ), (Connector::Mollie, fields(vec![], vec![], vec![])), (Connector::Nexinets, fields(vec![], vec![], vec![])), ( Connector::Nuvei, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::Email.to_tuple(), RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressCountries(vec![ "ES", "GB", "IT", "DE", "FR", "AT", "BE", "NL", "BE", "SK", ]) .to_tuple(), ]), common: HashMap::new(), }, ), ( Connector::Paypal, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingCountries(vec![ "ES", "GB", "AT", "NL", "DE", "BE", ]) .to_tuple(), RequiredField::BillingFirstName( "billing_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_name", FieldType::UserBillingName, ) .to_tuple(), ]), common: HashMap::new(), }, ), (Connector::Shift4, fields(vec![], vec![], vec![])), ( Connector::Stripe, RequiredFieldFinal { mandate: HashMap::from([RequiredField::BillingEmail.to_tuple()]), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BillingCountries(vec!["ES", "AT", "NL", "DE", "BE"]) .to_tuple(), RequiredField::BillingFirstName( "account_holder_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "account_holder_name", FieldType::UserBillingName, ) .to_tuple(), ]), }, ), ( Connector::Trustpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec![ "ES", "GB", "SE", "AT", "NL", "DE", "CH", "BE", "FR", "FI", "IT", "PL", ]) .to_tuple(), ]), common: HashMap::new(), }, ), ]), ), ( enums::PaymentMethodType::Eps, connectors(vec![ ( Connector::Adyen, fields(vec![], vec![], vec![RequiredField::EpsBankName]), ), ( Connector::Stripe, fields( vec![], vec![ RequiredField::BillingFirstName( "billing_name", FieldType::UserFullName, ), RequiredField::EpsBankOptions( bank_config .0 .get(&enums::PaymentMethodType::Eps) .and_then(|connector_bank_names| { connector_bank_names.0.get("stripe") }) .map(|bank_names| bank_names.banks.clone()) .unwrap_or_default(), ), RequiredField::BillingLastName("billing_name", FieldType::UserFullName), ], vec![], ), ), ( Connector::Aci, fields( vec![], vec![RequiredField::BillingCountries(vec!["AT"])], vec![], ), ), ( Connector::Globalpay, fields( vec![], vec![], vec![RequiredField::BillingAddressCountries(vec!["AT"])], ), ), (Connector::Mollie, fields(vec![], vec![], vec![])), ( Connector::Paypal, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingFirstName( "billing_name", FieldType::UserFullName, ) .to_tuple(), RequiredField::BillingLastName("billing_name", FieldType::UserFullName) .to_tuple(), RequiredField::BillingCountries(vec!["AT"]).to_tuple(), ]), common: HashMap::new(), }, ), ( Connector::Trustpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["AT"]).to_tuple(), ]), common: HashMap::new(), }, ), (Connector::Shift4, fields(vec![], vec![], vec![])), ( Connector::Nuvei, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::Email.to_tuple(), RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressCountries(vec!["AT"]).to_tuple(), ]), common: HashMap::new(), }, ), ]), ), ( enums::PaymentMethodType::Blik, connectors(vec![ ( Connector::Adyen, fields(vec![], vec![], vec![RequiredField::BlikCode]), ), ( Connector::Stripe, fields(vec![], vec![], vec![RequiredField::BlikCode]), ), ( Connector::Trustpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::Email.to_tuple(), RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), ]), }, ), ( Connector::Airwallex, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingUserFirstName.to_tuple(), RequiredField::BillingUserLastName.to_tuple(), ]), common: HashMap::new(), }, ), ]), ), ( enums::PaymentMethodType::Interac, connectors(vec![ ( Connector::Paysafe, fields(vec![], vec![RequiredField::BillingEmail], vec![]), ), ( Connector::Gigadat, fields( vec![], vec![ RequiredField::BillingEmail, RequiredField::BillingUserFirstName, RequiredField::BillingUserLastName, RequiredField::BillingPhone, ], vec![], ), ), ( Connector::Loonio, fields( vec![], vec![ RequiredField::BillingEmail, RequiredField::BillingUserFirstName, RequiredField::BillingUserLastName, ], vec![], ), ), ]), ), ]) } #[cfg(feature = "v1")] fn get_wallet_required_fields() -> HashMap<enums::PaymentMethodType, ConnectorFields> { HashMap::from([ ( enums::PaymentMethodType::ApplePay, connectors(vec![ (Connector::Stripe, fields(vec![], vec![], vec![])), (Connector::Adyen, fields(vec![], vec![], vec![])), ( Connector::Nuvei, fields( vec![], vec![], vec![ RequiredField::BillingEmail, RequiredField::BillingCountries(vec!["ALL"]), RequiredField::BillingFirstName("first_name", FieldType::UserFullName), RequiredField::BillingLastName("last_name", FieldType::UserFullName), ], ), ), ( Connector::Bankofamerica, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::Email.to_tuple(), RequiredField::BillingFirstName( "billing_first_name",
crates/payment_methods/src/configs/payment_connector_required_fields.rs#chunk1
payment_methods
chunk
null
null
null
8,186
null
null
null
null
null
null
null
// Struct: PayuPaymentsCaptureResponse // File: crates/hyperswitch_connectors/src/connectors/payu/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PayuPaymentsCaptureResponse
crates/hyperswitch_connectors/src/connectors/payu/transformers.rs
hyperswitch_connectors
struct_definition
PayuPaymentsCaptureResponse
0
[]
51
null
null
null
null
null
null
null
// File: crates/hyperswitch_domain_models/src/refunds.rs // Module: hyperswitch_domain_models // Public structs: 2 #[cfg(feature = "v2")] use crate::business_profile::Profile; #[cfg(feature = "v1")] use crate::errors; #[cfg(feature = "v1")] pub struct RefundListConstraints { pub payment_id: Option<common_utils::id_type::PaymentId>, pub refund_id: Option<String>, pub profile_id: Option<Vec<common_utils::id_type::ProfileId>>, pub limit: Option<i64>, pub offset: Option<i64>, pub time_range: Option<common_utils::types::TimeRange>, pub amount_filter: Option<api_models::payments::AmountFilter>, pub connector: Option<Vec<String>>, pub merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, pub currency: Option<Vec<common_enums::Currency>>, pub refund_status: Option<Vec<common_enums::RefundStatus>>, } #[cfg(feature = "v2")] pub struct RefundListConstraints { pub payment_id: Option<common_utils::id_type::GlobalPaymentId>, pub refund_id: Option<common_utils::id_type::GlobalRefundId>, pub profile_id: common_utils::id_type::ProfileId, pub limit: Option<i64>, pub offset: Option<i64>, pub time_range: Option<common_utils::types::TimeRange>, pub amount_filter: Option<api_models::payments::AmountFilter>, pub connector: Option<Vec<String>>, pub connector_id_list: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, pub currency: Option<Vec<common_enums::Currency>>, pub refund_status: Option<Vec<common_enums::RefundStatus>>, } #[cfg(feature = "v1")] impl TryFrom<( api_models::refunds::RefundListRequest, Option<Vec<common_utils::id_type::ProfileId>>, )> for RefundListConstraints { type Error = error_stack::Report<errors::api_error_response::ApiErrorResponse>; fn try_from( (value, auth_profile_id_list): ( api_models::refunds::RefundListRequest, Option<Vec<common_utils::id_type::ProfileId>>, ), ) -> Result<Self, Self::Error> { let api_models::refunds::RefundListRequest { connector, currency, refund_status, payment_id, refund_id, profile_id, limit, offset, time_range, amount_filter, merchant_connector_id, } = value; let profile_id_from_request_body = profile_id; let profile_id_list = match (profile_id_from_request_body, auth_profile_id_list) { (None, None) => None, (None, Some(auth_profile_id_list)) => Some(auth_profile_id_list), (Some(profile_id_from_request_body), None) => Some(vec![profile_id_from_request_body]), (Some(profile_id_from_request_body), Some(auth_profile_id_list)) => { let profile_id_from_request_body_is_available_in_auth_profile_id_list = auth_profile_id_list.contains(&profile_id_from_request_body); if profile_id_from_request_body_is_available_in_auth_profile_id_list { Some(vec![profile_id_from_request_body]) } else { // This scenario is very unlikely to happen return Err(error_stack::Report::new( errors::api_error_response::ApiErrorResponse::PreconditionFailed { message: format!( "Access not available for the given profile_id {profile_id_from_request_body:?}", ), }, )); } } }; Ok(Self { payment_id, refund_id, profile_id: profile_id_list, limit, offset, time_range, amount_filter, connector, merchant_connector_id, currency, refund_status, }) } } #[cfg(feature = "v2")] impl From<(api_models::refunds::RefundListRequest, Profile)> for RefundListConstraints { fn from((value, profile): (api_models::refunds::RefundListRequest, Profile)) -> Self { let api_models::refunds::RefundListRequest { payment_id, refund_id, connector, currency, refund_status, limit, offset, time_range, amount_filter, connector_id_list, } = value; Self { payment_id, refund_id, profile_id: profile.get_id().to_owned(), limit, offset, time_range, amount_filter, connector, connector_id_list, currency, refund_status, } } }
crates/hyperswitch_domain_models/src/refunds.rs
hyperswitch_domain_models
full_file
null
null
null
1,011
null
null
null
null
null
null
null
// Struct: SdkPaymentsSessionUpdateData // File: crates/hyperswitch_domain_models/src/router_request_types.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct SdkPaymentsSessionUpdateData
crates/hyperswitch_domain_models/src/router_request_types.rs
hyperswitch_domain_models
struct_definition
SdkPaymentsSessionUpdateData
0
[]
49
null
null
null
null
null
null
null
// Struct: PaypalConfirmRequest // File: crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PaypalConfirmRequest
crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
hyperswitch_connectors
struct_definition
PaypalConfirmRequest
0
[]
49
null
null
null
null
null
null
null
// Implementation: impl super::KafkaMessage for for KafkaFraudCheck // File: crates/router/src/services/kafka/fraud_check.rs // Module: router // Methods: 2 total (0 public) impl super::KafkaMessage for for KafkaFraudCheck
crates/router/src/services/kafka/fraud_check.rs
router
impl_block
null
null
null
57
null
KafkaFraudCheck
super::KafkaMessage for
2
0
null
null
// Struct: TaxjarRouterData // File: crates/hyperswitch_connectors/src/connectors/taxjar/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct TaxjarRouterData<T>
crates/hyperswitch_connectors/src/connectors/taxjar/transformers.rs
hyperswitch_connectors
struct_definition
TaxjarRouterData
0
[]
52
null
null
null
null
null
null
null
// Struct: StripePaymentMethod // File: crates/router/src/compatibility/stripe/setup_intents/types.rs // Module: router // Implementations: 0 pub struct StripePaymentMethod
crates/router/src/compatibility/stripe/setup_intents/types.rs
router
struct_definition
StripePaymentMethod
0
[]
41
null
null
null
null
null
null
null
// Struct: FieldError // File: crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct FieldError
crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
hyperswitch_connectors
struct_definition
FieldError
0
[]
46
null
null
null
null
null
null
null
// Struct: Reject // File: crates/hyperswitch_domain_models/src/router_flow_types/payments.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct Reject
crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
hyperswitch_domain_models
struct_definition
Reject
0
[]
41
null
null
null
null
null
null
null
// Struct: MonerisAuthRequest // File: crates/hyperswitch_connectors/src/connectors/moneris/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct MonerisAuthRequest
crates/hyperswitch_connectors/src/connectors/moneris/transformers.rs
hyperswitch_connectors
struct_definition
MonerisAuthRequest
0
[]
53
null
null
null
null
null
null
null
// File: crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs // Module: analytics use std::collections::HashSet; use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; use common_enums::DecoupledAuthenticationType; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, AuthInfo, }; #[derive(Default)] pub(super) struct FrictionlessFlowCount; #[async_trait::async_trait] impl<T> super::AuthEventMetric<T> for FrictionlessFlowCount where T: AnalyticsDataSource + super::AuthEventMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, auth: &AuthInfo, dimensions: &[AuthEventDimensions], filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Authentications); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(Aggregate::Count { field: None, alias: Some("count"), }) .switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; query_builder .add_filter_clause( "authentication_type", DecoupledAuthenticationType::Frictionless, ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; auth.set_filter_clause(&mut query_builder).switch()?; for dim in dimensions.iter() { query_builder .add_group_by_clause(dim) .attach_printable("Error grouping by dimensions") .switch()?; } if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } query_builder .execute_query::<AuthEventMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), i.acs_reference_number.clone(), i.mcc.clone(), i.currency.as_ref().map(|i| i.0), i.merchant_country.clone(), i.billing_country.clone(), i.shipping_country.clone(), i.issuer_country.clone(), i.earliest_supported_version.clone(), i.latest_supported_version.clone(), i.whitelist_decision, i.device_manufacturer.clone(), i.device_type.clone(), i.device_brand.clone(), i.device_os.clone(), i.device_display.clone(), i.browser_name.clone(), i.browser_version.clone(), i.issuer_id.clone(), i.scheme_name.clone(), i.exemption_requested, i.exemption_accepted, TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result< HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs
analytics
full_file
null
null
null
1,079
null
null
null
null
null
null
null
// Struct: CustomerDetails // File: crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct CustomerDetails
crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
hyperswitch_connectors
struct_definition
CustomerDetails
0
[]
47
null
null
null
null
null
null
null
// Function: retry_sync_task // File: crates/router/src/workflows/dispute_list.rs // Module: router // Documentation: Schedule the task for retry Returns bool which indicates whether this was the last retry or not pub fn retry_sync_task( db: &dyn StorageInterface, connector: String, merchant_id: common_utils::id_type::MerchantId, pt: storage::ProcessTracker, ) -> Result<bool, sch_errors::ProcessTrackerError>
crates/router/src/workflows/dispute_list.rs
router
function_signature
null
null
null
99
retry_sync_task
null
null
null
null
null
null
// Struct: SwitchOrganizationRequest // File: crates/api_models/src/user.rs // Module: api_models // Implementations: 0 pub struct SwitchOrganizationRequest
crates/api_models/src/user.rs
api_models
struct_definition
SwitchOrganizationRequest
0
[]
35
null
null
null
null
null
null
null
// File: crates/hyperswitch_interfaces/src/api/payments_v2.rs // Module: hyperswitch_interfaces //! Payments V2 interface use hyperswitch_domain_models::{ router_data_v2::{flow_common_types::GiftCardBalanceCheckFlowData, PaymentFlowData}, router_flow_types::{ payments::{ Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, ExternalVaultProxy, IncrementalAuthorization, PSync, PaymentMethodToken, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, Authenticate, GiftCardBalanceCheck, PostAuthenticate, PreAuthenticate, }, router_request_types::{ AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, ExternalVaultProxyPaymentsData, GiftCardBalanceCheckRequestData, PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostAuthenticateData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, }, router_response_types::{ GiftCardBalanceCheckResponseData, PaymentsResponseData, TaxCalculationResponseData, }, }; use crate::api::{ ConnectorCommon, ConnectorIntegrationV2, ConnectorSpecifications, ConnectorValidation, }; /// trait PaymentAuthorizeV2 pub trait PaymentAuthorizeV2: ConnectorIntegrationV2<Authorize, PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData> { } /// trait PaymentAuthorizeSessionTokenV2 pub trait PaymentAuthorizeSessionTokenV2: ConnectorIntegrationV2< AuthorizeSessionToken, PaymentFlowData, AuthorizeSessionTokenData, PaymentsResponseData, > { } /// trait PaymentSyncV2 pub trait PaymentSyncV2: ConnectorIntegrationV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData> { } /// trait PaymentVoidV2 pub trait PaymentVoidV2: ConnectorIntegrationV2<Void, PaymentFlowData, PaymentsCancelData, PaymentsResponseData> { } /// trait PaymentPostCaptureVoidV2 pub trait PaymentPostCaptureVoidV2: ConnectorIntegrationV2< PostCaptureVoid, PaymentFlowData, PaymentsCancelPostCaptureData, PaymentsResponseData, > { } /// trait PaymentApproveV2 pub trait PaymentApproveV2: ConnectorIntegrationV2<Approve, PaymentFlowData, PaymentsApproveData, PaymentsResponseData> { } /// trait PaymentRejectV2 pub trait PaymentRejectV2: ConnectorIntegrationV2<Reject, PaymentFlowData, PaymentsRejectData, PaymentsResponseData> { } /// trait PaymentCaptureV2 pub trait PaymentCaptureV2: ConnectorIntegrationV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData> { } /// trait PaymentSessionV2 pub trait PaymentSessionV2: ConnectorIntegrationV2<Session, PaymentFlowData, PaymentsSessionData, PaymentsResponseData> { } /// trait MandateSetupV2 pub trait MandateSetupV2: ConnectorIntegrationV2<SetupMandate, PaymentFlowData, SetupMandateRequestData, PaymentsResponseData> { } /// trait PaymentIncrementalAuthorizationV2 pub trait PaymentIncrementalAuthorizationV2: ConnectorIntegrationV2< IncrementalAuthorization, PaymentFlowData, PaymentsIncrementalAuthorizationData, PaymentsResponseData, > { } ///trait TaxCalculationV2 pub trait TaxCalculationV2: ConnectorIntegrationV2< CalculateTax, PaymentFlowData, PaymentsTaxCalculationData, TaxCalculationResponseData, > { } ///trait PaymentSessionUpdateV2 pub trait PaymentSessionUpdateV2: ConnectorIntegrationV2< SdkSessionUpdate, PaymentFlowData, SdkPaymentsSessionUpdateData, PaymentsResponseData, > { } ///trait PaymentPostSessionTokensV2 pub trait PaymentPostSessionTokensV2: ConnectorIntegrationV2< PostSessionTokens, PaymentFlowData, PaymentsPostSessionTokensData, PaymentsResponseData, > { } /// trait ConnectorCreateOrderV2 pub trait PaymentCreateOrderV2: ConnectorIntegrationV2<CreateOrder, PaymentFlowData, CreateOrderRequestData, PaymentsResponseData> { } /// trait PaymentUpdateMetadataV2 pub trait PaymentUpdateMetadataV2: ConnectorIntegrationV2< UpdateMetadata, PaymentFlowData, PaymentsUpdateMetadataData, PaymentsResponseData, > { } /// trait PaymentsCompleteAuthorizeV2 pub trait PaymentsCompleteAuthorizeV2: ConnectorIntegrationV2< CompleteAuthorize, PaymentFlowData, CompleteAuthorizeData, PaymentsResponseData, > { } /// trait PaymentTokenV2 pub trait PaymentTokenV2: ConnectorIntegrationV2< PaymentMethodToken, PaymentFlowData, PaymentMethodTokenizationData, PaymentsResponseData, > { } /// trait ConnectorCustomerV2 pub trait ConnectorCustomerV2: ConnectorIntegrationV2< CreateConnectorCustomer, PaymentFlowData, ConnectorCustomerData, PaymentsResponseData, > { } /// trait PaymentsPreProcessingV2 pub trait PaymentsPreProcessingV2: ConnectorIntegrationV2< PreProcessing, PaymentFlowData, PaymentsPreProcessingData, PaymentsResponseData, > { } /// trait PaymentsGiftCardBalanceCheckV2 pub trait PaymentsGiftCardBalanceCheckV2: ConnectorIntegrationV2< GiftCardBalanceCheck, GiftCardBalanceCheckFlowData, GiftCardBalanceCheckRequestData, GiftCardBalanceCheckResponseData, > { } /// trait PaymentsPreAuthenticateV2 pub trait PaymentsPreAuthenticateV2: ConnectorIntegrationV2< PreAuthenticate, PaymentFlowData, PaymentsPreAuthenticateData, PaymentsResponseData, > { } /// trait PaymentsAuthenticateV2 pub trait PaymentsAuthenticateV2: ConnectorIntegrationV2< Authenticate, PaymentFlowData, PaymentsAuthenticateData, PaymentsResponseData, > { } /// trait PaymentsPostAuthenticateV2 pub trait PaymentsPostAuthenticateV2: ConnectorIntegrationV2< PostAuthenticate, PaymentFlowData, PaymentsPostAuthenticateData, PaymentsResponseData, > { } /// trait PaymentsPostProcessingV2 pub trait PaymentsPostProcessingV2: ConnectorIntegrationV2< PostProcessing, PaymentFlowData, PaymentsPostProcessingData, PaymentsResponseData, > { } /// trait ExternalVaultProxyPaymentsCreate pub trait ExternalVaultProxyPaymentsCreate: ConnectorIntegrationV2< ExternalVaultProxy, PaymentFlowData, ExternalVaultProxyPaymentsData, PaymentsResponseData, > { } /// trait PaymentV2 pub trait PaymentV2: ConnectorCommon + ConnectorSpecifications + ConnectorValidation + PaymentAuthorizeV2 + PaymentAuthorizeSessionTokenV2 + PaymentsCompleteAuthorizeV2 + PaymentSyncV2 + PaymentCaptureV2 + PaymentVoidV2 + PaymentPostCaptureVoidV2 + PaymentApproveV2 + PaymentRejectV2 + MandateSetupV2 + PaymentSessionV2 + PaymentTokenV2 + PaymentsPreProcessingV2 + PaymentsPostProcessingV2 + ConnectorCustomerV2 + PaymentIncrementalAuthorizationV2 + TaxCalculationV2 + PaymentSessionUpdateV2 + PaymentPostSessionTokensV2 + PaymentUpdateMetadataV2 + PaymentCreateOrderV2 + ExternalVaultProxyPaymentsCreate + PaymentsGiftCardBalanceCheckV2 { }
crates/hyperswitch_interfaces/src/api/payments_v2.rs
hyperswitch_interfaces
full_file
null
null
null
1,706
null
null
null
null
null
null
null
// Function: get_merchant_auth_events_filters // File: crates/router/src/analytics.rs // Module: router pub fn get_merchant_auth_events_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<GetAuthEventFilterRequest>, ) -> impl Responder
crates/router/src/analytics.rs
router
function_signature
null
null
null
72
get_merchant_auth_events_filters
null
null
null
null
null
null