text
string
file_path
string
module
string
type
string
tokens
int64
language
string
struct_name
string
type_name
string
trait_name
string
impl_type
string
function_name
string
source
string
section
string
keys
list
macro_type
string
url
string
title
string
chunk_index
int64
File: crates/router/tests/connectors/checkbook.rs use std::str::FromStr; use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::Secret; use router::types::{self, api, storage::enums, Email}; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct CheckbookTest; impl ConnectorActions for CheckbookTest {} impl utils::Connector for CheckbookTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Checkbook; utils::construct_connector_data_old( Box::new(Checkbook::new()), types::Connector::Checkbook, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { types::ConnectorAuthType::BodyKey { key1: Secret::new("dummy_publishable_key".to_string()), api_key: Secret::new("dummy_secret_key".to_string()), } } fn get_name(&self) -> String { "checkbook".to_string() } } static CONNECTOR: CheckbookTest = CheckbookTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(types::PaymentAddress::new( None, None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("John".to_string())), last_name: Some(Secret::new("Doe".to_string())), ..Default::default() }), phone: None, email: Some(Email::from_str("[email protected]").unwrap()), }), None, )), ..Default::default() }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Creates a payment. #[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::AuthenticationPending); } // Synchronizes a payment. #[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::AuthenticationPending, 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::AuthenticationPending); } // Voids a payment. #[actix_web::test] async fn should_void_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 .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); }
crates/router/tests/connectors/checkbook.rs
router
full_file
753
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct SankeyRow { pub count: i64, pub authentication_status: Option<AuthenticationStatus>, pub exemption_requested: Option<bool>, pub exemption_accepted: Option<bool>, }
crates/analytics/src/auth_events/sankey.rs
analytics
struct_definition
41
rust
SankeyRow
null
null
null
null
null
null
null
null
null
null
null
pub fn new(risk_type: RiskType, risk: Risk) -> Self { Self { risk_type, detail: None, risk, } }
crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
hyperswitch_connectors
function_signature
36
rust
null
null
null
null
new
null
null
null
null
null
null
null
pub async fn should_call_unified_connector_service_for_webhooks( state: &SessionState, merchant_context: &MerchantContext, connector_name: &str, ) -> RouterResult<bool> { if state.grpc_client.unified_connector_service_client.is_none() { logger::debug!( connector = connector_name.to_string(), "Unified Connector Service client is not available for webhooks" ); return Ok(false); } let ucs_config_key = consts::UCS_ENABLED; if !is_ucs_enabled(state, ucs_config_key).await { return Ok(false); } let merchant_id = merchant_context .get_merchant_account() .get_id() .get_string_repr(); let config_key = format!( "{}_{}_{}_Webhooks", consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX, merchant_id, connector_name ); let should_execute = should_execute_based_on_rollout(state, &config_key).await?; Ok(should_execute) }
crates/router/src/core/unified_connector_service.rs
router
function_signature
217
rust
null
null
null
null
should_call_unified_connector_service_for_webhooks
null
null
null
null
null
null
null
/// Derives the `core::payments::Operation` trait on a type with a default base /// implementation. /// /// ## Usage /// On deriving, the conversion functions to be implemented need to be specified in an helper /// attribute `#[operation(..)]`. To derive all conversion functions, use `#[operation(all)]`. To /// derive specific conversion functions, pass the required identifiers to the attribute. /// `#[operation(validate_request, get_tracker)]`. Available conversions are listed below :- /// /// - validate_request /// - get_tracker /// - domain /// - update_tracker /// /// ## Example /// ```rust, ignore /// use router_derive::Operation; /// /// #[derive(Operation)] /// #[operation(all)] /// struct Point { /// x: u64, /// y: u64 /// } /// /// // The above will expand to this /// const _: () = { /// use crate::core::errors::RouterResult; /// use crate::core::payments::{GetTracker, PaymentData, UpdateTracker, ValidateRequest}; /// impl crate::core::payments::Operation for Point { /// fn to_validate_request(&self) -> RouterResult<&dyn ValidateRequest> { /// Ok(self) /// } /// fn to_get_tracker(&self) -> RouterResult<&dyn GetTracker<PaymentData>> { /// Ok(self) /// } /// fn to_domain(&self) -> RouterResult<&dyn Domain> { /// Ok(self) /// } /// fn to_update_tracker(&self) -> RouterResult<&dyn UpdateTracker<PaymentData>> { /// Ok(self) /// } /// } /// impl crate::core::payments::Operation for &Point { /// fn to_validate_request(&self) -> RouterResult<&dyn ValidateRequest> { /// Ok(*self) /// } /// fn to_get_tracker(&self) -> RouterResult<&dyn GetTracker<PaymentData>> { /// Ok(*self) /// } /// fn to_domain(&self) -> RouterResult<&dyn Domain> { /// Ok(*self) /// } /// fn to_update_tracker(&self) -> RouterResult<&dyn UpdateTracker<PaymentData>> { /// Ok(*self) /// } /// } /// }; /// /// #[derive(Operation)] /// #[operation(validate_request, get_tracker)] /// struct Point3 { /// x: u64, /// y: u64, /// z: u64 /// } /// /// // The above will expand to this /// const _: () = { /// use crate::core::errors::RouterResult; /// use crate::core::payments::{GetTracker, PaymentData, UpdateTracker, ValidateRequest}; /// impl crate::core::payments::Operation for Point3 { /// fn to_validate_request(&self) -> RouterResult<&dyn ValidateRequest> { /// Ok(self) /// } /// fn to_get_tracker(&self) -> RouterResult<&dyn GetTracker<PaymentData>> { /// Ok(self) /// } /// } /// impl crate::core::payments::Operation for &Point3 { /// fn to_validate_request(&self) -> RouterResult<&dyn ValidateRequest> { /// Ok(*self) /// } /// fn to_get_tracker(&self) -> RouterResult<&dyn GetTracker<PaymentData>> { /// Ok(*self) /// } /// } /// }; /// /// ``` /// /// The `const _: () = {}` allows us to import stuff with `use` without affecting the module /// imports, since use statements are not allowed inside of impl blocks. This technique is /// used by `diesel`. #[proc_macro_derive(PaymentOperation, attributes(operation))] pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::operation::operation_derive_inner(input) .unwrap_or_else(|err| err.to_compile_error().into()) }
crates/router_derive/src/lib.rs
router_derive
macro
849
rust
null
null
null
null
null
null
null
null
proc_derive
null
null
null
/// Get the merchant_id from the lineage pub fn merchant_id(&self) -> Option<&id_type::MerchantId> { match self { Self::Tenant { .. } | Self::Organization { .. } => None, Self::Merchant { merchant_id, .. } | Self::Profile { merchant_id, .. } => { Some(merchant_id) } } }
crates/common_utils/src/types/user/theme.rs
common_utils
function_signature
82
rust
null
null
null
null
merchant_id
null
null
null
null
null
null
null
pub async fn update_default_routing_config_for_profile( state: SessionState, merchant_context: domain::MerchantContext, updated_config: Vec<routing_types::RoutableConnectorChoice>, profile_id: common_utils::id_type::ProfileId, transaction_type: &enums::TransactionType, ) -> RouterResponse<routing_types::ProfileDefaultRoutingConfig> { metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, merchant_context.get_merchant_key_store(), Some(&profile_id), merchant_context.get_merchant_account().get_id(), ) .await? .get_required_value("Profile") .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let default_config = helpers::get_merchant_default_config( db, business_profile.get_id().get_string_repr(), transaction_type, ) .await?; utils::when(default_config.len() != updated_config.len(), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "current config and updated config have different lengths".to_string(), }) })?; let existing_set = FxHashSet::from_iter( default_config .iter() .map(|c| (c.connector.to_string(), c.merchant_connector_id.as_ref())), ); let updated_set = FxHashSet::from_iter( updated_config .iter() .map(|c| (c.connector.to_string(), c.merchant_connector_id.as_ref())), ); let symmetric_diff = existing_set .symmetric_difference(&updated_set) .cloned() .collect::<Vec<_>>(); utils::when(!symmetric_diff.is_empty(), || { let error_str = symmetric_diff .into_iter() .map(|(connector, ident)| format!("'{connector}:{ident:?}'")) .collect::<Vec<_>>() .join(", "); Err(errors::ApiErrorResponse::InvalidRequestData { message: format!("connector mismatch between old and new configs ({error_str})"), }) })?; helpers::update_merchant_default_config( db, business_profile.get_id().get_string_repr(), updated_config.clone(), transaction_type, ) .await?; metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json( routing_types::ProfileDefaultRoutingConfig { profile_id: business_profile.get_id().to_owned(), connectors: updated_config, }, )) }
crates/router/src/core/routing.rs
router
function_signature
585
rust
null
null
null
null
update_default_routing_config_for_profile
null
null
null
null
null
null
null
pub struct KlarnaAuthType { pub username: Secret<String>, pub password: Secret<String>, }
crates/hyperswitch_connectors/src/connectors/klarna/transformers.rs
hyperswitch_connectors
struct_definition
22
rust
KlarnaAuthType
null
null
null
null
null
null
null
null
null
null
null
File: crates/hyperswitch_connectors/src/connectors/mollie.rs Public functions: 1 Public structs: 1 pub mod transformers; use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ 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, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, TokenizationRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, consts, errors, events::connector_api_logs::ConnectorEvent, types::{self, Response}, webhooks, }; use lazy_static::lazy_static; use masking::{Mask, PeekInterface}; use transformers as mollie; // use self::mollie::{webhook_headers, MollieWebhookBodyEventType}; use crate::{constants::headers, types::ResponseRouterData, utils::convert_amount}; #[derive(Clone)] pub struct Mollie { amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), } impl Mollie { pub fn new() -> &'static Self { &Self { amount_converter: &StringMajorUnitForConnector, } } } impl api::Payment for Mollie {} impl api::PaymentSession for Mollie {} impl api::ConnectorAccessToken for Mollie {} impl api::MandateSetup for Mollie {} impl api::PaymentToken for Mollie {} impl api::PaymentAuthorize for Mollie {} impl api::PaymentsCompleteAuthorize for Mollie {} impl api::PaymentSync for Mollie {} impl api::PaymentCapture for Mollie {} impl api::PaymentVoid for Mollie {} impl api::Refund for Mollie {} impl api::RefundExecute for Mollie {} impl api::RefundSync for Mollie {} impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Mollie 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> { self.get_auth_header(&req.connector_auth_type) } } impl ConnectorCommon for Mollie { fn id(&self) -> &'static str { "mollie" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Base } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.mollie.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = mollie::MollieAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), format!("Bearer {}", auth.api_key.peek()).into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: mollie::MollieErrorResponse = res .response .parse_struct("MollieErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: response.status, code: response .title .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: response.detail, reason: response.field, 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 Mollie {} impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Mollie {} impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Mollie {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Mollie { fn get_headers( &self, req: &TokenizationRouterData, 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: &TokenizationRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let base_url = connectors .mollie .secondary_base_url .as_ref() .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?; Ok(format!("{base_url}card-tokens")) } fn get_request_body( &self, req: &TokenizationRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = mollie::MollieCardTokenRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &TokenizationRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::TokenizationType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::TokenizationType::get_headers(self, req, connectors)?) .set_body(types::TokenizationType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &TokenizationRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<TokenizationRouterData, errors::ConnectorError> where PaymentsResponseData: Clone, { let response: mollie::MollieCardTokenResponse = res .response .parse_struct("MollieTokenResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Mollie { fn build_request( &self, _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Mollie".to_string()) .into(), ) } } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Mollie { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}payments", self.base_url(connectors))) } 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 router_obj = mollie::MollieRouterData::from((amount, req)); let connector_req = mollie::MolliePaymentsRequest::try_from(&router_obj)?; Ok(RequestContent::Json(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() .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) .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: mollie::MolliePaymentsResponse = res .response .parse_struct("MolliePaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> for Mollie { } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Mollie { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}payments/{}", self.base_url(connectors), req.request .connector_transaction_id .get_connector_transaction_id() .change_context(errors::ConnectorError::RequestEncodingFailed)? )) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: mollie::MolliePaymentsResponse = res .response .parse_struct("mollie PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Mollie { fn build_request( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Capture".to_string(), connector: self.id().to_string(), } .into()) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Mollie { fn build_request( &self, _req: &PaymentsCancelRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Void".to_string(), connector: self.id().to_string(), } .into()) } } impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Mollie { 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(format!( "{}payments/{}/refunds", self.base_url(connectors), req.request.connector_transaction_id )) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let router_obj = mollie::MollieRouterData::from((amount, req)); let connector_req = mollie::MollieRefundRequest::try_from(&router_obj)?; Ok(RequestContent::Json(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() .headers(types::RefundExecuteType::get_headers( self, req, connectors, )?) .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: mollie::RefundResponse = res .response .parse_struct("MollieRefundResponse") .change_context(errors::ConnectorError::RequestEncodingFailed)?; 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 Mollie { 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> { let connector_refund_id = req .request .connector_refund_id .clone() .ok_or(errors::ConnectorError::RequestEncodingFailed)?; Ok(format!( "{}payments/{}/refunds/{}", self.base_url(connectors), req.request.connector_transaction_id, connector_refund_id )) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: mollie::RefundResponse = res .response .parse_struct("MollieRefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl webhooks::IncomingWebhook for Mollie { fn get_webhook_object_reference_id( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported) } fn get_webhook_resource_object( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } impl ConnectorRedirectResponse for Mollie { fn get_flow_type( &self, _query_params: &str, _json_payload: Option<serde_json::Value>, action: enums::PaymentAction, ) -> CustomResult<enums::CallConnectorAction, errors::ConnectorError> { match action { enums::PaymentAction::PSync | enums::PaymentAction::CompleteAuthorize | enums::PaymentAction::PaymentAuthenticateCompleteAuthorize => { Ok(enums::CallConnectorAction::Trigger) } } } } // impl ConnectorSpecifications for Mollie {} lazy_static! { static ref MOLLIE_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::SequentialAutomatic, ]; let supported_card_network = vec![ common_enums::CardNetwork::Visa, common_enums::CardNetwork::Mastercard, common_enums::CardNetwork::AmericanExpress, common_enums::CardNetwork::Discover, common_enums::CardNetwork::JCB, common_enums::CardNetwork::DinersClub, common_enums::CardNetwork::UnionPay, common_enums::CardNetwork::Interac, common_enums::CardNetwork::CartesBancaires, ]; let mut mollie_supported_payment_methods = SupportedPaymentMethods::new(); mollie_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Credit, PaymentMethodDetails{ mandates: common_enums::FeatureStatus::NotSupported, refunds: common_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(), } }), ), }, ); mollie_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Debit, PaymentMethodDetails{ mandates: common_enums::FeatureStatus::NotSupported, refunds: common_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(), } }), ), }, ); mollie_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Eps, PaymentMethodDetails{ mandates: common_enums::FeatureStatus::NotSupported, refunds: common_enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); mollie_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Giropay, PaymentMethodDetails{ mandates: common_enums::FeatureStatus::NotSupported, refunds: common_enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); mollie_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Ideal, PaymentMethodDetails{ mandates: common_enums::FeatureStatus::NotSupported, refunds: common_enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); mollie_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Sofort, PaymentMethodDetails{ mandates: common_enums::FeatureStatus::NotSupported, refunds: common_enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); mollie_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Przelewy24, PaymentMethodDetails{ mandates: common_enums::FeatureStatus::NotSupported, refunds: common_enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); mollie_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::BancontactCard, PaymentMethodDetails{ mandates: common_enums::FeatureStatus::NotSupported, refunds: common_enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); mollie_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::Paypal, PaymentMethodDetails{ mandates: common_enums::FeatureStatus::NotSupported, refunds: common_enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); mollie_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::ApplePay, PaymentMethodDetails{ mandates: common_enums::FeatureStatus::NotSupported, refunds: common_enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); mollie_supported_payment_methods.add( enums::PaymentMethod::BankDebit, enums::PaymentMethodType::Sepa, PaymentMethodDetails{ mandates: common_enums::FeatureStatus::NotSupported, refunds: common_enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); mollie_supported_payment_methods }; static ref MOLLIE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "MOLLIE", description: "Mollie is a Developer-friendly processor providing simple and customizable payment solutions for businesses of all sizes.", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Sandbox, }; static ref MOLLIE_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new(); } impl ConnectorSpecifications for Mollie { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&*MOLLIE_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*MOLLIE_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&*MOLLIE_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/mollie.rs
hyperswitch_connectors
full_file
6,124
null
null
null
null
null
null
null
null
null
null
null
null
null
pub fn get_not_implemented() -> Self { Self { code: "IR_00".to_string(), message: "This API is under development and will be made available soon.".to_string(), reason: None, status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(), attempt_status: None, connector_transaction_id: None, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_metadata: None, } }
crates/hyperswitch_domain_models/src/router_data.rs
hyperswitch_domain_models
function_signature
111
rust
null
null
null
null
get_not_implemented
null
null
null
null
null
null
null
amount_details: AttemptAmountDetails::from(amount_details), status: request.status, connector, authentication_type: storage_enums::AuthenticationType::NoThreeDs, created_at: transaction_created_at, modified_at: now, last_synced: None, cancellation_reason: None, browser_info: None, payment_token: None, connector_metadata: None, payment_experience: None, payment_method_data, routing_result: None, preprocessing_step_id: None, multiple_capture_count: None, connector_response_reference_id: None, updated_by: storage_scheme.to_string(), redirection_data: None, encoded_data: None, merchant_connector_id: request.payment_merchant_connector_id.clone(), external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, client_source: None, client_version: None, customer_acceptance: None, profile_id: payment_intent.profile_id.clone(), organization_id: payment_intent.organization_id.clone(), payment_method_type: request.payment_method_type, payment_method_id: None, connector_payment_id, payment_method_subtype: request.payment_method_subtype, authentication_applied: None, external_reference_id: None, payment_method_billing_address, error, feature_metadata: Some(feature_metadata), id, connector_token_details: Some(diesel_models::ConnectorTokenDetails { connector_mandate_id: Some(request.processor_payment_method_token.clone()), connector_token_request_reference_id: None, }), card_discovery: None, charges: None, processor_merchant_id: payment_intent.merchant_id.clone(), created_by: None, connector_request_reference_id, network_transaction_id: None, }) } pub fn get_attempt_merchant_connector_account_id( &self, ) -> CustomResult< id_type::MerchantConnectorAccountId, errors::api_error_response::ApiErrorResponse, > { let merchant_connector_id = self .merchant_connector_id .clone() .get_required_value("merchant_connector_id") .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Merchant connector id is None")?; Ok(merchant_connector_id) } } #[cfg(feature = "v1")] #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct PaymentAttempt { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub attempt_id: String, pub status: storage_enums::AttemptStatus, pub net_amount: NetAmount, pub currency: Option<storage_enums::Currency>, pub save_to_locker: Option<bool>, pub connector: Option<String>, pub error_message: Option<String>, pub offer_amount: Option<MinorUnit>, pub payment_method_id: Option<String>, pub payment_method: Option<storage_enums::PaymentMethod>, pub connector_transaction_id: Option<String>, pub capture_method: Option<storage_enums::CaptureMethod>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_on: Option<PrimitiveDateTime>, pub confirm: bool, pub authentication_type: Option<storage_enums::AuthenticationType>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub cancellation_reason: Option<String>, pub amount_to_capture: Option<MinorUnit>, pub mandate_id: Option<String>, pub browser_info: Option<serde_json::Value>, pub error_code: Option<String>, pub payment_token: Option<String>, pub connector_metadata: Option<serde_json::Value>, pub payment_experience: Option<storage_enums::PaymentExperience>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub payment_method_data: Option<serde_json::Value>, pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, // providing a location to store mandate details intermediately for transaction pub mandate_details: Option<MandateDataType>, pub error_reason: Option<String>, pub multiple_capture_count: Option<i16>, // reference to the payment at connector side pub connector_response_reference_id: Option<String>, pub amount_capturable: MinorUnit, pub updated_by: String, pub authentication_data: Option<serde_json::Value>, pub encoded_data: Option<String>, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub external_three_ds_authentication_attempted: Option<bool>, pub authentication_connector: Option<String>, pub authentication_id: Option<id_type::AuthenticationId>, pub mandate_data: Option<MandateDetails>, pub payment_method_billing_address_id: Option<String>, pub fingerprint_id: Option<String>, pub charge_id: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub profile_id: id_type::ProfileId, pub organization_id: id_type::OrganizationId, pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, pub capture_before: Option<PrimitiveDateTime>, pub card_discovery: Option<common_enums::CardDiscovery>, pub charges: Option<common_types::payments::ConnectorChargeResponseData>, pub issuer_error_code: Option<String>, pub issuer_error_message: Option<String>, /// merchant who owns the credentials of the processor, i.e. processor owner pub processor_merchant_id: id_type::MerchantId, /// merchantwho invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard)) pub created_by: Option<CreatedBy>, pub setup_future_usage_applied: Option<storage_enums::FutureUsage>, pub routing_approach: Option<storage_enums::RoutingApproach>, pub connector_request_reference_id: Option<String>, pub debit_routing_savings: Option<MinorUnit>, pub network_transaction_id: Option<String>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Default)] pub struct NetAmount { /// The payment amount order_amount: MinorUnit, /// The shipping cost of the order shipping_cost: Option<MinorUnit>, /// Tax amount related to the order order_tax_amount: Option<MinorUnit>, /// The surcharge amount to be added to the order surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v1")] impl NetAmount { pub fn new( order_amount: MinorUnit, shipping_cost: Option<MinorUnit>, order_tax_amount: Option<MinorUnit>, surcharge_amount: Option<MinorUnit>, tax_on_surcharge: Option<MinorUnit>, ) -> Self { Self { order_amount, shipping_cost, order_tax_amount, surcharge_amount, tax_on_surcharge, } } pub fn get_order_amount(&self) -> MinorUnit { self.order_amount } pub fn get_shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn get_order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn get_surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn get_tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } pub fn get_total_surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount .map(|surcharge_amount| surcharge_amount + self.tax_on_surcharge.unwrap_or_default()) } pub fn get_total_amount(&self) -> MinorUnit { self.order_amount + self.shipping_cost.unwrap_or_default() + self.order_tax_amount.unwrap_or_default() + self.surcharge_amount.unwrap_or_default() + self.tax_on_surcharge.unwrap_or_default() } pub fn get_additional_amount(&self) -> MinorUnit { self.get_total_amount() - self.get_order_amount() } pub fn set_order_amount(&mut self, order_amount: MinorUnit) { self.order_amount = order_amount; } pub fn set_order_tax_amount(&mut self, order_tax_amount: Option<MinorUnit>) { self.order_tax_amount = order_tax_amount; } pub fn set_surcharge_details( &mut self, surcharge_details: Option<router_request_types::SurchargeDetails>, ) { self.surcharge_amount = surcharge_details .clone() .map(|details| details.surcharge_amount); self.tax_on_surcharge = surcharge_details.map(|details| details.tax_on_surcharge_amount); } pub fn from_payments_request( payments_request: &api_models::payments::PaymentsRequest, order_amount: MinorUnit, ) -> Self { let surcharge_amount = payments_request .surcharge_details .map(|surcharge_details| surcharge_details.surcharge_amount); let tax_on_surcharge = payments_request .surcharge_details .and_then(|surcharge_details| surcharge_details.tax_amount); Self { order_amount, shipping_cost: payments_request.shipping_cost, order_tax_amount: payments_request.order_tax_amount, surcharge_amount, tax_on_surcharge, } } #[cfg(feature = "v1")] pub fn from_payments_request_and_payment_attempt( payments_request: &api_models::payments::PaymentsRequest, payment_attempt: Option<&PaymentAttempt>, ) -> Option<Self> { let option_order_amount = payments_request .amount .map(MinorUnit::from) .or(payment_attempt .map(|payment_attempt| payment_attempt.net_amount.get_order_amount())); option_order_amount.map(|order_amount| { let shipping_cost = payments_request.shipping_cost.or(payment_attempt .and_then(|payment_attempt| payment_attempt.net_amount.get_shipping_cost())); let order_tax_amount = payment_attempt .and_then(|payment_attempt| payment_attempt.net_amount.get_order_tax_amount()); let surcharge_amount = payments_request .surcharge_details .map(|surcharge_details| surcharge_details.get_surcharge_amount()) .or_else(|| { payment_attempt.and_then(|payment_attempt| { payment_attempt.net_amount.get_surcharge_amount() }) }); let tax_on_surcharge = payments_request .surcharge_details .and_then(|surcharge_details| surcharge_details.get_tax_amount()) .or_else(|| { payment_attempt.and_then(|payment_attempt| { payment_attempt.net_amount.get_tax_on_surcharge() }) }); Self { order_amount, shipping_cost, order_tax_amount, surcharge_amount, tax_on_surcharge, } }) } } #[cfg(feature = "v2")] impl PaymentAttempt { #[track_caller] pub fn get_total_amount(&self) -> MinorUnit { self.amount_details.get_net_amount() } pub fn get_total_surcharge_amount(&self) -> Option<MinorUnit> { self.amount_details.surcharge_amount } pub fn extract_card_network(&self) -> Option<common_enums::CardNetwork> { todo!() } } #[cfg(feature = "v1")] impl PaymentAttempt { pub fn get_total_amount(&self) -> MinorUnit { self.net_amount.get_total_amount() } pub fn get_total_surcharge_amount(&self) -> Option<MinorUnit> { self.net_amount.get_total_surcharge_amount() } pub fn set_debit_routing_savings(&mut self, debit_routing_savings: Option<&MinorUnit>) { self.debit_routing_savings = debit_routing_savings.copied(); } pub fn extract_card_network(&self) -> Option<common_enums::CardNetwork> { self.payment_method_data .as_ref() .and_then(|value| { value .clone() .parse_value::<api_models::payments::AdditionalPaymentData>( "AdditionalPaymentData", ) .ok() }) .and_then(|data| data.get_additional_card_info()) .and_then(|card_info| card_info.card_network) } pub fn get_payment_method_data(&self) -> Option<api_models::payments::AdditionalPaymentData> { self.payment_method_data .clone() .and_then(|data| match data { serde_json::Value::Null => None, _ => Some(data.parse_value("AdditionalPaymentData")), }) .transpose() .map_err(|err| logger::error!("Failed to parse AdditionalPaymentData {err:?}")) .ok() .flatten() } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct PaymentListFilters { pub connector: Vec<String>, pub currency: Vec<storage_enums::Currency>, pub status: Vec<storage_enums::IntentStatus>, pub payment_method: Vec<storage_enums::PaymentMethod>, pub payment_method_type: Vec<storage_enums::PaymentMethodType>, pub authentication_type: Vec<storage_enums::AuthenticationType>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, Serialize, Deserialize)] pub struct PaymentAttemptNew { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub attempt_id: String, pub status: storage_enums::AttemptStatus, /// amount + surcharge_amount + tax_amount /// This field will always be derived before updating in the Database pub net_amount: NetAmount, pub currency: Option<storage_enums::Currency>, // pub auto_capture: Option<bool>, pub save_to_locker: Option<bool>, pub connector: Option<String>, pub error_message: Option<String>, pub offer_amount: Option<MinorUnit>, pub payment_method_id: Option<String>, pub payment_method: Option<storage_enums::PaymentMethod>, pub capture_method: Option<storage_enums::CaptureMethod>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_on: Option<PrimitiveDateTime>, pub confirm: bool, pub authentication_type: Option<storage_enums::AuthenticationType>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created_at: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub modified_at: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub cancellation_reason: Option<String>, pub amount_to_capture: Option<MinorUnit>, pub mandate_id: Option<String>, pub browser_info: Option<serde_json::Value>, pub payment_token: Option<String>, pub error_code: Option<String>, pub connector_metadata: Option<serde_json::Value>, pub payment_experience: Option<storage_enums::PaymentExperience>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub payment_method_data: Option<serde_json::Value>, pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, pub mandate_details: Option<MandateDataType>, pub error_reason: Option<String>, pub connector_response_reference_id: Option<String>, pub multiple_capture_count: Option<i16>, pub amount_capturable: MinorUnit, pub updated_by: String, pub authentication_data: Option<serde_json::Value>, pub encoded_data: Option<String>, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub external_three_ds_authentication_attempted: Option<bool>, pub authentication_connector: Option<String>, pub authentication_id: Option<id_type::AuthenticationId>, pub mandate_data: Option<MandateDetails>, pub payment_method_billing_address_id: Option<String>, pub fingerprint_id: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub profile_id: id_type::ProfileId, pub organization_id: id_type::OrganizationId, pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, pub capture_before: Option<PrimitiveDateTime>, pub card_discovery: Option<common_enums::CardDiscovery>, /// merchant who owns the credentials of the processor, i.e. processor owner pub processor_merchant_id: id_type::MerchantId, /// merchantwho invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard)) pub created_by: Option<CreatedBy>, pub setup_future_usage_applied: Option<storage_enums::FutureUsage>, pub routing_approach: Option<storage_enums::RoutingApproach>, pub connector_request_reference_id: Option<String>, pub network_transaction_id: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PaymentAttemptUpdate { Update { net_amount: NetAmount, currency: storage_enums::Currency, status: storage_enums::AttemptStatus, authentication_type: Option<storage_enums::AuthenticationType>, payment_method: Option<storage_enums::PaymentMethod>, payment_token: Option<String>, payment_method_data: Option<serde_json::Value>, payment_method_type: Option<storage_enums::PaymentMethodType>, payment_experience: Option<storage_enums::PaymentExperience>, business_sub_label: Option<String>, amount_to_capture: Option<MinorUnit>, capture_method: Option<storage_enums::CaptureMethod>, fingerprint_id: Option<String>, payment_method_billing_address_id: Option<String>, updated_by: String, network_transaction_id: Option<String>, }, UpdateTrackers { payment_token: Option<String>, connector: Option<String>, straight_through_algorithm: Option<serde_json::Value>, amount_capturable: Option<MinorUnit>, surcharge_amount: Option<MinorUnit>, tax_amount: Option<MinorUnit>, updated_by: String, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, routing_approach: Option<storage_enums::RoutingApproach>, }, AuthenticationTypeUpdate { authentication_type: storage_enums::AuthenticationType, updated_by: String, }, ConfirmUpdate { net_amount: NetAmount, currency: storage_enums::Currency, status: storage_enums::AttemptStatus, authentication_type: Option<storage_enums::AuthenticationType>, capture_method: Option<storage_enums::CaptureMethod>, payment_method: Option<storage_enums::PaymentMethod>, browser_info: Option<serde_json::Value>, connector: Option<String>, payment_token: Option<String>, payment_method_data: Option<serde_json::Value>, payment_method_type: Option<storage_enums::PaymentMethodType>, payment_experience: Option<storage_enums::PaymentExperience>, business_sub_label: Option<String>, straight_through_algorithm: Option<serde_json::Value>, error_code: Option<Option<String>>, error_message: Option<Option<String>>, updated_by: String, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, external_three_ds_authentication_attempted: Option<bool>, authentication_connector: Option<String>, authentication_id: Option<id_type::AuthenticationId>, payment_method_billing_address_id: Option<String>, fingerprint_id: Option<String>, payment_method_id: Option<String>, client_source: Option<String>, client_version: Option<String>, customer_acceptance: Option<pii::SecretSerdeValue>, connector_mandate_detail: Option<ConnectorMandateReferenceId>, card_discovery: Option<common_enums::CardDiscovery>, routing_approach: Option<storage_enums::RoutingApproach>, connector_request_reference_id: Option<String>, network_transaction_id: Option<String>, }, RejectUpdate { status: storage_enums::AttemptStatus, error_code: Option<Option<String>>, error_message: Option<Option<String>>, updated_by: String, }, BlocklistUpdate { status: storage_enums::AttemptStatus, error_code: Option<Option<String>>, error_message: Option<Option<String>>, updated_by: String, }, PaymentMethodDetailsUpdate { payment_method_id: Option<String>, updated_by: String, }, ConnectorMandateDetailUpdate { connector_mandate_detail: Option<ConnectorMandateReferenceId>, updated_by: String, }, VoidUpdate { status: storage_enums::AttemptStatus, cancellation_reason: Option<String>, updated_by: String, }, ResponseUpdate { status: storage_enums::AttemptStatus, connector: Option<String>, connector_transaction_id: Option<String>, network_transaction_id: Option<String>, authentication_type: Option<storage_enums::AuthenticationType>, payment_method_id: Option<String>, mandate_id: Option<String>, connector_metadata: Option<serde_json::Value>, payment_token: Option<String>, error_code: Option<Option<String>>, error_message: Option<Option<String>>, error_reason: Option<Option<String>>, connector_response_reference_id: Option<String>, amount_capturable: Option<MinorUnit>, updated_by: String, authentication_data: Option<serde_json::Value>, encoded_data: Option<String>, unified_code: Option<Option<String>>, unified_message: Option<Option<String>>, capture_before: Option<PrimitiveDateTime>, extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, payment_method_data: Option<serde_json::Value>, connector_mandate_detail: Option<ConnectorMandateReferenceId>, charges: Option<common_types::payments::ConnectorChargeResponseData>, setup_future_usage_applied: Option<storage_enums::FutureUsage>, debit_routing_savings: Option<MinorUnit>, }, UnresolvedResponseUpdate { status: storage_enums::AttemptStatus, connector: Option<String>, connector_transaction_id: Option<String>, payment_method_id: Option<String>, error_code: Option<Option<String>>, error_message: Option<Option<String>>, error_reason: Option<Option<String>>, connector_response_reference_id: Option<String>, updated_by: String, }, StatusUpdate { status: storage_enums::AttemptStatus, updated_by: String, }, ErrorUpdate { connector: Option<String>, status: storage_enums::AttemptStatus, error_code: Option<Option<String>>, error_message: Option<Option<String>>, error_reason: Option<Option<String>>, amount_capturable: Option<MinorUnit>, updated_by: String, unified_code: Option<Option<String>>, unified_message: Option<Option<String>>, connector_transaction_id: Option<String>, payment_method_data: Option<serde_json::Value>, authentication_type: Option<storage_enums::AuthenticationType>, issuer_error_code: Option<String>, issuer_error_message: Option<String>, }, CaptureUpdate { amount_to_capture: Option<MinorUnit>, multiple_capture_count: Option<i16>, updated_by: String, }, AmountToCaptureUpdate { status: storage_enums::AttemptStatus, amount_capturable: MinorUnit, updated_by: String, }, PreprocessingUpdate { status: storage_enums::AttemptStatus, payment_method_id: Option<String>, connector_metadata: Option<serde_json::Value>, preprocessing_step_id: Option<String>, connector_transaction_id: Option<String>, connector_response_reference_id: Option<String>, updated_by: String, }, ConnectorResponse { authentication_data: Option<serde_json::Value>, encoded_data: Option<String>, connector_transaction_id: Option<String>, connector: Option<String>, charges: Option<common_types::payments::ConnectorChargeResponseData>, updated_by: String, }, IncrementalAuthorizationAmountUpdate { net_amount: NetAmount, amount_capturable: MinorUnit, }, AuthenticationUpdate { status: storage_enums::AttemptStatus, external_three_ds_authentication_attempted: Option<bool>, authentication_connector: Option<String>, authentication_id: Option<id_type::AuthenticationId>, updated_by: String, }, ManualUpdate { status: Option<storage_enums::AttemptStatus>, error_code: Option<String>, error_message: Option<String>, error_reason: Option<String>, updated_by: String, unified_code: Option<String>, unified_message: Option<String>, connector_transaction_id: Option<String>, }, PostSessionTokensUpdate { updated_by: String, connector_metadata: Option<serde_json::Value>, }, } #[cfg(feature = "v1")] impl PaymentAttemptUpdate { pub fn to_storage_model(self) -> diesel_models::PaymentAttemptUpdate { match self { Self::Update { net_amount, currency, status, authentication_type, payment_method, payment_token, payment_method_data, payment_method_type, payment_experience, business_sub_label, amount_to_capture, capture_method, fingerprint_id, network_transaction_id, payment_method_billing_address_id, updated_by, } => DieselPaymentAttemptUpdate::Update { amount: net_amount.get_order_amount(), currency, status, authentication_type, payment_method, payment_token, payment_method_data, payment_method_type, payment_experience, business_sub_label, amount_to_capture, capture_method, surcharge_amount: net_amount.get_surcharge_amount(), tax_amount: net_amount.get_tax_on_surcharge(), fingerprint_id, payment_method_billing_address_id, network_transaction_id, updated_by, }, Self::UpdateTrackers { payment_token, connector, straight_through_algorithm, amount_capturable, updated_by, surcharge_amount, tax_amount, merchant_connector_id, routing_approach, } => DieselPaymentAttemptUpdate::UpdateTrackers { payment_token, connector, straight_through_algorithm, amount_capturable, surcharge_amount, tax_amount, updated_by, merchant_connector_id, routing_approach: routing_approach.map(|approach| match approach { storage_enums::RoutingApproach::Other(_) => { // we need to make sure Other variant is not stored in DB, in the rare case // where we attempt to store an unknown value, we default to the default value storage_enums::RoutingApproach::default() } _ => approach, }), }, Self::AuthenticationTypeUpdate { authentication_type, updated_by, } => DieselPaymentAttemptUpdate::AuthenticationTypeUpdate { authentication_type, updated_by, }, Self::BlocklistUpdate { status, error_code, error_message, updated_by, } => DieselPaymentAttemptUpdate::BlocklistUpdate { status, error_code, error_message, updated_by, }, Self::ConnectorMandateDetailUpdate { connector_mandate_detail, updated_by, } => DieselPaymentAttemptUpdate::ConnectorMandateDetailUpdate { connector_mandate_detail, updated_by, }, Self::PaymentMethodDetailsUpdate { payment_method_id, updated_by, } => DieselPaymentAttemptUpdate::PaymentMethodDetailsUpdate { payment_method_id, updated_by, }, Self::ConfirmUpdate { net_amount, currency, status, authentication_type, capture_method, payment_method, browser_info, connector, payment_token, payment_method_data, payment_method_type, payment_experience, business_sub_label, straight_through_algorithm, error_code, error_message, fingerprint_id, updated_by, merchant_connector_id: connector_id, payment_method_id, external_three_ds_authentication_attempted, authentication_connector, authentication_id, payment_method_billing_address_id, client_source, client_version, customer_acceptance, connector_mandate_detail, card_discovery, routing_approach, connector_request_reference_id, network_transaction_id, } => DieselPaymentAttemptUpdate::ConfirmUpdate { amount: net_amount.get_order_amount(), currency, status, authentication_type, capture_method, payment_method, browser_info, connector, payment_token, payment_method_data, payment_method_type, payment_experience, business_sub_label, straight_through_algorithm, error_code, error_message, surcharge_amount: net_amount.get_surcharge_amount(), tax_amount: net_amount.get_tax_on_surcharge(), fingerprint_id, updated_by, merchant_connector_id: connector_id, payment_method_id, external_three_ds_authentication_attempted, authentication_connector, authentication_id, payment_method_billing_address_id, client_source, client_version, customer_acceptance, shipping_cost: net_amount.get_shipping_cost(), order_tax_amount: net_amount.get_order_tax_amount(), connector_mandate_detail, card_discovery, routing_approach: routing_approach.map(|approach| match approach { // we need to make sure Other variant is not stored in DB, in the rare case // where we attempt to store an unknown value, we default to the default value storage_enums::RoutingApproach::Other(_) => { storage_enums::RoutingApproach::default() } _ => approach, }), connector_request_reference_id, network_transaction_id, }, Self::VoidUpdate { status, cancellation_reason, updated_by, } => DieselPaymentAttemptUpdate::VoidUpdate { status, cancellation_reason, updated_by, }, Self::ResponseUpdate { status, connector, connector_transaction_id, authentication_type, payment_method_id, mandate_id, connector_metadata, payment_token, error_code, error_message, error_reason, connector_response_reference_id, amount_capturable, updated_by, authentication_data, encoded_data, unified_code, unified_message, capture_before, extended_authorization_applied, payment_method_data, connector_mandate_detail, charges, setup_future_usage_applied, network_transaction_id, debit_routing_savings: _, } => DieselPaymentAttemptUpdate::ResponseUpdate { status, connector, connector_transaction_id, authentication_type, payment_method_id, mandate_id, connector_metadata, payment_token, error_code, error_message, error_reason, connector_response_reference_id, amount_capturable, updated_by, authentication_data, encoded_data, unified_code, unified_message, capture_before, extended_authorization_applied, payment_method_data, connector_mandate_detail, charges, setup_future_usage_applied, network_transaction_id, }, Self::UnresolvedResponseUpdate { status, connector, connector_transaction_id, payment_method_id, error_code, error_message, error_reason, connector_response_reference_id, updated_by, } => DieselPaymentAttemptUpdate::UnresolvedResponseUpdate { status, connector, connector_transaction_id, payment_method_id, error_code, error_message, error_reason, connector_response_reference_id, updated_by, }, Self::StatusUpdate { status, updated_by } => { DieselPaymentAttemptUpdate::StatusUpdate { status, updated_by } } Self::ErrorUpdate { connector, status, error_code, error_message, error_reason, amount_capturable, updated_by, unified_code, unified_message, connector_transaction_id, payment_method_data, authentication_type, issuer_error_code, issuer_error_message, } => DieselPaymentAttemptUpdate::ErrorUpdate { connector, status, error_code, error_message, error_reason, amount_capturable, updated_by, unified_code, unified_message, connector_transaction_id, payment_method_data, authentication_type, issuer_error_code, issuer_error_message, }, Self::CaptureUpdate { multiple_capture_count, updated_by, amount_to_capture, } => DieselPaymentAttemptUpdate::CaptureUpdate { multiple_capture_count, updated_by, amount_to_capture, }, Self::PreprocessingUpdate { status, payment_method_id, connector_metadata, preprocessing_step_id, connector_transaction_id, connector_response_reference_id, updated_by, } => DieselPaymentAttemptUpdate::PreprocessingUpdate { status, payment_method_id, connector_metadata, preprocessing_step_id, connector_transaction_id, connector_response_reference_id, updated_by, }, Self::RejectUpdate { status, error_code, error_message, updated_by, } => DieselPaymentAttemptUpdate::RejectUpdate { status, error_code, error_message, updated_by, }, Self::AmountToCaptureUpdate { status, amount_capturable, updated_by, } => DieselPaymentAttemptUpdate::AmountToCaptureUpdate { status, amount_capturable, updated_by, }, Self::ConnectorResponse { authentication_data, encoded_data, connector_transaction_id, connector, charges, updated_by, } => DieselPaymentAttemptUpdate::ConnectorResponse { authentication_data, encoded_data, connector_transaction_id, charges, connector, updated_by, }, Self::IncrementalAuthorizationAmountUpdate { net_amount, amount_capturable, } => DieselPaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate { amount: net_amount.get_order_amount(), amount_capturable, }, Self::AuthenticationUpdate { status, external_three_ds_authentication_attempted, authentication_connector, authentication_id, updated_by, } => DieselPaymentAttemptUpdate::AuthenticationUpdate { status, external_three_ds_authentication_attempted, authentication_connector, authentication_id, updated_by, }, Self::ManualUpdate { status, error_code, error_message, error_reason, updated_by, unified_code, unified_message, connector_transaction_id, } => DieselPaymentAttemptUpdate::ManualUpdate { status, error_code, error_message, error_reason, updated_by, unified_code, unified_message, connector_transaction_id, }, Self::PostSessionTokensUpdate { updated_by, connector_metadata, } => DieselPaymentAttemptUpdate::PostSessionTokensUpdate { updated_by, connector_metadata, }, } } pub fn get_debit_routing_savings(&self) -> Option<&MinorUnit> { match self { Self::ResponseUpdate { debit_routing_savings, .. } => debit_routing_savings.as_ref(), Self::Update { .. } | Self::UpdateTrackers { .. } | Self::AuthenticationTypeUpdate { .. } | Self::ConfirmUpdate { .. } | Self::RejectUpdate { .. } | Self::BlocklistUpdate { .. } | Self::PaymentMethodDetailsUpdate { .. } | Self::ConnectorMandateDetailUpdate { .. } | Self::VoidUpdate { .. } | Self::UnresolvedResponseUpdate { .. } | Self::StatusUpdate { .. } | Self::ErrorUpdate { .. } | Self::CaptureUpdate { .. } | Self::AmountToCaptureUpdate { .. } | Self::PreprocessingUpdate { .. } | Self::ConnectorResponse { .. } | Self::IncrementalAuthorizationAmountUpdate { .. } | Self::AuthenticationUpdate { .. } | Self::ManualUpdate { .. } | Self::PostSessionTokensUpdate { .. } => None, } } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize)] pub struct ConfirmIntentResponseUpdate { pub status: storage_enums::AttemptStatus, pub connector_payment_id: Option<String>, pub updated_by: String, pub redirection_data: Option<router_response_types::RedirectForm>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub amount_capturable: Option<MinorUnit>, pub connector_token_details: Option<diesel_models::ConnectorTokenDetails>, pub connector_response_reference_id: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize)] pub enum PaymentAttemptUpdate { /// Update the payment attempt on confirming the intent, before calling the connector ConfirmIntent { status: storage_enums::AttemptStatus, updated_by: String, connector: String, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, authentication_type: storage_enums::AuthenticationType, connector_request_reference_id: Option<String>, connector_response_reference_id: Option<String>, },
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs#chunk1
hyperswitch_domain_models
chunk
8,192
null
null
null
null
null
null
null
null
null
null
null
null
null
OpenAPI Block Path: components.schemas.MerchantCountryCode { "type": "string", "description": "A wrapper type for merchant country codes that provides validation and conversion functionality.\n\nThis type stores a country code as a string and provides methods to validate it\nand convert it to a `Country` enum variant." }
./hyperswitch/api-reference/v1/openapi_spec_v1.json
null
openapi_block
70
.json
null
null
null
null
null
openapi_spec
components
[ "schemas", "MerchantCountryCode" ]
null
null
null
null
pub fn server(state: routes::AppState, service: String) -> Scope { web::scope("health") .app_data(web::Data::new(state)) .app_data(web::Data::new(service)) .service(web::resource("").route(web::get().to(health))) .service(web::resource("/ready").route(web::get().to(deep_health_check))) }
crates/router/src/bin/scheduler.rs
router
function_signature
83
rust
null
null
null
null
server
null
null
null
null
null
null
null
impl AnalyticsRequest { pub fn requires_forex_functionality(&self) -> bool { self.payment_attempt .as_ref() .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) .unwrap_or_default() || self .payment_intent .as_ref() .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) .unwrap_or_default() || self .refund .as_ref() .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) .unwrap_or_default() || self .dispute .as_ref() .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) .unwrap_or_default() } }
crates/api_models/src/analytics.rs
api_models
impl_block
176
rust
null
AnalyticsRequest
null
impl AnalyticsRequest
null
null
null
null
null
null
null
null
impl api::RefundSync for Tsys {}
crates/hyperswitch_connectors/src/connectors/tsys.rs
hyperswitch_connectors
impl_block
10
rust
null
Tsys
api::RefundSync for
impl api::RefundSync for for Tsys
null
null
null
null
null
null
null
null
impl AddressInterface for KafkaStore { async fn find_address_by_address_id( &self, state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { self.diesel_store .find_address_by_address_id(state, address_id, key_store) .await } async fn update_address( &self, state: &KeyManagerState, address_id: String, address: storage::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { self.diesel_store .update_address(state, address_id, address, key_store) .await } async fn update_address_for_payments( &self, state: &KeyManagerState, this: domain::PaymentAddress, address: domain::AddressUpdate, payment_id: id_type::PaymentId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { self.diesel_store .update_address_for_payments( state, this, address, payment_id, key_store, storage_scheme, ) .await } async fn insert_address_for_payments( &self, state: &KeyManagerState, payment_id: &id_type::PaymentId, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { self.diesel_store .insert_address_for_payments(state, payment_id, address, key_store, storage_scheme) .await } async fn find_address_by_merchant_id_payment_id_address_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, address_id: &str, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { self.diesel_store .find_address_by_merchant_id_payment_id_address_id( state, merchant_id, payment_id, address_id, key_store, storage_scheme, ) .await } async fn insert_address_for_customers( &self, state: &KeyManagerState, address: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { self.diesel_store .insert_address_for_customers(state, address, key_store) .await } async fn update_address_by_merchant_id_customer_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, address: storage::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Address>, errors::StorageError> { self.diesel_store .update_address_by_merchant_id_customer_id( state, customer_id, merchant_id, address, key_store, ) .await } }
crates/router/src/db/kafka_store.rs
router
impl_block
752
rust
null
KafkaStore
AddressInterface for
impl AddressInterface for for KafkaStore
null
null
null
null
null
null
null
null
impl ForexMetric for RefundMetrics { fn is_forex_metric(&self) -> bool { matches!( self, Self::RefundProcessedAmount | Self::SessionizedRefundProcessedAmount ) } }
crates/api_models/src/analytics/refunds.rs
api_models
impl_block
48
rust
null
RefundMetrics
ForexMetric for
impl ForexMetric for for RefundMetrics
null
null
null
null
null
null
null
null
pub struct CompleteAuthorize;
crates/router/src/core/payments/operations/payment_complete_authorize.rs
router
struct_definition
5
rust
CompleteAuthorize
null
null
null
null
null
null
null
null
null
null
null
pub struct DlocalPaymentsCaptureRequest { pub authorization_id: String, pub amount: i64, pub currency: String, pub order_id: String, }
crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs
hyperswitch_connectors
struct_definition
37
rust
DlocalPaymentsCaptureRequest
null
null
null
null
null
null
null
null
null
null
null
impl api::Refund for Globalpay {}
crates/hyperswitch_connectors/src/connectors/globalpay.rs
hyperswitch_connectors
impl_block
9
rust
null
Globalpay
api::Refund for
impl api::Refund for for Globalpay
null
null
null
null
null
null
null
null
impl<'a> NetworkTokenizationBuilder<'a, PmValidated> { pub fn set_card_details( self, card_from_locker: &'a api_models::payment_methods::Card, optional_card_info: Option<diesel_models::CardInfo>, card_cvc: Option<Secret<String>>, ) -> NetworkTokenizationBuilder<'a, PmAssigned> { let card = domain::CardDetail { card_number: card_from_locker.card_number.clone(), card_exp_month: card_from_locker.card_exp_month.clone(), card_exp_year: card_from_locker.card_exp_year.clone(), bank_code: optional_card_info .as_ref() .and_then(|card_info| card_info.bank_code.clone()), nick_name: card_from_locker .nick_name .as_ref() .map(|nick_name| Secret::new(nick_name.clone())), card_holder_name: card_from_locker.name_on_card.clone(), card_issuer: optional_card_info .as_ref() .and_then(|card_info| card_info.card_issuer.clone()), card_network: optional_card_info .as_ref() .and_then(|card_info| card_info.card_network.clone()), card_type: optional_card_info .as_ref() .and_then(|card_info| card_info.card_type.clone()), card_issuing_country: optional_card_info .as_ref() .and_then(|card_info| card_info.card_issuing_country.clone()), co_badged_card_data: None, }; NetworkTokenizationBuilder { state: std::marker::PhantomData, card: Some(card), card_cvc, customer: self.customer, network_token: self.network_token, stored_card: self.stored_card, stored_token: self.stored_token, payment_method_response: self.payment_method_response, card_tokenized: self.card_tokenized, error_code: self.error_code, error_message: self.error_message, } } }
crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
router
impl_block
433
rust
null
NetworkTokenizationBuilder
null
impl NetworkTokenizationBuilder
null
null
null
null
null
null
null
null
pub struct UpdateMetadata;
crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
hyperswitch_domain_models
struct_definition
5
rust
UpdateMetadata
null
null
null
null
null
null
null
null
null
null
null
pub struct LabelWithScoreEventResponse { pub score: f64, pub label: String, }
crates/api_models/src/routing.rs
api_models
struct_definition
23
rust
LabelWithScoreEventResponse
null
null
null
null
null
null
null
null
null
null
null
impl api::PaymentSync for Bamboraapac {}
crates/hyperswitch_connectors/src/connectors/bamboraapac.rs
hyperswitch_connectors
impl_block
12
rust
null
Bamboraapac
api::PaymentSync for
impl api::PaymentSync for for Bamboraapac
null
null
null
null
null
null
null
null
File: crates/analytics/src/payments/metrics/retries_count.rs use std::collections::HashSet; use api_models::{ analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, Granularity, TimeRange, }, enums::IntentStatus, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::PaymentMetricRow; use crate::{ enums::AuthInfo, query::{ Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window, }, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(super) struct RetriesCount; #[async_trait::async_trait] impl<T> super::PaymentMetric<T> for RetriesCount 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::PaymentIntent); query_builder .add_select_column(Aggregate::Count { field: None, alias: Some("count"), }) .switch()?; query_builder .add_select_column(Aggregate::Sum { field: "amount", alias: Some("total"), }) .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()?; auth.set_filter_clause(&mut query_builder).switch()?; query_builder .add_custom_filter_clause("attempt_count", "1", FilterTypes::Gt) .switch()?; query_builder .add_custom_filter_clause("status", IntentStatus::Succeeded, FilterTypes::Equal) .switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .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/retries_count.rs
analytics
full_file
968
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct Accept;
crates/hyperswitch_domain_models/src/router_flow_types/dispute.rs
hyperswitch_domain_models
struct_definition
4
rust
Accept
null
null
null
null
null
null
null
null
null
null
null
File: crates/hyperswitch_connectors/src/connectors/threedsecureio.rs Public structs: 1 pub mod transformers; use std::fmt::Debug; use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ authentication::{ Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall, }, AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session, SetupMandate, Void, }, router_request_types::{ authentication::{ ConnectorAuthenticationRequestData, ConnectorPostAuthenticationRequestData, PreAuthNRequestData, }, AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ AuthenticationResponseData, ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, }, }; use hyperswitch_interfaces::{ api::{ authentication::{ ConnectorAuthentication, ConnectorPostAuthentication, ConnectorPreAuthentication, ConnectorPreAuthenticationVersionCall, ExternalAuthentication, }, ConnectorAccessToken, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, CurrencyUnit, MandateSetup, Payment, PaymentAuthorize, PaymentCapture, PaymentSession, PaymentSync, PaymentToken, PaymentVoid, Refund, RefundExecute, RefundSync, }, configs::Connectors, consts::NO_ERROR_MESSAGE, errors::ConnectorError, events::connector_api_logs::ConnectorEvent, types::Response, webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; use masking::{ExposeInterface, Mask as _, Maskable}; use transformers as threedsecureio; use crate::{ constants::headers, types::{ ConnectorAuthenticationRouterData, ConnectorAuthenticationType, ConnectorPostAuthenticationRouterData, ConnectorPostAuthenticationType, ConnectorPreAuthenticationType, PreAuthNRouterData, ResponseRouterData, }, utils::handle_json_response_deserialization_failure, }; #[derive(Debug, Clone)] pub struct Threedsecureio; impl Payment for Threedsecureio {} impl PaymentSession for Threedsecureio {} impl ConnectorAccessToken for Threedsecureio {} impl MandateSetup for Threedsecureio {} impl PaymentAuthorize for Threedsecureio {} impl PaymentSync for Threedsecureio {} impl PaymentCapture for Threedsecureio {} impl PaymentVoid for Threedsecureio {} impl Refund for Threedsecureio {} impl RefundExecute for Threedsecureio {} impl RefundSync for Threedsecureio {} impl PaymentToken for Threedsecureio {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Threedsecureio { } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Threedsecureio where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), "application/json; charset=utf-8".to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Threedsecureio { fn id(&self) -> &'static str { "threedsecureio" } fn get_currency_unit(&self) -> CurrencyUnit { CurrencyUnit::Minor } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.threedsecureio.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let auth = threedsecureio::ThreedsecureioAuthType::try_from(auth_type) .change_context(ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::APIKEY.to_string(), auth.api_key.expose().into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { let response_result: Result< threedsecureio::ThreedsecureioErrorResponse, error_stack::Report<common_utils::errors::ParsingError>, > = res.response.parse_struct("ThreedsecureioErrorResponse"); match response_result { Ok(response) => { event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: response.error_code, message: response .error_description .clone() .unwrap_or(NO_ERROR_MESSAGE.to_owned()), reason: response.error_description, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } Err(err) => { router_env::logger::error!(deserialization_error =? err); handle_json_response_deserialization_failure(res, "threedsecureio") } } } } impl ConnectorValidation for Threedsecureio {} impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Threedsecureio {} impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Threedsecureio {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Threedsecureio { } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Threedsecureio { } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Threedsecureio {} impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Threedsecureio {} impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Threedsecureio {} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Threedsecureio {} impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Threedsecureio {} #[async_trait::async_trait] impl IncomingWebhook for Threedsecureio { fn get_webhook_object_reference_id( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<ObjectReferenceId, ConnectorError> { Err(report!(ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { Err(report!(ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { Err(report!(ConnectorError::WebhooksNotImplemented)) } } impl ConnectorPreAuthentication for Threedsecureio {} impl ConnectorPreAuthenticationVersionCall for Threedsecureio {} impl ExternalAuthentication for Threedsecureio {} impl ConnectorAuthentication for Threedsecureio {} impl ConnectorPostAuthentication for Threedsecureio {} impl ConnectorIntegration< Authentication, ConnectorAuthenticationRequestData, AuthenticationResponseData, > for Threedsecureio { fn get_headers( &self, req: &ConnectorAuthenticationRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &ConnectorAuthenticationRouterData, connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Ok(format!("{}/auth", self.base_url(connectors),)) } fn get_request_body( &self, req: &ConnectorAuthenticationRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, ConnectorError> { let connector_router_data = threedsecureio::ThreedsecureioRouterData::try_from(( &self.get_currency_unit(), req.request .currency .ok_or(ConnectorError::MissingRequiredField { field_name: "currency", })?, req.request .amount .ok_or(ConnectorError::MissingRequiredField { field_name: "amount", })?, req, ))?; let req_obj = threedsecureio::ThreedsecureioAuthenticationRequest::try_from(&connector_router_data); Ok(RequestContent::Json(Box::new(req_obj?))) } fn build_request( &self, req: &ConnectorAuthenticationRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&ConnectorAuthenticationType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(ConnectorAuthenticationType::get_headers( self, req, connectors, )?) .set_body(ConnectorAuthenticationType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &ConnectorAuthenticationRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<ConnectorAuthenticationRouterData, ConnectorError> { let response: threedsecureio::ThreedsecureioAuthenticationResponse = res .response .parse_struct("ThreedsecureioAuthenticationResponse") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PreAuthentication, PreAuthNRequestData, AuthenticationResponseData> for Threedsecureio { fn get_headers( &self, req: &PreAuthNRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PreAuthNRouterData, connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Ok(format!("{}/preauth", self.base_url(connectors),)) } fn get_request_body( &self, req: &PreAuthNRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, ConnectorError> { let connector_router_data = threedsecureio::ThreedsecureioRouterData::try_from((0, req))?; let req_obj = threedsecureio::ThreedsecureioPreAuthenticationRequest::try_from( &connector_router_data, )?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &PreAuthNRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&ConnectorPreAuthenticationType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(ConnectorPreAuthenticationType::get_headers( self, req, connectors, )?) .set_body(ConnectorPreAuthenticationType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PreAuthNRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PreAuthNRouterData, ConnectorError> { let response: threedsecureio::ThreedsecureioPreAuthenticationResponse = res .response .parse_struct("threedsecureio ThreedsecureioPreAuthenticationResponse") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration< PostAuthentication, ConnectorPostAuthenticationRequestData, AuthenticationResponseData, > for Threedsecureio { fn get_headers( &self, req: &ConnectorPostAuthenticationRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &ConnectorPostAuthenticationRouterData, connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Ok(format!("{}/postauth", self.base_url(connectors),)) } fn get_request_body( &self, req: &ConnectorPostAuthenticationRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, ConnectorError> { let req_obj = threedsecureio::ThreedsecureioPostAuthenticationRequest { three_ds_server_trans_id: req.request.threeds_server_transaction_id.clone(), }; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &ConnectorPostAuthenticationRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&ConnectorPostAuthenticationType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(ConnectorPostAuthenticationType::get_headers( self, req, connectors, )?) .set_body(ConnectorPostAuthenticationType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &ConnectorPostAuthenticationRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<ConnectorPostAuthenticationRouterData, ConnectorError> { let response: threedsecureio::ThreedsecureioPostAuthenticationResponse = res .response .parse_struct("threedsecureio PaymentsSyncResponse") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ConnectorPostAuthenticationRouterData { response: Ok(AuthenticationResponseData::PostAuthNResponse { trans_status: response.trans_status.into(), authentication_value: response.authentication_value, eci: response.eci, challenge_cancel: None, challenge_code_reason: None, }), ..data.clone() }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration< PreAuthenticationVersionCall, PreAuthNRequestData, AuthenticationResponseData, > for Threedsecureio { } static THREEDSECUREIO_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "3dsecure.io", description: "3DSecure.io is a service that facilitates 3-D Secure verifications for online credit and debit card transactions through a simple JSON API, enhancing payment security for merchants.docs.3dsecure.io3dsecure.io", connector_type: common_enums::HyperswitchConnectorCategory::AuthenticationProvider, integration_status: common_enums::ConnectorIntegrationStatus::Sandbox, }; impl ConnectorSpecifications for Threedsecureio { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&THREEDSECUREIO_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { None } fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> { None } }
crates/hyperswitch_connectors/src/connectors/threedsecureio.rs
hyperswitch_connectors
full_file
3,878
null
null
null
null
null
null
null
null
null
null
null
null
null
/// Indicates whether the syncing with the connector should be allowed or not pub fn should_force_sync_with_connector(self) -> bool { match self { // Confirm has not happened yet Self::RequiresConfirmation | Self::RequiresPaymentMethod // Once the status is success, failed or cancelled need not force sync with the connector | Self::Succeeded | Self::Failed | Self::Cancelled | Self::CancelledPostCapture | Self::PartiallyCaptured | Self::RequiresCapture | Self::Conflicted | Self::Expired=> false, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::PartiallyCapturedAndCapturable | Self::PartiallyAuthorizedAndRequiresCapture => true, } }
crates/common_enums/src/enums.rs
common_enums
function_signature
178
rust
null
null
null
null
should_force_sync_with_connector
null
null
null
null
null
null
null
impl PaymentCapture for Plaid {}
crates/hyperswitch_connectors/src/connectors/plaid.rs
hyperswitch_connectors
impl_block
7
rust
null
Plaid
PaymentCapture for
impl PaymentCapture for for Plaid
null
null
null
null
null
null
null
null
pub fn business_country_to_dir_value(c: api_enums::Country) -> dir::DirValue { dir::DirValue::BusinessCountry(get_dir_country_dir_value(c)) }
crates/kgraph_utils/src/transformers.rs
kgraph_utils
function_signature
37
rust
null
null
null
null
business_country_to_dir_value
null
null
null
null
null
null
null
impl api::RefundSync for Phonepe {}
crates/hyperswitch_connectors/src/connectors/phonepe.rs
hyperswitch_connectors
impl_block
10
rust
null
Phonepe
api::RefundSync for
impl api::RefundSync for for Phonepe
null
null
null
null
null
null
null
null
impl Responder { let flow = AnalyticsFlow::GetInfo; Box::pin(api::server_wrap( flow, state, &req, domain.into_inner(), |_, _: (), domain: analytics::AnalyticsDomain, _| async { analytics::core::get_domain_info(domain) .await .map(ApplicationResponse::Json) }, &auth::NoAuth, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/analytics.rs
router
impl_block
104
rust
null
Responder
null
impl Responder
null
null
null
null
null
null
null
null
impl api::ConnectorAccessToken for Braintree {}
crates/hyperswitch_connectors/src/connectors/braintree.rs
hyperswitch_connectors
impl_block
9
rust
null
Braintree
api::ConnectorAccessToken for
impl api::ConnectorAccessToken for for Braintree
null
null
null
null
null
null
null
null
pub struct RecurlyRouterData<T> { pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, }
crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs
hyperswitch_connectors
struct_definition
51
rust
RecurlyRouterData
null
null
null
null
null
null
null
null
null
null
null
pub struct SdkSessionUpdate;
crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
hyperswitch_domain_models
struct_definition
7
rust
SdkSessionUpdate
null
null
null
null
null
null
null
null
null
null
null
pub struct AirwallexRouterData<T> { pub amount: StringMajorUnit, pub router_data: T, }
crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
hyperswitch_connectors
struct_definition
26
rust
AirwallexRouterData
null
null
null
null
null
null
null
null
null
null
null
impl api::PaymentCapture for Paysafe {}
crates/hyperswitch_connectors/src/connectors/paysafe.rs
hyperswitch_connectors
impl_block
9
rust
null
Paysafe
api::PaymentCapture for
impl api::PaymentCapture for for Paysafe
null
null
null
null
null
null
null
null
impl api::PaymentSync for Payu {}
crates/hyperswitch_connectors/src/connectors/payu.rs
hyperswitch_connectors
impl_block
9
rust
null
Payu
api::PaymentSync for
impl api::PaymentSync for for Payu
null
null
null
null
null
null
null
null
pub struct ThreeDSEnolled { pub enrolled: bool, }
crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs
hyperswitch_connectors
struct_definition
16
rust
ThreeDSEnolled
null
null
null
null
null
null
null
null
null
null
null
pub struct Avs { code: Option<String>, code_raw: Option<String>, }
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
hyperswitch_connectors
struct_definition
19
rust
Avs
null
null
null
null
null
null
null
null
null
null
null
impl api::PaymentVoid for Bitpay {}
crates/hyperswitch_connectors/src/connectors/bitpay.rs
hyperswitch_connectors
impl_block
9
rust
null
Bitpay
api::PaymentVoid for
impl api::PaymentVoid for for Bitpay
null
null
null
null
null
null
null
null
pub struct ResponseIdStr { pub id: String, }
crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
hyperswitch_connectors
struct_definition
13
rust
ResponseIdStr
null
null
null
null
null
null
null
null
null
null
null
pub struct Worldpay { amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), }
crates/hyperswitch_connectors/src/connectors/worldpay.rs
hyperswitch_connectors
struct_definition
26
rust
Worldpay
null
null
null
null
null
null
null
null
null
null
null
pub struct PaysafePaymentHandleResponse { pub id: String, pub merchant_ref_num: String, pub payment_handle_token: Secret<String>, pub status: PaysafePaymentHandleStatus, }
crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
hyperswitch_connectors
struct_definition
42
rust
PaysafePaymentHandleResponse
null
null
null
null
null
null
null
null
null
null
null
pub struct UpdateSuccessRateWindowConfig { pub max_aggregates_size: Option<u32>, pub current_block_threshold: Option<api_routing::CurrentBlockThreshold>, }
crates/router/src/core/payments/routing/utils.rs
router
struct_definition
37
rust
UpdateSuccessRateWindowConfig
null
null
null
null
null
null
null
null
null
null
null
pub fn get_attempt_triggered_by(&self) -> Option<common_enums::TriggeredBy> { self.feature_metadata.as_ref().and_then(|metadata| { metadata .revenue_recovery .as_ref() .map(|recovery| recovery.attempt_triggered_by) }) }
crates/hyperswitch_domain_models/src/revenue_recovery.rs
hyperswitch_domain_models
function_signature
64
rust
null
null
null
null
get_attempt_triggered_by
null
null
null
null
null
null
null
pub async fn find_by_merchant_id_customer_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, customer_id: &common_utils::id_type::CustomerId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::customer_id.eq(customer_id.to_owned())), None, None, None, ) .await }
crates/diesel_models/src/query/mandate.rs
diesel_models
function_signature
144
rust
null
null
null
null
find_by_merchant_id_customer_id
null
null
null
null
null
null
null
File: crates/drainer/src/services.rs Public functions: 4 Public structs: 2 use std::sync::Arc; use actix_web::{body, HttpResponse, ResponseError}; use error_stack::Report; use redis_interface::RedisConnectionPool; use crate::{ connection::{diesel_make_pg_pool, PgPool}, logger, settings::Tenant, }; #[derive(Clone)] pub struct Store { pub master_pool: PgPool, pub redis_conn: Arc<RedisConnectionPool>, pub config: StoreConfig, pub request_id: Option<String>, } #[derive(Clone)] pub struct StoreConfig { pub drainer_stream_name: String, pub drainer_num_partitions: u8, pub use_legacy_version: bool, } impl Store { /// # Panics /// /// Panics if there is a failure while obtaining the HashiCorp client using the provided configuration. /// This panic indicates a critical failure in setting up external services, and the application cannot proceed without a valid HashiCorp client. pub async fn new(config: &crate::Settings, test_transaction: bool, tenant: &Tenant) -> Self { let redis_conn = crate::connection::redis_connection(config).await; Self { master_pool: diesel_make_pg_pool( config.master_database.get_inner(), test_transaction, &tenant.schema, ) .await, redis_conn: Arc::new(RedisConnectionPool::clone( &redis_conn, &tenant.redis_key_prefix, )), config: StoreConfig { drainer_stream_name: config.drainer.stream_name.clone(), drainer_num_partitions: config.drainer.num_partitions, use_legacy_version: config.redis.use_legacy_version, }, request_id: None, } } pub fn use_legacy_version(&self) -> bool { self.config.use_legacy_version } } pub fn log_and_return_error_response<T>(error: Report<T>) -> HttpResponse where T: error_stack::Context + ResponseError + Clone, { logger::error!(?error); let body = serde_json::json!({ "message": error.to_string() }) .to_string(); HttpResponse::InternalServerError() .content_type(mime::APPLICATION_JSON) .body(body) } pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpResponse { HttpResponse::Ok() .content_type(mime::APPLICATION_JSON) .body(response) }
crates/drainer/src/services.rs
drainer
full_file
525
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct ErrorResult { pub reason: String, pub count: i64, pub percentage: f64, }
crates/api_models/src/analytics/payment_intents.rs
api_models
struct_definition
28
rust
ErrorResult
null
null
null
null
null
null
null
null
null
null
null
impl ConnectorCommon for Phonepe { fn id(&self) -> &'static str { "phonepe" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Minor } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.phonepe.base_url.as_ref() } fn get_auth_header( &self, _auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { // This method is not implemented for Phonepe, as it will always call the UCS service which has the logic to create headers. Err(errors::ConnectorError::NotImplemented("get_auth_header method".to_string()).into()) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: phonepe::PhonepeErrorResponse = res .response .parse_struct("PhonepeErrorResponse") .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, }) } }
crates/hyperswitch_connectors/src/connectors/phonepe.rs
hyperswitch_connectors
impl_block
377
rust
null
Phonepe
ConnectorCommon for
impl ConnectorCommon for for Phonepe
null
null
null
null
null
null
null
null
pub fn new(algorithm_id: Option<T>) -> Self { Self { algorithm_id, timestamp: common_utils::date_time::now_unix_timestamp(), } }
crates/api_models/src/routing.rs
api_models
function_signature
37
rust
null
null
null
null
new
null
null
null
null
null
null
null
impl api::PaymentToken for Celero {}
crates/hyperswitch_connectors/src/connectors/celero.rs
hyperswitch_connectors
impl_block
9
rust
null
Celero
api::PaymentToken for
impl api::PaymentToken for for Celero
null
null
null
null
null
null
null
null
File: crates/router/tests/connectors/mifinity.rs use masking::Secret; use router::types::{self, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct MifinityTest; impl ConnectorActions for MifinityTest {} impl utils::Connector for MifinityTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Mifinity; utils::construct_connector_data_old( Box::new(Mifinity::new()), types::Connector::Mifinity, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .mifinity .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "mifinity".to_string() } } static CONNECTOR: MifinityTest = MifinityTest {}; 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/mifinity.rs
router
full_file
2,935
null
null
null
null
null
null
null
null
null
null
null
null
null
File: crates/router/src/types/fraud_check.rs Public structs: 1 pub use hyperswitch_domain_models::{ router_request_types::fraud_check::{ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, FraudCheckSaleData, FraudCheckTransactionData, RefundMethod, }, router_response_types::fraud_check::FraudCheckResponseData, }; use crate::{ services, types::{api, ErrorResponse, RouterData}, }; pub type FrmSaleRouterData = RouterData<api::Sale, FraudCheckSaleData, FraudCheckResponseData>; pub type FrmSaleType = dyn services::ConnectorIntegration<api::Sale, FraudCheckSaleData, FraudCheckResponseData>; #[derive(Debug, Clone)] pub struct FrmRouterData { pub merchant_id: common_utils::id_type::MerchantId, pub connector: String, // TODO: change this to PaymentId type pub payment_id: String, pub attempt_id: String, pub request: FrmRequest, pub response: FrmResponse, } #[derive(Debug, Clone)] pub enum FrmRequest { Sale(FraudCheckSaleData), Checkout(Box<FraudCheckCheckoutData>), Transaction(FraudCheckTransactionData), Fulfillment(FraudCheckFulfillmentData), RecordReturn(FraudCheckRecordReturnData), } #[derive(Debug, Clone)] pub enum FrmResponse { Sale(Result<FraudCheckResponseData, ErrorResponse>), Checkout(Result<FraudCheckResponseData, ErrorResponse>), Transaction(Result<FraudCheckResponseData, ErrorResponse>), Fulfillment(Result<FraudCheckResponseData, ErrorResponse>), RecordReturn(Result<FraudCheckResponseData, ErrorResponse>), } pub type FrmCheckoutRouterData = RouterData<api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>; pub type FrmCheckoutType = dyn services::ConnectorIntegration< api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData, >; pub type FrmTransactionRouterData = RouterData<api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>; pub type FrmTransactionType = dyn services::ConnectorIntegration< api::Transaction, FraudCheckTransactionData, FraudCheckResponseData, >; pub type FrmFulfillmentRouterData = RouterData<api::Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>; pub type FrmFulfillmentType = dyn services::ConnectorIntegration< api::Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData, >; pub type FrmRecordReturnRouterData = RouterData<api::RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>; pub type FrmRecordReturnType = dyn services::ConnectorIntegration< api::RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData, >;
crates/router/src/types/fraud_check.rs
router
full_file
597
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct ErrorMessagesResult { pub error_message: String, pub count: i64, pub percentage: f64, }
crates/api_models/src/analytics/refunds.rs
api_models
struct_definition
30
rust
ErrorMessagesResult
null
null
null
null
null
null
null
null
null
null
null
pub async fn update_all_merchant_accounts( conn: &PgPooledConn, merchant_account: MerchantAccountUpdateInternal, ) -> StorageResult<Vec<Self>> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id.ne_all(vec![""]), merchant_account, ) .await }
crates/diesel_models/src/query/merchant_account.rs
diesel_models
function_signature
83
rust
null
null
null
null
update_all_merchant_accounts
null
null
null
null
null
null
null
OpenAPI Block Path: components.schemas.Comparison { "type": "object", "description": "Represents a single comparison condition.", "required": [ "lhs", "comparison", "value", "metadata" ], "properties": { "lhs": { "type": "string", "description": "The left hand side which will always be a domain input identifier like \"payment.method.cardtype\"" }, "comparison": { "$ref": "#/components/schemas/ComparisonType" }, "value": { "$ref": "#/components/schemas/ValueType" }, "metadata": { "type": "object", "description": "Additional metadata that the Static Analyzer and Backend does not touch.\nThis can be used to store useful information for the frontend and is required for communication\nbetween the static analyzer and the frontend.", "additionalProperties": {} } } }
./hyperswitch/api-reference/v1/openapi_spec_v1.json
null
openapi_block
203
.json
null
null
null
null
null
openapi_spec
components
[ "schemas", "Comparison" ]
null
null
null
null
pub async fn perform_open_routing_for_debit_routing<F, D>( state: &SessionState, co_badged_card_request: or_types::CoBadgedCardRequest, card_isin: Option<Secret<String>>, old_payment_data: &mut D, ) -> RoutingResult<or_types::DebitRoutingOutput> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let payment_attempt = old_payment_data.get_payment_attempt().clone(); logger::debug!( "performing debit routing with open_router for profile {}", payment_attempt.profile_id.get_string_repr() ); let metadata = Some( serde_json::to_string(&co_badged_card_request) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode Vaulting data to string") .change_context(errors::RoutingError::MetadataParsingError)?, ); let open_router_req_body = OpenRouterDecideGatewayRequest::construct_debit_request( &payment_attempt, metadata, card_isin, Some(or_types::RankingAlgorithm::NtwBasedRouting), ); let routing_events_wrapper = utils::RoutingEventsWrapper::new( state.tenant.tenant_id.clone(), state.request_id, payment_attempt.payment_id.get_string_repr().to_string(), payment_attempt.profile_id.to_owned(), payment_attempt.merchant_id.to_owned(), "DecisionEngine: Debit Routing".to_string(), Some(open_router_req_body.clone()), true, true, ); let response: RoutingResult<utils::RoutingEventsResponse<DecidedGateway>> = utils::EuclidApiClient::send_decision_engine_request( state, services::Method::Post, "decide-gateway", Some(open_router_req_body), None, Some(routing_events_wrapper), ) .await; let output = match response { Ok(events_response) => { let response = events_response .response .ok_or(errors::RoutingError::OpenRouterError( "Response from decision engine API is empty".to_string(), ))?; let debit_routing_output = response .debit_routing_output .get_required_value("debit_routing_output") .change_context(errors::RoutingError::OpenRouterError( "Failed to parse the response from open_router".into(), )) .attach_printable("debit_routing_output is missing in the open routing response")?; old_payment_data.set_routing_approach_in_attempt(Some( common_enums::RoutingApproach::from_decision_engine_approach( &response.routing_approach, ), )); Ok(debit_routing_output) } Err(error_response) => { logger::error!("open_router_error_response: {:?}", error_response); Err(errors::RoutingError::OpenRouterError( "Failed to perform debit routing in open router".into(), )) } }?; Ok(output) }
crates/router/src/core/payments/routing.rs
router
function_signature
638
rust
null
null
null
null
perform_open_routing_for_debit_routing
null
null
null
null
null
null
null
pub struct AuthorizedotnetRouterData<T> { pub amount: FloatMajorUnit, pub router_data: T, }
crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
hyperswitch_connectors
struct_definition
26
rust
AuthorizedotnetRouterData
null
null
null
null
null
null
null
null
null
null
null
File: crates/hyperswitch_interfaces/src/connector_integration_interface.rs Public functions: 2 use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; use common_enums::PaymentAction; use common_utils::{crypto, errors::CustomResult, request::Request}; use hyperswitch_domain_models::{ api::ApplicationResponse, connector_endpoints::Connectors, errors::api_error_response::ApiErrorResponse, payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_data_v2::RouterDataV2, router_response_types::{ConnectorInfo, SupportedPaymentMethods}, }; use crate::{ api, api::{ BoxedConnectorIntegration, CaptureSyncMethod, Connector, ConnectorCommon, ConnectorIntegration, ConnectorRedirectResponse, ConnectorSpecifications, ConnectorValidation, CurrencyUnit, }, authentication::ExternalAuthenticationPayload, connector_integration_v2::{BoxedConnectorIntegrationV2, ConnectorIntegrationV2, ConnectorV2}, disputes, errors, events::connector_api_logs::ConnectorEvent, types, webhooks::{IncomingWebhook, IncomingWebhookFlowError, IncomingWebhookRequestDetails}, }; /// RouterDataConversion trait /// /// This trait must be implemented for conversion between Router data and RouterDataV2 pub trait RouterDataConversion<T, Req: Clone, Resp: Clone> { /// Convert RouterData to RouterDataV2 /// /// # Arguments /// /// * `old_router_data` - A reference to the old RouterData /// /// # Returns /// /// A `CustomResult` containing the new RouterDataV2 or a ConnectorError fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, errors::ConnectorError> where Self: Sized; /// Convert RouterDataV2 back to RouterData /// /// # Arguments /// /// * `new_router_data` - The new RouterDataV2 /// /// # Returns /// /// A `CustomResult` containing the old RouterData or a ConnectorError fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, errors::ConnectorError> where Self: Sized; } /// Alias for Box<&'static (dyn Connector + Sync)> pub type BoxedConnector = Box<&'static (dyn Connector + Sync)>; /// Alias for Box<&'static (dyn ConnectorV2 + Sync)> pub type BoxedConnectorV2 = Box<&'static (dyn ConnectorV2 + Sync)>; /// Enum representing the Connector #[derive(Clone)] pub enum ConnectorEnum { /// Old connector type Old(BoxedConnector), /// New connector type New(BoxedConnectorV2), } impl std::fmt::Debug for ConnectorEnum { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Old(_) => f .debug_tuple("Old") .field(&std::any::type_name::<BoxedConnector>().to_string()) .finish(), Self::New(_) => f .debug_tuple("New") .field(&std::any::type_name::<BoxedConnectorV2>().to_string()) .finish(), } } } #[allow(missing_debug_implementations)] /// Enum representing the Connector Integration #[derive(Clone)] pub enum ConnectorIntegrationEnum<'a, F, ResourceCommonData, Req, Resp> { /// Old connector integration type Old(BoxedConnectorIntegration<'a, F, Req, Resp>), /// New connector integration type New(BoxedConnectorIntegrationV2<'a, F, ResourceCommonData, Req, Resp>), } /// Alias for Box<dyn ConnectorIntegrationInterface> pub type BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp> = Box<dyn ConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp> + Send + Sync>; impl ConnectorEnum { /// Get the connector integration /// /// # Returns /// /// A `BoxedConnectorIntegrationInterface` containing the connector integration pub fn get_connector_integration<F, ResourceCommonData, Req, Resp>( &self, ) -> BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp> where dyn Connector + Sync: ConnectorIntegration<F, Req, Resp>, dyn ConnectorV2 + Sync: ConnectorIntegrationV2<F, ResourceCommonData, Req, Resp>, ResourceCommonData: RouterDataConversion<F, Req, Resp> + Clone + 'static, F: Clone + 'static, Req: Clone + 'static, Resp: Clone + 'static, { match self { Self::Old(old_integration) => Box::new(ConnectorIntegrationEnum::Old( old_integration.get_connector_integration(), )), Self::New(new_integration) => Box::new(ConnectorIntegrationEnum::New( new_integration.get_connector_integration_v2(), )), } } /// validates the file upload pub fn validate_file_upload( &self, purpose: api::files::FilePurpose, file_size: i32, file_type: mime::Mime, ) -> CustomResult<(), errors::ConnectorError> { match self { Self::Old(connector) => connector.validate_file_upload(purpose, file_size, file_type), Self::New(connector) => { connector.validate_file_upload_v2(purpose, file_size, file_type) } } } } #[async_trait::async_trait] impl IncomingWebhook for ConnectorEnum { fn get_webhook_body_decoding_algorithm( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::DecodeMessage + Send>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_body_decoding_algorithm(request), Self::New(connector) => connector.get_webhook_body_decoding_algorithm(request), } } fn get_webhook_body_decoding_message( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_body_decoding_message(request), Self::New(connector) => connector.get_webhook_body_decoding_message(request), } } async fn decode_webhook_body( &self, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, connector_name: &str, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { match self { Self::Old(connector) => { connector .decode_webhook_body( request, merchant_id, connector_webhook_details, connector_name, ) .await } Self::New(connector) => { connector .decode_webhook_body( request, merchant_id, connector_webhook_details, connector_name, ) .await } } } fn get_webhook_source_verification_algorithm( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_source_verification_algorithm(request), Self::New(connector) => connector.get_webhook_source_verification_algorithm(request), } } async fn get_webhook_source_verification_merchant_secret( &self, merchant_id: &common_utils::id_type::MerchantId, connector_name: &str, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<api_models::webhooks::ConnectorWebhookSecrets, errors::ConnectorError> { match self { Self::Old(connector) => { connector .get_webhook_source_verification_merchant_secret( merchant_id, connector_name, connector_webhook_details, ) .await } Self::New(connector) => { connector .get_webhook_source_verification_merchant_secret( merchant_id, connector_name, connector_webhook_details, ) .await } } } fn get_webhook_source_verification_signature( &self, request: &IncomingWebhookRequestDetails<'_>, connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { match self { Self::Old(connector) => connector .get_webhook_source_verification_signature(request, connector_webhook_secrets), Self::New(connector) => connector .get_webhook_source_verification_signature(request, connector_webhook_secrets), } } fn get_webhook_source_verification_message( &self, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_source_verification_message( request, merchant_id, connector_webhook_secrets, ), Self::New(connector) => connector.get_webhook_source_verification_message( request, merchant_id, connector_webhook_secrets, ), } } async fn verify_webhook_source( &self, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, connector_account_details: crypto::Encryptable<masking::Secret<serde_json::Value>>, connector_name: &str, ) -> CustomResult<bool, errors::ConnectorError> { match self { Self::Old(connector) => { connector .verify_webhook_source( request, merchant_id, connector_webhook_details, connector_account_details, connector_name, ) .await } Self::New(connector) => { connector .verify_webhook_source( request, merchant_id, connector_webhook_details, connector_account_details, connector_name, ) .await } } } fn get_webhook_object_reference_id( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<ObjectReferenceId, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_object_reference_id(request), Self::New(connector) => connector.get_webhook_object_reference_id(request), } } fn get_webhook_event_type( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_event_type(request), Self::New(connector) => connector.get_webhook_event_type(request), } } fn get_webhook_resource_object( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_resource_object(request), Self::New(connector) => connector.get_webhook_resource_object(request), } } fn get_webhook_api_response( &self, request: &IncomingWebhookRequestDetails<'_>, error_kind: Option<IncomingWebhookFlowError>, ) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_api_response(request, error_kind), Self::New(connector) => connector.get_webhook_api_response(request, error_kind), } } fn get_dispute_details( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<disputes::DisputePayload, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_dispute_details(request), Self::New(connector) => connector.get_dispute_details(request), } } fn get_external_authentication_details( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<ExternalAuthenticationPayload, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_external_authentication_details(request), Self::New(connector) => connector.get_external_authentication_details(request), } } fn get_mandate_details( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< Option<hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails>, errors::ConnectorError, > { match self { Self::Old(connector) => connector.get_mandate_details(request), Self::New(connector) => connector.get_mandate_details(request), } } fn get_network_txn_id( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< Option<hyperswitch_domain_models::router_flow_types::ConnectorNetworkTxnId>, errors::ConnectorError, > { match self { Self::Old(connector) => connector.get_network_txn_id(request), Self::New(connector) => connector.get_network_txn_id(request), } } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] fn get_revenue_recovery_invoice_details( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< hyperswitch_domain_models::revenue_recovery::RevenueRecoveryInvoiceData, errors::ConnectorError, > { match self { Self::Old(connector) => connector.get_revenue_recovery_invoice_details(request), Self::New(connector) => connector.get_revenue_recovery_invoice_details(request), } } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] fn get_revenue_recovery_attempt_details( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< hyperswitch_domain_models::revenue_recovery::RevenueRecoveryAttemptData, errors::ConnectorError, > { match self { Self::Old(connector) => connector.get_revenue_recovery_attempt_details(request), Self::New(connector) => connector.get_revenue_recovery_attempt_details(request), } } } impl ConnectorRedirectResponse for ConnectorEnum { fn get_flow_type( &self, query_params: &str, json_payload: Option<serde_json::Value>, action: PaymentAction, ) -> CustomResult<common_enums::CallConnectorAction, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_flow_type(query_params, json_payload, action), Self::New(connector) => connector.get_flow_type(query_params, json_payload, action), } } } impl ConnectorValidation for ConnectorEnum { fn validate_connector_against_payment_request( &self, capture_method: Option<common_enums::CaptureMethod>, payment_method: common_enums::PaymentMethod, pmt: Option<common_enums::PaymentMethodType>, ) -> CustomResult<(), errors::ConnectorError> { match self { Self::Old(connector) => connector.validate_connector_against_payment_request( capture_method, payment_method, pmt, ), Self::New(connector) => connector.validate_connector_against_payment_request( capture_method, payment_method, pmt, ), } } fn validate_mandate_payment( &self, pm_type: Option<common_enums::PaymentMethodType>, pm_data: PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { match self { Self::Old(connector) => connector.validate_mandate_payment(pm_type, pm_data), Self::New(connector) => connector.validate_mandate_payment(pm_type, pm_data), } } fn validate_psync_reference_id( &self, data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData, is_three_ds: bool, status: common_enums::enums::AttemptStatus, connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<(), errors::ConnectorError> { match self { Self::Old(connector) => connector.validate_psync_reference_id( data, is_three_ds, status, connector_meta_data, ), Self::New(connector) => connector.validate_psync_reference_id( data, is_three_ds, status, connector_meta_data, ), } } fn is_webhook_source_verification_mandatory(&self) -> bool { match self { Self::Old(connector) => connector.is_webhook_source_verification_mandatory(), Self::New(connector) => connector.is_webhook_source_verification_mandatory(), } } } impl ConnectorSpecifications for ConnectorEnum { fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { match self { Self::Old(connector) => connector.get_supported_payment_methods(), Self::New(connector) => connector.get_supported_payment_methods(), } } /// Supported webhooks flows fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::EventClass]> { match self { Self::Old(connector) => connector.get_supported_webhook_flows(), Self::New(connector) => connector.get_supported_webhook_flows(), } } /// Details related to connector fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { match self { Self::Old(connector) => connector.get_connector_about(), Self::New(connector) => connector.get_connector_about(), } } /// Check if connector supports authentication token fn authentication_token_for_token_creation(&self) -> bool { match self { Self::Old(connector) => connector.authentication_token_for_token_creation(), Self::New(connector) => connector.authentication_token_for_token_creation(), } } #[cfg(feature = "v1")] fn generate_connector_request_reference_id( &self, payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, is_config_enabled_to_send_payment_id_as_connector_request_id: bool, ) -> String { match self { Self::Old(connector) => connector.generate_connector_request_reference_id( payment_intent, payment_attempt, is_config_enabled_to_send_payment_id_as_connector_request_id, ), Self::New(connector) => connector.generate_connector_request_reference_id( payment_intent, payment_attempt, is_config_enabled_to_send_payment_id_as_connector_request_id, ), } } #[cfg(feature = "v2")] /// Generate connector request reference ID fn generate_connector_request_reference_id( &self, payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> String { match self { Self::Old(connector) => { connector.generate_connector_request_reference_id(payment_intent, payment_attempt) } Self::New(connector) => { connector.generate_connector_request_reference_id(payment_intent, payment_attempt) } } } } impl ConnectorCommon for ConnectorEnum { fn id(&self) -> &'static str { match self { Self::Old(connector) => connector.id(), Self::New(connector) => connector.id(), } } fn get_currency_unit(&self) -> CurrencyUnit { match self { Self::Old(connector) => connector.get_currency_unit(), Self::New(connector) => connector.get_currency_unit(), } } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_auth_header(auth_type), Self::New(connector) => connector.get_auth_header(auth_type), } } fn common_get_content_type(&self) -> &'static str { match self { Self::Old(connector) => connector.common_get_content_type(), Self::New(connector) => connector.common_get_content_type(), } } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { match self { Self::Old(connector) => connector.base_url(connectors), Self::New(connector) => connector.base_url(connectors), } } fn build_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { match self { Self::Old(connector) => connector.build_error_response(res, event_builder), Self::New(connector) => connector.build_error_response(res, event_builder), } } } /// Trait representing the connector integration interface /// /// This trait defines the methods required for a connector integration interface. pub trait ConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>: Send + Sync { /// Clone the connector integration interface /// /// # Returns /// /// A `Box` containing the cloned connector integration interface fn clone_box( &self, ) -> Box<dyn ConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp> + Send + Sync>; /// Get the multiple capture sync method /// /// # Returns /// /// A `CustomResult` containing the `CaptureSyncMethod` or a `ConnectorError` fn get_multiple_capture_sync_method( &self, ) -> CustomResult<CaptureSyncMethod, errors::ConnectorError>; /// Build a request for the connector integration /// /// # Arguments /// /// * `req` - A reference to the RouterData /// # Returns /// /// A `CustomResult` containing an optional Request or a ConnectorError fn build_request( &self, req: &RouterData<F, Req, Resp>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError>; /// handles response from the connector fn handle_response( &self, data: &RouterData<F, Req, Resp>, event_builder: Option<&mut ConnectorEvent>, _res: types::Response, ) -> CustomResult<RouterData<F, Req, Resp>, errors::ConnectorError> where F: Clone, Req: Clone, Resp: Clone; /// Get the error response /// /// # Arguments /// /// * `res` - The response /// * `event_builder` - An optional event builder /// /// # Returns /// /// A `CustomResult` containing the `ErrorResponse` or a `ConnectorError` fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError>; /// Get the 5xx error response /// /// # Arguments /// /// * `res` - The response /// * `event_builder` - An optional event builder /// /// # Returns /// /// A `CustomResult` containing the `ErrorResponse` or a `ConnectorError` fn get_5xx_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError>; } impl<T: 'static, ResourceCommonData: 'static, Req: 'static, Resp: 'static> ConnectorIntegrationInterface<T, ResourceCommonData, Req, Resp> for ConnectorIntegrationEnum<'static, T, ResourceCommonData, Req, Resp> where ResourceCommonData: RouterDataConversion<T, Req, Resp> + Clone, T: Clone, Req: Clone, Resp: Clone, { fn get_multiple_capture_sync_method( &self, ) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> { match self { ConnectorIntegrationEnum::Old(old_integration) => { old_integration.get_multiple_capture_sync_method() } ConnectorIntegrationEnum::New(new_integration) => { new_integration.get_multiple_capture_sync_method() } } } fn build_request( &self, req: &RouterData<T, Req, Resp>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { match self { ConnectorIntegrationEnum::Old(old_integration) => { old_integration.build_request(req, connectors) } ConnectorIntegrationEnum::New(new_integration) => { let new_router_data = ResourceCommonData::from_old_router_data(req)?; new_integration.build_request_v2(&new_router_data) } } } fn handle_response( &self, data: &RouterData<T, Req, Resp>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<RouterData<T, Req, Resp>, errors::ConnectorError> where T: Clone, Req: Clone, Resp: Clone, { match self { ConnectorIntegrationEnum::Old(old_integration) => { old_integration.handle_response(data, event_builder, res) } ConnectorIntegrationEnum::New(new_integration) => { let new_router_data = ResourceCommonData::from_old_router_data(data)?; new_integration .handle_response_v2(&new_router_data, event_builder, res) .map(ResourceCommonData::to_old_router_data)? } } } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { match self { ConnectorIntegrationEnum::Old(old_integration) => { old_integration.get_error_response(res, event_builder) } ConnectorIntegrationEnum::New(new_integration) => { new_integration.get_error_response_v2(res, event_builder) } } } fn get_5xx_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { match self { ConnectorIntegrationEnum::Old(old_integration) => { old_integration.get_5xx_error_response(res, event_builder) } ConnectorIntegrationEnum::New(new_integration) => { new_integration.get_5xx_error_response(res, event_builder) } } } fn clone_box( &self, ) -> Box<dyn ConnectorIntegrationInterface<T, ResourceCommonData, Req, Resp> + Send + Sync> { Box::new(self.clone()) } } impl api::ConnectorTransactionId for ConnectorEnum { /// Get the connector transaction ID /// /// # Arguments /// /// * `payment_attempt` - The payment attempt /// /// # Returns /// /// A `Result` containing an optional transaction ID or an ApiErrorResponse fn connector_transaction_id( &self, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> Result<Option<String>, ApiErrorResponse> { match self { Self::Old(connector) => connector.connector_transaction_id(payment_attempt), Self::New(connector) => connector.connector_transaction_id(payment_attempt), } } }
crates/hyperswitch_interfaces/src/connector_integration_interface.rs
hyperswitch_interfaces
full_file
6,125
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct DisputesFlowData { pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: String, pub attempt_id: String, pub payment_method: common_enums::enums::PaymentMethod, pub connector_meta_data: Option<pii::SecretSerdeValue>, pub amount_captured: Option<i64>, // minor amount for amount framework pub minor_amount_captured: Option<MinorUnit>, /// Contains a reference ID that should be sent in the connector request pub connector_request_reference_id: String, pub dispute_id: String, }
crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
hyperswitch_domain_models
struct_definition
128
rust
DisputesFlowData
null
null
null
null
null
null
null
null
null
null
null
pub struct TrustpayWebhookResponse { pub payment_information: WebhookPaymentInformation, pub signature: String, }
crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
hyperswitch_connectors
struct_definition
25
rust
TrustpayWebhookResponse
null
null
null
null
null
null
null
null
null
null
null
pub fn create_authorization(self, source: Authorization) -> Authorization { Authorization { status: self.status.unwrap_or(source.status), error_code: self.error_code.or(source.error_code), error_message: self.error_message.or(source.error_message), modified_at: self.modified_at.unwrap_or(common_utils::date_time::now()), connector_authorization_id: self .connector_authorization_id .or(source.connector_authorization_id), ..source } }
crates/diesel_models/src/authorization.rs
diesel_models
function_signature
100
rust
null
null
null
null
create_authorization
null
null
null
null
null
null
null
pub struct FilterResourceParams<'a> { pub key: PartitionKey<'a>, pub pattern: &'static str, pub limit: Option<i64>, }
crates/storage_impl/src/kv_router_store.rs
storage_impl
struct_definition
36
rust
FilterResourceParams
null
null
null
null
null
null
null
null
null
null
null
pub struct CaptureResponseData { pub statuses: Statuses, pub descriptor: String, pub notifications: NotificationContainer, #[serde(rename = "merchant-account-id")] pub merchant_account_id: MerchantAccountId, #[serde(rename = "transaction-id")] pub transaction_id: String, #[serde(rename = "request-id")] pub request_id: String, #[serde(rename = "transaction-type")] pub transaction_type: GetnetTransactionType, #[serde(rename = "transaction-state")] pub transaction_state: GetnetPaymentStatus, #[serde(rename = "completion-time-stamp")] pub completion_time_stamp: Option<i64>, #[serde(rename = "requested-amount")] pub requested_amount: Amount, #[serde(rename = "parent-transaction-id")] pub parent_transaction_id: String, #[serde(rename = "account-holder")] pub account_holder: Option<AccountHolder>, #[serde(rename = "card-token")] pub card_token: CardToken, #[serde(rename = "ip-address")] pub ip_address: Option<Secret<String, IpAddress>>, #[serde(rename = "payment-methods")] pub payment_methods: PaymentMethodContainer, #[serde(rename = "parent-transaction-amount")] pub parent_transaction_amount: Amount, #[serde(rename = "authorization-code")] pub authorization_code: String, #[serde(rename = "api-id")] pub api_id: String, #[serde(rename = "self")] pub self_url: String, }
crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs
hyperswitch_connectors
struct_definition
317
rust
CaptureResponseData
null
null
null
null
null
null
null
null
null
null
null
impl ConnectorValidation for Bitpay {}
crates/hyperswitch_connectors/src/connectors/bitpay.rs
hyperswitch_connectors
impl_block
7
rust
null
Bitpay
ConnectorValidation for
impl ConnectorValidation for for Bitpay
null
null
null
null
null
null
null
null
pub async fn generate_token_data_response( state: &SessionState, request: payment_methods::GetTokenDataRequest, profile: domain::Profile, payment_method: &domain_payment_methods::PaymentMethod, ) -> RouterResult<api::TokenDataResponse> { let token_details = match request.token_type { common_enums::TokenDataType::NetworkToken => { let is_network_tokenization_enabled = profile.is_network_tokenization_enabled; if !is_network_tokenization_enabled { return Err(errors::ApiErrorResponse::UnprocessableEntity { message: "Network tokenization is not enabled for this profile".to_string(), } .into()); } let network_token_requestor_ref_id = payment_method .network_token_requestor_reference_id .clone() .ok_or(errors::ApiErrorResponse::GenericNotFoundError { message: "NetworkTokenRequestorReferenceId is not present".to_string(), })?; let network_token = network_tokenization::get_token_from_tokenization_service( state, network_token_requestor_ref_id, payment_method, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch network token data from tokenization service")?; api::TokenDetailsResponse::NetworkTokenDetails(api::NetworkTokenDetailsResponse { network_token: network_token.network_token, network_token_exp_month: network_token.network_token_exp_month, network_token_exp_year: network_token.network_token_exp_year, cryptogram: network_token.cryptogram, card_issuer: network_token.card_issuer, card_network: network_token.card_network, card_type: network_token.card_type, card_issuing_country: network_token.card_issuing_country, bank_code: network_token.bank_code, card_holder_name: network_token.card_holder_name, nick_name: network_token.nick_name, eci: network_token.eci, }) } common_enums::TokenDataType::SingleUseToken | common_enums::TokenDataType::MultiUseToken => { return Err(errors::ApiErrorResponse::UnprocessableEntity { message: "Token type not supported".to_string(), } .into()); } }; Ok(api::TokenDataResponse { payment_method_id: payment_method.id.clone(), token_type: request.token_type, token_details, }) }
crates/router/src/core/payment_methods.rs
router
function_signature
504
rust
null
null
null
null
generate_token_data_response
null
null
null
null
null
null
null
impl FrmMetricAccumulator for BlockedRateAccumulator { type MetricOutput = Option<f64>; fn add_metrics_bucket(&mut self, metrics: &FrmMetricRow) { if let Some(ref frm_status) = metrics.frm_status { if frm_status.as_ref() == &storage_enums::FraudCheckStatus::Fraud { self.fraud += metrics.count.unwrap_or_default(); } }; self.total += metrics.count.unwrap_or_default(); } fn collect(self) -> Self::MetricOutput { if self.total <= 0 { None } else { Some( f64::from(u32::try_from(self.fraud).ok()?) * 100.0 / f64::from(u32::try_from(self.total).ok()?), ) } } }
crates/analytics/src/frm/accumulator.rs
analytics
impl_block
185
rust
null
BlockedRateAccumulator
FrmMetricAccumulator for
impl FrmMetricAccumulator for for BlockedRateAccumulator
null
null
null
null
null
null
null
null
pub struct PlaidRecipientCreateRequest { pub name: String, #[serde(flatten)] pub account_data: PlaidRecipientAccountData, pub address: Option<PlaidRecipientCreateAddress>, }
crates/pm_auth/src/connector/plaid/transformers.rs
pm_auth
struct_definition
44
rust
PlaidRecipientCreateRequest
null
null
null
null
null
null
null
null
null
null
null
pub async fn find_all_by_merchant_id_payment_id_authorized_attempt_id( merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, authorized_attempt_id: &str, conn: &PgPooledConn, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::authorized_attempt_id .eq(authorized_attempt_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())) .and(dsl::payment_id.eq(payment_id.to_owned())), None, None, Some(dsl::created_at.asc()), ) .await }
crates/diesel_models/src/query/capture.rs
diesel_models
function_signature
161
rust
null
null
null
null
find_all_by_merchant_id_payment_id_authorized_attempt_id
null
null
null
null
null
null
null
OpenAPI Block Path: components.schemas.PaylaterResponse { "type": "object", "properties": { "klarna_sdk": { "allOf": [ { "$ref": "#/components/schemas/KlarnaSdkPaymentMethodResponse" } ], "nullable": true } } }
./hyperswitch/api-reference/v1/openapi_spec_v1.json
null
openapi_block
72
.json
null
null
null
null
null
openapi_spec
components
[ "schemas", "PaylaterResponse" ]
null
null
null
null
pub struct OrderFulfillment { id: String, fulfillments: FulfilmentData, }
crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs
hyperswitch_connectors
struct_definition
22
rust
OrderFulfillment
null
null
null
null
null
null
null
null
null
null
null
OpenAPI Block Path: paths."/payments/{payment_id}/update_metadata" { "post": { "tags": [ "Payments" ], "summary": "Payments - Update Metadata", "operationId": "Update Metadata for a Payment", "parameters": [ { "name": "payment_id", "in": "path", "description": "The identifier for payment", "required": true, "schema": { "type": "string" } } ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/PaymentsUpdateMetadataRequest" } } }, "required": true }, "responses": { "200": { "description": "Metadata updated successfully", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/PaymentsUpdateMetadataResponse" } } } }, "400": { "description": "Missing mandatory fields", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/GenericErrorResponseOpenApi" } } } } }, "security": [ { "api_key": [] } ] } }
./hyperswitch/api-reference/v1/openapi_spec_v1.json
null
openapi_block
300
.json
null
null
null
null
null
openapi_spec
paths
[ "/payments/{payment_id}/update_metadata" ]
null
null
null
null
impl<T: serde::Serialize> GetLockingInput for PaymentsGenericRequestWithResourceId<T> { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: self.global_payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, } } }
crates/router/src/routes/payments.rs
router
impl_block
132
rust
null
PaymentsGenericRequestWithResourceId
GetLockingInput for
impl GetLockingInput for for PaymentsGenericRequestWithResourceId
null
null
null
null
null
null
null
null
pub fn custom_json_error_handler(err: JsonPayloadError, _req: &HttpRequest) -> Error { Error::from(CustomJsonError { err }) }
crates/router/src/utils.rs
router
function_signature
34
rust
null
null
null
null
custom_json_error_handler
null
null
null
null
null
null
null
pub struct PmAssigned;
crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
router
struct_definition
6
rust
PmAssigned
null
null
null
null
null
null
null
null
null
null
null
impl RefundMetricAccumulator for SuccessRateAccumulator { type MetricOutput = (Option<u32>, Option<u32>, Option<f64>); fn add_metrics_bucket(&mut self, metrics: &RefundMetricRow) { if let Some(ref refund_status) = metrics.refund_status { if refund_status.as_ref() == &storage_enums::RefundStatus::Success { if let Some(success) = metrics .count .and_then(|success| u32::try_from(success).ok()) { self.success += success; } } }; if let Some(total) = metrics.count.and_then(|total| u32::try_from(total).ok()) { self.total += total; } } fn collect(self) -> Self::MetricOutput { if self.total == 0 { (None, None, None) } else { let success = Some(self.success); let total = Some(self.total); let success_rate = match (success, total) { (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), _ => None, }; (success, total, success_rate) } } }
crates/analytics/src/refunds/accumulator.rs
analytics
impl_block
283
rust
null
SuccessRateAccumulator
RefundMetricAccumulator for
impl RefundMetricAccumulator for for SuccessRateAccumulator
null
null
null
null
null
null
null
null
File: crates/router/src/routes/tokenization.rs Public functions: 2 #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use std::sync::Arc; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use actix_web::{web, HttpRequest, HttpResponse}; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use api_models; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use common_utils::{ ext_traits::{BytesExt, Encode}, id_type, }; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use error_stack::ResultExt; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use hyperswitch_domain_models; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use masking::Secret; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use router_env::{instrument, logger, tracing, Flow}; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use serde::Serialize; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use crate::{ core::{ api_locking, errors::{self, RouterResult}, tokenization, }, headers::X_CUSTOMER_ID, routes::{app::StorageInterface, AppState, SessionState}, services::{self, api as api_service, authentication as auth}, types::{api, domain, payment_methods as pm_types}, }; #[instrument(skip_all, fields(flow = ?Flow::TokenizationCreate))] #[cfg(all(feature = "v2", feature = "tokenization_v2"))] pub async fn create_token_vault_api( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_models::tokenization::GenericTokenizationRequest>, ) -> HttpResponse { let flow = Flow::TokenizationCreate; let payload = json_payload.into_inner(); let customer_id = payload.customer_id.clone(); Box::pin(api_service::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, request, _| async move { tokenization::create_vault_token_core( state, &auth.merchant_account, &auth.key_store, request, ) .await }, auth::api_or_client_auth( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Customer( customer_id, )), req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::TokenizationDelete))] #[cfg(all(feature = "v2", feature = "tokenization_v2"))] pub async fn delete_tokenized_data_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalTokenId>, json_payload: web::Json<api_models::tokenization::DeleteTokenDataRequest>, ) -> HttpResponse { let flow = Flow::TokenizationDelete; let payload = json_payload.into_inner(); let session_id = payload.session_id.clone(); let token_id = path.into_inner(); Box::pin(api_service::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); tokenization::delete_tokenized_data_core(state, merchant_context, &token_id, req) }, auth::api_or_client_auth( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::V2ClientAuth( common_utils::types::authentication::ResourceId::PaymentMethodSession(session_id), ), req.headers(), ), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/tokenization.rs
router
full_file
919
null
null
null
null
null
null
null
null
null
null
null
null
null
File: crates/test_utils/tests/connectors/authorizedotnet_ui.rs use rand::Rng; use serial_test::serial; use thirtyfour::{prelude::*, WebDriver}; use crate::{selenium::*, tester}; struct AuthorizedotnetSeleniumTest; impl SeleniumTest for AuthorizedotnetSeleniumTest { fn get_connector_name(&self) -> String { "authorizedotnet".to_string() } } async fn should_make_gpay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> { let conn = AuthorizedotnetSeleniumTest {}; let amount = rand::thread_rng().gen_range(1..1000); //This connector detects it as fraudulent payment if the same amount is used for multiple payments so random amount is passed for testing let pub_key = conn .get_configs() .automation_configs .unwrap() .authorizedotnet_gateway_merchant_id .unwrap(); conn.make_gpay_payment(web_driver, &format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=authorizenet&gatewaymerchantid={pub_key}&amount={amount}&country=US&currency=USD"), vec![ Event::Assert(Assert::IsPresent("status")), Event::Assert(Assert::IsPresent("processing")), // This connector status will be processing for one day ]).await?; Ok(()) } async fn should_make_paypal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> { let conn = AuthorizedotnetSeleniumTest {}; conn.make_paypal_payment( web_driver, &format!("{CHECKOUT_BASE_URL}/saved/156"), vec![ Event::EitherOr( Assert::IsElePresent(By::Css(".reviewButton")), vec![Event::Trigger(Trigger::Click(By::Css(".reviewButton")))], vec![Event::Trigger(Trigger::Click(By::Id("payment-submit-btn")))], ), Event::Assert(Assert::IsPresent("status")), Event::Assert(Assert::IsPresent("processing")), // This connector status will be processing for one day ], ) .await?; Ok(()) } #[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/authorizedotnet_ui.rs
test_utils
full_file
511
null
null
null
null
null
null
null
null
null
null
null
null
null
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserKeyStore> { generics::generic_insert(conn, self).await }
crates/diesel_models/src/query/user_key_store.rs
diesel_models
function_signature
35
rust
null
null
null
null
insert
null
null
null
null
null
null
null
pub struct NovalnetRefundsTransactionData { pub amount: Option<MinorUnit>, pub date: Option<String>, pub currency: Option<common_enums::Currency>, pub order_no: Option<String>, pub payment_type: String, pub refund: RefundData, pub refunded_amount: Option<u64>, pub status: NovalnetTransactionStatus, pub status_code: u64, pub test_mode: u8, pub tid: Option<Secret<i64>>, }
crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
hyperswitch_connectors
struct_definition
110
rust
NovalnetRefundsTransactionData
null
null
null
null
null
null
null
null
null
null
null
pub struct RazorpayWebhookPayload { // pub event: RazorpayWebhookEventType, // pub payload: RazorpayWebhookPayloadBody, // }
crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs
hyperswitch_connectors
struct_definition
33
rust
RazorpayWebhookPayload
null
null
null
null
null
null
null
null
null
null
null
impl CustomerUpdateRequest { pub fn get_address(&self) -> Option<payments::AddressDetails> { self.address.clone() } }
crates/api_models/src/customers.rs
api_models
impl_block
31
rust
null
CustomerUpdateRequest
null
impl CustomerUpdateRequest
null
null
null
null
null
null
null
null
pub struct SwitchMerchantRequest { pub merchant_id: id_type::MerchantId, }
crates/api_models/src/user.rs
api_models
struct_definition
18
rust
SwitchMerchantRequest
null
null
null
null
null
null
null
null
null
null
null
pub trait GsmValidation { // TODO : move this function to appropriate place later. fn should_call_gsm(&self) -> bool; }
crates/router/src/core/payouts/retry.rs
router
trait_definition
31
rust
null
null
GsmValidation
null
null
null
null
null
null
null
null
null
File: crates/router/src/routes/webhook_events.rs Public functions: 4 use actix_web::{web, HttpRequest, Responder}; use router_env::{instrument, tracing, Flow}; use crate::{ core::{api_locking, webhooks::webhook_events}, routes::AppState, services::{ api, authentication::{self as auth, UserFromToken}, authorization::permissions::Permission, }, types::api::webhook_events::{ EventListConstraints, EventListRequestInternal, WebhookDeliveryAttemptListRequestInternal, WebhookDeliveryRetryRequestInternal, }, }; #[instrument(skip_all, fields(flow = ?Flow::WebhookEventInitialDeliveryAttemptList))] pub async fn list_initial_webhook_delivery_attempts( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, json_payload: web::Json<EventListConstraints>, ) -> impl Responder { let flow = Flow::WebhookEventInitialDeliveryAttemptList; let merchant_id = path.into_inner(); let constraints = json_payload.into_inner(); let request_internal = EventListRequestInternal { merchant_id: merchant_id.clone(), constraints, }; Box::pin(api::server_wrap( flow, state, &req, request_internal, |state, _, request_internal, _| { webhook_events::list_initial_delivery_attempts( state, request_internal.merchant_id, request_internal.constraints, ) }, auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantWebhookEventRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::WebhookEventInitialDeliveryAttemptList))] pub async fn list_initial_webhook_delivery_attempts_with_jwtauth( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<EventListConstraints>, ) -> impl Responder { let flow = Flow::WebhookEventInitialDeliveryAttemptList; let constraints = json_payload.into_inner(); let request_internal = EventListRequestInternal { merchant_id: common_utils::id_type::MerchantId::default(), constraints, }; Box::pin(api::server_wrap( flow, state, &req, request_internal, |state, auth: UserFromToken, mut request_internal, _| { let merchant_id = auth.merchant_id; let profile_id = auth.profile_id; request_internal.merchant_id = merchant_id; request_internal.constraints.profile_id = Some(profile_id); webhook_events::list_initial_delivery_attempts( state, request_internal.merchant_id, request_internal.constraints, ) }, &auth::JWTAuth { permission: Permission::ProfileWebhookEventRead, }, api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::WebhookEventDeliveryAttemptList))] pub async fn list_webhook_delivery_attempts( state: web::Data<AppState>, req: HttpRequest, path: web::Path<(common_utils::id_type::MerchantId, String)>, ) -> impl Responder { let flow = Flow::WebhookEventDeliveryAttemptList; let (merchant_id, initial_attempt_id) = path.into_inner(); let request_internal = WebhookDeliveryAttemptListRequestInternal { merchant_id: merchant_id.clone(), initial_attempt_id, }; Box::pin(api::server_wrap( flow, state, &req, request_internal, |state, _, request_internal, _| { webhook_events::list_delivery_attempts( state, request_internal.merchant_id, request_internal.initial_attempt_id, ) }, auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantWebhookEventRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::WebhookEventDeliveryRetry))] #[cfg(feature = "v1")] pub async fn retry_webhook_delivery_attempt( state: web::Data<AppState>, req: HttpRequest, path: web::Path<(common_utils::id_type::MerchantId, String)>, ) -> impl Responder { let flow = Flow::WebhookEventDeliveryRetry; let (merchant_id, event_id) = path.into_inner(); let request_internal = WebhookDeliveryRetryRequestInternal { merchant_id: merchant_id.clone(), event_id, }; Box::pin(api::server_wrap( flow, state, &req, request_internal, |state, _, request_internal, _| { webhook_events::retry_delivery_attempt( state, request_internal.merchant_id, request_internal.event_id, ) }, auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantWebhookEventWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/webhook_events.rs
router
full_file
1,152
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct PaypalData { paypal: PaypalDetails, #[serde(rename = "type")] payment_method_type: AirwallexPaymentType, }
crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
hyperswitch_connectors
struct_definition
31
rust
PaypalData
null
null
null
null
null
null
null
null
null
null
null
pub struct DecideGatewayResponse { pub decided_gateway: Option<String>, pub gateway_priority_map: Option<serde_json::Value>, pub filter_wise_gateways: Option<serde_json::Value>, pub priority_logic_tag: Option<String>, pub routing_approach: Option<String>, pub gateway_before_evaluation: Option<String>, pub priority_logic_output: Option<PriorityLogicOutput>, pub reset_approach: Option<String>, pub routing_dimension: Option<String>, pub routing_dimension_level: Option<String>, pub is_scheduled_outage: Option<bool>, pub is_dynamic_mga_enabled: Option<bool>, pub gateway_mga_id_map: Option<serde_json::Value>, }
crates/api_models/src/open_router.rs
api_models
struct_definition
145
rust
DecideGatewayResponse
null
null
null
null
null
null
null
null
null
null
null
pub struct SantanderBoletoPaymentRequest { pub environment: Environment, pub nsu_code: String, pub nsu_date: String, pub covenant_code: String, pub bank_number: Secret<String>, pub client_number: Option<id_type::CustomerId>, pub due_date: String, pub issue_date: String, pub currency: Option<enums::Currency>, pub nominal_value: StringMajorUnit, pub participant_code: Option<String>, pub payer: Payer, pub beneficiary: Option<Beneficiary>, pub document_kind: BoletoDocumentKind, pub discount: Option<Discount>, pub fine_percentage: Option<String>, pub fine_quantity_days: Option<String>, pub interest_percentage: Option<String>, pub deduction_value: Option<FloatMajorUnit>, pub protest_type: Option<ProtestType>, pub protest_quantity_days: Option<i64>, pub write_off_quantity_days: Option<String>, pub payment_type: PaymentType, pub parcels_quantity: Option<i64>, pub value_type: Option<String>, pub min_value_or_percentage: Option<f64>, pub max_value_or_percentage: Option<f64>, pub iof_percentage: Option<f64>, pub sharing: Option<Sharing>, pub key: Option<Key>, pub tx_id: Option<String>, pub messages: Option<Vec<String>>, }
crates/hyperswitch_connectors/src/connectors/santander/transformers.rs
hyperswitch_connectors
struct_definition
295
rust
SantanderBoletoPaymentRequest
null
null
null
null
null
null
null
null
null
null
null
pub struct AdyenBalanceAccount { description: String, id: String, }
crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs
hyperswitch_connectors
struct_definition
18
rust
AdyenBalanceAccount
null
null
null
null
null
null
null
null
null
null
null
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Address> { generics::generic_insert(conn, self).await }
crates/diesel_models/src/query/address.rs
diesel_models
function_signature
33
rust
null
null
null
null
insert
null
null
null
null
null
null
null
/// Insert a new payment token reference for the given connector_id pub fn insert_payment_token_reference_record( &mut self, connector_id: &common_utils::id_type::MerchantConnectorAccountId, record: ConnectorTokenReferenceRecord, ) { match self.payments { Some(ref mut payments_reference) => { payments_reference.insert(connector_id.clone(), record); } None => { let mut payments_reference = HashMap::new(); payments_reference.insert(connector_id.clone(), record); self.payments = Some(PaymentsTokenReference(payments_reference)); } } }
crates/diesel_models/src/payment_method.rs
diesel_models
function_signature
128
rust
null
null
null
null
insert_payment_token_reference_record
null
null
null
null
null
null
null
pub fn transform_payment_method( connector: Connector, provider: Vec<Provider>, payment_method: PaymentMethod, ) -> Vec<payment_methods::RequestPaymentMethodTypes> { let mut payment_method_types = Vec::new(); for method_type in provider { let data = payment_methods::RequestPaymentMethodTypes { payment_method_type: method_type.payment_method_type, card_networks: None, minimum_amount: Some(MinorUnit::zero()), maximum_amount: Some(MinorUnit::new(68607706)), recurring_enabled: Some(true), installment_payment_enabled: Some(false), accepted_currencies: method_type.accepted_currencies, accepted_countries: method_type.accepted_countries, payment_experience: Self::get_payment_experience( connector, method_type.payment_method_type, payment_method, method_type.payment_experience, ), }; payment_method_types.push(data) } payment_method_types }
crates/connector_configs/src/transformer.rs
connector_configs
function_signature
207
rust
null
null
null
null
transform_payment_method
null
null
null
null
null
null
null
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)) }
crates/router/src/core/payment_methods/tokenize.rs
router
function_signature
267
rust
null
null
null
null
tokenize_cards
null
null
null
null
null
null
null
impl api::RefundSync for Vgs {}
crates/hyperswitch_connectors/src/connectors/vgs.rs
hyperswitch_connectors
impl_block
10
rust
null
Vgs
api::RefundSync for
impl api::RefundSync for for Vgs
null
null
null
null
null
null
null
null
pub async fn verify_merchant_creds_for_applepay( state: SessionState, body: verifications::ApplepayMerchantVerificationRequest, merchant_id: common_utils::id_type::MerchantId, profile_id: Option<common_utils::id_type::ProfileId>, ) -> CustomResult<services::ApplicationResponse<ApplepayMerchantResponse>, errors::ApiErrorResponse> { let applepay_merchant_configs = state.conf.applepay_merchant_configs.get_inner(); let applepay_internal_merchant_identifier = applepay_merchant_configs .common_merchant_identifier .clone() .expose(); let cert_data = applepay_merchant_configs.merchant_cert.clone(); let key_data = applepay_merchant_configs.merchant_cert_key.clone(); let applepay_endpoint = &applepay_merchant_configs.applepay_endpoint; let request_body = verifications::ApplepayMerchantVerificationConfigs { domain_names: body.domain_names.clone(), encrypt_to: applepay_internal_merchant_identifier.clone(), partner_internal_merchant_identifier: applepay_internal_merchant_identifier, partner_merchant_name: APPLEPAY_INTERNAL_MERCHANT_NAME.to_string(), }; let apple_pay_merch_verification_req = services::RequestBuilder::new() .method(services::Method::Post) .url(applepay_endpoint) .attach_default_headers() .headers(vec![( headers::CONTENT_TYPE.to_string(), "application/json".to_string().into(), )]) .set_body(RequestContent::Json(Box::new(request_body))) .add_certificate(Some(cert_data)) .add_certificate_key(Some(key_data)) .build(); let response = services::call_connector_api( &state, apple_pay_merch_verification_req, "verify_merchant_creds_for_applepay", ) .await; utils::log_applepay_verification_response_if_error(&response); let applepay_response = response.change_context(errors::ApiErrorResponse::InternalServerError)?; // Error is already logged match applepay_response { Ok(_) => { utils::check_existence_and_add_domain_to_db( &state, merchant_id, profile_id, body.merchant_connector_account_id.clone(), body.domain_names.clone(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; Ok(services::api::ApplicationResponse::Json( ApplepayMerchantResponse { status_message: "Applepay verification Completed".to_string(), }, )) } Err(error) => { logger::error!(?error); Err(errors::ApiErrorResponse::InvalidRequestData { message: "Applepay verification Failed".to_string(), } .into()) } } }
crates/router/src/core/verification.rs
router
function_signature
576
rust
null
null
null
null
verify_merchant_creds_for_applepay
null
null
null
null
null
null
null
pub(super) struct SerializeStructVariant<T: Serializer> { name: String, map: Map<String, Value>, ser: T, }
crates/masking/src/serde.rs
masking
struct_definition
32
rust
SerializeStructVariant
null
null
null
null
null
null
null
null
null
null
null
File: crates/hyperswitch_domain_models/src/router_flow_types/access_token_auth.rs Public structs: 2 #[derive(Clone, Debug)] pub struct AccessTokenAuthentication; #[derive(Clone, Debug)] pub struct AccessTokenAuth;
crates/hyperswitch_domain_models/src/router_flow_types/access_token_auth.rs
hyperswitch_domain_models
full_file
46
null
null
null
null
null
null
null
null
null
null
null
null
null
impl api::PaymentSession for Checkbook {}
crates/hyperswitch_connectors/src/connectors/checkbook.rs
hyperswitch_connectors
impl_block
9
rust
null
Checkbook
api::PaymentSession for
impl api::PaymentSession for for Checkbook
null
null
null
null
null
null
null
null
impl PaymentMethodVaultingData { pub fn get_card(&self) -> Option<&payment_methods::CardDetail> { match self { Self::Card(card) => Some(card), #[cfg(feature = "v2")] Self::NetworkToken(_) => None, } } pub fn get_payment_methods_data(&self) -> payment_method_data::PaymentMethodsData { match self { Self::Card(card) => payment_method_data::PaymentMethodsData::Card( payment_method_data::CardDetailsPaymentMethod::from(card.clone()), ), #[cfg(feature = "v2")] Self::NetworkToken(network_token) => { payment_method_data::PaymentMethodsData::NetworkToken( payment_method_data::NetworkTokenDetailsPaymentMethod::from( network_token.clone(), ), ) } } } }
crates/hyperswitch_domain_models/src/vault.rs
hyperswitch_domain_models
impl_block
177
rust
null
PaymentMethodVaultingData
null
impl PaymentMethodVaultingData
null
null
null
null
null
null
null
null