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
pub struct RefundsCreateRequest { /// The payment id against which refund is initiated #[schema( max_length = 30, min_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: common_utils::id_type::GlobalPaymentId, /// Unique Identifier for the Refund given by the Merchant. #[schema( max_length = 64, min_length = 1, example = "ref_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub merchant_reference_id: common_utils::id_type::RefundReferenceId, /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>)] pub merchant_id: Option<common_utils::id_type::MerchantId>, /// Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, this will default to the amount_captured of the payment #[schema(value_type = Option<i64> , minimum = 100, example = 6540)] pub amount: Option<MinorUnit>, /// Reason for the refund. Often useful for displaying to users and your customer support executive. #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, /// To indicate whether to refund needs to be instant or scheduled. Default value is instant #[schema(default = "Instant", example = "Instant")] pub refund_type: Option<RefundType>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorAuthDetails>)] pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, }
crates/api_models/src/refunds.rs
api_models
struct_definition
520
rust
RefundsCreateRequest
null
null
null
null
null
null
null
null
null
null
null
pub async fn get_mca_status( state: &routes::SessionState, key_store: &domain::MerchantKeyStore, profile_id: Option<id_type::ProfileId>, merchant_id: &id_type::MerchantId, is_connector_agnostic_mit_enabled: bool, connector_mandate_details: Option<&CommonMandateReference>, network_transaction_id: Option<&String>, merchant_connector_accounts: &domain::MerchantConnectorAccounts, ) -> bool { if is_connector_agnostic_mit_enabled && network_transaction_id.is_some() { return true; } match connector_mandate_details { Some(connector_mandate_details) => merchant_connector_accounts .is_merchant_connector_account_id_in_connector_mandate_details( profile_id.as_ref(), connector_mandate_details, ), None => false, } }
crates/router/src/core/payment_methods/cards.rs
router
function_signature
185
rust
null
null
null
null
get_mca_status
null
null
null
null
null
null
null
pub struct ProfileSetter { pub id: common_utils::id_type::ProfileId, pub merchant_id: common_utils::id_type::MerchantId, pub profile_name: String, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub return_url: Option<common_utils::types::Url>, pub enable_payment_response_hash: bool, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: bool, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub is_recon_enabled: bool, pub applepay_verified_domains: Option<Vec<String>>, pub payment_link_config: Option<BusinessPaymentLinkConfig>, pub session_expiry: Option<i64>, pub authentication_connector_details: Option<AuthenticationConnectorDetails>, pub payout_link_config: Option<BusinessPayoutLinkConfig>, pub is_extended_card_info_enabled: Option<bool>, pub extended_card_info_config: Option<pii::SecretSerdeValue>, pub is_connector_agnostic_mit_enabled: Option<bool>, pub use_billing_as_payment_method_billing: Option<bool>, pub collect_shipping_details_from_wallet_connector: Option<bool>, pub collect_billing_details_from_wallet_connector: Option<bool>, pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue, pub always_collect_billing_details_from_wallet_connector: Option<bool>, pub always_collect_shipping_details_from_wallet_connector: Option<bool>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub order_fulfillment_time: Option<i64>, pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, pub frm_routing_algorithm_id: Option<String>, pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub default_fallback_routing: Option<pii::SecretSerdeValue>, pub should_collect_cvv_during_payment: Option<primitive_wrappers::ShouldCollectCvvDuringPayment>, pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_tax_connector_enabled: bool, pub is_network_tokenization_enabled: bool, pub is_click_to_pay_enabled: bool, pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: OptionalEncryptableName, pub is_clear_pan_retries_enabled: bool, pub is_debit_routing_enabled: bool, pub merchant_business_country: Option<api_enums::CountryAlpha2>, pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>, pub revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>, pub is_iframe_redirection_enabled: Option<bool>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub split_txns_enabled: common_enums::SplitTxnsEnabled, }
crates/hyperswitch_domain_models/src/business_profile.rs
hyperswitch_domain_models
struct_definition
704
rust
ProfileSetter
null
null
null
null
null
null
null
null
null
null
null
impl api::RefundExecute for Bluecode {}
crates/hyperswitch_connectors/src/connectors/bluecode.rs
hyperswitch_connectors
impl_block
10
rust
null
Bluecode
api::RefundExecute for
impl api::RefundExecute for for Bluecode
null
null
null
null
null
null
null
null
pub struct KlarnaConnectorMetadataObject { pub klarna_region: Option<KlarnaEndpoint>, }
crates/hyperswitch_connectors/src/connectors/klarna/transformers.rs
hyperswitch_connectors
struct_definition
21
rust
KlarnaConnectorMetadataObject
null
null
null
null
null
null
null
null
null
null
null
pub async fn internal_call_connector_service_prerequisites<F, RouterDReq, ApiRequest, D>( state: &SessionState, merchant_context: &domain::MerchantContext, connector: api::ConnectorData, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, business_profile: &domain::Profile, ) -> RouterResult<( domain::MerchantConnectorAccountTypeDetails, RouterData<F, RouterDReq, router_types::PaymentsResponseData>, )> where F: Send + Clone + Sync, RouterDReq: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { let merchant_connector_details = payment_data .get_merchant_connector_details() .ok_or_else(|| { error_stack::report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Merchant connector details not found in payment data") })?; let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails( merchant_connector_details, ); operation .to_domain()? .populate_payment_data( state, payment_data, merchant_context, business_profile, &connector, ) .await?; let router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_context, &None, &merchant_connector_account, None, None, ) .await?; Ok((merchant_connector_account, router_data)) }
crates/router/src/core/payments.rs
router
function_signature
426
rust
null
null
null
null
internal_call_connector_service_prerequisites
null
null
null
null
null
null
null
pub async fn update_payout_link( self, conn: &PgPooledConn, payout_link_update: PayoutLinkUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::link_id.eq(self.link_id.to_owned()), GenericLinkUpdateInternal::from(payout_link_update), ) .await .and_then(|mut payout_links| { payout_links .pop() .ok_or(error_stack::report!(db_errors::DatabaseError::NotFound)) }) .or_else(|error| match error.current_context() { db_errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }) }
crates/diesel_models/src/query/generic_link.rs
diesel_models
function_signature
166
rust
null
null
null
null
update_payout_link
null
null
null
null
null
null
null
pub async fn record_operation_time<F, R, T>( future: F, metric: &router_env::opentelemetry::metrics::Histogram<f64>, metric_name: &T, source: &crate::AnalyticsProvider, ) -> R where F: futures::Future<Output = R>, T: ToString, { let (result, time) = common_utils::metrics::utils::time_future(future).await; let attributes = router_env::metric_attributes!( ("metric_name", metric_name.to_string()), ("source", source.to_string()), ); let value = time.as_secs_f64(); metric.record(value, attributes); router_env::logger::debug!("Attributes: {:?}, Time: {}", attributes, value); result }
crates/analytics/src/metrics/request.rs
analytics
function_signature
168
rust
null
null
null
null
record_operation_time
null
null
null
null
null
null
null
File: crates/hyperswitch_connectors/src/connectors/trustpay.rs Public functions: 1 Public structs: 1 pub mod transformers; use std::sync::LazyLock; use base64::Engine; use common_enums::{enums, PaymentAction}; use common_utils::{ crypto, errors::{CustomResult, ReportSwitchExt}, ext_traits::ByteSliceExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{ AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector, StringMajorUnit, StringMajorUnitForConnector, StringMinorUnit, StringMinorUnitForConnector, }, }; 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}, PreProcessing, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ PaymentsAuthorizeRouterData, PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefreshTokenRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, consts, disputes::DisputePayload, errors, events::connector_api_logs::ConnectorEvent, types::{ PaymentsAuthorizeType, PaymentsPreProcessingType, PaymentsSyncType, RefreshTokenType, RefundExecuteType, RefundSyncType, Response, }, webhooks, }; use masking::{Mask, PeekInterface}; use transformers as trustpay; use crate::{ constants::headers, types::ResponseRouterData, utils::{self, self as connector_utils, ConnectorErrorType, PaymentsPreProcessingRequestData}, }; #[derive(Clone)] pub struct Trustpay { amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), amount_converter_to_float_major_unit: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), amount_converter_to_string_minor_unit: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), } impl Trustpay { pub fn new() -> &'static Self { &Self { amount_converter: &StringMajorUnitForConnector, amount_converter_to_float_major_unit: &FloatMajorUnitForConnector, amount_converter_to_string_minor_unit: &StringMinorUnitForConnector, } } } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Trustpay 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> { match req.payment_method { enums::PaymentMethod::BankRedirect | enums::PaymentMethod::BankTransfer => { let token = req .access_token .clone() .ok_or(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![ ( headers::CONTENT_TYPE.to_string(), "application/json".to_owned().into(), ), ( headers::AUTHORIZATION.to_string(), format!("Bearer {}", token.token.peek()).into_masked(), ), ]) } _ => { let mut header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } } } impl ConnectorCommon for Trustpay { fn id(&self) -> &'static str { "trustpay" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Base } fn common_get_content_type(&self) -> &'static str { "application/x-www-form-urlencoded" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.trustpay.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = trustpay::TrustpayAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::X_API_KEY.to_string(), auth.api_key.into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: Result< trustpay::TrustpayErrorResponse, Report<common_utils::errors::ParsingError>, > = res.response.parse_struct("trustpay ErrorResponse"); match response { Ok(response_data) => { event_builder.map(|i| i.set_error_response_body(&response_data)); router_env::logger::info!(connector_response=?response_data); let error_list = response_data.errors.clone().unwrap_or_default(); let option_error_code_message = utils::get_error_code_error_message_based_on_priority( self.clone(), error_list.into_iter().map(|errors| errors.into()).collect(), ); let reason = response_data.errors.map(|errors| { errors .iter() .map(|error| error.description.clone()) .collect::<Vec<String>>() .join(" & ") }); Ok(ErrorResponse { status_code: res.status_code, code: option_error_code_message .clone() .map(|error_code_message| error_code_message.error_code) .unwrap_or(consts::NO_ERROR_CODE.to_string()), // message vary for the same code, so relying on code alone as it is unique message: option_error_code_message .map(|error_code_message| error_code_message.error_code) .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), reason: reason .or(response_data.description) .or(response_data.payment_description), attempt_status: None, connector_transaction_id: response_data.instance_id, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } Err(error_msg) => { event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); router_env::logger::error!(deserialization_error =? error_msg); utils::handle_json_response_deserialization_failure(res, "trustpay") } } } } impl ConnectorValidation for Trustpay {} impl api::Payment for Trustpay {} impl api::PaymentToken for Trustpay {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Trustpay { // Not Implemented (R) } impl api::MandateSetup for Trustpay {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Trustpay { fn build_request( &self, _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Trustpay".to_string()) .into(), ) } } impl api::PaymentVoid for Trustpay {} impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Trustpay {} impl api::ConnectorAccessToken for Trustpay {} impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Trustpay { fn get_url( &self, _req: &RefreshTokenRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", connectors.trustpay.base_url_bank_redirects, "api/oauth2/token" )) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_headers( &self, req: &RefreshTokenRouterData, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = trustpay::TrustpayAuthType::try_from(&req.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let auth_value = auth .project_id .zip(auth.secret_key) .map(|(project_id, secret_key)| { format!( "Basic {}", common_utils::consts::BASE64_ENGINE .encode(format!("{project_id}:{secret_key}")) ) }); Ok(vec![ ( headers::CONTENT_TYPE.to_string(), RefreshTokenType::get_content_type(self).to_string().into(), ), (headers::AUTHORIZATION.to_string(), auth_value.into_masked()), ]) } fn get_request_body( &self, req: &RefreshTokenRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = trustpay::TrustpayAuthUpdateRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &RefreshTokenRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let req = Some( RequestBuilder::new() .method(Method::Post) .attach_default_headers() .headers(RefreshTokenType::get_headers(self, req, connectors)?) .url(&RefreshTokenType::get_url(self, req, connectors)?) .set_body(RefreshTokenType::get_request_body(self, req, connectors)?) .build(), ); Ok(req) } fn handle_response( &self, data: &RefreshTokenRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> { let response: trustpay::TrustpayAuthUpdateResponse = res .response .parse_struct("trustpay TrustpayAuthUpdateResponse") .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, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: trustpay::TrustpayAccessTokenErrorResponse = res .response .parse_struct("Trustpay AccessTokenErrorResponse") .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.result_info.result_code.to_string(), // message vary for the same code, so relying on code alone as it is unique message: response.result_info.result_code.to_string(), reason: response.result_info.additional_info, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl api::PaymentSync for Trustpay {} impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Trustpay { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let id = req.request.connector_transaction_id.clone(); match req.payment_method { enums::PaymentMethod::BankRedirect | enums::PaymentMethod::BankTransfer => Ok(format!( "{}{}/{}", connectors.trustpay.base_url_bank_redirects, "api/Payments/Payment", id.get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)? )), _ => Ok(format!( "{}{}/{}", self.base_url(connectors), "api/v1/instance", id.get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)? )), } } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: trustpay::TrustpayPaymentsResponse = res .response .parse_struct("trustpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; match &response { trustpay::TrustpayPaymentsResponse::WebhookResponse(webhook_response) => { let response_integrity_object = connector_utils::get_sync_integrity_object( self.amount_converter_to_float_major_unit, webhook_response.amount.amount, webhook_response.amount.currency.to_string(), )?; 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, }) .map(|mut router_data| { router_data.request.integrity_object = Some(response_integrity_object); router_data }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } trustpay::TrustpayPaymentsResponse::BankRedirectSync(bank_redirect_sync_response) => { let response_integrity_object = connector_utils::get_sync_integrity_object( self.amount_converter_to_float_major_unit, bank_redirect_sync_response .payment_information .amount .amount, bank_redirect_sync_response .payment_information .amount .currency .to_string(), )?; 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, }) .map(|mut router_data| { router_data.request.integrity_object = Some(response_integrity_object); router_data }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } _ => { 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, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } } } } impl api::PaymentCapture for Trustpay {} impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Trustpay {} impl api::PaymentsPreProcessing for Trustpay {} impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> for Trustpay { fn get_headers( &self, req: &PaymentsPreProcessingRouterData, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), PaymentsPreProcessingType::get_content_type(self) .to_string() .into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "api/v1/intent")) } fn get_request_body( &self, req: &PaymentsPreProcessingRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let req_currency = req.request.get_currency()?; let req_amount = req.request.get_minor_amount()?; let amount = utils::convert_amount(self.amount_converter, req_amount, req_currency)?; let connector_router_data = trustpay::TrustpayRouterData::try_from((amount, req))?; let connector_req = trustpay::TrustpayCreateIntentRequest::try_from(&connector_router_data)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let req = Some( RequestBuilder::new() .method(Method::Post) .attach_default_headers() .headers(PaymentsPreProcessingType::get_headers( self, req, connectors, )?) .url(&PaymentsPreProcessingType::get_url(self, req, connectors)?) .set_body(PaymentsPreProcessingType::get_request_body( self, req, connectors, )?) .build(), ); Ok(req) } fn handle_response( &self, data: &PaymentsPreProcessingRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> { let response: trustpay::TrustpayCreateIntentResponse = res .response .parse_struct("TrustpayCreateIntentResponse") .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, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl api::PaymentSession for Trustpay {} impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Trustpay {} impl api::PaymentAuthorize for Trustpay {} impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Trustpay { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { match req.payment_method { enums::PaymentMethod::BankRedirect | enums::PaymentMethod::BankTransfer => Ok(format!( "{}{}", connectors.trustpay.base_url_bank_redirects, "api/Payments/Payment" )), _ => Ok(format!( "{}{}", self.base_url(connectors), "api/v1/purchase" )), } } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = trustpay::TrustpayRouterData::try_from((amount, req))?; let connector_req = trustpay::TrustpayPaymentsRequest::try_from(&connector_router_data)?; match req.payment_method { enums::PaymentMethod::BankRedirect | enums::PaymentMethod::BankTransfer => { Ok(RequestContent::Json(Box::new(connector_req))) } _ => Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))), } } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: trustpay::TrustpayPaymentsResponse = res .response .parse_struct("trustpay PaymentsResponse") .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, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl api::Refund for Trustpay {} impl api::RefundExecute for Trustpay {} impl api::RefundSync for Trustpay {} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Trustpay { 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> { match req.payment_method { enums::PaymentMethod::BankRedirect | enums::PaymentMethod::BankTransfer => Ok(format!( "{}{}{}{}", connectors.trustpay.base_url_bank_redirects, "api/Payments/Payment/", req.request.connector_transaction_id, "/Refund" )), _ => Ok(format!("{}{}", self.base_url(connectors), "api/v1/Refund")), } } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = trustpay::TrustpayRouterData::try_from((amount, req))?; let connector_req = trustpay::TrustpayRefundRequest::try_from(&connector_router_data)?; match req.payment_method { enums::PaymentMethod::BankRedirect | enums::PaymentMethod::BankTransfer => { Ok(RequestContent::Json(Box::new(connector_req))) } _ => Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))), } } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(RefundExecuteType::get_headers(self, req, connectors)?) .set_body(RefundExecuteType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: trustpay::RefundResponse = res .response .parse_struct("trustpay RefundResponse") .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, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } 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 Trustpay { 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 id = req .request .connector_refund_id .to_owned() .ok_or(errors::ConnectorError::MissingConnectorRefundID)?; match req.payment_method { enums::PaymentMethod::BankRedirect | enums::PaymentMethod::BankTransfer => Ok(format!( "{}{}/{}", connectors.trustpay.base_url_bank_redirects, "api/Payments/Payment", id )), _ => Ok(format!( "{}{}/{}", self.base_url(connectors), "api/v1/instance", id )), } } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(RefundSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: trustpay::RefundResponse = res .response .parse_struct("trustpay RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; if let trustpay::RefundResponse::WebhookRefund(ref webhook_response) = response { let response_integrity_object = connector_utils::get_refund_integrity_object( self.amount_converter_to_float_major_unit, webhook_response.amount.amount, webhook_response.amount.currency.to_string(), )?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let new_router_data = RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }); return new_router_data .map(|mut router_data| { router_data.request.integrity_object = Some(response_integrity_object); router_data }) .change_context(errors::ConnectorError::ResponseHandlingFailed); } 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, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } 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 Trustpay { fn get_webhook_object_reference_id( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let details: trustpay::TrustpayWebhookResponse = request .body .parse_struct("TrustpayWebhookResponse") .switch()?; let payment_attempt_id = details .payment_information .references .merchant_reference .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?; match details.payment_information.credit_debit_indicator { trustpay::CreditDebitIndicator::Crdt => { Ok(api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PaymentAttemptId(payment_attempt_id), )) } trustpay::CreditDebitIndicator::Dbit => { if details.payment_information.status == trustpay::WebhookStatus::Chargebacked { Ok(api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PaymentAttemptId(payment_attempt_id), )) } else { Ok(api_models::webhooks::ObjectReferenceId::RefundId( api_models::webhooks::RefundIdType::RefundId(payment_attempt_id), )) } } } } fn get_webhook_event_type( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { let response: trustpay::TrustpayWebhookResponse = request .body .parse_struct("TrustpayWebhookResponse") .switch()?; match ( response.payment_information.credit_debit_indicator, response.payment_information.status, ) { (trustpay::CreditDebitIndicator::Crdt, trustpay::WebhookStatus::Paid) => { Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess) } (trustpay::CreditDebitIndicator::Crdt, trustpay::WebhookStatus::Rejected) => { Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure) } (trustpay::CreditDebitIndicator::Dbit, trustpay::WebhookStatus::Paid) => { Ok(api_models::webhooks::IncomingWebhookEvent::RefundSuccess) } (trustpay::CreditDebitIndicator::Dbit, trustpay::WebhookStatus::Refunded) => { Ok(api_models::webhooks::IncomingWebhookEvent::RefundSuccess) } (trustpay::CreditDebitIndicator::Dbit, trustpay::WebhookStatus::Rejected) => { Ok(api_models::webhooks::IncomingWebhookEvent::RefundFailure) } (trustpay::CreditDebitIndicator::Dbit, trustpay::WebhookStatus::Chargebacked) => { Ok(api_models::webhooks::IncomingWebhookEvent::DisputeLost) } ( trustpay::CreditDebitIndicator::Dbit | trustpay::CreditDebitIndicator::Crdt, trustpay::WebhookStatus::Unknown, ) => Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported), (trustpay::CreditDebitIndicator::Crdt, trustpay::WebhookStatus::Refunded) => { Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported) } (trustpay::CreditDebitIndicator::Crdt, trustpay::WebhookStatus::Chargebacked) => { Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported) } } } fn get_webhook_resource_object( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let details: trustpay::TrustpayWebhookResponse = request .body .parse_struct("TrustpayWebhookResponse") .switch()?; Ok(Box::new(details.payment_information)) } fn get_webhook_source_verification_algorithm( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let response: trustpay::TrustpayWebhookResponse = request .body .parse_struct("TrustpayWebhookResponse") .switch()?; hex::decode(response.signature) .change_context(errors::ConnectorError::WebhookSignatureNotFound) } fn get_webhook_source_verification_message( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let trustpay_response: trustpay::TrustpayWebhookResponse = request .body .parse_struct("TrustpayWebhookResponse") .switch()?; let response: serde_json::Value = request.body.parse_struct("Webhook Value").switch()?; let values = utils::collect_and_sort_values_by_removing_signature( &response, &trustpay_response.signature, ); let payload = values.join("/"); Ok(payload.into_bytes()) } fn get_dispute_details( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>,
crates/hyperswitch_connectors/src/connectors/trustpay.rs#chunk0
hyperswitch_connectors
chunk
8,191
null
null
null
null
null
null
null
null
null
null
null
null
null
pub async fn get_role_from_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { let flow = Flow::GetRoleFromToken; Box::pin(api::server_wrap( flow, state.clone(), &req, (), |state, user, _, _| async move { role_core::get_role_from_token_with_groups(state, user).await }, &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/user_role.rs
router
function_signature
112
rust
null
null
null
null
get_role_from_token
null
null
null
null
null
null
null
pub trait DecisionEngineErrorsInterface { fn get_error_message(&self) -> String; fn get_error_code(&self) -> String; fn get_error_data(&self) -> Option<String>; }
crates/router/src/core/payments/routing/utils.rs
router
trait_definition
42
rust
null
null
DecisionEngineErrorsInterface
null
null
null
null
null
null
null
null
null
impl ConnectorSpecifications for Adyenplatform { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&ADYENPLATFORM_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/adyenplatform.rs
hyperswitch_connectors
impl_block
95
rust
null
Adyenplatform
ConnectorSpecifications for
impl ConnectorSpecifications for for Adyenplatform
null
null
null
null
null
null
null
null
pub fn connector_transaction_id( &self, connector_meta: Option<&serde_json::Value>, ) -> CustomResult<Option<String>, errors::ConnectorError> { let meta: helcim::HelcimMetaData = to_connector_meta(connector_meta.cloned())?; Ok(Some(meta.preauth_transaction_id.to_string())) }
crates/hyperswitch_connectors/src/connectors/helcim.rs
hyperswitch_connectors
function_signature
71
rust
null
null
null
null
connector_transaction_id
null
null
null
null
null
null
null
pub fn into_inner(self) -> T { self.inner }
crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs
hyperswitch_interfaces
function_signature
15
rust
null
null
null
null
into_inner
null
null
null
null
null
null
null
pub fn temporary_generic(token: String) -> Self { Self::TemporaryGeneric(GenericTokenData { token }) }
crates/router/src/types/storage/payment_method.rs
router
function_signature
25
rust
null
null
null
null
temporary_generic
null
null
null
null
null
null
null
impl api::PaymentToken for Nexinets {}
crates/hyperswitch_connectors/src/connectors/nexinets.rs
hyperswitch_connectors
impl_block
10
rust
null
Nexinets
api::PaymentToken for
impl api::PaymentToken for for Nexinets
null
null
null
null
null
null
null
null
pub fn get_expired_page(dummy_connector_conf: &settings::DummyConnector) -> String { html! { head { title { "Authorize Payment" } style { (consts::THREE_DS_CSS) } link rel="icon" href="https://app.hyperswitch.io/HyperswitchFavicon.png" {} } body { div.heading { img.logo src="https://app.hyperswitch.io/assets/Dark/hyperswitchLogoIconWithText.svg" alt="Hyperswitch Logo" {} h1 { "Test Payment Page" } } div.container { p.disclaimer { "This link is not valid or it is expired" } } div.container { p.disclaimer { "What is this page?" } p { "This page is just a simulation for integration and testing purpose.\ In live mode, this is not visible. Contact us for any queries." } div.contact { div.contact_item.hover_cursor onclick=(dummy_connector_conf.slack_invite_url) { img src="https://hyperswitch.io/logos/logo_slack.svg" alt="Slack Logo" {} } div.contact_item.hover_cursor onclick=(dummy_connector_conf.discord_invite_url) { img src="https://hyperswitch.io/logos/logo_discord.svg" alt="Discord Logo" {} } div.border_vertical {} div.contact_item.email { p { "Or email us at" } a href="mailto:hyperswitch@juspay.in" { "hyperswitch@juspay.in" } } } } } } .into_string() }
crates/router/src/routes/dummy_connector/utils.rs
router
function_signature
354
rust
null
null
null
null
get_expired_page
null
null
null
null
null
null
null
pub async fn refunds_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<refunds::RefundRequest>, ) -> HttpResponse { let flow = Flow::RefundsCreate; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); refund_create_core(state, merchant_context, auth.profile_id, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRefundWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/refunds.rs
router
function_signature
214
rust
null
null
null
null
refunds_create
null
null
null
null
null
null
null
OpenAPI Block Path: components.schemas.ProgramThreeDsDecisionRule { "type": "object", "required": [ "defaultSelection", "rules", "metadata" ], "properties": { "defaultSelection": { "$ref": "#/components/schemas/ThreeDSDecisionRule" }, "rules": { "$ref": "#/components/schemas/RuleThreeDsDecisionRule" }, "metadata": { "type": "object", "additionalProperties": {} } } }
./hyperswitch/api-reference/v1/openapi_spec_v1.json
null
openapi_block
116
.json
null
null
null
null
null
openapi_spec
components
[ "schemas", "ProgramThreeDsDecisionRule" ]
null
null
null
null
pub struct NovalnetGooglePay { wallet_data: Secret<String>, }
crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
hyperswitch_connectors
struct_definition
16
rust
NovalnetGooglePay
null
null
null
null
null
null
null
null
null
null
null
pub fn get_pm_authentication_processor_config( connector: PmAuthConnectors, ) -> Result<Option<ConnectorTomlConfig>, String> { let connector_data = Self::new()?; match connector { PmAuthConnectors::Plaid => Ok(connector_data.plaid), } }
crates/connector_configs/src/connector.rs
connector_configs
function_signature
65
rust
null
null
null
null
get_pm_authentication_processor_config
null
null
null
null
null
null
null
pub struct KafkaPaymentAttemptEvent<'a> { pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a id_type::MerchantId, pub attempt_id: &'a String, pub status: storage_enums::AttemptStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub save_to_locker: Option<bool>, pub connector: Option<&'a String>, pub error_message: Option<&'a String>, pub offer_amount: Option<MinorUnit>, pub surcharge_amount: Option<MinorUnit>, pub tax_amount: Option<MinorUnit>, pub payment_method_id: Option<&'a String>, pub payment_method: Option<storage_enums::PaymentMethod>, pub connector_transaction_id: Option<&'a String>, pub capture_method: Option<storage_enums::CaptureMethod>, #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub capture_on: Option<OffsetDateTime>, pub confirm: bool, pub authentication_type: Option<storage_enums::AuthenticationType>, #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub last_synced: Option<OffsetDateTime>, pub cancellation_reason: Option<&'a String>, pub amount_to_capture: Option<MinorUnit>, pub mandate_id: Option<&'a String>, pub browser_info: Option<String>, pub error_code: Option<&'a String>, pub connector_metadata: Option<String>, // TODO: These types should implement copy ideally pub payment_experience: Option<&'a storage_enums::PaymentExperience>, pub payment_method_type: Option<&'a storage_enums::PaymentMethodType>, pub payment_method_data: Option<String>, pub error_reason: Option<&'a String>, pub multiple_capture_count: Option<i16>, pub amount_capturable: MinorUnit, pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>, pub net_amount: MinorUnit, pub unified_code: Option<&'a String>, pub unified_message: Option<&'a String>, pub mandate_data: Option<&'a MandateDetails>, pub client_source: Option<&'a String>, pub client_version: Option<&'a String>, pub profile_id: &'a id_type::ProfileId, pub organization_id: &'a id_type::OrganizationId, pub card_network: Option<String>, pub card_discovery: Option<String>, pub routing_approach: Option<storage_enums::RoutingApproach>, pub debit_routing_savings: Option<MinorUnit>, pub signature_network: Option<common_enums::CardNetwork>, pub is_issuer_regulated: Option<bool>, }
crates/router/src/services/kafka/payment_attempt_event.rs
router
struct_definition
639
rust
KafkaPaymentAttemptEvent
null
null
null
null
null
null
null
null
null
null
null
pub struct RecordMigrationStatus { pub card_migrated: Option<bool>, pub network_token_migrated: Option<bool>, pub connector_mandate_details_migrated: Option<bool>, pub network_transaction_migrated: Option<bool>, }
crates/payment_methods/src/core/migration.rs
payment_methods
struct_definition
49
rust
RecordMigrationStatus
null
null
null
null
null
null
null
null
null
null
null
impl FromStr for ReversalReason { type Err = error_stack::Report<errors::ConnectorError>; fn from_str(s: &str) -> Result<Self, Self::Err> { match s.to_uppercase().as_str() { "NO_RESPONSE" => Ok(Self::NoResponse), "LATE_RESPONSE" => Ok(Self::LateResponse), "UNABLE_TO_DELIVER" => Ok(Self::UnableToDeliver), "CARD_DECLINED" => Ok(Self::CardDeclined), "MAC_NOT_VERIFIED" => Ok(Self::MacNotVerified), "MAC_SYNC_ERROR" => Ok(Self::MacSyncError), "ZEK_SYNC_ERROR" => Ok(Self::ZekSyncError), "SYSTEM_MALFUNCTION" => Ok(Self::SystemMalfunction), "SUSPECTED_FRAUD" => Ok(Self::SuspectedFraud), _ => Err(report!(errors::ConnectorError::InvalidDataFormat { field_name: "cancellation_reason", })), } } }
crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs
hyperswitch_connectors
impl_block
218
rust
null
ReversalReason
FromStr for
impl FromStr for for ReversalReason
null
null
null
null
null
null
null
null
File: crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs Public structs: 21 use std::collections::HashMap; use api_models::payments::{self, AdditionalPaymentData}; use common_enums::enums; use common_utils::{pii::Email, request::Method, types::MinorUnit}; use hyperswitch_domain_models::{ payment_method_data::{Card, PaymentMethodData}, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::{PaymentsAuthorizeData, ResponseId, SetupMandateRequestData}, router_response_types::{ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, }, types, }; use hyperswitch_interfaces::{ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, errors, }; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ types::{ PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData, }, utils::{ get_unimplemented_payment_method_error_message, AdditionalCardInfo, CardData as _, PaymentsAuthorizeRequestData, RouterData as _, }, }; const TRANSACTION_ALREADY_CANCELLED: &str = "transaction already canceled"; const TRANSACTION_ALREADY_SETTLED: &str = "already settled"; const REDIRECTION_SBX_URL: &str = "https://pay.sandbox.datatrans.com"; const REDIRECTION_PROD_URL: &str = "https://pay.datatrans.com"; #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct DatatransErrorResponse { pub error: DatatransError, } pub struct DatatransAuthType { pub(super) merchant_id: Secret<String>, pub(super) passcode: Secret<String>, } pub struct DatatransRouterData<T> { pub amount: MinorUnit, pub router_data: T, } #[derive(Debug, Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct DatatransPaymentsRequest { pub amount: Option<MinorUnit>, pub currency: enums::Currency, pub card: DataTransPaymentDetails, pub refno: String, pub auto_settle: bool, #[serde(skip_serializing_if = "Option::is_none")] pub redirect: Option<RedirectUrls>, pub option: Option<DataTransCreateAlias>, } #[derive(Debug, Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct DataTransCreateAlias { pub create_alias: bool, } #[derive(Debug, Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct RedirectUrls { pub success_url: Option<String>, pub cancel_url: Option<String>, pub error_url: Option<String>, } #[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "snake_case")] pub enum TransactionType { Payment, Credit, CardCheck, } #[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "snake_case")] pub enum TransactionStatus { Initialized, Authenticated, Authorized, Settled, Canceled, Transmitted, Failed, ChallengeOngoing, ChallengeRequired, } #[derive(Debug, Deserialize, Clone, Serialize)] #[serde(untagged)] pub enum DatatransSyncResponse { Error(DatatransError), Response(SyncResponse), } #[derive(Debug, Deserialize, Serialize)] pub enum DataTransCaptureResponse { Error(DatatransError), Empty, } #[derive(Debug, Deserialize, Serialize)] pub enum DataTransCancelResponse { Error(DatatransError), Empty, } #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct SyncResponse { pub transaction_id: String, #[serde(rename = "type")] pub res_type: TransactionType, pub status: TransactionStatus, pub detail: SyncDetails, pub card: Option<SyncCardDetails>, } #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct SyncCardDetails { pub alias: Option<String>, } #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct SyncDetails { fail: Option<FailDetails>, } #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct FailDetails { reason: Option<String>, message: Option<String>, } #[derive(Serialize, Clone, Debug)] #[serde(rename_all = "camelCase")] #[serde(untagged)] pub enum DataTransPaymentDetails { Cards(PlainCardDetails), Mandate(MandateDetails), } #[derive(Serialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct PlainCardDetails { #[serde(rename = "type")] pub res_type: String, pub number: cards::CardNumber, pub expiry_month: Secret<String>, pub expiry_year: Secret<String>, pub cvv: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "3D")] pub three_ds: Option<ThreeDSecureData>, } #[derive(Serialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct MandateDetails { #[serde(rename = "type")] pub res_type: String, pub alias: String, pub expiry_month: Secret<String>, pub expiry_year: Secret<String>, } #[derive(Serialize, Clone, Debug)] pub struct ThreedsInfo { cardholder: CardHolder, } #[derive(Serialize, Clone, Debug)] #[serde(untagged)] pub enum ThreeDSecureData { Cardholder(ThreedsInfo), Authentication(ThreeDSData), } #[derive(Debug, Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct ThreeDSData { #[serde(rename = "threeDSTransactionId")] pub three_ds_transaction_id: Option<Secret<String>>, pub cavv: Secret<String>, pub eci: Option<String>, pub xid: Option<Secret<String>>, #[serde(rename = "threeDSVersion")] pub three_ds_version: Option<String>, #[serde(rename = "authenticationResponse")] pub authentication_response: String, } #[derive(Debug, Serialize, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CardHolder { cardholder_name: Secret<String>, email: Email, } #[derive(Debug, Clone, Serialize, Default, Deserialize)] pub struct DatatransError { pub code: String, pub message: String, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DatatransResponse { TransactionResponse(DatatransSuccessResponse), ErrorResponse(DatatransError), ThreeDSResponse(Datatrans3DSResponse), } #[derive(Default, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct DatatransSuccessResponse { pub transaction_id: String, pub acquirer_authorization_code: String, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DatatransRefundsResponse { Success(DatatransSuccessResponse), Error(DatatransError), } #[derive(Default, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Datatrans3DSResponse { pub transaction_id: String, #[serde(rename = "3D")] pub three_ds_enrolled: ThreeDSEnolled, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ThreeDSEnolled { pub enrolled: bool, } #[derive(Default, Debug, Serialize)] pub struct DatatransRefundRequest { pub amount: MinorUnit, pub currency: enums::Currency, pub refno: String, } #[derive(Debug, Serialize, Clone)] pub struct DataPaymentCaptureRequest { pub amount: MinorUnit, pub currency: enums::Currency, pub refno: String, } impl<T> TryFrom<(MinorUnit, T)> for DatatransRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data: item, }) } } impl TryFrom<&types::SetupMandateRouterData> for DatatransPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> { match item.request.payment_method_data.clone() { PaymentMethodData::Card(req_card) => Ok(Self { amount: None, currency: item.request.currency, card: DataTransPaymentDetails::Cards(PlainCardDetails { res_type: "PLAIN".to_string(), number: req_card.card_number.clone(), expiry_month: req_card.card_exp_month.clone(), expiry_year: req_card.get_card_expiry_year_2_digit()?, cvv: req_card.card_cvc.clone(), three_ds: Some(ThreeDSecureData::Cardholder(ThreedsInfo { cardholder: CardHolder { cardholder_name: item.get_billing_full_name()?, email: item.get_billing_email()?, }, })), }), refno: item.connector_request_reference_id.clone(), auto_settle: true, // zero auth doesn't support manual capture option: Some(DataTransCreateAlias { create_alias: true }), redirect: Some(RedirectUrls { success_url: item.request.router_return_url.clone(), cancel_url: item.request.router_return_url.clone(), error_url: item.request.router_return_url.clone(), }), }), PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Crypto(_) | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("Datatrans"), ))? } } } } impl TryFrom<&DatatransRouterData<&types::PaymentsAuthorizeRouterData>> for DatatransPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &DatatransRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(req_card) => { let is_mandate_payment = item.router_data.request.is_mandate_payment(); let option = is_mandate_payment.then_some(DataTransCreateAlias { create_alias: true }); // provides return url for only mandate payment(CIT) or 3ds through datatrans let redirect = if is_mandate_payment || (item.router_data.is_three_ds() && item.router_data.request.authentication_data.is_none()) { Some(RedirectUrls { success_url: item.router_data.request.router_return_url.clone(), cancel_url: item.router_data.request.router_return_url.clone(), error_url: item.router_data.request.router_return_url.clone(), }) } else { None }; Ok(Self { amount: Some(item.amount), currency: item.router_data.request.currency, card: create_card_details(item, &req_card)?, refno: item.router_data.connector_request_reference_id.clone(), auto_settle: item.router_data.request.is_auto_capture()?, option, redirect, }) } PaymentMethodData::MandatePayment => { let additional_payment_data = match item .router_data .request .additional_payment_method_data .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "additional_payment_method_data", })? { AdditionalPaymentData::Card(card) => *card, _ => Err(errors::ConnectorError::NotSupported { message: "Payment Method Not Supported".to_string(), connector: "DataTrans", })?, }; Ok(Self { amount: Some(item.amount), currency: item.router_data.request.currency, card: create_mandate_details(item, &additional_payment_data)?, refno: item.router_data.connector_request_reference_id.clone(), auto_settle: item.router_data.request.is_auto_capture()?, option: None, redirect: None, }) } PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("Datatrans"), ))? } } } } impl TryFrom<&ConnectorAuthType> for DatatransAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { merchant_id: key1.clone(), passcode: api_key.clone(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } fn get_status(item: &DatatransResponse, is_auto_capture: bool) -> enums::AttemptStatus { match item { DatatransResponse::ErrorResponse(_) => enums::AttemptStatus::Failure, DatatransResponse::TransactionResponse(_) => { if is_auto_capture { enums::AttemptStatus::Charged } else { enums::AttemptStatus::Authorized } } DatatransResponse::ThreeDSResponse(_) => enums::AttemptStatus::AuthenticationPending, } } fn create_card_details( item: &DatatransRouterData<&types::PaymentsAuthorizeRouterData>, card: &Card, ) -> Result<DataTransPaymentDetails, error_stack::Report<errors::ConnectorError>> { let mut details = PlainCardDetails { res_type: "PLAIN".to_string(), number: card.card_number.clone(), expiry_month: card.card_exp_month.clone(), expiry_year: card.get_card_expiry_year_2_digit()?, cvv: card.card_cvc.clone(), three_ds: None, }; if let Some(auth_data) = &item.router_data.request.authentication_data { details.three_ds = Some(ThreeDSecureData::Authentication(ThreeDSData { three_ds_transaction_id: auth_data .threeds_server_transaction_id .clone() .map(Secret::new), cavv: auth_data.cavv.clone(), eci: auth_data.eci.clone(), xid: auth_data.ds_trans_id.clone().map(Secret::new), three_ds_version: auth_data .message_version .clone() .map(|version| version.to_string()), authentication_response: "Y".to_string(), })); } else if item.router_data.is_three_ds() { details.three_ds = Some(ThreeDSecureData::Cardholder(ThreedsInfo { cardholder: CardHolder { cardholder_name: item.router_data.get_billing_full_name()?, email: item.router_data.get_billing_email()?, }, })); } Ok(DataTransPaymentDetails::Cards(details)) } fn create_mandate_details( item: &DatatransRouterData<&types::PaymentsAuthorizeRouterData>, additional_card_details: &payments::AdditionalCardInfo, ) -> Result<DataTransPaymentDetails, error_stack::Report<errors::ConnectorError>> { let alias = item.router_data.request.get_connector_mandate_id()?; Ok(DataTransPaymentDetails::Mandate(MandateDetails { res_type: "ALIAS".to_string(), alias, expiry_month: additional_card_details.card_exp_month.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "card_exp_month", }, )?, expiry_year: additional_card_details.get_card_expiry_year_2_digit()?, })) } impl From<SyncResponse> for enums::AttemptStatus { fn from(item: SyncResponse) -> Self { match item.res_type { TransactionType::Payment => match item.status { TransactionStatus::Authorized => Self::Authorized, TransactionStatus::Settled | TransactionStatus::Transmitted => Self::Charged, TransactionStatus::ChallengeOngoing | TransactionStatus::ChallengeRequired => { Self::AuthenticationPending } TransactionStatus::Canceled => Self::Voided, TransactionStatus::Failed => Self::Failure, TransactionStatus::Initialized | TransactionStatus::Authenticated => Self::Pending, }, TransactionType::CardCheck => match item.status { TransactionStatus::Settled | TransactionStatus::Transmitted | TransactionStatus::Authorized => Self::Charged, TransactionStatus::ChallengeOngoing | TransactionStatus::ChallengeRequired => { Self::AuthenticationPending } TransactionStatus::Canceled => Self::Voided, TransactionStatus::Failed => Self::Failure, TransactionStatus::Initialized | TransactionStatus::Authenticated => Self::Pending, }, TransactionType::Credit => Self::Failure, } } } impl From<SyncResponse> for enums::RefundStatus { fn from(item: SyncResponse) -> Self { match item.res_type { TransactionType::Credit => match item.status { TransactionStatus::Settled | TransactionStatus::Transmitted => Self::Success, TransactionStatus::ChallengeOngoing | TransactionStatus::ChallengeRequired => { Self::Pending } TransactionStatus::Initialized | TransactionStatus::Authenticated | TransactionStatus::Authorized | TransactionStatus::Canceled | TransactionStatus::Failed => Self::Failure, }, TransactionType::Payment | TransactionType::CardCheck => Self::Failure, } } } impl<F> TryFrom<ResponseRouterData<F, DatatransResponse, PaymentsAuthorizeData, PaymentsResponseData>> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, DatatransResponse, PaymentsAuthorizeData, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let status = get_status(&item.response, item.data.request.is_auto_capture()?); let response = match &item.response { DatatransResponse::ErrorResponse(error) => Err(ErrorResponse { code: error.code.clone(), message: error.message.clone(), reason: Some(error.message.clone()), attempt_status: None, connector_transaction_id: None, status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), DatatransResponse::TransactionResponse(response) => { Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( response.transaction_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }) } DatatransResponse::ThreeDSResponse(response) => { let redirection_link = match item.data.test_mode { Some(true) => format!("{REDIRECTION_SBX_URL}/v1/start"), Some(false) | None => format!("{REDIRECTION_PROD_URL}/v1/start"), }; Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( response.transaction_id.clone(), ), redirection_data: Box::new(Some(RedirectForm::Form { endpoint: format!("{}/{}", redirection_link, response.transaction_id), method: Method::Get, form_fields: HashMap::new(), })), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }) } }; Ok(Self { status, response, ..item.data }) } } impl<F> TryFrom<ResponseRouterData<F, DatatransResponse, SetupMandateRequestData, PaymentsResponseData>> for RouterData<F, SetupMandateRequestData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, DatatransResponse, SetupMandateRequestData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { // zero auth doesn't support manual capture let status = get_status(&item.response, true); let response = match &item.response { DatatransResponse::ErrorResponse(error) => Err(ErrorResponse { code: error.code.clone(), message: error.message.clone(), reason: Some(error.message.clone()), attempt_status: None, connector_transaction_id: None, status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), DatatransResponse::TransactionResponse(response) => { Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( response.transaction_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }) } DatatransResponse::ThreeDSResponse(response) => { let redirection_link = match item.data.test_mode { Some(true) => format!("{REDIRECTION_SBX_URL}/v1/start"), Some(false) | None => format!("{REDIRECTION_PROD_URL}/v1/start"), }; Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( response.transaction_id.clone(), ), redirection_data: Box::new(Some(RedirectForm::Form { endpoint: format!("{}/{}", redirection_link, response.transaction_id), method: Method::Get, form_fields: HashMap::new(), })), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }) } }; Ok(Self { status, response, ..item.data }) } } impl<F> TryFrom<&DatatransRouterData<&types::RefundsRouterData<F>>> for DatatransRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &DatatransRouterData<&types::RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount.to_owned(), currency: item.router_data.request.currency, refno: item.router_data.request.refund_id.clone(), }) } } impl TryFrom<RefundsResponseRouterData<Execute, DatatransRefundsResponse>> for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, DatatransRefundsResponse>, ) -> Result<Self, Self::Error> { match item.response { DatatransRefundsResponse::Error(error) => Ok(Self { response: Err(ErrorResponse { code: error.code.clone(), message: error.message.clone(), reason: Some(error.message), attempt_status: None, connector_transaction_id: None, status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }), DatatransRefundsResponse::Success(response) => Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: response.transaction_id, refund_status: enums::RefundStatus::Success, }), ..item.data }), } } } impl TryFrom<RefundsResponseRouterData<RSync, DatatransSyncResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, DatatransSyncResponse>, ) -> Result<Self, Self::Error> { let response = match item.response { DatatransSyncResponse::Error(error) => Err(ErrorResponse { code: error.code.clone(), message: error.message.clone(), reason: Some(error.message), attempt_status: None, connector_transaction_id: None, status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), DatatransSyncResponse::Response(response) => Ok(RefundsResponseData { connector_refund_id: response.transaction_id.to_string(), refund_status: enums::RefundStatus::from(response), }), }; Ok(Self { response, ..item.data }) } } impl TryFrom<PaymentsSyncResponseRouterData<DatatransSyncResponse>> for types::PaymentsSyncRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PaymentsSyncResponseRouterData<DatatransSyncResponse>, ) -> Result<Self, Self::Error> { match item.response { DatatransSyncResponse::Error(error) => { let response = Err(ErrorResponse { code: error.code.clone(), message: error.message.clone(), reason: Some(error.message), attempt_status: None, connector_transaction_id: None, status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }); Ok(Self { response, ..item.data }) } DatatransSyncResponse::Response(sync_response) => { let status = enums::AttemptStatus::from(sync_response.clone()); let response = if status == enums::AttemptStatus::Failure { let (code, message) = match sync_response.detail.fail { Some(fail_details) => ( fail_details.reason.unwrap_or(NO_ERROR_CODE.to_string()), fail_details.message.unwrap_or(NO_ERROR_MESSAGE.to_string()), ), None => (NO_ERROR_CODE.to_string(), NO_ERROR_MESSAGE.to_string()), }; Err(ErrorResponse { code, message: message.clone(), reason: Some(message), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { let mandate_reference = sync_response .card .as_ref() .and_then(|card| card.alias.as_ref()) .map(|alias| MandateReference { connector_mandate_id: Some(alias.clone()), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, }); Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( sync_response.transaction_id.to_string(), ), redirection_data: Box::new(None), mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }) }; Ok(Self { status, response, ..item.data }) } } } } impl TryFrom<&DatatransRouterData<&types::PaymentsCaptureRouterData>> for DataPaymentCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &DatatransRouterData<&types::PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount, currency: item.router_data.request.currency, refno: item.router_data.connector_request_reference_id.clone(), }) } } impl TryFrom<PaymentsCaptureResponseRouterData<DataTransCaptureResponse>> for types::PaymentsCaptureRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PaymentsCaptureResponseRouterData<DataTransCaptureResponse>, ) -> Result<Self, Self::Error> { let status = match item.response { DataTransCaptureResponse::Error(error) => { if error.message == *TRANSACTION_ALREADY_SETTLED { common_enums::AttemptStatus::Charged } else { common_enums::AttemptStatus::Failure } } // Datatrans http code 204 implies Successful Capture //https://api-reference.datatrans.ch/#tag/v1transactions/operation/settle DataTransCaptureResponse::Empty => { if item.http_code == 204 { common_enums::AttemptStatus::Charged } else { common_enums::AttemptStatus::Failure } } }; Ok(Self { status, ..item.data }) } } impl TryFrom<PaymentsCancelResponseRouterData<DataTransCancelResponse>> for types::PaymentsCancelRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PaymentsCancelResponseRouterData<DataTransCancelResponse>, ) -> Result<Self, Self::Error> { let status = match item.response { // Datatrans http code 204 implies Successful Cancellation //https://api-reference.datatrans.ch/#tag/v1transactions/operation/cancel DataTransCancelResponse::Empty => { if item.http_code == 204 { common_enums::AttemptStatus::Voided } else { common_enums::AttemptStatus::Failure } } DataTransCancelResponse::Error(error) => { if error.message == *TRANSACTION_ALREADY_CANCELLED { common_enums::AttemptStatus::Voided } else { common_enums::AttemptStatus::Failure } } }; Ok(Self { status, ..item.data }) } }
crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs
hyperswitch_connectors
full_file
6,917
null
null
null
null
null
null
null
null
null
null
null
null
null
None, HeaderPayload::with_source(common_enums::PaymentSource::Webhook), )) .await } else { Err(report!( errors::ApiErrorResponse::WebhookAuthenticationFailed )) }; match response? { services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => { let payment_id = payments_response.payment_id.clone(); let event_type: Option<enums::EventType> = payments_response.status.into(); let status = payments_response.status; // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook if let Some(outgoing_event_type) = event_type { let primary_object_created_at = payments_response.created; Box::pin(super::create_event_and_trigger_outgoing_webhook( state, merchant_context, business_profile, outgoing_event_type, enums::EventClass::Payments, payment_id.get_string_repr().to_owned(), enums::EventObjectType::PaymentDetails, api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)), primary_object_created_at, )) .await?; } Ok(WebhookResponseTracker::Payment { payment_id, status }) } _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("received non-json response from payments core")?, } } async fn get_payment_id( db: &dyn StorageInterface, payment_id: &api::PaymentIdType, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: enums::MerchantStorageScheme, ) -> errors::RouterResult<common_utils::id_type::PaymentId> { let pay_id = || async { match payment_id { api_models::payments::PaymentIdType::PaymentIntentId(ref id) => Ok(id.to_owned()), api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => db .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_id, id, storage_scheme, ) .await .map(|p| p.payment_id), api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => db .find_payment_attempt_by_attempt_id_merchant_id(id, merchant_id, storage_scheme) .await .map(|p| p.payment_id), api_models::payments::PaymentIdType::PreprocessingId(ref id) => db .find_payment_attempt_by_preprocessing_id_merchant_id( id, merchant_id, storage_scheme, ) .await .map(|p| p.payment_id), } }; pay_id() .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } #[inline] async fn verify_webhook_source_verification_call( connector: ConnectorEnum, state: &SessionState, merchant_context: &domain::MerchantContext, merchant_connector_account: domain::MerchantConnectorAccount, connector_name: &str, request_details: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<bool, errors::ConnectorError> { let connector_data = ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, GetToken::Connector, None, ) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) .attach_printable("invalid connector name received in payment attempt")?; let connector_integration: services::BoxedWebhookSourceVerificationConnectorIntegrationInterface< hyperswitch_domain_models::router_flow_types::VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, > = connector_data.connector.get_connector_integration(); let connector_webhook_secrets = connector .get_webhook_source_verification_merchant_secret( merchant_context.get_merchant_account().get_id(), connector_name, merchant_connector_account.connector_webhook_details.clone(), ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let router_data = construct_webhook_router_data( state, connector_name, merchant_connector_account, merchant_context, &connector_webhook_secrets, request_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) .attach_printable("Failed while constructing webhook router data")?; let response = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await?; let verification_result = response .response .map(|response| response.verify_webhook_status); match verification_result { Ok(VerifyWebhookStatus::SourceVerified) => Ok(true), _ => Ok(false), } } pub fn get_connector_by_connector_name( state: &SessionState, connector_name: &str, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, ) -> CustomResult<(ConnectorEnum, String), errors::ApiErrorResponse> { let authentication_connector = api_models::enums::convert_authentication_connector(connector_name); #[cfg(feature = "frm")] { let frm_connector = api_models::enums::convert_frm_connector(connector_name); if frm_connector.is_some() { let frm_connector_data = api::FraudCheckConnectorData::get_connector_by_name(connector_name)?; return Ok(( frm_connector_data.connector, frm_connector_data.connector_name.to_string(), )); } } let (connector, connector_name) = if authentication_connector.is_some() { let authentication_connector_data = api::AuthenticationConnectorData::get_connector_by_name(connector_name)?; ( authentication_connector_data.connector, authentication_connector_data.connector_name.to_string(), ) } else { let connector_data = ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, GetToken::Connector, merchant_connector_id, ) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "invalid connector name received".to_string(), }) .attach_printable("Failed construction of ConnectorData")?; ( connector_data.connector, connector_data.connector_name.to_string(), ) }; Ok((connector, connector_name)) } /// This function fetches the merchant connector account ( if the url used is /{merchant_connector_id}) /// if merchant connector id is not passed in the request, then this will return None for mca async fn fetch_optional_mca_and_connector( state: &SessionState, merchant_context: &domain::MerchantContext, connector_name_or_mca_id: &str, ) -> CustomResult< ( Option<domain::MerchantConnectorAccount>, ConnectorEnum, String, ), errors::ApiErrorResponse, > { let db = &state.store; if connector_name_or_mca_id.starts_with("mca_") { #[cfg(feature = "v1")] let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( &state.into(), merchant_context.get_merchant_account().get_id(), &common_utils::id_type::MerchantConnectorAccountId::wrap( connector_name_or_mca_id.to_owned(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Error while converting MerchanConnectorAccountId from string ", )?, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: connector_name_or_mca_id.to_string(), }) .attach_printable( "error while fetching merchant_connector_account from connector_id", )?; #[cfg(feature = "v2")] let mca: domain::MerchantConnectorAccount = { let _ = merchant_account; let _ = key_store; let _ = db; todo!() }; let (connector, connector_name) = get_connector_by_connector_name(state, &mca.connector_name, Some(mca.get_id()))?; Ok((Some(mca), connector, connector_name)) } else { // Merchant connector account is already being queried, it is safe to set connector id as None let (connector, connector_name) = get_connector_by_connector_name(state, connector_name_or_mca_id, None)?; Ok((None, connector, connector_name)) } } fn should_update_connector_mandate_details( source_verified: bool, event_type: webhooks::IncomingWebhookEvent, ) -> bool { source_verified && event_type == webhooks::IncomingWebhookEvent::PaymentIntentSuccess } async fn update_connector_mandate_details( state: &SessionState, merchant_context: &domain::MerchantContext, object_ref_id: api::ObjectReferenceId, connector: &ConnectorEnum, request_details: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<(), errors::ApiErrorResponse> { let webhook_connector_mandate_details = connector .get_mandate_details(request_details) .switch() .attach_printable("Could not find connector mandate details in incoming webhook body")?; let webhook_connector_network_transaction_id = connector .get_network_txn_id(request_details) .switch() .attach_printable( "Could not find connector network transaction id in incoming webhook body", )?; // Either one OR both of the fields are present if webhook_connector_mandate_details.is_some() || webhook_connector_network_transaction_id.is_some() { let payment_attempt = get_payment_attempt_from_object_reference_id(state, object_ref_id, merchant_context) .await?; if let Some(ref payment_method_id) = payment_attempt.payment_method_id { let key_manager_state = &state.into(); let payment_method_info = state .store .find_payment_method( key_manager_state, merchant_context.get_merchant_key_store(), payment_method_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; // Update connector's mandate details let updated_connector_mandate_details = if let Some(webhook_mandate_details) = webhook_connector_mandate_details { let mandate_details = payment_method_info .get_common_mandate_reference() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize to Payment Mandate Reference")?; let merchant_connector_account_id = payment_attempt .merchant_connector_id .clone() .get_required_value("merchant_connector_id")?; if mandate_details.payments.as_ref().map_or(true, |payments| { !payments.0.contains_key(&merchant_connector_account_id) }) { // Update the payment attempt to maintain consistency across tables. let (mandate_metadata, connector_mandate_request_reference_id) = payment_attempt .connector_mandate_detail .as_ref() .map(|details| { ( details.mandate_metadata.clone(), details.connector_mandate_request_reference_id.clone(), ) }) .unwrap_or((None, None)); let connector_mandate_reference_id = ConnectorMandateReferenceId { connector_mandate_id: Some( webhook_mandate_details .connector_mandate_id .peek() .to_string(), ), payment_method_id: Some(payment_method_id.to_string()), mandate_metadata, connector_mandate_request_reference_id, }; let attempt_update = storage::PaymentAttemptUpdate::ConnectorMandateDetailUpdate { connector_mandate_detail: Some(connector_mandate_reference_id), updated_by: merchant_context .get_merchant_account() .storage_scheme .to_string(), }; state .store .update_payment_attempt_with_attempt_id( payment_attempt.clone(), attempt_update, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; insert_mandate_details( &payment_attempt, &webhook_mandate_details, Some(mandate_details), )? } else { logger::info!( "Skipping connector mandate details update since they are already present." ); None } } else { None }; let connector_mandate_details_value = updated_connector_mandate_details .map(|common_mandate| { common_mandate.get_mandate_details_value().map_err(|err| { router_env::logger::error!( "Failed to get get_mandate_details_value : {:?}", err ); errors::ApiErrorResponse::MandateUpdateFailed }) }) .transpose()?; let pm_update = diesel_models::PaymentMethodUpdate::ConnectorNetworkTransactionIdAndMandateDetailsUpdate { connector_mandate_details: connector_mandate_details_value.map(masking::Secret::new), network_transaction_id: webhook_connector_network_transaction_id .map(|webhook_network_transaction_id| webhook_network_transaction_id.get_id().clone()), }; state .store .update_payment_method( key_manager_state, merchant_context.get_merchant_key_store(), payment_method_info, pm_update, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; } } Ok(()) } fn insert_mandate_details( payment_attempt: &PaymentAttempt, webhook_mandate_details: &hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails, payment_method_mandate_details: Option<CommonMandateReference>, ) -> CustomResult<Option<CommonMandateReference>, errors::ApiErrorResponse> { let (mandate_metadata, connector_mandate_request_reference_id) = payment_attempt .connector_mandate_detail .clone() .map(|mandate_reference| { ( mandate_reference.mandate_metadata, mandate_reference.connector_mandate_request_reference_id, ) }) .unwrap_or((None, None)); let connector_mandate_details = tokenization::update_connector_mandate_details( payment_method_mandate_details, payment_attempt.payment_method_type, Some( payment_attempt .net_amount .get_total_amount() .get_amount_as_i64(), ), payment_attempt.currency, payment_attempt.merchant_connector_id.clone(), Some( webhook_mandate_details .connector_mandate_id .peek() .to_string(), ), mandate_metadata, connector_mandate_request_reference_id, )?; Ok(connector_mandate_details) }
crates/router/src/core/webhooks/incoming.rs#chunk2
router
chunk
3,227
null
null
null
null
null
null
null
null
null
null
null
null
null
File: crates/router/src/routes/hypersense.rs Public functions: 3 use actix_web::{web, HttpRequest, HttpResponse}; use api_models::external_service_auth as external_service_auth_api; use router_env::Flow; use super::AppState; use crate::{ core::{api_locking, external_service_auth}, services::{ api, authentication::{self, ExternalServiceType}, }, }; pub async fn get_hypersense_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { let flow = Flow::HypersenseTokenRequest; Box::pin(api::server_wrap( flow, state, &req, (), |state, user, _, _| { external_service_auth::generate_external_token( state, user, ExternalServiceType::Hypersense, ) }, &authentication::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn signout_hypersense_token( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<external_service_auth_api::ExternalSignoutTokenRequest>, ) -> HttpResponse { let flow = Flow::HypersenseSignoutToken; Box::pin(api::server_wrap( flow, state.clone(), &http_req, json_payload.into_inner(), |state, _: (), json_payload, _| { external_service_auth::signout_external_token(state, json_payload) }, &authentication::NoAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn verify_hypersense_token( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<external_service_auth_api::ExternalVerifyTokenRequest>, ) -> HttpResponse { let flow = Flow::HypersenseVerifyToken; Box::pin(api::server_wrap( flow, state.clone(), &http_req, json_payload.into_inner(), |state, _: (), json_payload, _| { external_service_auth::verify_external_token( state, json_payload, ExternalServiceType::Hypersense, ) }, &authentication::NoAuth, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/hypersense.rs
router
full_file
506
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct ListUsersInEntityRequest { pub entity_type: Option<common_enums::EntityType>, }
crates/api_models/src/user_role.rs
api_models
struct_definition
22
rust
ListUsersInEntityRequest
null
null
null
null
null
null
null
null
null
null
null
File: crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs Public structs: 9 use common_enums::enums; use common_utils::{ext_traits::Encode, types::MinorUnit}; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{PaymentMethodData, WalletData}, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{self, RefundsRouterData}, }; use hyperswitch_interfaces::{consts, errors}; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{get_unimplemented_payment_method_error_message, RouterData as _}, }; type Error = error_stack::Report<errors::ConnectorError>; #[derive(Debug, Serialize)] pub struct GlobepayRouterData<T> { pub amount: MinorUnit, pub router_data: T, } impl<T> From<(MinorUnit, T)> for GlobepayRouterData<T> { fn from((amount, router_data): (MinorUnit, T)) -> Self { Self { amount, router_data, } } } #[derive(Debug, Serialize)] pub struct GlobepayPaymentsRequest { price: MinorUnit, description: String, currency: enums::Currency, channel: GlobepayChannel, } #[derive(Debug, Serialize)] pub enum GlobepayChannel { Alipay, Wechat, } impl TryFrom<&GlobepayRouterData<&types::PaymentsAuthorizeRouterData>> for GlobepayPaymentsRequest { type Error = Error; fn try_from( item_data: &GlobepayRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let item = item_data.router_data.clone(); let channel: GlobepayChannel = match &item.request.payment_method_data { PaymentMethodData::Wallet(ref wallet_data) => match wallet_data { WalletData::AliPayQr(_) => GlobepayChannel::Alipay, WalletData::WeChatPayQr(_) => GlobepayChannel::Wechat, WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPay(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::BluecodeRedirect {} | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::ApplePay(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePay(_) | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MbWayRedirect(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayRedirect(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::Mifinity(_) | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("globepay"), ))?, }, PaymentMethodData::Card(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("globepay"), ))? } }; let description = item.get_description()?; Ok(Self { price: item_data.amount, description, currency: item.request.currency, channel, }) } } pub struct GlobepayAuthType { pub(super) partner_code: Secret<String>, pub(super) credential_code: Secret<String>, } impl TryFrom<&ConnectorAuthType> for GlobepayAuthType { type Error = Error; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { partner_code: api_key.to_owned(), credential_code: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GlobepayPaymentStatus { Success, Exists, } impl From<GlobepayPaymentStatus> for enums::AttemptStatus { fn from(item: GlobepayPaymentStatus) -> Self { match item { GlobepayPaymentStatus::Success => Self::AuthenticationPending, // this connector only have redirection flows so "Success" is mapped to authenticatoin pending ,ref = "https://pay.globepay.co/docs/en/#api-QRCode-NewQRCode" GlobepayPaymentStatus::Exists => Self::Failure, } } } #[derive(Debug, Deserialize, Serialize)] pub struct GlobepayConnectorMetadata { image_data_url: url::Url, } #[derive(Debug, Deserialize, Serialize)] pub struct GlobepayPaymentsResponse { result_code: Option<GlobepayPaymentStatus>, order_id: Option<String>, qrcode_img: Option<url::Url>, return_code: GlobepayReturnCode, //Execution result return_msg: Option<String>, } #[derive(Debug, Deserialize, PartialEq, strum::Display, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GlobepayReturnCode { Success, OrderNotExist, OrderMismatch, Systemerror, InvalidShortId, SignTimeout, InvalidSign, ParamInvalid, NotPermitted, InvalidChannel, DuplicateOrderId, OrderNotPaid, } impl<F, T> TryFrom<ResponseRouterData<F, GlobepayPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = Error; fn try_from( item: ResponseRouterData<F, GlobepayPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { if item.response.return_code == GlobepayReturnCode::Success { let globepay_metadata = GlobepayConnectorMetadata { image_data_url: item .response .qrcode_img .ok_or(errors::ConnectorError::ResponseHandlingFailed)?, }; let connector_metadata = Some(globepay_metadata.encode_to_value()) .transpose() .change_context(errors::ConnectorError::ResponseHandlingFailed)?; let globepay_status = item .response .result_code .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; Ok(Self { status: enums::AttemptStatus::from(globepay_status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response .order_id .ok_or(errors::ConnectorError::ResponseHandlingFailed)?, ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } else { Ok(Self { status: enums::AttemptStatus::Failure, //As this connector gives 200 in failed scenarios . if return_code is not success status is mapped to failure. ref = "https://pay.globepay.co/docs/en/#api-QRCode-NewQRCode" response: Err(get_error_response( item.response.return_code, item.response.return_msg, item.http_code, )), ..item.data }) } } } #[derive(Debug, Deserialize, Serialize)] pub struct GlobepaySyncResponse { pub result_code: Option<GlobepayPaymentPsyncStatus>, pub order_id: Option<String>, pub return_code: GlobepayReturnCode, pub return_msg: Option<String>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GlobepayPaymentPsyncStatus { Paying, CreateFail, Closed, PayFail, PaySuccess, } impl From<GlobepayPaymentPsyncStatus> for enums::AttemptStatus { fn from(item: GlobepayPaymentPsyncStatus) -> Self { match item { GlobepayPaymentPsyncStatus::PaySuccess => Self::Charged, GlobepayPaymentPsyncStatus::PayFail | GlobepayPaymentPsyncStatus::CreateFail | GlobepayPaymentPsyncStatus::Closed => Self::Failure, GlobepayPaymentPsyncStatus::Paying => Self::AuthenticationPending, } } } impl<F, T> TryFrom<ResponseRouterData<F, GlobepaySyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = Error; fn try_from( item: ResponseRouterData<F, GlobepaySyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { if item.response.return_code == GlobepayReturnCode::Success { let globepay_status = item .response .result_code .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; let globepay_id = item .response .order_id .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; Ok(Self { status: enums::AttemptStatus::from(globepay_status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(globepay_id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } else { Ok(Self { status: enums::AttemptStatus::Failure, //As this connector gives 200 in failed scenarios . if return_code is not success status is mapped to failure. ref = "https://pay.globepay.co/docs/en/#api-QRCode-NewQRCode" response: Err(get_error_response( item.response.return_code, item.response.return_msg, item.http_code, )), ..item.data }) } } } fn get_error_response( return_code: GlobepayReturnCode, return_msg: Option<String>, status_code: u16, ) -> ErrorResponse { ErrorResponse { code: return_code.to_string(), message: consts::NO_ERROR_MESSAGE.to_string(), reason: return_msg, status_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, } } #[derive(Debug, Serialize)] pub struct GlobepayRefundRequest { pub fee: MinorUnit, } impl<F> TryFrom<&GlobepayRouterData<&RefundsRouterData<F>>> for GlobepayRefundRequest { type Error = Error; fn try_from(item: &GlobepayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { fee: item.amount }) } } #[derive(Debug, Deserialize, Serialize)] pub enum GlobepayRefundStatus { Waiting, CreateFailed, Failed, Success, Finished, Change, } impl From<GlobepayRefundStatus> for enums::RefundStatus { fn from(item: GlobepayRefundStatus) -> Self { match item { GlobepayRefundStatus::Finished => Self::Success, //FINISHED: Refund success(funds has already been returned to user's account) GlobepayRefundStatus::Failed | GlobepayRefundStatus::CreateFailed | GlobepayRefundStatus::Change => Self::Failure, //CHANGE: Refund can not return to user's account. Manual operation is required GlobepayRefundStatus::Waiting | GlobepayRefundStatus::Success => Self::Pending, // SUCCESS: Submission succeeded, but refund is not yet complete. Waiting = Submission succeeded, but refund is not yet complete. } } } #[derive(Debug, Deserialize, Serialize)] pub struct GlobepayRefundResponse { pub result_code: Option<GlobepayRefundStatus>, pub refund_id: Option<String>, pub return_code: GlobepayReturnCode, pub return_msg: Option<String>, } impl<T> TryFrom<RefundsResponseRouterData<T, GlobepayRefundResponse>> for RefundsRouterData<T> { type Error = Error; fn try_from( item: RefundsResponseRouterData<T, GlobepayRefundResponse>, ) -> Result<Self, Self::Error> { if item.response.return_code == GlobepayReturnCode::Success { let globepay_refund_id = item .response .refund_id .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; let globepay_refund_status = item .response .result_code .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: globepay_refund_id, refund_status: enums::RefundStatus::from(globepay_refund_status), }), ..item.data }) } else { Ok(Self { response: Err(get_error_response( item.response.return_code, item.response.return_msg, item.http_code, )), ..item.data }) } } } #[derive(Debug, Deserialize, Serialize)] pub struct GlobepayErrorResponse { pub return_msg: String, pub return_code: GlobepayReturnCode, pub message: String, }
crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
hyperswitch_connectors
full_file
3,337
null
null
null
null
null
null
null
null
null
null
null
null
null
impl ApiEventMetric for AuthenticationCreateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { self.authentication_id .as_ref() .map(|id| ApiEventsType::Authentication { authentication_id: id.clone(), }) } }
crates/api_models/src/authentication.rs
api_models
impl_block
60
rust
null
AuthenticationCreateRequest
ApiEventMetric for
impl ApiEventMetric for for AuthenticationCreateRequest
null
null
null
null
null
null
null
null
pub struct GsmDeleteResponse { pub gsm_rule_delete: bool, /// The connector through which payment has gone through pub connector: String, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector pub sub_flow: String, /// code received from the connector pub code: String, }
crates/api_models/src/gsm.rs
api_models
struct_definition
93
rust
GsmDeleteResponse
null
null
null
null
null
null
null
null
null
null
null
pub async fn decision_engine_routing( state: &SessionState, backend_input: BackendInput, business_profile: &domain::Profile, payment_id: String, merchant_fallback_config: Vec<RoutableConnectorChoice>, ) -> RoutingResult<Vec<RoutableConnectorChoice>> { let routing_events_wrapper = RoutingEventsWrapper::new( state.tenant.tenant_id.clone(), state.request_id, payment_id, business_profile.get_id().to_owned(), business_profile.merchant_id.to_owned(), "DecisionEngine: Euclid Static Routing".to_string(), None, true, false, ); let de_euclid_evaluate_response = perform_decision_euclid_routing( state, backend_input.clone(), business_profile.get_id().get_string_repr().to_string(), routing_events_wrapper, merchant_fallback_config, ) .await; let Ok(de_euclid_response) = de_euclid_evaluate_response else { logger::error!("decision_engine_euclid_evaluation_error: error in evaluation of rule"); return Ok(Vec::default()); }; let de_output_connector = extract_de_output_connectors(de_euclid_response.output) .map_err(|e| { logger::error!(error=?e, "decision_engine_euclid_evaluation_error: Failed to extract connector from Output"); e })?; transform_de_output_for_router( de_output_connector.clone(), de_euclid_response.evaluated_output.clone(), ) .map_err(|e| { logger::error!(error=?e, "decision_engine_euclid_evaluation_error: failed to transform connector from de-output"); e }) }
crates/router/src/core/payments/routing/utils.rs
router
function_signature
358
rust
null
null
null
null
decision_engine_routing
null
null
null
null
null
null
null
pub struct AirwallexRedirectResponse { status: AirwallexPaymentStatus, id: String, amount: Option<f32>, payment_consent_id: Option<Secret<String>>, next_action: Option<AirwallexRedirectNextAction>, }
crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
hyperswitch_connectors
struct_definition
55
rust
AirwallexRedirectResponse
null
null
null
null
null
null
null
null
null
null
null
pub struct UnifiedTranslationsUpdateInternal { pub translation: Option<String>, pub last_modified_at: PrimitiveDateTime, }
crates/diesel_models/src/unified_translations.rs
diesel_models
struct_definition
24
rust
UnifiedTranslationsUpdateInternal
null
null
null
null
null
null
null
null
null
null
null
impl api::PaymentSession for Adyenplatform {}
crates/hyperswitch_connectors/src/connectors/adyenplatform.rs
hyperswitch_connectors
impl_block
10
rust
null
Adyenplatform
api::PaymentSession for
impl api::PaymentSession for for Adyenplatform
null
null
null
null
null
null
null
null
pub async fn delete_payment_intents( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Vec<PaymentIntent>> { let query = diesel::delete(<PaymentIntent>::table()) .filter(payment_intent_dsl::merchant_id.eq(merchant_id.to_owned())) .filter(payment_intent_dsl::merchant_reference_id.like("test_%")); logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while deleting payment intents") .and_then(|result| match result.len() { n if n > 0 => { logger::debug!("{n} records deleted"); Ok(result) } 0 => Err(error_stack::report!(errors::DatabaseError::NotFound) .attach_printable("No records deleted")), _ => Ok(result), }) }
crates/diesel_models/src/query/user/sample_data.rs
diesel_models
function_signature
221
rust
null
null
null
null
delete_payment_intents
null
null
null
null
null
null
null
OpenAPI Block Path: components.schemas.MerchantConnectorResponse { "type": "object", "description": "Response of creating a new Merchant Connector for the merchant account.\"", "required": [ "connector_type", "connector_name", "merchant_connector_id", "profile_id", "status" ], "properties": { "connector_type": { "$ref": "#/components/schemas/ConnectorType" }, "connector_name": { "$ref": "#/components/schemas/Connector" }, "connector_label": { "type": "string", "description": "A unique label to identify the connector account created under a profile", "example": "stripe_US_travel", "nullable": true }, "merchant_connector_id": { "type": "string", "description": "Unique ID of the merchant connector account", "example": "mca_5apGeP94tMts6rg3U3kR" }, "profile_id": { "type": "string", "description": "Identifier for the profile, if not provided default will be chosen from merchant account", "maxLength": 64 }, "connector_account_details": { "allOf": [ { "$ref": "#/components/schemas/MerchantConnectorDetails" } ], "nullable": true }, "payment_methods_enabled": { "type": "array", "items": { "$ref": "#/components/schemas/PaymentMethodsEnabled" }, "description": "An object containing the details about the payment methods that need to be enabled under this merchant connector account", "example": [ { "accepted_countries": { "list": [ "FR", "DE", "IN" ], "type": "disable_only" }, "accepted_currencies": { "list": [ "USD", "EUR" ], "type": "enable_only" }, "installment_payment_enabled": true, "maximum_amount": 68607706, "minimum_amount": 1, "payment_method": "wallet", "payment_method_issuers": [ "labore magna ipsum", "aute" ], "payment_method_types": [ "upi_collect", "upi_intent" ], "payment_schemes": [ "Discover", "Discover" ], "recurring_enabled": true } ], "nullable": true }, "connector_webhook_details": { "allOf": [ { "$ref": "#/components/schemas/MerchantConnectorWebhookDetails" } ], "nullable": true }, "metadata": { "type": "object", "description": "Metadata is useful for storing additional, unstructured information on an object.", "nullable": true }, "test_mode": { "type": "boolean", "description": "A boolean value to indicate if the connector is in Test mode. By default, its value is false.", "default": false, "example": false, "nullable": true }, "disabled": { "type": "boolean", "description": "A boolean value to indicate if the connector is disabled. By default, its value is false.", "default": false, "example": false, "nullable": true }, "frm_configs": { "type": "array", "items": { "$ref": "#/components/schemas/FrmConfigs" }, "description": "Contains the frm configs for the merchant connector", "example": "\n[{\"gateway\":\"stripe\",\"payment_methods\":[{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"credit\",\"card_networks\":[\"Visa\"],\"flow\":\"pre\",\"action\":\"cancel_txn\"},{\"payment_method_type\":\"debit\",\"card_networks\":[\"Visa\"],\"flow\":\"pre\"}]}]}]\n", "nullable": true }, "business_country": { "allOf": [ { "$ref": "#/components/schemas/CountryAlpha2" } ], "nullable": true }, "business_label": { "type": "string", "description": "The business label to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead", "example": "travel", "nullable": true }, "business_sub_label": { "type": "string", "description": "The business sublabel to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead", "example": "chase", "nullable": true }, "applepay_verified_domains": { "type": "array", "items": { "type": "string" }, "description": "identifier for the verified domains of a particular connector account", "nullable": true }, "pm_auth_config": { "type": "object", "nullable": true }, "status": { "$ref": "#/components/schemas/ConnectorStatus" }, "additional_merchant_data": { "allOf": [ { "$ref": "#/components/schemas/AdditionalMerchantData" } ], "nullable": true }, "connector_wallets_details": { "allOf": [ { "$ref": "#/components/schemas/ConnectorWalletDetails" } ], "nullable": true } }, "additionalProperties": false }
./hyperswitch/api-reference/v1/openapi_spec_v1.json
null
openapi_block
1,241
.json
null
null
null
null
null
openapi_spec
components
[ "schemas", "MerchantConnectorResponse" ]
null
null
null
null
pub struct PaymentMethodCollectLinkRequest { /// The unique identifier for the collect link. #[schema(value_type = Option<String>, example = "pm_collect_link_2bdacf398vwzq5n422S1")] pub pm_collect_link_id: Option<String>, /// The unique identifier of the customer. #[schema(value_type = String, example = "cus_92dnwed8s32bV9D8Snbiasd8v")] pub customer_id: id_type::CustomerId, #[serde(flatten)] #[schema(value_type = Option<GenericLinkUiConfig>)] pub ui_config: Option<link_utils::GenericLinkUiConfig>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds /// (900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Redirect to this URL post completion #[schema(value_type = Option<String>, example = "https://sandbox.hyperswitch.io/payment_method/collect/pm_collect_link_2bdacf398vwzq5n422S1/status")] pub return_url: Option<String>, /// List of payment methods shown on collect UI #[schema(value_type = Option<Vec<EnabledPaymentMethod>>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs"]}]"#)] pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, }
crates/api_models/src/payment_methods.rs
api_models
struct_definition
343
rust
PaymentMethodCollectLinkRequest
null
null
null
null
null
null
null
null
null
null
null
pub struct PaymentAccountFeatureInformation { health_card: Option<String>, }
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
hyperswitch_connectors
struct_definition
15
rust
PaymentAccountFeatureInformation
null
null
null
null
null
null
null
null
null
null
null
merchant_account: storage::MerchantAccountUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store .update_specific_fields_in_merchant(state, merchant_id, merchant_account, key_store) .await } async fn update_all_merchant_account( &self, merchant_account: storage::MerchantAccountUpdate, ) -> CustomResult<usize, errors::StorageError> { self.diesel_store .update_all_merchant_account(merchant_account) .await } async fn find_merchant_account_by_publishable_key( &self, state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<(domain::MerchantAccount, domain::MerchantKeyStore), errors::StorageError> { self.diesel_store .find_merchant_account_by_publishable_key(state, publishable_key) .await } #[cfg(feature = "olap")] async fn list_merchant_accounts_by_organization_id( &self, state: &KeyManagerState, organization_id: &id_type::OrganizationId, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { self.diesel_store .list_merchant_accounts_by_organization_id(state, organization_id) .await } async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_merchant_account_by_merchant_id(merchant_id) .await } #[cfg(feature = "olap")] async fn list_multiple_merchant_accounts( &self, state: &KeyManagerState, merchant_ids: Vec<id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { self.diesel_store .list_multiple_merchant_accounts(state, merchant_ids) .await } #[cfg(feature = "olap")] async fn list_merchant_and_org_ids( &self, state: &KeyManagerState, limit: u32, offset: Option<u32>, ) -> CustomResult<Vec<(id_type::MerchantId, id_type::OrganizationId)>, errors::StorageError> { self.diesel_store .list_merchant_and_org_ids(state, limit, offset) .await } } #[async_trait::async_trait] impl ConnectorAccessToken for KafkaStore { async fn get_access_token( &self, merchant_id: &id_type::MerchantId, merchant_connector_id: &str, ) -> CustomResult<Option<AccessToken>, errors::StorageError> { self.diesel_store .get_access_token(merchant_id, merchant_connector_id) .await } async fn set_access_token( &self, merchant_id: &id_type::MerchantId, merchant_connector_id: &str, access_token: AccessToken, ) -> CustomResult<(), errors::StorageError> { self.diesel_store .set_access_token(merchant_id, merchant_connector_id, access_token) .await } } #[async_trait::async_trait] impl FileMetadataInterface for KafkaStore { async fn insert_file_metadata( &self, file: storage::FileMetadataNew, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { self.diesel_store.insert_file_metadata(file).await } async fn find_file_metadata_by_merchant_id_file_id( &self, merchant_id: &id_type::MerchantId, file_id: &str, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { self.diesel_store .find_file_metadata_by_merchant_id_file_id(merchant_id, file_id) .await } async fn delete_file_metadata_by_merchant_id_file_id( &self, merchant_id: &id_type::MerchantId, file_id: &str, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_file_metadata_by_merchant_id_file_id(merchant_id, file_id) .await } async fn update_file_metadata( &self, this: storage::FileMetadata, file_metadata: storage::FileMetadataUpdate, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { self.diesel_store .update_file_metadata(this, file_metadata) .await } } #[async_trait::async_trait] impl MerchantConnectorAccountInterface for KafkaStore { async fn update_multiple_merchant_connector_accounts( &self, merchant_connector_accounts: Vec<( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, )>, ) -> CustomResult<(), errors::StorageError> { self.diesel_store .update_multiple_merchant_connector_accounts(merchant_connector_accounts) .await } #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, connector: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_merchant_id_connector_label( state, merchant_id, connector, key_store, ) .await } #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, connector_name: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_merchant_id_connector_name( state, merchant_id, connector_name, key_store, ) .await } #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_profile_id_connector_name( &self, state: &KeyManagerState, profile_id: &id_type::ProfileId, connector_name: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_profile_id_connector_name( state, profile_id, connector_name, key_store, ) .await } async fn list_enabled_connector_accounts_by_profile_id( &self, state: &KeyManagerState, profile_id: &id_type::ProfileId, key_store: &domain::MerchantKeyStore, connector_type: common_enums::ConnectorType, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { self.diesel_store .list_enabled_connector_accounts_by_profile_id( state, profile_id, key_store, connector_type, ) .await } async fn insert_merchant_connector_account( &self, state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .insert_merchant_connector_account(state, t, key_store) .await } #[cfg(feature = "v1")] async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, merchant_connector_id: &id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( state, merchant_id, merchant_connector_id, key_store, ) .await } #[cfg(feature = "v2")] async fn find_merchant_connector_account_by_id( &self, state: &KeyManagerState, id: &id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_id(state, id, key_store) .await } async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, get_disabled: bool, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccounts, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_merchant_id_and_disabled_list( state, merchant_id, get_disabled, key_store, ) .await } #[cfg(all(feature = "olap", feature = "v2"))] async fn list_connector_account_by_profile_id( &self, state: &KeyManagerState, profile_id: &id_type::ProfileId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { self.diesel_store .list_connector_account_by_profile_id(state, profile_id, key_store) .await } async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .update_merchant_connector_account(state, this, merchant_connector_account, key_store) .await } #[cfg(feature = "v1")] async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &self, merchant_id: &id_type::MerchantId, merchant_connector_id: &id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_merchant_connector_account_by_merchant_id_merchant_connector_id( merchant_id, merchant_connector_id, ) .await } #[cfg(feature = "v2")] async fn delete_merchant_connector_account_by_id( &self, id: &id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_merchant_connector_account_by_id(id) .await } } #[async_trait::async_trait] impl QueueInterface for KafkaStore { async fn fetch_consumer_tasks( &self, stream_name: &str, group_name: &str, consumer_name: &str, ) -> CustomResult<Vec<storage::ProcessTracker>, ProcessTrackerError> { self.diesel_store .fetch_consumer_tasks(stream_name, group_name, consumer_name) .await } async fn consumer_group_create( &self, stream: &str, group: &str, id: &RedisEntryId, ) -> CustomResult<(), RedisError> { self.diesel_store .consumer_group_create(stream, group, id) .await } async fn acquire_pt_lock( &self, tag: &str, lock_key: &str, lock_val: &str, ttl: i64, ) -> CustomResult<bool, RedisError> { self.diesel_store .acquire_pt_lock(tag, lock_key, lock_val, ttl) .await } async fn release_pt_lock(&self, tag: &str, lock_key: &str) -> CustomResult<bool, RedisError> { self.diesel_store.release_pt_lock(tag, lock_key).await } async fn stream_append_entry( &self, stream: &str, entry_id: &RedisEntryId, fields: Vec<(&str, String)>, ) -> CustomResult<(), RedisError> { self.diesel_store .stream_append_entry(stream, entry_id, fields) .await } async fn get_key(&self, key: &str) -> CustomResult<Vec<u8>, RedisError> { self.diesel_store.get_key(key).await } } #[async_trait::async_trait] impl PaymentAttemptInterface for KafkaStore { type Error = errors::StorageError; #[cfg(feature = "v1")] async fn insert_payment_attempt( &self, payment_attempt: storage::PaymentAttemptNew, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { let attempt = self .diesel_store .insert_payment_attempt(payment_attempt, storage_scheme) .await?; if let Err(er) = self .kafka_producer .log_payment_attempt(&attempt, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er) } Ok(attempt) } #[cfg(feature = "v2")] async fn insert_payment_attempt( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, payment_attempt: storage::PaymentAttempt, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { let attempt = self .diesel_store .insert_payment_attempt( key_manager_state, merchant_key_store, payment_attempt, storage_scheme, ) .await?; if let Err(er) = self .kafka_producer .log_payment_attempt(&attempt, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er) } Ok(attempt) } #[cfg(feature = "v1")] async fn update_payment_attempt_with_attempt_id( &self, this: storage::PaymentAttempt, payment_attempt: storage::PaymentAttemptUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { let mut attempt = self .diesel_store .update_payment_attempt_with_attempt_id( this.clone(), payment_attempt.clone(), storage_scheme, ) .await?; let debit_routing_savings = payment_attempt.get_debit_routing_savings(); attempt.set_debit_routing_savings(debit_routing_savings); if let Err(er) = self .kafka_producer .log_payment_attempt(&attempt, Some(this), self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er) } Ok(attempt) } #[cfg(feature = "v2")] async fn update_payment_attempt( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, this: storage::PaymentAttempt, payment_attempt: storage::PaymentAttemptUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { let attempt = self .diesel_store .update_payment_attempt( key_manager_state, merchant_key_store, this.clone(), payment_attempt, storage_scheme, ) .await?; if let Err(er) = self .kafka_producer .log_payment_attempt(&attempt, Some(this), self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er) } Ok(attempt) } #[cfg(feature = "v1")] async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, connector_transaction_id: &common_utils::types::ConnectorTransactionId, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( connector_transaction_id, payment_id, merchant_id, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, merchant_id: &id_type::MerchantId, connector_txn_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_id, connector_txn_id, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_payment_attempt_by_profile_id_connector_transaction_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_id: &id_type::ProfileId, connector_transaction_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_profile_id_connector_transaction_id( key_manager_state, merchant_key_store, profile_id, connector_transaction_id, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, attempt_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_payment_id_merchant_id_attempt_id( payment_id, merchant_id, attempt_id, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_payment_attempt_by_attempt_id_merchant_id( &self, attempt_id: &str, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_attempt_id_merchant_id(attempt_id, merchant_id, storage_scheme) .await } #[cfg(feature = "v2")] async fn find_payment_attempt_by_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, attempt_id: &id_type::GlobalAttemptId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_id( key_manager_state, merchant_key_store, attempt_id, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_payment_attempts_by_payment_intent_id( &self, key_manager_state: &KeyManagerState, payment_id: &id_type::GlobalPaymentId, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<storage::PaymentAttempt>, errors::StorageError> { self.diesel_store .find_payment_attempts_by_payment_intent_id( key_manager_state, payment_id, merchant_key_store, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( payment_id, merchant_id, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( payment_id, merchant_id, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, payment_id: &id_type::GlobalPaymentId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( key_manager_state, merchant_key_store, payment_id, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, preprocessing_id: &str, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_preprocessing_id_merchant_id( preprocessing_id, merchant_id, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn get_filters_for_payments( &self, pi: &[hyperswitch_domain_models::payments::PaymentIntent], merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult< hyperswitch_domain_models::payments::payment_attempt::PaymentListFilters, errors::StorageError, > { self.diesel_store .get_filters_for_payments(pi, merchant_id, storage_scheme) .await } #[cfg(feature = "v1")] async fn get_total_count_of_filtered_payment_attempts( &self, merchant_id: &id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<api_models::enums::Connector>>, payment_method: Option<Vec<common_enums::PaymentMethod>>, payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<common_enums::CardNetwork>>, card_discovery: Option<Vec<common_enums::CardDiscovery>>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { self.diesel_store .get_total_count_of_filtered_payment_attempts( merchant_id, active_attempt_ids, connector, payment_method, payment_method_type, authentication_type, merchant_connector_id, card_network, card_discovery, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn get_total_count_of_filtered_payment_attempts( &self, merchant_id: &id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<api_models::enums::Connector>>, payment_method_type: Option<Vec<common_enums::PaymentMethod>>, payment_method_subtype: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<common_enums::CardNetwork>>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { self.diesel_store .get_total_count_of_filtered_payment_attempts( merchant_id, active_attempt_ids, connector, payment_method_type, payment_method_subtype, authentication_type, merchant_connector_id, card_network, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_attempts_by_merchant_id_payment_id( &self, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::PaymentAttempt>, errors::StorageError> { self.diesel_store .find_attempts_by_merchant_id_payment_id(merchant_id, payment_id, storage_scheme) .await } } #[async_trait::async_trait] impl PaymentIntentInterface for KafkaStore { type Error = errors::StorageError; async fn update_payment_intent( &self, state: &KeyManagerState, this: storage::PaymentIntent, payment_intent: storage::PaymentIntentUpdate, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentIntent, errors::StorageError> { let intent = self .diesel_store .update_payment_intent( state, this.clone(), payment_intent.clone(), key_store, storage_scheme, ) .await?; if let Err(er) = self .kafka_producer .log_payment_intent( &intent, Some(this), self.tenant_id.clone(), state.add_confirm_value_in_infra_values(payment_intent.is_confirm_operation()), ) .await { logger::error!(message="Failed to add analytics entry for Payment Intent {intent:?}", error_message=?er); }; Ok(intent) } async fn insert_payment_intent( &self, state: &KeyManagerState, new: storage::PaymentIntent, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentIntent, errors::StorageError> { logger::debug!("Inserting PaymentIntent Via KafkaStore"); let intent = self .diesel_store .insert_payment_intent(state, new, key_store, storage_scheme) .await?; if let Err(er) = self .kafka_producer .log_payment_intent( &intent, None, self.tenant_id.clone(), state.infra_values.clone(), ) .await { logger::error!(message="Failed to add analytics entry for Payment Intent {intent:?}", error_message=?er); }; Ok(intent) } #[cfg(feature = "v1")] async fn find_payment_intent_by_payment_id_merchant_id( &self, state: &KeyManagerState, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentIntent, errors::StorageError> { self.diesel_store .find_payment_intent_by_payment_id_merchant_id( state, payment_id, merchant_id, key_store, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_payment_intent_by_id( &self, state: &KeyManagerState, payment_id: &id_type::GlobalPaymentId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentIntent, errors::StorageError> { self.diesel_store .find_payment_intent_by_id(state, payment_id, key_store, storage_scheme) .await } #[cfg(all(feature = "olap", feature = "v1"))] async fn filter_payment_intent_by_constraints( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::PaymentIntent>, errors::StorageError> { self.diesel_store .filter_payment_intent_by_constraints( state, merchant_id, filters, key_store, storage_scheme, ) .await } #[cfg(all(feature = "olap", feature = "v1"))] async fn filter_payment_intents_by_time_range_constraints( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, time_range: &common_utils::types::TimeRange, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::PaymentIntent>, errors::StorageError> { self.diesel_store .filter_payment_intents_by_time_range_constraints( state, merchant_id, time_range, key_store, storage_scheme, ) .await } #[cfg(feature = "olap")] async fn get_intent_status_with_count( &self, merchant_id: &id_type::MerchantId, profile_id_list: Option<Vec<id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, errors::StorageError> { self.diesel_store .get_intent_status_with_count(merchant_id, profile_id_list, time_range) .await } #[cfg(all(feature = "olap", feature = "v1"))] async fn get_filtered_payment_intents_attempt( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult< Vec<( hyperswitch_domain_models::payments::PaymentIntent, hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, )>, errors::StorageError, > { self.diesel_store .get_filtered_payment_intents_attempt( state, merchant_id, constraints, key_store, storage_scheme, ) .await } #[cfg(all(feature = "olap", feature = "v2"))] async fn get_filtered_payment_intents_attempt( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult< Vec<( hyperswitch_domain_models::payments::PaymentIntent, Option<hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>, )>, errors::StorageError, > { self.diesel_store .get_filtered_payment_intents_attempt( state, merchant_id, constraints, key_store, storage_scheme, ) .await } #[cfg(all(feature = "olap", feature = "v1"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &id_type::MerchantId, constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<String>, errors::StorageError> { self.diesel_store .get_filtered_active_attempt_ids_for_total_count( merchant_id, constraints, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_payment_intent_by_merchant_reference_id_profile_id( &self, state: &KeyManagerState, merchant_reference_id: &id_type::PaymentReferenceId, profile_id: &id_type::ProfileId, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: &MerchantStorageScheme, ) -> error_stack::Result<hyperswitch_domain_models::payments::PaymentIntent, errors::StorageError> { self.diesel_store .find_payment_intent_by_merchant_reference_id_profile_id( state, merchant_reference_id, profile_id, merchant_key_store, storage_scheme, ) .await } #[cfg(all(feature = "olap", feature = "v2"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &id_type::MerchantId, constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<Option<String>>, errors::StorageError> { self.diesel_store .get_filtered_active_attempt_ids_for_total_count( merchant_id, constraints, storage_scheme, ) .await } } #[async_trait::async_trait] impl PaymentMethodInterface for KafkaStore { type Error = errors::StorageError; #[cfg(feature = "v1")] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, payment_method_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentMethod, errors::StorageError> { self.diesel_store .find_payment_method(state, key_store, payment_method_id, storage_scheme) .await } #[cfg(feature = "v2")] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, payment_method_id: &id_type::GlobalPaymentMethodId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentMethod, errors::StorageError> { self.diesel_store .find_payment_method(state, key_store, payment_method_id, storage_scheme) .await } #[cfg(feature = "v1")] async fn find_payment_method_by_customer_id_merchant_id_list( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, limit: Option<i64>, ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> { self.diesel_store .find_payment_method_by_customer_id_merchant_id_list( state, key_store, customer_id, merchant_id, limit, ) .await } #[cfg(feature = "v2")] async fn find_payment_method_list_by_global_customer_id( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, id: &id_type::GlobalCustomerId, limit: Option<i64>, ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> { self.diesel_store .find_payment_method_list_by_global_customer_id(state, key_store, id, limit) .await } #[cfg(feature = "v1")] async fn find_payment_method_by_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> { self.diesel_store .find_payment_method_by_customer_id_merchant_id_status( state, key_store, customer_id, merchant_id, status, limit, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_payment_method_by_global_customer_id_merchant_id_status( &self,
crates/router/src/db/kafka_store.rs#chunk1
router
chunk
8,189
null
null
null
null
null
null
null
null
null
null
null
null
null
pub async fn verify_totp( state: SessionState, user_token: auth::UserIdFromAuth, req: user_api::VerifyTotpRequest, ) -> UserResponse<user_api::TokenResponse> { let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_id(&user_token.user_id) .await .change_context(UserErrors::InternalServerError)? .into(); if user_from_db.get_totp_status() != TotpStatus::Set { return Err(UserErrors::TotpNotSetup.into()); } let user_totp_attempts = tfa_utils::get_totp_attempts_from_redis(&state, &user_token.user_id).await?; if user_totp_attempts >= consts::user::TOTP_MAX_ATTEMPTS { return Err(UserErrors::MaxTotpAttemptsReached.into()); } let user_totp_secret = user_from_db .decrypt_and_get_totp_secret(&state) .await? .ok_or(UserErrors::InternalServerError)?; let totp = tfa_utils::generate_default_totp( user_from_db.get_email(), Some(user_totp_secret), state.conf.user.totp_issuer_name.clone(), )?; if totp .generate_current() .change_context(UserErrors::InternalServerError)? != req.totp.expose() { let _ = tfa_utils::insert_totp_attempts_in_redis( &state, &user_token.user_id, user_totp_attempts + 1, ) .await .inspect_err(|error| logger::error!(?error)); return Err(UserErrors::InvalidTotp.into()); } tfa_utils::insert_totp_in_redis(&state, &user_token.user_id).await?; Ok(ApplicationResponse::StatusOk) }
crates/router/src/core/user.rs
router
function_signature
391
rust
null
null
null
null
verify_totp
null
null
null
null
null
null
null
File: crates/router/src/core/fraud_check/flows/transaction_flow.rs Public functions: 1 use async_trait::async_trait; use common_utils::ext_traits::ValueExt; use error_stack::ResultExt; use crate::{ core::{ errors::{ConnectorErrorExt, RouterResult}, fraud_check::{FeatureFrm, FrmData}, payments::{self, flows::ConstructFlowSpecificData, helpers}, }, errors, services, types::{ api::fraud_check as frm_api, domain, fraud_check::{ FraudCheckResponseData, FraudCheckTransactionData, FrmTransactionRouterData, }, storage::enums as storage_enums, ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData, }, SessionState, }; #[async_trait] impl ConstructFlowSpecificData< frm_api::Transaction, FraudCheckTransactionData, FraudCheckResponseData, > for FrmData { #[cfg(feature = "v2")] async fn construct_router_data<'a>( &self, _state: &SessionState, _connector_id: &str, _merchant_context: &domain::MerchantContext, _customer: &Option<domain::Customer>, _merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails, _merchant_recipient_data: Option<MerchantRecipientData>, _header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult< RouterData<frm_api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>, > { todo!() } #[cfg(feature = "v1")] async fn construct_router_data<'a>( &self, state: &SessionState, connector_id: &str, merchant_context: &domain::MerchantContext, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, _merchant_recipient_data: Option<MerchantRecipientData>, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult< RouterData<frm_api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>, > { let status = storage_enums::AttemptStatus::Pending; let auth_type: ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: "ConnectorAuthType".to_string(), })?; let customer_id = customer.to_owned().map(|customer| customer.customer_id); let payment_method = self.payment_attempt.payment_method; let currency = self.payment_attempt.currency; let router_data = RouterData { flow: std::marker::PhantomData, merchant_id: merchant_context.get_merchant_account().get_id().clone(), tenant_id: state.tenant.tenant_id.clone(), customer_id, connector: connector_id.to_string(), payment_id: self.payment_intent.payment_id.get_string_repr().to_owned(), attempt_id: self.payment_attempt.attempt_id.clone(), status, payment_method: self .payment_attempt .payment_method .ok_or(errors::ApiErrorResponse::PaymentMethodNotFound)?, connector_auth_type: auth_type, description: None, address: self.address.clone(), auth_type: storage_enums::AuthenticationType::NoThreeDs, connector_meta_data: None, connector_wallets_details: None, amount_captured: None, minor_amount_captured: None, request: FraudCheckTransactionData { amount: self .payment_attempt .net_amount .get_total_amount() .get_amount_as_i64(), order_details: self.order_details.clone(), currency, payment_method, error_code: self.payment_attempt.error_code.clone(), error_message: self.payment_attempt.error_message.clone(), connector_transaction_id: self .payment_attempt .get_connector_payment_id() .map(ToString::to_string), connector: self.payment_attempt.connector.clone(), }, // self.order_details response: Ok(FraudCheckResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId("".to_string()), connector_metadata: None, status: storage_enums::FraudCheckStatus::Pending, score: None, reason: None, }), access_token: None, session_token: None, reference_id: None, payment_method_token: None, connector_customer: None, preprocessing_id: None, connector_request_reference_id: uuid::Uuid::new_v4().to_string(), test_mode: None, recurring_mandate_payment_data: None, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, payment_method_balance: None, connector_http_status_code: None, external_latency: None, connector_api_version: None, payment_method_status: None, apple_pay_flow: None, frm_metadata: self.frm_metadata.clone(), refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, }; Ok(router_data) } } #[async_trait] impl FeatureFrm<frm_api::Transaction, FraudCheckTransactionData> for FrmTransactionRouterData { async fn decide_frm_flows<'a>( mut self, state: &SessionState, connector: &frm_api::FraudCheckConnectorData, call_connector_action: payments::CallConnectorAction, merchant_context: &domain::MerchantContext, ) -> RouterResult<Self> { decide_frm_flow( &mut self, state, connector, call_connector_action, merchant_context, ) .await } } pub async fn decide_frm_flow( router_data: &mut FrmTransactionRouterData, state: &SessionState, connector: &frm_api::FraudCheckConnectorData, call_connector_action: payments::CallConnectorAction, _merchant_context: &domain::MerchantContext, ) -> RouterResult<FrmTransactionRouterData> { let connector_integration: services::BoxedFrmConnectorIntegrationInterface< frm_api::Transaction, FraudCheckTransactionData, FraudCheckResponseData, > = connector.connector.get_connector_integration(); let resp = services::execute_connector_processing_step( state, connector_integration, router_data, call_connector_action, None, None, ) .await .to_payment_failed_response()?; Ok(resp) }
crates/router/src/core/fraud_check/flows/transaction_flow.rs
router
full_file
1,492
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct FailedTransactionData { id: String, payment_details: Vec<DeclinedPaymentDetails>, }
crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs
hyperswitch_connectors
struct_definition
23
rust
FailedTransactionData
null
null
null
null
null
null
null
null
null
null
null
File: crates/diesel_models/src/cards_info.rs Public structs: 2 use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::cards_info}; #[derive( Clone, Debug, Queryable, Identifiable, Selectable, serde::Deserialize, serde::Serialize, Insertable, )] #[diesel(table_name = cards_info, primary_key(card_iin), check_for_backend(diesel::pg::Pg))] pub struct CardInfo { pub card_iin: String, pub card_issuer: Option<String>, pub card_network: Option<storage_enums::CardNetwork>, pub card_type: Option<String>, pub card_subtype: Option<String>, pub card_issuing_country: Option<String>, pub bank_code_id: Option<String>, pub bank_code: Option<String>, pub country_code: Option<String>, pub date_created: PrimitiveDateTime, pub last_updated: Option<PrimitiveDateTime>, pub last_updated_provider: Option<String>, } #[derive( Clone, Debug, PartialEq, Eq, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize, )] #[diesel(table_name = cards_info)] pub struct UpdateCardInfo { pub card_issuer: Option<String>, pub card_network: Option<storage_enums::CardNetwork>, pub card_type: Option<String>, pub card_subtype: Option<String>, pub card_issuing_country: Option<String>, pub bank_code_id: Option<String>, pub bank_code: Option<String>, pub country_code: Option<String>, pub last_updated: Option<PrimitiveDateTime>, pub last_updated_provider: Option<String>, }
crates/diesel_models/src/cards_info.rs
diesel_models
full_file
372
null
null
null
null
null
null
null
null
null
null
null
null
null
pub async fn get_metrics( pool: &AnalyticsProvider, auth: &AuthInfo, req: GetAuthEventMetricRequest, ) -> AnalyticsResult<AuthEventMetricsResponse<MetricsBucketResponse>> { let mut metrics_accumulator: HashMap< AuthEventMetricsBucketIdentifier, AuthEventMetricsAccumulator, > = HashMap::new(); let mut set = tokio::task::JoinSet::new(); for metric_type in req.metrics.iter().cloned() { let req = req.clone(); let auth_scoped = auth.to_owned(); let pool = pool.clone(); set.spawn(async move { let data = pool .get_auth_event_metrics( &metric_type, &req.group_by_names.clone(), &auth_scoped, &req.filters, req.time_series.map(|t| t.granularity), &req.time_range, ) .await .change_context(AnalyticsError::UnknownError); (metric_type, data) }); } while let Some((metric, data)) = set .join_next() .await .transpose() .change_context(AnalyticsError::UnknownError)? { for (id, value) in data? { let metrics_builder = metrics_accumulator.entry(id).or_default(); match metric { AuthEventMetrics::AuthenticationCount => metrics_builder .authentication_count .add_metrics_bucket(&value), AuthEventMetrics::AuthenticationAttemptCount => metrics_builder .authentication_attempt_count .add_metrics_bucket(&value), AuthEventMetrics::AuthenticationSuccessCount => metrics_builder .authentication_success_count .add_metrics_bucket(&value), AuthEventMetrics::ChallengeFlowCount => metrics_builder .challenge_flow_count .add_metrics_bucket(&value), AuthEventMetrics::ChallengeAttemptCount => metrics_builder .challenge_attempt_count .add_metrics_bucket(&value), AuthEventMetrics::ChallengeSuccessCount => metrics_builder .challenge_success_count .add_metrics_bucket(&value), AuthEventMetrics::FrictionlessFlowCount => metrics_builder .frictionless_flow_count .add_metrics_bucket(&value), AuthEventMetrics::FrictionlessSuccessCount => metrics_builder .frictionless_success_count .add_metrics_bucket(&value), AuthEventMetrics::AuthenticationErrorMessage => metrics_builder .authentication_error_message .add_metrics_bucket(&value), AuthEventMetrics::AuthenticationFunnel => metrics_builder .authentication_funnel .add_metrics_bucket(&value), AuthEventMetrics::AuthenticationExemptionApprovedCount => metrics_builder .authentication_exemption_approved_count .add_metrics_bucket(&value), AuthEventMetrics::AuthenticationExemptionRequestedCount => metrics_builder .authentication_exemption_requested_count .add_metrics_bucket(&value), } } } let mut total_error_message_count = 0; let query_data: Vec<MetricsBucketResponse> = metrics_accumulator .into_iter() .map(|(id, val)| { let collected_values = val.collect(); if let Some(count) = collected_values.error_message_count { total_error_message_count += count; } MetricsBucketResponse { values: collected_values, dimensions: id, } }) .collect(); Ok(AuthEventMetricsResponse { query_data, meta_data: [AuthEventsAnalyticsMetadata { total_error_message_count: Some(total_error_message_count), }], }) }
crates/analytics/src/auth_events/core.rs
analytics
function_signature
750
rust
null
null
null
null
get_metrics
null
null
null
null
null
null
null
pub fn validate_and_get_payment_method_records(self) -> MigrationValidationResult { // Step 1: Validate form-level conflicts let form_has_single_id = self.merchant_connector_id.is_some(); let form_has_multiple_ids = self.merchant_connector_ids.is_some(); if form_has_single_id && form_has_multiple_ids { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Both merchant_connector_id and merchant_connector_ids cannot be provided" .to_string(), }); } // Ensure at least one is provided if !form_has_single_id && !form_has_multiple_ids { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Either merchant_connector_id or merchant_connector_ids must be provided" .to_string(), }); } // Step 2: Parse CSV let records = parse_csv(self.file.data.to_bytes()).map_err(|e| { errors::ApiErrorResponse::PreconditionFailed { message: e.to_string(), } })?; // Step 3: Validate CSV vs Form conflicts MerchantConnectorValidator::validate_form_csv_conflicts( &records, form_has_single_id, form_has_multiple_ids, )?; // Step 4: Prepare the merchant connector account IDs for return let mca_ids = if let Some(ref single_id) = self.merchant_connector_id { Some(vec![(**single_id).clone()]) } else if let Some(ref ids_string) = self.merchant_connector_ids { let parsed_ids = MerchantConnectorValidator::parse_comma_separated_ids(ids_string)?; if parsed_ids.is_empty() { None } else { Some(parsed_ids) } } else { None }; // Step 5: Return the updated structure Ok((self.merchant_id.clone(), records, mca_ids)) }
crates/payment_methods/src/core/migration.rs
payment_methods
function_signature
396
rust
null
null
null
null
validate_and_get_payment_method_records
null
null
null
null
null
null
null
pub struct PayoutRetrieveBody { pub force_sync: Option<bool>, #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, }
crates/api_models/src/payouts.rs
api_models
struct_definition
39
rust
PayoutRetrieveBody
null
null
null
null
null
null
null
null
null
null
null
pub struct RefundMetricsBucketValue { pub successful_refunds: Option<u32>, pub total_refunds: Option<u32>, pub refund_success_rate: Option<f64>, pub refund_count: Option<u64>, pub refund_success_count: Option<u64>, pub refund_processed_amount: Option<u64>, pub refund_processed_amount_in_usd: Option<u64>, pub refund_processed_count: Option<u64>, pub refund_reason_distribution: Option<Vec<ReasonsResult>>, pub refund_error_message_distribution: Option<Vec<ErrorMessagesResult>>, pub refund_reason_count: Option<u64>, pub refund_error_message_count: Option<u64>, }
crates/api_models/src/analytics/refunds.rs
api_models
struct_definition
149
rust
RefundMetricsBucketValue
null
null
null
null
null
null
null
null
null
null
null
impl<Flow, ResourceCommonData, FlowSpecificRequest, FlowSpecificResponse> Deref for RouterDataV2<Flow, ResourceCommonData, FlowSpecificRequest, FlowSpecificResponse> { type Target = ResourceCommonData; fn deref(&self) -> &Self::Target { &self.resource_common_data } }
crates/hyperswitch_domain_models/src/router_data_v2.rs
hyperswitch_domain_models
impl_block
72
rust
null
RouterDataV2
Deref for
impl Deref for for RouterDataV2
null
null
null
null
null
null
null
null
impl NuveiPaymentsResponse { /// returns amount_captured and minor_amount_capturable pub fn get_amount_captured( &self, ) -> Result<(Option<i64>, Option<MinorUnit>), error_stack::Report<errors::ConnectorError>> { match &self.partial_approval { Some(partial_approval) => { let amount = utils::convert_back_amount_to_minor_units( NUVEI_AMOUNT_CONVERTOR, partial_approval.processed_amount.clone(), partial_approval.processed_currency, )?; match self.transaction_type { None => Ok((None, None)), Some(NuveiTransactionType::Sale) => { Ok((Some(MinorUnit::get_amount_as_i64(amount)), None)) } Some(NuveiTransactionType::Auth) => Ok((None, Some(amount))), Some(NuveiTransactionType::Auth3D) => { Ok((Some(MinorUnit::get_amount_as_i64(amount)), None)) } Some(NuveiTransactionType::InitAuth3D) => Ok((None, Some(amount))), Some(NuveiTransactionType::Credit) => Ok((None, None)), Some(NuveiTransactionType::Void) => Ok((None, None)), Some(NuveiTransactionType::Settle) => Ok((None, None)), } } None => Ok((None, None)), } } }
crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
hyperswitch_connectors
impl_block
305
rust
null
NuveiPaymentsResponse
null
impl NuveiPaymentsResponse
null
null
null
null
null
null
null
null
File: crates/hyperswitch_connectors/src/connectors/santander.rs Public functions: 1 Public structs: 1 pub mod transformers; use std::sync::LazyLock; use base64::Engine; use common_enums::enums; use common_utils::{ crypto, errors::CustomResult, ext_traits::{ByteSliceExt, BytesExt}, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ router_data::{AccessToken, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, consts::NO_ERROR_MESSAGE, errors, events::connector_api_logs::ConnectorEvent, types::{self, RefreshTokenType, Response}, webhooks, }; use masking::{Mask, Maskable, PeekInterface, Secret}; use transformers as santander; use crate::{ constants::headers, types::{RefreshTokenRouterData, ResponseRouterData}, utils::{self as connector_utils, convert_amount, RefundsRequestData}, }; #[derive(Clone)] pub struct Santander { amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), } impl Santander { pub fn new() -> &'static Self { &Self { amount_converter: &StringMajorUnitForConnector, } } } pub mod santander_constants { pub const SANTANDER_VERSION: &str = "v2"; } impl api::Payment for Santander {} impl api::PaymentSession for Santander {} impl api::ConnectorAccessToken for Santander {} impl api::MandateSetup for Santander {} impl api::PaymentAuthorize for Santander {} impl api::PaymentSync for Santander {} impl api::PaymentCapture for Santander {} impl api::PaymentVoid for Santander {} impl api::Refund for Santander {} impl api::RefundExecute for Santander {} impl api::RefundSync for Santander {} impl api::PaymentToken for Santander {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Santander { // Not Implemented (R) } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Santander where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Santander { fn id(&self) -> &'static str { "santander" } 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.santander.base_url.as_ref() } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: santander::SantanderErrorResponse = res .response .parse_struct("SantanderErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); match response { santander::SantanderErrorResponse::PixQrCode(response) => { let message = response .detail .as_ref() .cloned() .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()); Ok(ErrorResponse { status_code: res.status_code, code: response.status.to_string(), message, reason: response.detail.clone(), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } santander::SantanderErrorResponse::Boleto(response) => Ok(ErrorResponse { status_code: res.status_code, code: response.error_code.to_string(), message: response.error_message.clone(), reason: Some( response .errors .as_ref() .and_then(|v| v.first()) .map(|e| e.message.clone()) .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), ), 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 Santander { //TODO: implement functions when support enabled } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Santander { //TODO: implement sessions flow } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Santander { fn get_headers( &self, req: &RefreshTokenRouterData, _connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let client_id = req.request.app_id.clone(); let client_secret = req.request.id.clone(); let creds = format!( "{}:{}", client_id.peek(), client_secret.unwrap_or_default().peek() ); let encoded_creds = common_utils::consts::BASE64_ENGINE.encode(creds); let auth_string = format!("Basic {encoded_creds}"); Ok(vec![ ( headers::CONTENT_TYPE.to_string(), RefreshTokenType::get_content_type(self).to_string().into(), ), ( headers::AUTHORIZATION.to_string(), auth_string.into_masked(), ), ]) } fn get_content_type(&self) -> &'static str { "application/x-www-form-urlencoded" } fn get_url( &self, _req: &RefreshTokenRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}/oauth/token?grant_type=client_credentials", connectors.santander.base_url )) } fn build_request( &self, req: &RefreshTokenRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let req = Some( RequestBuilder::new() .method(Method::Post) .attach_default_headers() .headers(RefreshTokenType::get_headers(self, req, connectors)?) .url(&RefreshTokenType::get_url(self, req, connectors)?) .build(), ); Ok(req) } fn handle_response( &self, data: &RefreshTokenRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> { let response: santander::SantanderAuthUpdateResponse = res .response .parse_struct("santander SantanderAuthUpdateResponse") .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, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } } impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Santander { fn build_request( &self, _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Santander".to_string()) .into(), ) } } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Santander { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let santander_mca_metadata = santander::SantanderMetadataObject::try_from(&req.connector_meta_data)?; match req.payment_method { enums::PaymentMethod::BankTransfer => match req.request.payment_method_type { Some(enums::PaymentMethodType::Pix) => Ok(format!( "{}cob/{}", self.base_url(connectors), req.payment_id )), _ => Err(errors::ConnectorError::NotSupported { message: req.payment_method.to_string(), connector: "Santander", } .into()), }, enums::PaymentMethod::Voucher => match req.request.payment_method_type { Some(enums::PaymentMethodType::Boleto) => Ok(format!( "{:?}{}/workspaces/{}/bank_slips", connectors.santander.secondary_base_url.clone(), santander_constants::SANTANDER_VERSION, santander_mca_metadata.workspace_id )), _ => Err(errors::ConnectorError::NotSupported { message: req.payment_method.to_string(), connector: "Santander", } .into()), }, _ => Err(errors::ConnectorError::NotSupported { message: req.payment_method.to_string(), connector: "Santander", } .into()), } } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = santander::SantanderRouterData::from((amount, req)); let connector_req = santander::SantanderPaymentRequest::try_from(&connector_router_data)?; 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::Put) .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: santander::SantanderPaymentsResponse = res .response .parse_struct("Santander PaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let original_amount = match response { santander::SantanderPaymentsResponse::PixQRCode(ref pix_data) => { pix_data.value.original.clone() } santander::SantanderPaymentsResponse::Boleto(_) => { convert_amount( self.amount_converter, MinorUnit::new(data.request.amount), data.request.currency, )? // no amount field in the boleto response } }; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let response_integrity_object = connector_utils::get_authorise_integrity_object( self.amount_converter, original_amount, enums::Currency::BRL.to_string(), )?; let new_router_data = RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }); new_router_data .change_context(errors::ConnectorError::ResponseHandlingFailed) .map(|mut router_data| { router_data.request.integrity_object = Some(response_integrity_object); router_data }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Santander { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, 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: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { match req.request.payment_method_type { Some(enums::PaymentMethodType::Pix) => { let connector_payment_id = req .request .connector_transaction_id .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; Ok(format!( "{}{}{}", self.base_url(connectors), "cob/", connector_payment_id )) } Some(enums::PaymentMethodType::Boleto) => { let bill_id = req .request .connector_meta .clone() .and_then(|val| val.as_str().map(|s| s.to_string())) .ok_or_else(|| errors::ConnectorError::MissingRequiredField { field_name: "bill_id", })?; Ok(format!( "{:?}/{}/bills/{}/bank_slips", connectors.santander.secondary_base_url.clone(), santander_constants::SANTANDER_VERSION, bill_id )) } _ => Err(errors::ConnectorError::MissingRequiredField { field_name: "payment_method_type", } .into()), } } fn get_request_body( &self, req: &PaymentsSyncRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.amount, req.request.currency, )?; let connector_router_data = santander::SantanderRouterData::from((amount, req)); let connector_req = santander::SantanderPSyncBoletoRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { match req.request.payment_method_type { Some(enums::PaymentMethodType::Pix) => 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(), )), Some(enums::PaymentMethodType::Boleto) => Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .set_body(types::PaymentsSyncType::get_request_body( self, req, connectors, )?) .build(), )), _ => Err(errors::ConnectorError::MissingRequiredField { field_name: "payment_method_type", } .into()), } } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: santander::SantanderPaymentsSyncResponse = res .response .parse_struct("santander SantanderPaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let original_amount = match response { santander::SantanderPaymentsSyncResponse::PixQRCode(ref pix_data) => { pix_data.base.value.original.clone() } santander::SantanderPaymentsSyncResponse::Boleto(_) => convert_amount( self.amount_converter, data.request.amount, data.request.currency, )?, }; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let response_integrity_object = connector_utils::get_sync_integrity_object( self.amount_converter, original_amount, enums::Currency::BRL.to_string(), )?; let new_router_data = RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }); new_router_data .change_context(errors::ConnectorError::ResponseHandlingFailed) .map(|mut router_data| { router_data.request.integrity_object = Some(response_integrity_object); router_data }) } 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 Santander { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Capture".to_string(), connector: "Santander".to_string(), } .into()) } fn get_request_body( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Capture".to_string(), connector: "Santander".to_string(), } .into()) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: santander::SantanderPaymentsResponse = res .response .parse_struct("Santander PaymentsCaptureResponse") .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<Void, PaymentsCancelData, PaymentsResponseData> for Santander { fn get_headers( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, 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: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { match req.payment_method { enums::PaymentMethod::BankTransfer => { let connector_payment_id = req.request.connector_transaction_id.clone(); Ok(format!( "{}cob/{}", self.base_url(connectors), connector_payment_id )) } _ => Err(errors::ConnectorError::NotSupported { message: req.payment_method.to_string(), connector: "Santander", } .into()), } } fn get_request_body( &self, req: &PaymentsCancelRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = santander::SantanderPaymentsCancelRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Patch) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) .set_body(types::PaymentsVoidType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { let response: santander::SantanderPixVoidResponse = res .response .parse_struct("Santander PaymentsResponse") .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<Execute, RefundsData, RefundsResponseData> for Santander { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, 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> { match req.payment_method { enums::PaymentMethod::BankTransfer => { let end_to_end_id = req .request .connector_metadata .as_ref() .and_then(|metadata| metadata.get("end_to_end_id")) .and_then(|val| val.as_str().map(|id| id.to_string())) .ok_or_else(|| errors::ConnectorError::MissingRequiredField { field_name: "end_to_end_id", })?; let refund_id = req.request.connector_refund_id.clone(); Ok(format!( "{}{}{}{}{:?}", self.base_url(connectors), "pix/", end_to_end_id, "/refund/", refund_id )) } _ => Err(errors::ConnectorError::NotSupported { message: req.payment_method.to_string(), connector: "Santander", } .into()), } } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let refund_amount = convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = santander::SantanderRouterData::from((refund_amount, req)); let connector_req = santander::SantanderRefundRequest::try_from(&connector_router_data)?; 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::Put) .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: santander::SantanderRefundResponse = res .response .parse_struct("santander RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let original_amount = response.value.clone(); event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let response_integrity_object = connector_utils::get_refund_integrity_object( self.amount_converter, original_amount, enums::Currency::BRL.to_string(), )?; let new_router_data = RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }); new_router_data .change_context(errors::ConnectorError::ResponseHandlingFailed) .map(|mut router_data| { router_data.request.integrity_object = Some(response_integrity_object); router_data }) } 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 Santander { fn get_headers( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, 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_metadata = req.request.connector_metadata.clone(); let end_to_end_id = match &connector_metadata { Some(metadata) => match metadata.get("end_to_end_id") { Some(val) => val.as_str().map(|id| id.to_string()), None => None, }, None => None, } .ok_or_else(|| errors::ConnectorError::MissingRequiredField { field_name: "end_to_end_id", })?; Ok(format!( "{}{}{}{}{}", self.base_url(connectors), "pix/", end_to_end_id, "/return/", req.request.get_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)?) .set_body(types::RefundSyncType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: santander::SantanderRefundResponse = res .response .parse_struct("santander RefundSyncResponse") .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) } } fn get_webhook_object_from_body( body: &[u8], ) -> CustomResult<santander::SantanderWebhookBody, common_utils::errors::ParsingError> { let webhook: santander::SantanderWebhookBody = body.parse_struct("SantanderIncomingWebhook")?; Ok(webhook) } #[async_trait::async_trait] impl webhooks::IncomingWebhook for Santander { async fn verify_webhook_source( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, _connector_name: &str, ) -> CustomResult<bool, errors::ConnectorError> { Ok(true) // Hardcoded to true as the source verification algorithm for Santander remains to be unknown (in docs it is mentioned as MTLS) } fn get_webhook_object_reference_id( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let webhook_body = transformers::get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; Ok(api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId( webhook_body.participant_code, ), )) } fn get_webhook_event_type( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { let body = get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; Ok(transformers::get_santander_webhook_event(body.function)) } fn get_webhook_resource_object( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let webhook_body = transformers::get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; Ok(Box::new(webhook_body)) } } static SANTANDER_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { let supported_capture_methods = vec![enums::CaptureMethod::Automatic]; let mut santander_supported_payment_methods = SupportedPaymentMethods::new(); santander_supported_payment_methods.add( enums::PaymentMethod::BankTransfer, enums::PaymentMethodType::Pix, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); santander_supported_payment_methods.add( enums::PaymentMethod::Voucher, enums::PaymentMethodType::Boleto, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::NotSupported, supported_capture_methods, specific_features: None, }, ); santander_supported_payment_methods }); static SANTANDER_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Santander", description: "Santander is a leading private bank in Brazil, offering a wide range of financial services across retail and corporate segments. It is part of the global Santander Group, one of Europe’s largest financial institutions.", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Alpha, }; static SANTANDER_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] = [enums::EventClass::Payments, enums::EventClass::Refunds]; impl ConnectorSpecifications for Santander { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&SANTANDER_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*SANTANDER_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&SANTANDER_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/santander.rs
hyperswitch_connectors
full_file
8,002
null
null
null
null
null
null
null
null
null
null
null
null
null
File: crates/router/src/services/kafka/fraud_check_event.rs Public functions: 1 Public structs: 1 use diesel_models::{ enums as storage_enums, enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType}, fraud_check::FraudCheck, }; use time::OffsetDateTime; #[derive(serde::Serialize, Debug)] pub struct KafkaFraudCheckEvent<'a> { pub frm_id: &'a String, pub payment_id: &'a common_utils::id_type::PaymentId, pub merchant_id: &'a common_utils::id_type::MerchantId, pub attempt_id: &'a String, #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, pub frm_name: &'a String, pub frm_transaction_id: Option<&'a String>, pub frm_transaction_type: FraudCheckType, pub frm_status: FraudCheckStatus, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<&'a String>, pub payment_details: Option<serde_json::Value>, pub metadata: Option<serde_json::Value>, #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, pub last_step: FraudCheckLastStep, pub payment_capture_method: Option<storage_enums::CaptureMethod>, // In postFrm, we are updating capture method from automatic to manual. To store the merchant actual capture method, we are storing the actual capture method in payment_capture_method. It will be useful while approving the FRM decision. } impl<'a> KafkaFraudCheckEvent<'a> { pub fn from_storage(check: &'a FraudCheck) -> Self { Self { frm_id: &check.frm_id, payment_id: &check.payment_id, merchant_id: &check.merchant_id, attempt_id: &check.attempt_id, created_at: check.created_at.assume_utc(), frm_name: &check.frm_name, frm_transaction_id: check.frm_transaction_id.as_ref(), frm_transaction_type: check.frm_transaction_type, frm_status: check.frm_status, frm_score: check.frm_score, frm_reason: check.frm_reason.clone(), frm_error: check.frm_error.as_ref(), payment_details: check.payment_details.clone(), metadata: check.metadata.clone(), modified_at: check.modified_at.assume_utc(), last_step: check.last_step, payment_capture_method: check.payment_capture_method, } } } impl super::KafkaMessage for KafkaFraudCheckEvent<'_> { fn key(&self) -> String { format!( "{}_{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id, self.frm_id ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::FraudCheck } }
crates/router/src/services/kafka/fraud_check_event.rs
router
full_file
653
null
null
null
null
null
null
null
null
null
null
null
null
null
impl super::behaviour::Conversion for Relay { type DstType = diesel_models::relay::Relay; type NewDstType = diesel_models::relay::RelayNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::relay::Relay { id: self.id, connector_resource_id: self.connector_resource_id, connector_id: self.connector_id, profile_id: self.profile_id, merchant_id: self.merchant_id, relay_type: self.relay_type, request_data: self .request_data .map(|data| { serde_json::to_value(data).change_context(ValidationError::InvalidValue { message: "Failed while decrypting business profile data".to_string(), }) }) .transpose()? .map(Secret::new), status: self.status, connector_reference_id: self.connector_reference_id, error_code: self.error_code, error_message: self.error_message, created_at: self.created_at, modified_at: self.modified_at, response_data: self.response_data, }) } async fn convert_back( _state: &keymanager::KeyManagerState, item: Self::DstType, _key: &Secret<Vec<u8>>, _key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> { Ok(Self { id: item.id, connector_resource_id: item.connector_resource_id, connector_id: item.connector_id, profile_id: item.profile_id, merchant_id: item.merchant_id, relay_type: enums::RelayType::Refund, request_data: item .request_data .map(|data| { serde_json::from_value(data.expose()).change_context( ValidationError::InvalidValue { message: "Failed while decrypting business profile data".to_string(), }, ) }) .transpose()?, status: item.status, connector_reference_id: item.connector_reference_id, error_code: item.error_code, error_message: item.error_message, created_at: item.created_at, modified_at: item.modified_at, response_data: item.response_data, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(diesel_models::relay::RelayNew { id: self.id, connector_resource_id: self.connector_resource_id, connector_id: self.connector_id, profile_id: self.profile_id, merchant_id: self.merchant_id, relay_type: self.relay_type, request_data: self .request_data .map(|data| { serde_json::to_value(data).change_context(ValidationError::InvalidValue { message: "Failed while decrypting business profile data".to_string(), }) }) .transpose()? .map(Secret::new), status: self.status, connector_reference_id: self.connector_reference_id, error_code: self.error_code, error_message: self.error_message, created_at: self.created_at, modified_at: self.modified_at, response_data: self.response_data, }) } }
crates/hyperswitch_domain_models/src/relay.rs
hyperswitch_domain_models
impl_block
689
rust
null
Relay
super::behaviour::Conversion for
impl super::behaviour::Conversion for for Relay
null
null
null
null
null
null
null
null
pub struct RefundResponse { status: HelcimPaymentStatus, transaction_id: u64, #[serde(rename = "type")] transaction_type: HelcimRefundTransactionType, }
crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs
hyperswitch_connectors
struct_definition
44
rust
RefundResponse
null
null
null
null
null
null
null
null
null
null
null
impl api::PaymentIncrementalAuthorization for Wellsfargo {}
crates/hyperswitch_connectors/src/connectors/wellsfargo.rs
hyperswitch_connectors
impl_block
12
rust
null
Wellsfargo
api::PaymentIncrementalAuthorization for
impl api::PaymentIncrementalAuthorization for for Wellsfargo
null
null
null
null
null
null
null
null
pub struct WeChatPayRedirection {}
crates/hyperswitch_domain_models/src/payment_method_data.rs
hyperswitch_domain_models
struct_definition
8
rust
WeChatPayRedirection
null
null
null
null
null
null
null
null
null
null
null
pub fn server(state: AppState) -> Scope { web::scope("/relay") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(relay::relay))) .service(web::resource("/{relay_id}").route(web::get().to(relay::relay_retrieve))) }
crates/router/src/routes/app.rs
router
function_signature
72
rust
null
null
null
null
server
null
null
null
null
null
null
null
pub async fn list_by_merchant_id( conn: &PgPooledConn, merchant_id: &id_type::MerchantId, constraints: CustomerListConstraints, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()), Some(constraints.limit), constraints.offset, Some(dsl::created_at), ) .await }
crates/diesel_models/src/query/customers.rs
diesel_models
function_signature
105
rust
null
null
null
null
list_by_merchant_id
null
null
null
null
null
null
null
impl SchedulerInterface for MockDb {}
crates/scheduler/src/scheduler.rs
scheduler
impl_block
7
rust
null
MockDb
SchedulerInterface for
impl SchedulerInterface for for MockDb
null
null
null
null
null
null
null
null
File: crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs use std::collections::HashSet; use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::RefundMetricRow; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(crate) struct RefundCount {} #[async_trait::async_trait] impl<T> super::RefundMetric<T> for RefundCount where T: AnalyticsDataSource + super::RefundMetricAnalytics, 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: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::RefundSessionized); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(Aggregate::Count { field: None, alias: Some("count"), }) .switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; auth.set_filter_clause(&mut query_builder).switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; for dim in dimensions.iter() { query_builder .add_group_by_clause(dim) .attach_printable("Error grouping by dimensions") .switch()?; } if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } query_builder .execute_query::<RefundMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( RefundMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), i.refund_status.as_ref().map(|i| i.0.to_string()), i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), i.refund_reason.clone(), i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs
analytics
full_file
871
null
null
null
null
null
null
null
null
null
null
null
null
null
pub async fn insert_totp_in_redis(state: &SessionState, user_id: &str) -> UserResult<()> { let redis_conn = super::get_redis_connection_for_global_tenant(state)?; let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id); redis_conn .set_key_with_expiry( &key.as_str().into(), common_utils::date_time::now_unix_timestamp(), state.conf.user.two_factor_auth_expiry_in_secs, ) .await .change_context(UserErrors::InternalServerError) }
crates/router/src/utils/user/two_factor_auth.rs
router
function_signature
118
rust
null
null
null
null
insert_totp_in_redis
null
null
null
null
null
null
null
impl SerializableSecret for i64 {}
crates/masking/src/serde.rs
masking
impl_block
8
rust
null
i64
SerializableSecret for
impl SerializableSecret for for i64
null
null
null
null
null
null
null
null
pub struct BokuErrorResponse { pub status_code: u16, pub code: String, pub message: String, pub reason: Option<String>, }
crates/hyperswitch_connectors/src/connectors/boku/transformers.rs
hyperswitch_connectors
struct_definition
35
rust
BokuErrorResponse
null
null
null
null
null
null
null
null
null
null
null
pub fn get_trans_id( details: &AuthorizedotnetWebhookObjectId, ) -> Result<String, errors::ConnectorError> { details .payload .id .clone() .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound) }
crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
hyperswitch_connectors
function_signature
59
rust
null
null
null
null
get_trans_id
null
null
null
null
null
null
null
pub async fn create_and_insert_business_profile( state: &SessionState, request: api::ProfileCreate, merchant_account: domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<domain::Profile> { let business_profile_new = admin::create_profile_from_merchant_account(state, merchant_account, request, key_store) .await?; let profile_name = business_profile_new.profile_name.clone(); state .store .insert_business_profile(&state.into(), key_store, business_profile_new) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: format!( "Business Profile with the profile_name {profile_name} already exists" ), }) .attach_printable("Failed to insert Business profile because of duplication error") }
crates/router/src/core/admin.rs
router
function_signature
177
rust
null
null
null
null
create_and_insert_business_profile
null
null
null
null
null
null
null
pub fn get_vault_response_for_delete_payment_method_data<F>( router_data: VaultRouterData<F>, customer_id: id_type::GlobalCustomerId, ) -> RouterResult<pm_types::VaultDeleteResponse> { match router_data.response { Ok(response) => match response { types::VaultResponseData::ExternalVaultDeleteResponse { connector_vault_id } => { Ok(pm_types::VaultDeleteResponse { vault_id: domain::VaultId::generate(connector_vault_id), // converted to VaultId type entity_id: customer_id, }) } types::VaultResponseData::ExternalVaultInsertResponse { .. } | types::VaultResponseData::ExternalVaultRetrieveResponse { .. } | types::VaultResponseData::ExternalVaultCreateResponse { .. } => { Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid Vault Response")) } }, Err(err) => Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve payment method")), } }
crates/router/src/core/payment_methods/vault.rs
router
function_signature
222
rust
null
null
null
null
get_vault_response_for_delete_payment_method_data
null
null
null
null
null
null
null
pub struct ProfileNew { pub profile_id: common_utils::id_type::ProfileId, pub merchant_id: common_utils::id_type::MerchantId, pub profile_name: String, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub return_url: Option<String>, pub enable_payment_response_hash: bool, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: bool, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub intent_fulfillment_time: Option<i64>, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub is_recon_enabled: bool, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub payment_link_config: Option<BusinessPaymentLinkConfig>, pub session_expiry: Option<i64>, pub authentication_connector_details: Option<AuthenticationConnectorDetails>, pub payout_link_config: Option<BusinessPayoutLinkConfig>, pub is_extended_card_info_enabled: Option<bool>, pub extended_card_info_config: Option<pii::SecretSerdeValue>, pub is_connector_agnostic_mit_enabled: Option<bool>, pub use_billing_as_payment_method_billing: Option<bool>, pub collect_shipping_details_from_wallet_connector: Option<bool>, pub collect_billing_details_from_wallet_connector: Option<bool>, pub outgoing_webhook_custom_http_headers: Option<Encryption>, pub always_collect_billing_details_from_wallet_connector: Option<bool>, pub always_collect_shipping_details_from_wallet_connector: Option<bool>, pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_tax_connector_enabled: Option<bool>, pub version: common_enums::ApiVersion, pub is_network_tokenization_enabled: bool, pub is_auto_retries_enabled: Option<bool>, pub max_auto_retries_enabled: Option<i16>, pub is_click_to_pay_enabled: bool, pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: Option<Encryption>, pub is_clear_pan_retries_enabled: bool, pub force_3ds_challenge: Option<bool>, pub is_debit_routing_enabled: bool, pub merchant_business_country: Option<common_enums::CountryAlpha2>, pub id: Option<common_utils::id_type::ProfileId>, pub is_iframe_redirection_enabled: Option<bool>, pub is_pre_network_tokenization_enabled: Option<bool>, pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, }
crates/diesel_models/src/business_profile.rs
diesel_models
struct_definition
653
rust
ProfileNew
null
null
null
null
null
null
null
null
null
null
null
pub struct BusinessPaymentLinkConfig { pub domain_name: Option<String>, #[serde(flatten)] pub default_config: Option<PaymentLinkConfigRequest>, pub business_specific_configs: Option<HashMap<String, PaymentLinkConfigRequest>>, pub allowed_domains: Option<HashSet<String>>, pub branding_visibility: Option<bool>, }
crates/diesel_models/src/business_profile.rs
diesel_models
struct_definition
67
rust
BusinessPaymentLinkConfig
null
null
null
null
null
null
null
null
null
null
null
Documentation: api-reference/v1/payouts/payouts--list-filters.mdx # Type: Doc File --- openapi: post /payouts/filter ---
api-reference/v1/payouts/payouts--list-filters.mdx
null
doc_file
37
doc
null
null
null
null
null
null
null
null
null
null
null
null
pub struct KlarnaPaymentsRequest { order_lines: Vec<OrderLines>, order_amount: MinorUnit, purchase_country: enums::CountryAlpha2, purchase_currency: enums::Currency, merchant_reference1: Option<String>, merchant_reference2: Option<String>, shipping_address: Option<KlarnaShippingAddress>, auto_capture: Option<bool>, order_tax_amount: Option<MinorUnit>, #[serde(flatten)] payment_method_specifics: Option<PaymentMethodSpecifics>, }
crates/hyperswitch_connectors/src/connectors/klarna/transformers.rs
hyperswitch_connectors
struct_definition
104
rust
KlarnaPaymentsRequest
null
null
null
null
null
null
null
null
null
null
null
impl api::PaymentSync for Shift4 {}
crates/hyperswitch_connectors/src/connectors/shift4.rs
hyperswitch_connectors
impl_block
9
rust
null
Shift4
api::PaymentSync for
impl api::PaymentSync for for Shift4
null
null
null
null
null
null
null
null
pub struct BankAccountCredentialsOptions { account_ids: Vec<String>, }
crates/pm_auth/src/connector/plaid/transformers.rs
pm_auth
struct_definition
15
rust
BankAccountCredentialsOptions
null
null
null
null
null
null
null
null
null
null
null
pub struct OpayoPaymentsResponse { status: OpayoPaymentStatus, id: String, transaction_id: String, }
crates/hyperswitch_connectors/src/connectors/opayo/transformers.rs
hyperswitch_connectors
struct_definition
27
rust
OpayoPaymentsResponse
null
null
null
null
null
null
null
null
null
null
null
impl ConnectorValidation for Nordea {}
crates/hyperswitch_connectors/src/connectors/nordea.rs
hyperswitch_connectors
impl_block
7
rust
null
Nordea
ConnectorValidation for
impl ConnectorValidation for for Nordea
null
null
null
null
null
null
null
null
pub struct SenderInformation { payment_information: Option<PaymentInformationResponse>, }
crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
hyperswitch_connectors
struct_definition
16
rust
SenderInformation
null
null
null
null
null
null
null
null
null
null
null
pub struct VoltAuthErrorResponse { pub code: u64, pub message: String, }
crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
hyperswitch_connectors
struct_definition
21
rust
VoltAuthErrorResponse
null
null
null
null
null
null
null
null
null
null
null
pub struct SamsungPayTokenizedCard { transaction_type: TransactionType, }
crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
hyperswitch_connectors
struct_definition
16
rust
SamsungPayTokenizedCard
null
null
null
null
null
null
null
null
null
null
null
pub async fn organization_update() {}
crates/openapi/src/routes/organization.rs
openapi
function_signature
7
rust
null
null
null
null
organization_update
null
null
null
null
null
null
null
impl OutgoingWebhookEventMetric for OutgoingWebhookContent { fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent> { match self { Self::PaymentDetails(payment_payload) => Some(OutgoingWebhookEventContent::Payment { payment_id: payment_payload.id.clone(), content: masking::masked_serialize(&payment_payload) .unwrap_or(serde_json::json!({"error":"failed to serialize"})), }), Self::RefundDetails(refund_payload) => Some(OutgoingWebhookEventContent::Refund { payment_id: refund_payload.payment_id.clone(), refund_id: refund_payload.id.clone(), content: masking::masked_serialize(&refund_payload) .unwrap_or(serde_json::json!({"error":"failed to serialize"})), }), Self::DisputeDetails(dispute_payload) => { //TODO: add support for dispute outgoing webhook todo!() } Self::MandateDetails(mandate_payload) => Some(OutgoingWebhookEventContent::Mandate { payment_method_id: mandate_payload.payment_method_id.clone(), mandate_id: mandate_payload.mandate_id.clone(), content: masking::masked_serialize(&mandate_payload) .unwrap_or(serde_json::json!({"error":"failed to serialize"})), }), #[cfg(feature = "payouts")] Self::PayoutDetails(payout_payload) => Some(OutgoingWebhookEventContent::Payout { payout_id: payout_payload.payout_id.clone(), content: masking::masked_serialize(&payout_payload) .unwrap_or(serde_json::json!({"error":"failed to serialize"})), }), } } }
crates/router/src/events/outgoing_webhook_logs.rs
router
impl_block
366
rust
null
OutgoingWebhookContent
OutgoingWebhookEventMetric for
impl OutgoingWebhookEventMetric for for OutgoingWebhookContent
null
null
null
null
null
null
null
null
impl api::PaymentCapture for Cybersource {}
crates/hyperswitch_connectors/src/connectors/cybersource.rs
hyperswitch_connectors
impl_block
10
rust
null
Cybersource
api::PaymentCapture for
impl api::PaymentCapture for for Cybersource
null
null
null
null
null
null
null
null
impl api::RefundExecute for Mollie {}
crates/hyperswitch_connectors/src/connectors/mollie.rs
hyperswitch_connectors
impl_block
11
rust
null
Mollie
api::RefundExecute for
impl api::RefundExecute for for Mollie
null
null
null
null
null
null
null
null
pub struct V2AdminApiAuth;
crates/router/src/services/authentication.rs
router
struct_definition
8
rust
V2AdminApiAuth
null
null
null
null
null
null
null
null
null
null
null
impl api::Payment for Payme {}
crates/hyperswitch_connectors/src/connectors/payme.rs
hyperswitch_connectors
impl_block
8
rust
null
Payme
api::Payment for
impl api::Payment for for Payme
null
null
null
null
null
null
null
null
pub fn set_three_d_s_server_trans_i_d(mut self, three_d_s_server_trans_i_d: String) -> Self { self.three_d_s_server_trans_i_d = Some(three_d_s_server_trans_i_d); self }
crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
hyperswitch_connectors
function_signature
52
rust
null
null
null
null
set_three_d_s_server_trans_i_d
null
null
null
null
null
null
null
pub(crate) fn diesel_enum_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let storage_type = ast.get_metadata()?; match storage_type .first() .ok_or(syn::Error::new( Span::call_site(), "Storage type must be specified", ))? .get_storage_type() { StorageType::Text => diesel_enum_text_derive_inner(ast), StorageType::DbEnum => diesel_enum_db_enum_derive_inner(ast), } }
crates/router_derive/src/macros/diesel.rs
router_derive
function_signature
112
rust
null
null
null
null
diesel_enum_derive_inner
null
null
null
null
null
null
null
impl Capturable for PaymentsTaxCalculationData {}
crates/router/src/types.rs
router
impl_block
10
rust
null
PaymentsTaxCalculationData
Capturable for
impl Capturable for for PaymentsTaxCalculationData
null
null
null
null
null
null
null
null
impl ConnectorValidation for Thunes { //TODO: implement functions when support enabled }
crates/hyperswitch_connectors/src/connectors/thunes.rs
hyperswitch_connectors
impl_block
18
rust
null
Thunes
ConnectorValidation for
impl ConnectorValidation for for Thunes
null
null
null
null
null
null
null
null
where F: Send + Clone + Sync, Req: Send + Sync + Authenticate, FData: Send + Sync + Clone, Op: Operation<F, Req, Data = D> + ValidateStatusForOperation + Send + Sync + Clone, Req: Debug, D: OperationSessionGetters<F> + OperationSessionSetters<F> + transformers::GenerateResponse<Res> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, PaymentResponse: Operation<F, FData, Data = D>, RouterData<F, FData, router_types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>, { operation .to_validate_request()? .validate_request(&req, &merchant_context)?; let get_tracker_response = operation .to_get_tracker()? .get_trackers( &state, &payment_id, &req, &merchant_context, &profile, &header_payload, ) .await?; let (payment_data, _req, connector_http_status_code, external_latency) = external_vault_proxy_for_payments_operation_core::<_, _, _, _, _>( &state, req_state, merchant_context.clone(), profile.clone(), operation.clone(), req, get_tracker_response, call_connector_action, header_payload.clone(), return_raw_connector_response, ) .await?; payment_data.generate_response( &state, connector_http_status_code, external_latency, header_payload.x_hs_latency, &merchant_context, &profile, None, ) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn record_attempt_core( state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, req: api_models::payments::PaymentsAttemptRecordRequest, payment_id: id_type::GlobalPaymentId, header_payload: HeaderPayload, ) -> RouterResponse<api_models::payments::PaymentAttemptRecordResponse> { tracing::Span::current().record( "merchant_id", merchant_context .get_merchant_account() .get_id() .get_string_repr(), ); let operation: &operations::payment_attempt_record::PaymentAttemptRecord = &operations::payment_attempt_record::PaymentAttemptRecord; let boxed_operation: BoxedOperation< '_, api::RecordAttempt, api_models::payments::PaymentsAttemptRecordRequest, domain_payments::PaymentAttemptRecordData<api::RecordAttempt>, > = Box::new(operation); let _validate_result = boxed_operation .to_validate_request()? .validate_request(&req, &merchant_context)?; tracing::Span::current().record("global_payment_id", payment_id.get_string_repr()); let operations::GetTrackerResponse { payment_data } = boxed_operation .to_get_tracker()? .get_trackers( &state, &payment_id, &req, &merchant_context, &profile, &header_payload, ) .await?; let default_payment_status_data = PaymentStatusData { flow: PhantomData, payment_intent: payment_data.payment_intent.clone(), payment_attempt: payment_data.payment_attempt.clone(), attempts: None, should_sync_with_connector: false, payment_address: payment_data.payment_address.clone(), merchant_connector_details: None, }; let payment_status_data = (req.triggered_by == common_enums::TriggeredBy::Internal) .then(|| default_payment_status_data.clone()) .async_unwrap_or_else(|| async { match Box::pin(proxy_for_payments_operation_core::< api::PSync, _, _, _, PaymentStatusData<api::PSync>, >( &state, req_state.clone(), merchant_context.clone(), profile.clone(), operations::PaymentGet, api::PaymentsRetrieveRequest { force_sync: true, expand_attempts: false, param: None, return_raw_connector_response: None, merchant_connector_details: None, }, operations::GetTrackerResponse { payment_data: PaymentStatusData { flow: PhantomData, payment_intent: payment_data.payment_intent.clone(), payment_attempt: payment_data.payment_attempt.clone(), attempts: None, should_sync_with_connector: true, payment_address: payment_data.payment_address.clone(), merchant_connector_details: None, }, }, CallConnectorAction::Trigger, HeaderPayload::default(), None, )) .await { Ok((data, _, _, _)) => data, Err(err) => { router_env::logger::error!(error=?err, "proxy_for_payments_operation_core failed for external payment attempt"); default_payment_status_data } } }) .await; let record_payment_data = domain_payments::PaymentAttemptRecordData { flow: PhantomData, payment_intent: payment_status_data.payment_intent, payment_attempt: payment_status_data.payment_attempt, revenue_recovery_data: payment_data.revenue_recovery_data.clone(), payment_address: payment_data.payment_address.clone(), }; let (_operation, final_payment_data) = boxed_operation .to_update_tracker()? .update_trackers( &state, req_state, record_payment_data, None, merchant_context.get_merchant_account().storage_scheme, None, merchant_context.get_merchant_key_store(), None, header_payload.clone(), ) .await?; transformers::GenerateResponse::generate_response( final_payment_data, &state, None, None, header_payload.x_hs_latency, &merchant_context, &profile, None, ) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn payments_intent_core<F, Res, Req, Op, D>( state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, operation: Op, req: Req, payment_id: id_type::GlobalPaymentId, header_payload: HeaderPayload, ) -> RouterResponse<Res> where F: Send + Clone + Sync, Op: Operation<F, Req, Data = D> + Send + Sync + Clone, Req: Debug + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, Res: transformers::ToResponse<F, D, Op>, { let (payment_data, _req, customer) = payments_intent_operation_core::<_, _, _, _>( &state, req_state, merchant_context.clone(), profile, operation.clone(), req, payment_id, header_payload.clone(), ) .await?; Res::generate_response( payment_data, customer, &state.base_url, operation, &state.conf.connector_request_reference_id_config, None, None, header_payload.x_hs_latency, &merchant_context, ) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn payments_list_attempts_using_payment_intent_id<F, Res, Req, Op, D>( state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, operation: Op, req: Req, payment_id: id_type::GlobalPaymentId, header_payload: HeaderPayload, ) -> RouterResponse<Res> where F: Send + Clone + Sync, Op: Operation<F, Req, Data = D> + Send + Sync + Clone, Req: Debug + Clone, D: OperationSessionGetters<F> + Send + Sync + Clone, Res: transformers::ToResponse<F, D, Op>, { let (payment_data, _req, customer) = payments_attempt_operation_core::<_, _, _, _>( &state, req_state, merchant_context.clone(), profile, operation.clone(), req, payment_id, header_payload.clone(), ) .await?; Res::generate_response( payment_data, customer, &state.base_url, operation, &state.conf.connector_request_reference_id_config, None, None, header_payload.x_hs_latency, &merchant_context, ) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn payments_get_intent_using_merchant_reference( state: SessionState, merchant_context: domain::MerchantContext, profile: domain::Profile, req_state: ReqState, merchant_reference_id: &id_type::PaymentReferenceId, header_payload: HeaderPayload, ) -> RouterResponse<api::PaymentsIntentResponse> { let db = state.store.as_ref(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let key_manager_state = &(&state).into(); let payment_intent = db .find_payment_intent_by_merchant_reference_id_profile_id( key_manager_state, merchant_reference_id, profile.get_id(), merchant_context.get_merchant_key_store(), &storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let (payment_data, _req, customer) = Box::pin(payments_intent_operation_core::< api::PaymentGetIntent, _, _, PaymentIntentData<api::PaymentGetIntent>, >( &state, req_state, merchant_context.clone(), profile.clone(), operations::PaymentGetIntent, api_models::payments::PaymentsGetIntentRequest { id: payment_intent.get_id().clone(), }, payment_intent.get_id().clone(), header_payload.clone(), )) .await?; transformers::ToResponse::< api::PaymentGetIntent, PaymentIntentData<api::PaymentGetIntent>, operations::PaymentGetIntent, >::generate_response( payment_data, customer, &state.base_url, operations::PaymentGetIntent, &state.conf.connector_request_reference_id_config, None, None, header_payload.x_hs_latency, &merchant_context, ) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn payments_core<F, Res, Req, Op, FData, D>( state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, operation: Op, req: Req, payment_id: id_type::GlobalPaymentId, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, ) -> RouterResponse<Res> where F: Send + Clone + Sync, Req: Send + Sync + Authenticate, FData: Send + Sync + Clone, Op: Operation<F, Req, Data = D> + ValidateStatusForOperation + Send + Sync + Clone, Req: Debug, D: OperationSessionGetters<F> + OperationSessionSetters<F> + transformers::GenerateResponse<Res> + Send + Sync + Clone, // To create connector flow specific interface data D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, // To perform router related operation for PaymentResponse PaymentResponse: Operation<F, FData, Data = D>, // To create updatable objects in post update tracker RouterData<F, FData, router_types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>, { // Validate the request fields operation .to_validate_request()? .validate_request(&req, &merchant_context)?; // Get the tracker related information. This includes payment intent and payment attempt let get_tracker_response = operation .to_get_tracker()? .get_trackers( &state, &payment_id, &req, &merchant_context, &profile, &header_payload, ) .await?; let (payment_data, connector_http_status_code, external_latency, connector_response_data) = if state.conf.merchant_id_auth.merchant_id_auth_enabled { let ( payment_data, _req, connector_http_status_code, external_latency, connector_response_data, ) = internal_payments_operation_core::<_, _, _, _, _>( &state, req_state, merchant_context.clone(), &profile, operation.clone(), req, get_tracker_response, call_connector_action, header_payload.clone(), ) .await?; ( payment_data, connector_http_status_code, external_latency, connector_response_data, ) } else { let ( payment_data, _req, _customer, connector_http_status_code, external_latency, connector_response_data, ) = payments_operation_core::<_, _, _, _, _>( &state, req_state, merchant_context.clone(), &profile, operation.clone(), req, get_tracker_response, call_connector_action, header_payload.clone(), ) .await?; ( payment_data, connector_http_status_code, external_latency, connector_response_data, ) }; payment_data.generate_response( &state, connector_http_status_code, external_latency, header_payload.x_hs_latency, &merchant_context, &profile, Some(connector_response_data), ) } #[allow(clippy::too_many_arguments)] #[cfg(feature = "v2")] pub(crate) async fn payments_create_and_confirm_intent( state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, request: payments_api::PaymentsRequest, mut header_payload: HeaderPayload, ) -> RouterResponse<payments_api::PaymentsResponse> { use hyperswitch_domain_models::{ payments::PaymentIntentData, router_flow_types::PaymentCreateIntent, }; let payment_id = id_type::GlobalPaymentId::generate(&state.conf.cell_information.id); let payload = payments_api::PaymentsCreateIntentRequest::from(&request); let create_intent_response = Box::pin(payments_intent_core::< PaymentCreateIntent, payments_api::PaymentsIntentResponse, _, _, PaymentIntentData<PaymentCreateIntent>, >( state.clone(), req_state.clone(), merchant_context.clone(), profile.clone(), operations::PaymentIntentCreate, payload, payment_id.clone(), header_payload.clone(), )) .await?; logger::info!(?create_intent_response); let create_intent_response = create_intent_response .get_json_body() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unexpected response from payments core")?; let payload = payments_api::PaymentsConfirmIntentRequest::from(&request); let confirm_intent_response = decide_authorize_or_setup_intent_flow( state, req_state, merchant_context, profile, &create_intent_response, payload, payment_id, header_payload, ) .await?; logger::info!(?confirm_intent_response); Ok(confirm_intent_response) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn decide_authorize_or_setup_intent_flow( state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, create_intent_response: &payments_api::PaymentsIntentResponse, confirm_intent_request: payments_api::PaymentsConfirmIntentRequest, payment_id: id_type::GlobalPaymentId, header_payload: HeaderPayload, ) -> RouterResponse<payments_api::PaymentsResponse> { use hyperswitch_domain_models::{ payments::PaymentConfirmData, router_flow_types::{Authorize, SetupMandate}, }; if create_intent_response.amount_details.order_amount == MinorUnit::zero() { Box::pin(payments_core::< SetupMandate, api_models::payments::PaymentsResponse, _, _, _, PaymentConfirmData<SetupMandate>, >( state, req_state, merchant_context, profile, operations::PaymentIntentConfirm, confirm_intent_request, payment_id, CallConnectorAction::Trigger, header_payload, )) .await } else { Box::pin(payments_core::< Authorize, api_models::payments::PaymentsResponse, _, _, _, PaymentConfirmData<Authorize>, >( state, req_state, merchant_context, profile, operations::PaymentIntentConfirm, confirm_intent_request, payment_id, CallConnectorAction::Trigger, header_payload, )) .await } } fn is_start_pay<Op: Debug>(operation: &Op) -> bool { format!("{operation:?}").eq("PaymentStart") } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsRedirectResponseData { pub connector: Option<String>, pub param: Option<String>, pub merchant_id: Option<id_type::MerchantId>, pub json_payload: Option<serde_json::Value>, pub resource_id: api::PaymentIdType, pub force_sync: bool, pub creds_identifier: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsRedirectResponseData { pub payment_id: id_type::GlobalPaymentId, pub query_params: String, pub json_payload: Option<serde_json::Value>, } #[async_trait::async_trait] pub trait PaymentRedirectFlow: Sync { // Associated type for call_payment_flow response type PaymentFlowResponse; #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn call_payment_flow( &self, state: &SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, req: PaymentsRedirectResponseData, connector_action: CallConnectorAction, connector: String, payment_id: id_type::PaymentId, ) -> RouterResult<Self::PaymentFlowResponse>; #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn call_payment_flow( &self, state: &SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, req: PaymentsRedirectResponseData, ) -> RouterResult<Self::PaymentFlowResponse>; fn get_payment_action(&self) -> services::PaymentAction; #[cfg(feature = "v1")] fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, payment_id: id_type::PaymentId, connector: String, ) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>>; #[cfg(feature = "v2")] fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, ) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>>; #[cfg(feature = "v1")] async fn handle_payments_redirect_response( &self, state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, req: PaymentsRedirectResponseData, ) -> RouterResponse<api::RedirectionResponse> { metrics::REDIRECTION_TRIGGERED.add( 1, router_env::metric_attributes!( ( "connector", req.connector.to_owned().unwrap_or("null".to_string()), ), ( "merchant_id", merchant_context.get_merchant_account().get_id().clone() ), ), ); let connector = req.connector.clone().get_required_value("connector")?; let query_params = req.param.clone().get_required_value("param")?; #[cfg(feature = "v1")] let resource_id = api::PaymentIdTypeExt::get_payment_intent_id(&req.resource_id) .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "payment_id", })?; #[cfg(feature = "v2")] //TODO: Will get the global payment id from the resource id, we need to handle this in the further flow let resource_id: id_type::PaymentId = todo!(); // This connector data is ephemeral, the call payment flow will get new connector data // with merchant account details, so the connector_id can be safely set to None here let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector, api::GetToken::Connector, None, )?; let flow_type = connector_data .connector .get_flow_type( &query_params, req.json_payload.clone(), self.get_payment_action(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to decide the response flow")?; let payment_flow_response = self .call_payment_flow( &state, req_state, merchant_context, req.clone(), flow_type, connector.clone(), resource_id.clone(), ) .await?; self.generate_response(&payment_flow_response, resource_id, connector) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn handle_payments_redirect_response( &self, state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, request: PaymentsRedirectResponseData, ) -> RouterResponse<api::RedirectionResponse> { metrics::REDIRECTION_TRIGGERED.add( 1, router_env::metric_attributes!(( "merchant_id", merchant_context.get_merchant_account().get_id().clone() )), ); let payment_flow_response = self .call_payment_flow(&state, req_state, merchant_context, profile, request) .await?; self.generate_response(&payment_flow_response) } } #[derive(Clone, Debug)] pub struct PaymentRedirectCompleteAuthorize; #[cfg(feature = "v1")] #[async_trait::async_trait] impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { type PaymentFlowResponse = router_types::RedirectPaymentFlowResponse; #[allow(clippy::too_many_arguments)] async fn call_payment_flow( &self, state: &SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, req: PaymentsRedirectResponseData, connector_action: CallConnectorAction, _connector: String, _payment_id: id_type::PaymentId, ) -> RouterResult<Self::PaymentFlowResponse> { let key_manager_state = &state.into(); let payment_confirm_req = api::PaymentsRequest { payment_id: Some(req.resource_id.clone()), merchant_id: req.merchant_id.clone(), merchant_connector_details: req.creds_identifier.map(|creds_id| { api::MerchantConnectorDetailsWrap { creds_identifier: creds_id, encoded_data: None, } }), feature_metadata: Some(api_models::payments::FeatureMetadata { redirect_response: Some(api_models::payments::RedirectResponse { param: req.param.map(Secret::new), json_payload: Some(req.json_payload.unwrap_or(serde_json::json!({})).into()), }), search_tags: None, apple_pay_recurring_details: None, }), ..Default::default() }; let response = Box::pin(payments_core::< api::CompleteAuthorize, api::PaymentsResponse, _, _, _, _, >( state.clone(), req_state, merchant_context.clone(), None, operations::payment_complete_authorize::CompleteAuthorize, payment_confirm_req, services::api::AuthFlow::Merchant, connector_action, None, HeaderPayload::default(), )) .await?; let payments_response = match response { services::ApplicationResponse::Json(response) => Ok(response), services::ApplicationResponse::JsonWithHeaders((response, _)) => Ok(response), _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the response in json"), }?; let profile_id = payments_response .profile_id .as_ref() .get_required_value("profile_id")?; let business_profile = state .store .find_business_profile_by_profile_id( key_manager_state, merchant_context.get_merchant_key_store(), profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(router_types::RedirectPaymentFlowResponse { payments_response, business_profile, }) } fn get_payment_action(&self) -> services::PaymentAction { services::PaymentAction::CompleteAuthorize } fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, payment_id: id_type::PaymentId, connector: String, ) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>> { let payments_response = &payment_flow_response.payments_response; // There might be multiple redirections needed for some flows // If the status is requires customer action, then send the startpay url again // The redirection data must have been provided and updated by the connector let redirection_response = match payments_response.status { enums::IntentStatus::RequiresCustomerAction => { let startpay_url = payments_response .next_action .clone() .and_then(|next_action_data| match next_action_data { api_models::payments::NextActionData::RedirectToUrl { redirect_to_url } => Some(redirect_to_url), api_models::payments::NextActionData::RedirectInsidePopup{popup_url, ..} => Some(popup_url), api_models::payments::NextActionData::DisplayBankTransferInformation { .. } => None, api_models::payments::NextActionData::ThirdPartySdkSessionToken { .. } => None, api_models::payments::NextActionData::QrCodeInformation{..} => None, api_models::payments::NextActionData::FetchQrCodeInformation{..} => None, api_models::payments::NextActionData::DisplayVoucherInformation{ .. } => None, api_models::payments::NextActionData::WaitScreenInformation{..} => None, api_models::payments::NextActionData::ThreeDsInvoke{..} => None, api_models::payments::NextActionData::InvokeSdkClient{..} => None, api_models::payments::NextActionData::CollectOtp{ .. } => None, api_models::payments::NextActionData::InvokeHiddenIframe{ .. } => None, }) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable( "did not receive redirect to url when status is requires customer action", )?; Ok(api::RedirectionResponse { return_url: String::new(), params: vec![], return_url_with_query_params: startpay_url, http_method: "GET".to_string(), headers: vec![], }) } // If the status is terminal status, then redirect to merchant return url to provide status enums::IntentStatus::Succeeded | enums::IntentStatus::Failed | enums::IntentStatus::Cancelled | enums::IntentStatus::RequiresCapture| enums::IntentStatus::Processing=> helpers::get_handle_response_url( payment_id, &payment_flow_response.business_profile, payments_response, connector, ), _ => Err(errors::ApiErrorResponse::InternalServerError).attach_printable_lazy(|| format!("Could not proceed with payment as payment status {} cannot be handled during redirection",payments_response.status))? }?; if payments_response .is_iframe_redirection_enabled .unwrap_or(false) { // html script to check if inside iframe, then send post message to parent for redirection else redirect self to return_url let html = core_utils::get_html_redirect_response_popup( redirection_response.return_url_with_query_params, )?; Ok(services::ApplicationResponse::Form(Box::new( services::RedirectionFormData { redirect_form: services::RedirectForm::Html { html_data: html }, payment_method_data: None, amount: payments_response.amount.to_string(), currency: payments_response.currency.clone(), }, ))) } else { Ok(services::ApplicationResponse::JsonForRedirection( redirection_response, )) } } } #[derive(Clone, Debug)] pub struct PaymentRedirectSync; #[cfg(feature = "v1")] #[async_trait::async_trait] impl PaymentRedirectFlow for PaymentRedirectSync { type PaymentFlowResponse = router_types::RedirectPaymentFlowResponse; #[allow(clippy::too_many_arguments)] async fn call_payment_flow( &self, state: &SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, req: PaymentsRedirectResponseData, connector_action: CallConnectorAction, _connector: String, _payment_id: id_type::PaymentId, ) -> RouterResult<Self::PaymentFlowResponse> { let key_manager_state = &state.into(); let payment_sync_req = api::PaymentsRetrieveRequest { resource_id: req.resource_id, merchant_id: req.merchant_id, param: req.param, force_sync: req.force_sync, connector: req.connector, merchant_connector_details: req.creds_identifier.map(|creds_id| { api::MerchantConnectorDetailsWrap { creds_identifier: creds_id, encoded_data: None, } }), client_secret: None, expand_attempts: None, expand_captures: None, all_keys_required: None, }; let response = Box::pin( payments_core::<api::PSync, api::PaymentsResponse, _, _, _, _>( state.clone(), req_state, merchant_context.clone(), None, PaymentStatus, payment_sync_req, services::api::AuthFlow::Merchant, connector_action, None, HeaderPayload::default(), ), ) .await?; let payments_response = match response { services::ApplicationResponse::Json(response) => Ok(response), services::ApplicationResponse::JsonWithHeaders((response, _)) => Ok(response), _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the response in json"), }?; let profile_id = payments_response .profile_id .as_ref() .get_required_value("profile_id")?; let business_profile = state .store .find_business_profile_by_profile_id( key_manager_state, merchant_context.get_merchant_key_store(), profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(router_types::RedirectPaymentFlowResponse { payments_response, business_profile, }) } fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, payment_id: id_type::PaymentId, connector: String, ) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>> { let payments_response = &payment_flow_response.payments_response; let redirect_response = helpers::get_handle_response_url( payment_id.clone(), &payment_flow_response.business_profile, payments_response, connector.clone(), )?; if payments_response .is_iframe_redirection_enabled .unwrap_or(false) { // html script to check if inside iframe, then send post message to parent for redirection else redirect self to return_url let html = core_utils::get_html_redirect_response_popup( redirect_response.return_url_with_query_params, )?; Ok(services::ApplicationResponse::Form(Box::new( services::RedirectionFormData { redirect_form: services::RedirectForm::Html { html_data: html }, payment_method_data: None, amount: payments_response.amount.to_string(), currency: payments_response.currency.clone(), }, ))) } else { Ok(services::ApplicationResponse::JsonForRedirection( redirect_response, )) } } fn get_payment_action(&self) -> services::PaymentAction { services::PaymentAction::PSync } } #[cfg(feature = "v2")] impl ValidateStatusForOperation for &PaymentRedirectSync { fn validate_status_for_operation( &self, intent_status: common_enums::IntentStatus, ) -> Result<(), errors::ApiErrorResponse> { match intent_status { common_enums::IntentStatus::RequiresCustomerAction => Ok(()), common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Processing | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::Expired => { Err(errors::ApiErrorResponse::PaymentUnexpectedState { current_flow: format!("{self:?}"), field_name: "status".to_string(), current_value: intent_status.to_string(), states: ["requires_customer_action".to_string()].join(", "), }) } } } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl PaymentRedirectFlow for PaymentRedirectSync { type PaymentFlowResponse = router_types::RedirectPaymentFlowResponse<PaymentStatusData<api::PSync>>; async fn call_payment_flow( &self, state: &SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, req: PaymentsRedirectResponseData, ) -> RouterResult<Self::PaymentFlowResponse> { let payment_id = req.payment_id.clone(); let payment_sync_request = api::PaymentsRetrieveRequest { param: Some(req.query_params.clone()), force_sync: true, expand_attempts: false, return_raw_connector_response: None, merchant_connector_details: None, // TODO: Implement for connectors requiring 3DS or redirection-based authentication flows. }; let operation = operations::PaymentGet; let boxed_operation: BoxedOperation< '_, api::PSync, api::PaymentsRetrieveRequest, PaymentStatusData<api::PSync>, > = Box::new(operation); let get_tracker_response = boxed_operation .to_get_tracker()? .get_trackers( state, &payment_id, &payment_sync_request, &merchant_context, &profile, &HeaderPayload::default(), ) .await?; let payment_data = &get_tracker_response.payment_data; self.validate_status_for_operation(payment_data.payment_intent.status)?; let payment_attempt = payment_data.payment_attempt.clone(); let connector = payment_attempt .connector .as_ref() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable( "connector is not set in payment attempt in finish redirection flow", )?; // This connector data is ephemeral, the call payment flow will get new connector data // with merchant account details, so the connector_id can be safely set to None here let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, connector, api::GetToken::Connector, None, )?; let call_connector_action = connector_data .connector .get_flow_type( &req.query_params, req.json_payload.clone(), self.get_payment_action(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to decide the response flow")?; let (payment_data, _, _, _, _, _) = Box::pin(payments_operation_core::<api::PSync, _, _, _, _>( state, req_state, merchant_context, &profile, operation, payment_sync_request, get_tracker_response, call_connector_action, HeaderPayload::default(), )) .await?; Ok(router_types::RedirectPaymentFlowResponse { payment_data, profile, }) } fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse,
crates/router/src/core/payments.rs#chunk2
router
chunk
8,181
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct CustomerUpdateRequestInternal { pub id: id_type::GlobalCustomerId, pub request: CustomerUpdateRequest, }
crates/api_models/src/customers.rs
api_models
struct_definition
26
rust
CustomerUpdateRequestInternal
null
null
null
null
null
null
null
null
null
null
null
pub async fn toggle_elimination_routing() {}
crates/openapi/src/routes/routing.rs
openapi
function_signature
9
rust
null
null
null
null
toggle_elimination_routing
null
null
null
null
null
null
null
pub struct CybersourcePaymentInitiator { #[serde(rename = "type")] initiator_type: Option<CybersourcePaymentInitiatorTypes>, credential_stored_on_file: Option<bool>, stored_credential_used: Option<bool>, }
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
hyperswitch_connectors
struct_definition
51
rust
CybersourcePaymentInitiator
null
null
null
null
null
null
null
null
null
null
null
pub async fn from_role_id_org_id_tenant_id( state: &SessionState, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> CustomResult<Self, errors::StorageError> { if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) { Ok(role.clone()) } else { state .global_store .find_by_role_id_org_id_tenant_id(role_id, org_id, tenant_id) .await .map(Self::from) } }
crates/router/src/services/authorization/roles.rs
router
function_signature
132
rust
null
null
null
null
from_role_id_org_id_tenant_id
null
null
null
null
null
null
null
}, card_acceptor_tax_id: l2_l3_data.merchant_tax_registration_id.clone(), tax_amount: l2_l3_data.order_details.as_ref().map(|orders| { orders .iter() .filter_map(|order| order.total_tax_amount) .fold(MinorUnit::zero(), |acc, tax| acc + tax) }), }) } else { None }; let enhanced_data = EnhancedData { customer_reference, sales_tax: l2_l3_data.order_tax_amount, tax_exempt, discount_amount: l2_l3_data.discount_amount, shipping_amount: l2_l3_data.shipping_cost, duty_amount: l2_l3_data.duty_amount, ship_from_postal_code: l2_l3_data.shipping_origin_zip, destination_postal_code: l2_l3_data.shipping_destination_zip, destination_country_code: l2_l3_data.shipping_country, detail_tax, line_item_data, }; Ok(Some(enhanced_data)) } else { Ok(None) } } fn get_processing_info( request: &PaymentsAuthorizeData, ) -> Result<VantivMandateDetail, error_stack::Report<errors::ConnectorError>> { if request.is_customer_initiated_mandate_payment() { Ok(VantivMandateDetail { processing_type: Some(VantivProcessingType::InitialCOF), network_transaction_id: None, token: None, }) } else { match request .mandate_id .as_ref() .and_then(|mandate| mandate.mandate_reference_id.clone()) { Some(api_models::payments::MandateReferenceId::NetworkMandateId( network_transaction_id, )) => Ok(VantivMandateDetail { processing_type: Some(VantivProcessingType::MerchantInitiatedCOF), network_transaction_id: Some(network_transaction_id.into()), token: None, }), Some(api_models::payments::MandateReferenceId::ConnectorMandateId(mandate_data)) => { let card_mandate_data = request.get_card_mandate_info()?; Ok(VantivMandateDetail { processing_type: None, network_transaction_id: None, token: Some(TokenizationData { cnp_token: mandate_data .get_connector_mandate_id() .ok_or(errors::ConnectorError::MissingConnectorMandateID)? .into(), exp_date: format!( "{}{}", card_mandate_data.card_exp_month.peek(), card_mandate_data.card_exp_year.peek() ) .into(), }), }) } _ => Ok(VantivMandateDetail { processing_type: None, network_transaction_id: None, token: None, }), } } } impl TryFrom<&WorldpayvantivRouterData<&PaymentsCaptureRouterData>> for CnpOnlineRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &WorldpayvantivRouterData<&PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { let report_group_metadata: WorldpayvantivPaymentMetadata = connector_utils::to_connector_meta(item.router_data.request.connector_meta.clone())?; let report_group = report_group_metadata.report_group.clone().ok_or( errors::ConnectorError::RequestEncodingFailedWithReason( "Failed to obtain report_group from metadata".to_string(), ), )?; let merchant_txn_id = get_valid_transaction_id( item.router_data.connector_request_reference_id.clone(), "capture.id", )?; let capture = Some(Capture { id: format!("{}_{}", OperationId::Capture, merchant_txn_id), report_group, cnp_txn_id: item.router_data.request.connector_transaction_id.clone(), amount: item.amount, }); let worldpayvantiv_auth_type = WorldpayvantivAuthType::try_from(&item.router_data.connector_auth_type)?; let authentication = Authentication { user: worldpayvantiv_auth_type.user, password: worldpayvantiv_auth_type.password, }; Ok(Self { version: worldpayvantiv_constants::WORLDPAYVANTIV_VERSION.to_string(), xmlns: worldpayvantiv_constants::XMLNS.to_string(), merchant_id: worldpayvantiv_auth_type.merchant_id, authentication, authorization: None, sale: None, capture, auth_reversal: None, credit: None, void: None, }) } } impl<F> TryFrom<&WorldpayvantivRouterData<&RefundsRouterData<F>>> for CnpOnlineRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &WorldpayvantivRouterData<&RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { let report_group_metadata: WorldpayvantivPaymentMetadata = connector_utils::to_connector_meta( item.router_data.request.connector_metadata.clone(), )?; let report_group = report_group_metadata.report_group.clone().ok_or( errors::ConnectorError::RequestEncodingFailedWithReason( "Failed to obtain report_group from metadata".to_string(), ), )?; let customer_id = extract_customer_id(item.router_data); let merchant_txn_id = get_valid_transaction_id( item.router_data.connector_request_reference_id.clone(), "credit.id", )?; let credit = Some(RefundRequest { id: format!("{}_{merchant_txn_id}", OperationId::Refund), report_group, customer_id, cnp_txn_id: item.router_data.request.connector_transaction_id.clone(), amount: item.amount, }); let worldpayvantiv_auth_type = WorldpayvantivAuthType::try_from(&item.router_data.connector_auth_type)?; let authentication = Authentication { user: worldpayvantiv_auth_type.user, password: worldpayvantiv_auth_type.password, }; Ok(Self { version: worldpayvantiv_constants::WORLDPAYVANTIV_VERSION.to_string(), xmlns: worldpayvantiv_constants::XMLNS.to_string(), merchant_id: worldpayvantiv_auth_type.merchant_id, authentication, authorization: None, sale: None, capture: None, auth_reversal: None, credit, void: None, }) } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct VantivSyncErrorResponse { pub error_messages: Vec<String>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename = "errorResponse")] pub struct VantivDisputeErrorResponse { #[serde(rename = "@xmlns")] pub xmlns: String, pub errors: Vec<VantivDisputeErrors>, } #[derive(Debug, Serialize, Deserialize)] pub struct VantivDisputeErrors { pub error: String, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename = "cnpOnlineResponse", rename_all = "camelCase")] pub struct CnpOnlineResponse { #[serde(rename = "@version")] pub version: String, #[serde(rename = "@response")] pub response_code: String, #[serde(rename = "@message")] pub message: String, pub authorization_response: Option<PaymentResponse>, pub sale_response: Option<PaymentResponse>, pub capture_response: Option<CaptureResponse>, pub auth_reversal_response: Option<AuthReversalResponse>, pub void_response: Option<VoidResponse>, pub credit_response: Option<CreditResponse>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct VantivSyncResponse { pub payment_id: u64, pub request_uuid: String, pub payment_status: PaymentStatus, pub payment_detail: Option<PaymentDetail>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaymentDetail { pub payment_id: Option<u64>, pub batch_id: Option<u64>, pub session_id: Option<u64>, pub response_reason_code: Option<String>, pub response_reason_message: Option<String>, pub reject_type: Option<String>, pub dupe_txn_id: Option<u64>, pub amount: Option<String>, pub purchase_currency: Option<String>, pub post_day: Option<String>, pub reported_timestamp: Option<String>, pub payment_type: Option<String>, pub merchant_order_number: Option<String>, pub merchant_txn_id: Option<String>, pub parent_id: Option<u64>, pub reporting_group: Option<String>, } #[derive(Debug, strum::Display, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaymentStatus { NotYetProcessed, ProcessedSuccessfully, TransactionDeclined, StatusUnavailable, PaymentStatusNotFound, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CaptureResponse { #[serde(rename = "@id")] pub id: String, #[serde(rename = "@reportGroup")] pub report_group: String, #[serde(rename = "@customerId", skip_serializing_if = "Option::is_none")] pub customer_id: Option<String>, #[serde(rename = "cnpTxnId")] pub cnp_txn_id: String, pub response: WorldpayvantivResponseCode, pub response_time: String, pub message: String, pub location: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct FraudResult { pub avs_result: Option<String>, pub card_validation_result: Option<String>, pub authentication_result: Option<String>, pub advanced_a_v_s_result: Option<String>, pub advanced_fraud_results: Option<AdvancedFraudResults>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AdvancedFraudResults { pub device_review_status: Option<String>, pub device_reputation_score: Option<String>, pub triggered_rule: Option<Vec<String>>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PaymentResponse { #[serde(rename = "@id")] pub id: String, #[serde(rename = "@reportGroup")] pub report_group: String, #[serde(rename = "@customerId", skip_serializing_if = "Option::is_none")] pub customer_id: Option<String>, pub cnp_txn_id: String, pub order_id: String, pub response: WorldpayvantivResponseCode, pub message: String, pub response_time: String, pub auth_code: Option<Secret<String>>, pub fraud_result: Option<FraudResult>, pub token_response: Option<TokenResponse>, pub network_transaction_id: Option<Secret<String>>, pub approved_amount: Option<MinorUnit>, pub enhanced_auth_response: Option<EnhancedAuthResponse>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct EnhancedAuthResponse { pub network_response: Option<NetworkResponse>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct NetworkResponse { pub endpoint: Option<String>, #[serde(default)] #[serde(rename = "networkField")] pub network_fields: Vec<NetworkField>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct NetworkField { #[serde(rename = "@fieldNumber")] pub field_number: String, #[serde(rename = "@fieldName", skip_serializing_if = "Option::is_none")] pub field_name: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub field_value: Option<String>, #[serde(default)] #[serde(rename = "networkSubField")] pub network_sub_fields: Vec<NetworkSubField>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct NetworkSubField { #[serde(rename = "@fieldNumber")] pub field_number: String, pub field_value: String, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct TokenResponse { pub cnp_token: Secret<String>, pub token_response_code: String, pub token_message: String, #[serde(rename = "type")] pub card_type: Option<String>, pub bin: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AuthReversalResponse { #[serde(rename = "@id")] pub id: String, #[serde(rename = "@reportGroup")] pub report_group: String, #[serde(rename = "@customerId", skip_serializing_if = "Option::is_none")] pub customer_id: Option<String>, pub cnp_txn_id: String, pub response: WorldpayvantivResponseCode, pub response_time: String, pub post_date: Option<String>, pub message: String, pub location: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct VoidResponse { #[serde(rename = "@id")] pub id: String, #[serde(rename = "@reportGroup")] pub report_group: String, pub cnp_txn_id: String, pub response: WorldpayvantivResponseCode, pub response_time: String, pub post_date: Option<String>, pub message: String, pub location: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CreditResponse { #[serde(rename = "@id")] pub id: String, #[serde(rename = "@reportGroup")] pub report_group: String, #[serde(rename = "@customerId", skip_serializing_if = "Option::is_none")] pub customer_id: Option<String>, pub cnp_txn_id: String, pub response: WorldpayvantivResponseCode, pub response_time: String, pub message: String, pub location: Option<String>, } impl<F> TryFrom<ResponseRouterData<F, CnpOnlineResponse, PaymentsCaptureData, PaymentsResponseData>> for RouterData<F, PaymentsCaptureData, PaymentsResponseData> where F: Send, { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, CnpOnlineResponse, PaymentsCaptureData, PaymentsResponseData>, ) -> Result<Self, Self::Error> { match item.response.capture_response { Some(capture_response) => { let status = get_attempt_status( WorldpayvantivPaymentFlow::Capture, capture_response.response, )?; if connector_utils::is_payment_failure(status) { let network_decline_code = item .response .sale_response .as_ref() .and_then(|pr| pr.enhanced_auth_response.as_ref()) .and_then(|ea| ea.network_response.as_ref()) .and_then(|nr| { nr.network_fields .iter() .find(|f| { f.field_number == *worldpayvantiv_constants::MAC_FIELD_NUMBER }) .and_then(|f| f.field_value.clone()) }); let network_error_message = network_decline_code .as_ref() .map(|_| capture_response.message.clone()); Ok(Self { status, response: Err(ErrorResponse { code: capture_response.response.to_string(), message: capture_response.message.clone(), reason: Some(capture_response.message.clone()), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(capture_response.cnp_txn_id), network_advice_code: None, network_decline_code, network_error_message, connector_metadata: None, }), ..item.data }) } else { Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( capture_response.cnp_txn_id, ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } None => { let network_decline_code = item .response .sale_response .as_ref() .and_then(|pr| pr.enhanced_auth_response.as_ref()) .and_then(|ea| ea.network_response.as_ref()) .and_then(|nr| { nr.network_fields .iter() .find(|f| f.field_number == *worldpayvantiv_constants::MAC_FIELD_NUMBER) .and_then(|f| f.field_value.clone()) }); let network_error_message = network_decline_code .as_ref() .map(|_| item.response.message.clone()); Ok(Self { status: common_enums::AttemptStatus::CaptureFailed, response: Err(ErrorResponse { code: item.response.response_code, message: item.response.message.clone(), reason: Some(item.response.message.clone()), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code, network_error_message, connector_metadata: None, }), ..item.data }) } } } } fn get_vantiv_customer_reference(customer_id: &Option<String>) -> Option<String> { customer_id.clone().and_then(|id| { if id.len() <= worldpayvantiv_constants::CUSTOMER_REFERENCE_MAX_LENGTH { Some(id) } else { None } }) } impl<F> TryFrom<ResponseRouterData<F, CnpOnlineResponse, PaymentsCancelData, PaymentsResponseData>> for RouterData<F, PaymentsCancelData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, CnpOnlineResponse, PaymentsCancelData, PaymentsResponseData>, ) -> Result<Self, Self::Error> { match item.response.auth_reversal_response { Some(auth_reversal_response) => { let status = get_attempt_status( WorldpayvantivPaymentFlow::Void, auth_reversal_response.response, )?; if connector_utils::is_payment_failure(status) { let network_decline_code = item .response .sale_response .as_ref() .and_then(|pr| pr.enhanced_auth_response.as_ref()) .and_then(|ea| ea.network_response.as_ref()) .and_then(|nr| { nr.network_fields .iter() .find(|f| { f.field_number == *worldpayvantiv_constants::MAC_FIELD_NUMBER }) .and_then(|f| f.field_value.clone()) }); let network_error_message = network_decline_code .as_ref() .map(|_| auth_reversal_response.message.clone()); Ok(Self { status, response: Err(ErrorResponse { code: auth_reversal_response.response.to_string(), message: auth_reversal_response.message.clone(), reason: Some(auth_reversal_response.message.clone()), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(auth_reversal_response.cnp_txn_id), network_advice_code: None, network_decline_code, network_error_message, connector_metadata: None, }), ..item.data }) } else { Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( auth_reversal_response.cnp_txn_id, ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } None => { let network_decline_code = item .response .sale_response .as_ref() .and_then(|pr| pr.enhanced_auth_response.as_ref()) .and_then(|ea| ea.network_response.as_ref()) .and_then(|nr| { nr.network_fields .iter() .find(|f| f.field_number == *worldpayvantiv_constants::MAC_FIELD_NUMBER) .and_then(|f| f.field_value.clone()) }); let network_error_message = network_decline_code .as_ref() .map(|_| item.response.message.clone()); Ok(Self { // Incase of API failure status: common_enums::AttemptStatus::VoidFailed, response: Err(ErrorResponse { code: item.response.response_code, message: item.response.message.clone(), reason: Some(item.response.message.clone()), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, // Transaction id not created at connector network_advice_code: None, network_decline_code, network_error_message, connector_metadata: None, }), ..item.data }) } } } } impl<F> TryFrom< ResponseRouterData< F, CnpOnlineResponse, PaymentsCancelPostCaptureData, PaymentsResponseData, >, > for RouterData<F, PaymentsCancelPostCaptureData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, CnpOnlineResponse, PaymentsCancelPostCaptureData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { match item.response.void_response { Some(void_response) => { let status = get_attempt_status(WorldpayvantivPaymentFlow::VoidPC, void_response.response)?; if connector_utils::is_payment_failure(status) { Ok(Self { status, response: Err(ErrorResponse { code: void_response.response.to_string(), message: void_response.message.clone(), reason: Some(void_response.message.clone()), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(void_response.cnp_txn_id), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } else { Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( void_response.cnp_txn_id, ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } None => Ok(Self { // Incase of API failure status: common_enums::AttemptStatus::VoidFailed, response: Err(ErrorResponse { code: item.response.response_code, message: item.response.message.clone(), reason: Some(item.response.message.clone()), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }), } } } impl TryFrom<RefundsResponseRouterData<Execute, CnpOnlineResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, CnpOnlineResponse>, ) -> Result<Self, Self::Error> { match item.response.credit_response { Some(credit_response) => { let refund_status = get_refund_status(credit_response.response)?; if connector_utils::is_refund_failure(refund_status) { let network_decline_code = item .response .sale_response .as_ref() .and_then(|pr| pr.enhanced_auth_response.as_ref()) .and_then(|ea| ea.network_response.as_ref()) .and_then(|nr| { nr.network_fields .iter() .find(|f| { f.field_number == *worldpayvantiv_constants::MAC_FIELD_NUMBER }) .and_then(|f| f.field_value.clone()) }); let network_error_message = network_decline_code .as_ref() .map(|_| credit_response.message.clone()); Ok(Self { response: Err(ErrorResponse { code: credit_response.response.to_string(), message: credit_response.message.clone(), reason: Some(credit_response.message.clone()), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code, network_error_message, connector_metadata: None, }), ..item.data }) } else { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: credit_response.cnp_txn_id, refund_status, }), ..item.data }) } } None => { let network_decline_code = item .response .sale_response .as_ref() .and_then(|pr| pr.enhanced_auth_response.as_ref()) .and_then(|ea| ea.network_response.as_ref()) .and_then(|nr| { nr.network_fields .iter() .find(|f| f.field_number == *worldpayvantiv_constants::MAC_FIELD_NUMBER) .and_then(|f| f.field_value.clone()) }); let network_error_message = network_decline_code .as_ref() .map(|_| item.response.message.clone()); Ok(Self { response: Err(ErrorResponse { code: item.response.response_code, message: item.response.message.clone(), reason: Some(item.response.message.clone()), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code, network_error_message, connector_metadata: None, }), ..item.data }) } } } } impl TryFrom<&PaymentsCancelRouterData> for CnpOnlineRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { let report_group_metadata: WorldpayvantivPaymentMetadata = connector_utils::to_connector_meta(item.request.connector_meta.clone())?; let report_group = report_group_metadata.report_group.clone().ok_or( errors::ConnectorError::RequestEncodingFailedWithReason( "Failed to obtain report_group from metadata".to_string(), ), )?; let merchant_txn_id = get_valid_transaction_id( item.connector_request_reference_id.clone(), "authReversal.id", )?; let auth_reversal = Some(AuthReversal { id: format!("{}_{merchant_txn_id}", OperationId::Void), report_group, cnp_txn_id: item.request.connector_transaction_id.clone(), }); let worldpayvantiv_auth_type = WorldpayvantivAuthType::try_from(&item.connector_auth_type)?; let authentication = Authentication { user: worldpayvantiv_auth_type.user, password: worldpayvantiv_auth_type.password, }; Ok(Self { version: worldpayvantiv_constants::WORLDPAYVANTIV_VERSION.to_string(), xmlns: worldpayvantiv_constants::XMLNS.to_string(), merchant_id: worldpayvantiv_auth_type.merchant_id, authentication, authorization: None, sale: None, capture: None, auth_reversal, credit: None, void: None, }) } } impl TryFrom<&PaymentsCancelPostCaptureRouterData> for CnpOnlineRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsCancelPostCaptureRouterData) -> Result<Self, Self::Error> { let report_group_metadata: WorldpayvantivPaymentMetadata = connector_utils::to_connector_meta(item.request.connector_meta.clone())?; let report_group = report_group_metadata.report_group.clone().ok_or( errors::ConnectorError::RequestEncodingFailedWithReason( "Failed to obtain report_group from metadata".to_string(), ), )?; let merchant_txn_id = get_valid_transaction_id(item.connector_request_reference_id.clone(), "void.id")?; let void = Some(Void { id: format!("{}_{merchant_txn_id}", OperationId::VoidPC,), report_group, cnp_txn_id: item.request.connector_transaction_id.clone(), }); let worldpayvantiv_auth_type = WorldpayvantivAuthType::try_from(&item.connector_auth_type)?; let authentication = Authentication { user: worldpayvantiv_auth_type.user, password: worldpayvantiv_auth_type.password, }; Ok(Self { version: worldpayvantiv_constants::WORLDPAYVANTIV_VERSION.to_string(), xmlns: worldpayvantiv_constants::XMLNS.to_string(), merchant_id: worldpayvantiv_auth_type.merchant_id, authentication, authorization: None, sale: None, capture: None, void, auth_reversal: None, credit: None, }) } } impl<F> TryFrom<ResponseRouterData<F, CnpOnlineResponse, PaymentsAuthorizeData, PaymentsResponseData>> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, CnpOnlineResponse, PaymentsAuthorizeData, PaymentsResponseData>, ) -> Result<Self, Self::Error> { match (item.response.sale_response.as_ref(), item.response.authorization_response.as_ref()) { (Some(sale_response), None) => { let status = get_attempt_status(WorldpayvantivPaymentFlow::Sale, sale_response.response)?; if connector_utils::is_payment_failure(status) { let network_decline_code = item .response .sale_response .as_ref() .and_then(|pr| pr.enhanced_auth_response.as_ref()) .and_then(|ea| ea.network_response.as_ref()) .and_then(|nr| { nr.network_fields .iter() .find(|f| f.field_number == *worldpayvantiv_constants::MAC_FIELD_NUMBER) .and_then(|f| f.field_value.clone()) }); let network_error_message = network_decline_code .as_ref() .map(|_| sale_response.message.clone()); Ok(Self { status, response: Err(ErrorResponse { code: sale_response.response.to_string(), message: sale_response.message.clone(), reason: Some(sale_response.message.clone()), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(sale_response.cnp_txn_id.clone()), network_advice_code: None, network_decline_code, network_error_message, connector_metadata: None, }), ..item.data }) } else { let report_group = WorldpayvantivPaymentMetadata { report_group: Some(sale_response.report_group.clone()), }; let connector_metadata = Some(report_group.encode_to_value() .change_context(errors::ConnectorError::ResponseHandlingFailed)?); let mandate_reference_data = sale_response.token_response.clone().map(MandateReference::from); let connector_response = sale_response.fraud_result.as_ref().map(get_connector_response); Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(sale_response.cnp_txn_id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(mandate_reference_data), connector_metadata, network_txn_id: sale_response.network_transaction_id.clone().map(|network_transaction_id| network_transaction_id.expose()), connector_response_reference_id: Some(sale_response.order_id.clone()), incremental_authorization_allowed: None, charges: None, }), connector_response, amount_captured: sale_response.approved_amount.map(MinorUnit::get_amount_as_i64), ..item.data }) } }, (None, Some(auth_response)) => { let payment_flow_type = if item.data.request.is_auto_capture()? { WorldpayvantivPaymentFlow::Sale } else { WorldpayvantivPaymentFlow::Auth }; let status = get_attempt_status(payment_flow_type, auth_response.response)?; if connector_utils::is_payment_failure(status) { let network_decline_code = item .response .authorization_response .as_ref() .and_then(|pr| pr.enhanced_auth_response.as_ref()) .and_then(|ea| ea.network_response.as_ref()) .and_then(|nr| { nr.network_fields .iter() .find(|f| f.field_number == *worldpayvantiv_constants::MAC_FIELD_NUMBER) .and_then(|f| f.field_value.clone()) }); let network_error_message = network_decline_code .as_ref() .map(|_| auth_response.message.clone()); Ok(Self { status, response: Err(ErrorResponse { code: auth_response.response.to_string(), message: auth_response.message.clone(), reason: Some(auth_response.message.clone()), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(auth_response.cnp_txn_id.clone()), network_advice_code: None, network_decline_code, network_error_message, connector_metadata: None, }), ..item.data }) } else { let report_group = WorldpayvantivPaymentMetadata { report_group: Some(auth_response.report_group.clone()), }; let connector_metadata = Some(report_group.encode_to_value() .change_context(errors::ConnectorError::ResponseHandlingFailed)?); let mandate_reference_data = auth_response.token_response.clone().map(MandateReference::from); let connector_response = auth_response.fraud_result.as_ref().map(get_connector_response); Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(auth_response.cnp_txn_id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(mandate_reference_data), connector_metadata, network_txn_id: auth_response.network_transaction_id.clone().map(|network_transaction_id| network_transaction_id.expose()), connector_response_reference_id: Some(auth_response.order_id.clone()), incremental_authorization_allowed: None, charges: None, }), connector_response, amount_captured: if payment_flow_type == WorldpayvantivPaymentFlow::Sale { auth_response.approved_amount.map(MinorUnit::get_amount_as_i64) } else { None }, minor_amount_capturable: if payment_flow_type == WorldpayvantivPaymentFlow::Auth { auth_response.approved_amount } else { None }, ..item.data }) } }, (None, None) => { Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(ErrorResponse { code: item.response.response_code.clone(), message: item.response.message.clone(), reason: Some(item.response.message.clone()), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, // Transaction id not created at connector network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data })}, (_, _) => { Err(errors::ConnectorError::UnexpectedResponseError( bytes::Bytes::from("Only one of 'sale_response' or 'authorisation_response' is expected, but both were received".to_string()), ))? }, } } } impl<F> TryFrom<ResponseRouterData<F, CnpOnlineResponse, SetupMandateRequestData, PaymentsResponseData>> for RouterData<F, SetupMandateRequestData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, CnpOnlineResponse, SetupMandateRequestData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { match item.response.authorization_response.as_ref() { Some(auth_response) => { let status = get_attempt_status(WorldpayvantivPaymentFlow::Sale, auth_response.response)?; if connector_utils::is_payment_failure(status) { let network_decline_code = item .response .authorization_response .as_ref() .and_then(|pr| pr.enhanced_auth_response.as_ref()) .and_then(|ea| ea.network_response.as_ref()) .and_then(|nr| { nr.network_fields .iter() .find(|f| {
crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs#chunk1
hyperswitch_connectors
chunk
8,187
null
null
null
null
null
null
null
null
null
null
null
null
null
impl IncomingWebhook for Billwerk { fn get_webhook_object_reference_id( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } }
crates/hyperswitch_connectors/src/connectors/billwerk.rs
hyperswitch_connectors
impl_block
185
rust
null
Billwerk
IncomingWebhook for
impl IncomingWebhook for for Billwerk
null
null
null
null
null
null
null
null
File: crates/hyperswitch_connectors/src/connectors/mpgs.rs Public functions: 1 Public structs: 1 pub mod transformers; use std::sync::LazyLock; use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, }, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, types::{self, Response}, webhooks, }; use masking::{ExposeInterface, Mask}; use transformers as mpgs; use crate::{constants::headers, types::ResponseRouterData, utils}; #[derive(Clone)] pub struct Mpgs { amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), } impl Mpgs { pub fn new() -> &'static Self { &Self { amount_converter: &StringMinorUnitForConnector, } } } impl api::Payment for Mpgs {} impl api::PaymentSession for Mpgs {} impl api::ConnectorAccessToken for Mpgs {} impl api::MandateSetup for Mpgs {} impl api::PaymentAuthorize for Mpgs {} impl api::PaymentSync for Mpgs {} impl api::PaymentCapture for Mpgs {} impl api::PaymentVoid for Mpgs {} impl api::Refund for Mpgs {} impl api::RefundExecute for Mpgs {} impl api::RefundSync for Mpgs {} impl api::PaymentToken for Mpgs {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Mpgs { // Not Implemented (R) } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Mpgs where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Mpgs { fn id(&self) -> &'static str { "mpgs" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Minor // TODO! Check connector documentation, on which unit they are processing the currency. // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor, // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.mpgs.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = mpgs::MpgsAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), auth.api_key.expose().into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: mpgs::MpgsErrorResponse = res .response .parse_struct("MpgsErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: response.code, message: response.message, reason: response.reason, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl ConnectorValidation for Mpgs { fn validate_mandate_payment( &self, _pm_type: Option<enums::PaymentMethodType>, pm_data: PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { match pm_data { PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( "validate_mandate_payment does not support cards".to_string(), ) .into()), _ => Ok(()), } } fn validate_psync_reference_id( &self, _data: &PaymentsSyncData, _is_three_ds: bool, _status: enums::AttemptStatus, _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<(), errors::ConnectorError> { Ok(()) } } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Mpgs { //TODO: implement sessions flow } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Mpgs {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Mpgs {} impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Mpgs { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = mpgs::MpgsRouterData::from((amount, req)); let connector_req = mpgs::MpgsPaymentsRequest::try_from(&connector_router_data)?; 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: mpgs::MpgsPaymentsResponse = res .response .parse_struct("Mpgs PaymentsAuthorizeResponse") .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<PSync, PaymentsSyncData, PaymentsResponseData> for Mpgs { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsSyncRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } 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: mpgs::MpgsPaymentsResponse = res .response .parse_struct("mpgs 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 Mpgs { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: mpgs::MpgsPaymentsResponse = res .response .parse_struct("Mpgs PaymentsCaptureResponse") .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<Void, PaymentsCancelData, PaymentsResponseData> for Mpgs {} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Mpgs { 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> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let refund_amount = utils::convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = mpgs::MpgsRouterData::from((refund_amount, req)); let connector_req = mpgs::MpgsRefundRequest::try_from(&connector_router_data)?; 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: mpgs::RefundResponse = res .response .parse_struct("mpgs RefundResponse") .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<RSync, RefundsData, RefundsResponseData> for Mpgs { 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> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } 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)?) .set_body(types::RefundSyncType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: mpgs::RefundResponse = res.response .parse_struct("mpgs RefundSyncResponse") .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 Mpgs { 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> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } static MPGS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(SupportedPaymentMethods::new); static MPGS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Mpgs", description: "Mpgs connector", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Alpha, }; static MPGS_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; impl ConnectorSpecifications for Mpgs { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&MPGS_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*MPGS_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&MPGS_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/mpgs.rs
hyperswitch_connectors
full_file
4,748
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct SantanderDebtor { pub cpf: Secret<String>, #[serde(rename = "nome")] pub name: Secret<String>, }
crates/hyperswitch_connectors/src/connectors/santander/transformers.rs
hyperswitch_connectors
struct_definition
31
rust
SantanderDebtor
null
null
null
null
null
null
null
null
null
null
null
pub fn get_tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge }
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
hyperswitch_domain_models
function_signature
26
rust
null
null
null
null
get_tax_on_surcharge
null
null
null
null
null
null
null
impl ConnectorValidation for Airwallex {}
crates/hyperswitch_connectors/src/connectors/airwallex.rs
hyperswitch_connectors
impl_block
8
rust
null
Airwallex
ConnectorValidation for
impl ConnectorValidation for for Airwallex
null
null
null
null
null
null
null
null
pub struct BraintreeRefundTransaction { pub refund: BraintreeRefundTransactionBody, }
crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
hyperswitch_connectors
struct_definition
20
rust
BraintreeRefundTransaction
null
null
null
null
null
null
null
null
null
null
null
OpenAPI Block Path: components.schemas.TokenizePaymentMethodRequest { "type": "object", "properties": { "card_cvc": { "type": "string", "description": "The CVC number for the card", "example": "242", "nullable": true } } }
./hyperswitch/api-reference/v1/openapi_spec_v1.json
null
openapi_block
74
.json
null
null
null
null
null
openapi_spec
components
[ "schemas", "TokenizePaymentMethodRequest" ]
null
null
null
null