Dataset Viewer
Auto-converted to Parquet
text
stringlengths
65
57.3k
file_path
stringlengths
22
92
module
stringclasses
38 values
type
stringclasses
7 values
struct_name
stringlengths
3
60
βŒ€
impl_count
int64
0
60
βŒ€
traits
listlengths
0
59
βŒ€
tokens
int64
16
8.19k
function_name
stringlengths
3
85
βŒ€
type_name
stringlengths
1
67
βŒ€
trait_name
stringclasses
573 values
method_count
int64
0
31
βŒ€
public_method_count
int64
0
19
βŒ€
submodule_count
int64
0
56
βŒ€
export_count
int64
0
9
βŒ€
// Struct: CustomerBankAccountResponse // File: crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct CustomerBankAccountResponse
crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs
hyperswitch_connectors
struct_definition
CustomerBankAccountResponse
0
[]
50
null
null
null
null
null
null
null
// File: crates/hyperswitch_connectors/src/connectors/custombilling.rs // Module: hyperswitch_connectors // Public functions: 1 // Public structs: 1 pub mod transformers; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ 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::{PaymentsResponseData, RefundsResponseData}, 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 transformers as custombilling; use crate::{constants::headers, types::ResponseRouterData, utils}; #[derive(Clone)] pub struct Custombilling { amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), } impl Custombilling { pub fn new() -> &'static Self { &Self { amount_converter: &StringMinorUnitForConnector, } } } impl api::Payment for Custombilling {} impl api::PaymentSession for Custombilling {} impl api::ConnectorAccessToken for Custombilling {} impl api::MandateSetup for Custombilling {} impl api::PaymentAuthorize for Custombilling {} impl api::PaymentSync for Custombilling {} impl api::PaymentCapture for Custombilling {} impl api::PaymentVoid for Custombilling {} impl api::Refund for Custombilling {} impl api::RefundExecute for Custombilling {} impl api::RefundSync for Custombilling {} impl api::PaymentToken for Custombilling {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Custombilling { // Not Implemented (R) } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Custombilling 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 Custombilling { fn id(&self) -> &'static str { "custombilling" } 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 { "" } fn get_auth_header( &self, _auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { Ok(vec![]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: custombilling::CustombillingErrorResponse = res .response .parse_struct("CustombillingErrorResponse") .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 Custombilling { //TODO: implement functions when support enabled } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Custombilling { //TODO: implement sessions flow } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Custombilling {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Custombilling { } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Custombilling { 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 = custombilling::CustombillingRouterData::from((amount, req)); let connector_req = custombilling::CustombillingPaymentsRequest::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: custombilling::CustombillingPaymentsResponse = res .response .parse_struct("Custombilling 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 Custombilling { 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: custombilling::CustombillingPaymentsResponse = res .response .parse_struct("custombilling 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 Custombilling { 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: custombilling::CustombillingPaymentsResponse = res .response .parse_struct("Custombilling 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 Custombilling {} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Custombilling { 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 = custombilling::CustombillingRouterData::from((refund_amount, req)); let connector_req = custombilling::CustombillingRefundRequest::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: custombilling::RefundResponse = res .response .parse_struct("custombilling 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 Custombilling { 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: custombilling::RefundResponse = res .response .parse_struct("custombilling 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 Custombilling { 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)) } } impl ConnectorSpecifications for Custombilling {}
crates/hyperswitch_connectors/src/connectors/custombilling.rs
hyperswitch_connectors
full_file
null
null
null
4,258
null
null
null
null
null
null
null
// Struct: AffirmCancelRequest // File: crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct AffirmCancelRequest
crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs
hyperswitch_connectors
struct_definition
AffirmCancelRequest
0
[]
50
null
null
null
null
null
null
null
// Function: payment_methods_session_delete_payment_method // File: crates/router/src/core/payment_methods.rs // Module: router pub fn payment_methods_session_delete_payment_method( state: SessionState, merchant_context: domain::MerchantContext, profile: domain::Profile, pm_id: id_type::GlobalPaymentMethodId, payment_method_session_id: id_type::GlobalPaymentMethodSessionId, ) -> RouterResponse<api::PaymentMethodDeleteResponse>
crates/router/src/core/payment_methods.rs
router
function_signature
null
null
null
96
payment_methods_session_delete_payment_method
null
null
null
null
null
null
// File: crates/router/src/core/payments/operations/payment_reject.rs // Module: router // Public structs: 1 use std::marker::PhantomData; use api_models::{enums::FrmSuggestion, payments::PaymentsCancelRequest}; use async_trait::async_trait; use error_stack::ResultExt; use router_derive; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{helpers, operations, PaymentAddress, PaymentData}, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ api::{self, PaymentIdTypeExt}, domain, storage::{self, enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, router_derive::PaymentOperation)] #[operation(operations = "all", flow = "cancel")] pub struct PaymentReject; type PaymentRejectOperation<'b, F> = BoxedOperation<'b, F, PaymentsCancelRequest, PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for PaymentReject { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, _request: &PaymentsCancelRequest, merchant_context: &domain::MerchantContext, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsCancelRequest, PaymentData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, merchant_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; helpers::validate_payment_status_against_not_allowed_statuses( payment_intent.status, &[ enums::IntentStatus::Cancelled, enums::IntentStatus::Failed, enums::IntentStatus::Succeeded, enums::IntentStatus::Processing, ], "reject", )?; let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, attempt_id.clone().as_str(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let shipping_address = helpers::get_address_by_id( state, payment_intent.shipping_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let payment_method_billing = helpers::get_address_by_id( state, payment_attempt.payment_method_billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let currency = payment_attempt.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount().into(); let frm_response = if cfg!(feature = "frm") { db.find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_context.get_merchant_account().get_id().clone()) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {attempt_id}", merchant_context.get_merchant_account().get_id()) }) .ok() } else { None }; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; 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(), })?; let payment_data = PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount, email: None, mandate_id: None, mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, address: PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ), token_data: None, confirm: None, payment_method_data: None, payment_method_token: None, payment_method_info: None, force_sync: None, all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: None, creds_identifier: None, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, redirect_response: None, surcharge_details: None, frm_message: frm_response, payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], authentication: None, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, whole_connector_response: None, is_manual_retry_enabled: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, PaymentsCancelRequest> for PaymentReject { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, req_state: ReqState, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, _should_decline_transaction: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(PaymentRejectOperation<'b, F>, PaymentData<F>)> where F: 'b + Send, { let intent_status_update = storage::PaymentIntentUpdate::RejectUpdate { status: enums::IntentStatus::Failed, merchant_decision: Some(enums::MerchantDecision::Rejected.to_string()), updated_by: storage_scheme.to_string(), }; let (error_code, error_message) = payment_data .frm_message .clone() .map_or((None, None), |fraud_check| { ( Some(Some(fraud_check.frm_status.to_string())), Some(fraud_check.frm_reason.map(|reason| reason.to_string())), ) }); let attempt_status_update = storage::PaymentAttemptUpdate::RejectUpdate { status: enums::AttemptStatus::Failure, error_code, error_message, updated_by: storage_scheme.to_string(), }; payment_data.payment_intent = state .store .update_payment_intent( &state.into(), payment_data.payment_intent, intent_status_update, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_data.payment_attempt = state .store .update_payment_attempt_with_attempt_id( payment_data.payment_attempt.clone(), attempt_status_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let error_code = payment_data.payment_attempt.error_code.clone(); let error_message = payment_data.payment_attempt.error_message.clone(); req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentReject { error_code, error_message, })) .with(payment_data.to_event()) .emit(); Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, PaymentsCancelRequest, PaymentData<F>> for PaymentReject { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &PaymentsCancelRequest, merchant_context: &'a domain::MerchantContext, ) -> RouterResult<(PaymentRejectOperation<'b, F>, operations::ValidateResult)> { Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()), storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: false, }, )) } }
crates/router/src/core/payments/operations/payment_reject.rs
router
full_file
null
null
null
2,250
null
null
null
null
null
null
null
// Struct: BitpayPaymentsRequest // File: crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct BitpayPaymentsRequest
crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs
hyperswitch_connectors
struct_definition
BitpayPaymentsRequest
0
[]
49
null
null
null
null
null
null
null
// File: crates/hyperswitch_connectors/src/connectors/paystack.rs // Module: hyperswitch_connectors // Public functions: 1 // Public structs: 1 pub mod transformers; use std::sync::LazyLock; use common_enums::enums; use common_utils::{ crypto, errors::CustomResult, ext_traits::{ByteSliceExt, BytesExt}, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; use error_stack::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}, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, 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 paystack; use crate::{constants::headers, types::ResponseRouterData, utils}; #[derive(Clone)] pub struct Paystack { amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), } impl Paystack { pub fn new() -> &'static Self { &Self { amount_converter: &MinorUnitForConnector, } } } impl api::Payment for Paystack {} impl api::PaymentSession for Paystack {} impl api::ConnectorAccessToken for Paystack {} impl api::MandateSetup for Paystack {} impl api::PaymentAuthorize for Paystack {} impl api::PaymentSync for Paystack {} impl api::PaymentCapture for Paystack {} impl api::PaymentVoid for Paystack {} impl api::Refund for Paystack {} impl api::RefundExecute for Paystack {} impl api::RefundSync for Paystack {} impl api::PaymentToken for Paystack {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Paystack { // Not Implemented (R) } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Paystack 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 Paystack { fn id(&self) -> &'static str { "paystack" } 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.paystack.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = paystack::PaystackAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), format!("Bearer {}", auth.api_key.expose()).into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: paystack::PaystackErrorResponse = res .response .parse_struct("PaystackErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let error_message = paystack::get_error_message(response.clone()); Ok(ErrorResponse { status_code: res.status_code, code: response.code, message: error_message, reason: Some(response.message), 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 Paystack { //TODO: implement functions when support enabled } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Paystack { //TODO: implement sessions flow } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Paystack {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Paystack { } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Paystack { 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> { Ok(format!("{}/charge", self.base_url(connectors))) } 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 = paystack::PaystackRouterData::from((amount, req)); let connector_req = paystack::PaystackPaymentsRequest::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: paystack::PaystackPaymentsResponse = res .response .parse_struct("Paystack 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 Paystack { 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 connector_payment_id = req .request .connector_transaction_id .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; Ok(format!( "{}{}{}", self.base_url(connectors), "/transaction/verify/", connector_payment_id, )) } 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: paystack::PaystackPSyncResponse = res .response .parse_struct("paystack 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 Paystack { 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: paystack::PaystackPaymentsResponse = res .response .parse_struct("Paystack 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 Paystack {} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Paystack { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/refund", self.base_url(connectors))) } 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 = paystack::PaystackRouterData::from((refund_amount, req)); let connector_req = paystack::PaystackRefundRequest::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: paystack::PaystackRefundsResponse = res .response .parse_struct("paystack 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 Paystack { fn get_headers( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_refund_id = req .request .connector_refund_id .clone() .ok_or(errors::ConnectorError::MissingConnectorRefundID)?; Ok(format!( "{}{}{}", self.base_url(connectors), "/refund/", 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: paystack::PaystackRefundsResponse = res .response .parse_struct("paystack 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 Paystack { fn get_webhook_source_verification_algorithm( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(crypto::HmacSha512)) } fn get_webhook_source_verification_signature( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let signature = utils::get_header_key_value("x-paystack-signature", request.headers) .change_context(errors::ConnectorError::WebhookSignatureNotFound)?; hex::decode(signature) .change_context(errors::ConnectorError::WebhookVerificationSecretInvalid) } 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 message = std::str::from_utf8(request.body) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; Ok(message.to_string().into_bytes()) } fn get_webhook_object_reference_id( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let webhook_body = request .body .parse_struct::<paystack::PaystackWebhookData>("PaystackWebhookData") .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; match webhook_body.data { paystack::PaystackWebhookEventData::Payment(data) => { Ok(api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId(data.reference), )) } paystack::PaystackWebhookEventData::Refund(data) => { Ok(api_models::webhooks::ObjectReferenceId::RefundId( api_models::webhooks::RefundIdType::ConnectorRefundId(data.id), )) } } } fn get_webhook_event_type( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { let webhook_body = request .body .parse_struct::<paystack::PaystackWebhookData>("PaystackWebhookData") .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(api_models::webhooks::IncomingWebhookEvent::from( webhook_body.data, )) } fn get_webhook_resource_object( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let webhook_body = request .body .parse_struct::<paystack::PaystackWebhookData>("PaystackWebhookData") .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(match webhook_body.data { paystack::PaystackWebhookEventData::Payment(payment_webhook_data) => { Box::new(payment_webhook_data) } paystack::PaystackWebhookEventData::Refund(refund_webhook_data) => { Box::new(refund_webhook_data) } }) } } static PAYSTACK_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::SequentialAutomatic, ]; let mut paystack_supported_payment_methods = SupportedPaymentMethods::new(); paystack_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Eft, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods, specific_features: None, }, ); paystack_supported_payment_methods }); static PAYSTACK_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Paystack", description: "Paystack is a Nigerian financial technology company that provides online and offline payment solutions to businesses across Africa.", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Sandbox, }; static PAYSTACK_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] = [enums::EventClass::Payments, enums::EventClass::Refunds]; impl ConnectorSpecifications for Paystack { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&PAYSTACK_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*PAYSTACK_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&PAYSTACK_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/paystack.rs
hyperswitch_connectors
full_file
null
null
null
5,343
null
null
null
null
null
null
null
// File: crates/external_services/src/managers/secrets_management.rs // Module: external_services // Public functions: 2 //! Secrets management util module use common_utils::errors::CustomResult; #[cfg(feature = "hashicorp-vault")] use error_stack::ResultExt; use hyperswitch_interfaces::secrets_interface::{ SecretManagementInterface, SecretsManagementError, }; #[cfg(feature = "aws_kms")] use crate::aws_kms; #[cfg(feature = "hashicorp-vault")] use crate::hashicorp_vault; use crate::no_encryption::core::NoEncryption; /// Enum representing configuration options for secrets management. #[derive(Debug, Clone, Default, serde::Deserialize)] #[serde(tag = "secrets_manager")] #[serde(rename_all = "snake_case")] pub enum SecretsManagementConfig { /// AWS KMS configuration #[cfg(feature = "aws_kms")] AwsKms { /// AWS KMS config aws_kms: aws_kms::core::AwsKmsConfig, }, /// HashiCorp-Vault configuration #[cfg(feature = "hashicorp-vault")] HashiCorpVault { /// HC-Vault config hc_vault: hashicorp_vault::core::HashiCorpVaultConfig, }, /// Variant representing no encryption #[default] NoEncryption, } impl SecretsManagementConfig { /// Verifies that the client configuration is usable pub fn validate(&self) -> Result<(), &'static str> { match self { #[cfg(feature = "aws_kms")] Self::AwsKms { aws_kms } => aws_kms.validate(), #[cfg(feature = "hashicorp-vault")] Self::HashiCorpVault { hc_vault } => hc_vault.validate(), Self::NoEncryption => Ok(()), } } /// Retrieves the appropriate secret management client based on the configuration. pub async fn get_secret_management_client( &self, ) -> CustomResult<Box<dyn SecretManagementInterface>, SecretsManagementError> { match self { #[cfg(feature = "aws_kms")] Self::AwsKms { aws_kms } => { Ok(Box::new(aws_kms::core::AwsKmsClient::new(aws_kms).await)) } #[cfg(feature = "hashicorp-vault")] Self::HashiCorpVault { hc_vault } => { hashicorp_vault::core::HashiCorpVault::new(hc_vault) .change_context(SecretsManagementError::ClientCreationFailed) .map(|inner| -> Box<dyn SecretManagementInterface> { Box::new(inner) }) } Self::NoEncryption => Ok(Box::new(NoEncryption)), } } }
crates/external_services/src/managers/secrets_management.rs
external_services
full_file
null
null
null
593
null
null
null
null
null
null
null
// Struct: RefundBodyResponse // File: crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct RefundBodyResponse
crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs
hyperswitch_connectors
struct_definition
RefundBodyResponse
0
[]
52
null
null
null
null
null
null
null
// Struct: KafkaFraudCheckEvent // File: crates/router/src/services/kafka/fraud_check_event.rs // Module: router // Implementations: 2 // Traits: super::KafkaMessage pub struct KafkaFraudCheckEvent<'a>
crates/router/src/services/kafka/fraud_check_event.rs
router
struct_definition
KafkaFraudCheckEvent
2
[ "super::KafkaMessage" ]
55
null
null
null
null
null
null
null
// File: crates/router/src/types/api/mandates.rs // Module: router use ::payment_methods::controller::PaymentMethodsController; use api_models::mandates; pub use api_models::mandates::{MandateId, MandateResponse, MandateRevokedResponse}; use common_utils::ext_traits::OptionExt; use error_stack::ResultExt; use serde::{Deserialize, Serialize}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payment_methods, }, newtype, routes::SessionState, types::{ api, domain, storage::{self, enums as storage_enums}, }, }; newtype!( pub MandateCardDetails = mandates::MandateCardDetails, derives = (Default, Debug, Deserialize, Serialize) ); #[async_trait::async_trait] pub(crate) trait MandateResponseExt: Sized { async fn from_db_mandate( state: &SessionState, key_store: domain::MerchantKeyStore, mandate: storage::Mandate, merchant_account: &domain::MerchantAccount, ) -> RouterResult<Self>; } #[cfg(feature = "v1")] #[async_trait::async_trait] impl MandateResponseExt for MandateResponse { async fn from_db_mandate( state: &SessionState, key_store: domain::MerchantKeyStore, mandate: storage::Mandate, merchant_account: &domain::MerchantAccount, ) -> RouterResult<Self> { let db = &*state.store; let payment_method = db .find_payment_method( &(state.into()), &key_store, &mandate.payment_method_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; let pm = payment_method .get_payment_method_type() .get_required_value("payment_method") .change_context(errors::ApiErrorResponse::PaymentMethodNotFound) .attach_printable("payment_method not found")?; let card = if pm == storage_enums::PaymentMethod::Card { // if locker is disabled , decrypt the payment method data let card_details = if state.conf.locker.locker_enabled { let card = payment_methods::cards::get_card_from_locker( state, &payment_method.customer_id, &payment_method.merchant_id, payment_method .locker_id .as_ref() .unwrap_or(payment_method.get_id()), ) .await?; payment_methods::transformers::get_card_detail(&payment_method, card) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting card details")? } else { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(merchant_account.clone(), key_store), )); payment_methods::cards::PmCards { state, merchant_context: &merchant_context, } .get_card_details_without_locker_fallback(&payment_method) .await? }; Some(MandateCardDetails::from(card_details).into_inner()) } else { None }; let payment_method_type = payment_method .get_payment_method_subtype() .map(|pmt| pmt.to_string()); let user_agent = mandate.get_user_agent_extended().unwrap_or_default(); Ok(Self { mandate_id: mandate.mandate_id, customer_acceptance: Some(api::payments::CustomerAcceptance { acceptance_type: if mandate.customer_ip_address.is_some() { api::payments::AcceptanceType::Online } else { api::payments::AcceptanceType::Offline }, accepted_at: mandate.customer_accepted_at, online: Some(api::payments::OnlineMandate { ip_address: mandate.customer_ip_address, user_agent, }), }), card, status: mandate.mandate_status, payment_method: pm.to_string(), payment_method_type, payment_method_id: mandate.payment_method_id, }) } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl MandateResponseExt for MandateResponse { async fn from_db_mandate( state: &SessionState, key_store: domain::MerchantKeyStore, mandate: storage::Mandate, merchant_account: &domain::MerchantAccount, ) -> RouterResult<Self> { todo!() } } #[cfg(feature = "v1")] impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails { fn from(card_details_from_locker: api::payment_methods::CardDetailFromLocker) -> Self { mandates::MandateCardDetails { last4_digits: card_details_from_locker.last4_digits, card_exp_month: card_details_from_locker.expiry_month.clone(), card_exp_year: card_details_from_locker.expiry_year.clone(), card_holder_name: card_details_from_locker.card_holder_name, card_token: card_details_from_locker.card_token, scheme: card_details_from_locker.scheme, issuer_country: card_details_from_locker.issuer_country, card_fingerprint: card_details_from_locker.card_fingerprint, card_isin: card_details_from_locker.card_isin, card_issuer: card_details_from_locker.card_issuer, card_network: card_details_from_locker.card_network, card_type: card_details_from_locker.card_type, nick_name: card_details_from_locker.nick_name, } .into() } } #[cfg(feature = "v2")] impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails { fn from(card_details_from_locker: api::payment_methods::CardDetailFromLocker) -> Self { mandates::MandateCardDetails { last4_digits: card_details_from_locker.last4_digits, card_exp_month: card_details_from_locker.expiry_month.clone(), card_exp_year: card_details_from_locker.expiry_year.clone(), card_holder_name: card_details_from_locker.card_holder_name, card_token: None, scheme: None, issuer_country: card_details_from_locker .issuer_country .map(|country| country.to_string()), card_fingerprint: card_details_from_locker.card_fingerprint, card_isin: card_details_from_locker.card_isin, card_issuer: card_details_from_locker.card_issuer, card_network: card_details_from_locker.card_network, card_type: card_details_from_locker .card_type .as_ref() .map(|c| c.to_string()), nick_name: card_details_from_locker.nick_name, } .into() } }
crates/router/src/types/api/mandates.rs
router
full_file
null
null
null
1,451
null
null
null
null
null
null
null
// Struct: ApplicationInformation // File: crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ApplicationInformation
crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
hyperswitch_connectors
struct_definition
ApplicationInformation
0
[]
48
null
null
null
null
null
null
null
// Function: new_list // File: crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs // Module: hyperswitch_connectors pub fn new_list(value: Vec<T>) -> Self
crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs
hyperswitch_connectors
function_signature
null
null
null
49
new_list
null
null
null
null
null
null
// File: crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs // Module: hyperswitch_connectors // Public structs: 26 use common_enums::{enums, CountryAlpha2, Currency}; use common_utils::{pii, request::Method, types::MinorUnit}; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ payment_method_data::{PayLaterData, PaymentMethodData}, router_data::{ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::{PaymentsCancelData, PaymentsCaptureData, ResponseId}, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{PaymentsAuthorizeRequestData, RouterData as OtherRouterData}, }; pub struct AffirmRouterData<T> { pub amount: MinorUnit, pub router_data: T, } impl<T> From<(MinorUnit, T)> for AffirmRouterData<T> { fn from((amount, item): (MinorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Debug, Serialize)] pub struct AffirmPaymentsRequest { pub merchant: Merchant, pub items: Vec<Item>, pub shipping: Option<Shipping>, pub billing: Option<Billing>, pub total: MinorUnit, pub currency: Currency, pub order_id: Option<String>, } #[derive(Debug, Serialize)] pub struct AffirmCompleteAuthorizeRequest { pub order_id: Option<String>, pub reference_id: Option<String>, pub transaction_id: String, } impl TryFrom<&PaymentsCompleteAuthorizeRouterData> for AffirmCompleteAuthorizeRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> { let transaction_id = item.request.connector_transaction_id.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "connector_transaction_id", }, )?; let reference_id = item.reference_id.clone(); let order_id = item.connector_request_reference_id.clone(); Ok(Self { transaction_id, order_id: Some(order_id), reference_id, }) } } #[derive(Debug, Serialize)] pub struct Merchant { pub public_api_key: Secret<String>, pub user_confirmation_url: String, pub user_cancel_url: String, pub user_confirmation_url_action: Option<String>, pub use_vcn: Option<String>, pub name: Option<String>, } #[derive(Debug, Serialize)] pub struct Item { pub display_name: String, pub sku: String, pub unit_price: MinorUnit, pub qty: i64, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Shipping { pub name: Name, pub address: Address, #[serde(skip_serializing_if = "Option::is_none")] pub phone_number: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub email: Option<pii::Email>, } #[derive(Debug, Serialize)] pub struct Billing { pub name: Name, pub address: Address, #[serde(skip_serializing_if = "Option::is_none")] pub phone_number: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub email: Option<pii::Email>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Name { pub first: Option<Secret<String>>, pub last: Option<Secret<String>>, pub full: Option<Secret<String>>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Address { pub line1: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub line2: Option<Secret<String>>, pub city: Option<String>, pub state: Option<Secret<String>>, pub zipcode: Option<Secret<String>>, pub country: Option<CountryAlpha2>, } #[derive(Debug, Serialize)] pub struct Metadata { #[serde(skip_serializing_if = "Option::is_none")] pub shipping_type: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub entity_name: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub platform_type: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub platform_version: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub platform_affirm: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub webhook_session_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub mode: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub customer: Option<Value>, #[serde(skip_serializing_if = "Option::is_none")] pub itinerary: Option<Vec<Value>>, #[serde(skip_serializing_if = "Option::is_none")] pub checkout_channel_type: Option<String>, #[serde(rename = "BOPIS", skip_serializing_if = "Option::is_none")] pub bopis: Option<bool>, } #[derive(Debug, Serialize)] pub struct Discount { pub discount_amount: MinorUnit, pub discount_display_name: String, pub discount_code: Option<String>, } impl TryFrom<&AffirmRouterData<&PaymentsAuthorizeRouterData>> for AffirmPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &AffirmRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let router_data = &item.router_data; let request = &router_data.request; let billing = Some(Billing { name: Name { first: item.router_data.get_optional_billing_first_name(), last: item.router_data.get_optional_billing_last_name(), full: item.router_data.get_optional_billing_full_name(), }, address: Address { line1: item.router_data.get_optional_billing_line1(), line2: item.router_data.get_optional_billing_line2(), city: item.router_data.get_optional_billing_city(), state: item.router_data.get_optional_billing_state(), zipcode: item.router_data.get_optional_billing_zip(), country: item.router_data.get_optional_billing_country(), }, phone_number: item.router_data.get_optional_billing_phone_number(), email: item.router_data.get_optional_billing_email(), }); let shipping = Some(Shipping { name: Name { first: item.router_data.get_optional_shipping_first_name(), last: item.router_data.get_optional_shipping_last_name(), full: item.router_data.get_optional_shipping_full_name(), }, address: Address { line1: item.router_data.get_optional_shipping_line1(), line2: item.router_data.get_optional_shipping_line2(), city: item.router_data.get_optional_shipping_city(), state: item.router_data.get_optional_shipping_state(), zipcode: item.router_data.get_optional_shipping_zip(), country: item.router_data.get_optional_shipping_country(), }, phone_number: item.router_data.get_optional_shipping_phone_number(), email: item.router_data.get_optional_shipping_email(), }); match request.payment_method_data.clone() { PaymentMethodData::PayLater(PayLaterData::AffirmRedirect {}) => { let items = match request.order_details.clone() { Some(order_details) => order_details .iter() .map(|data| { Ok(Item { display_name: data.product_name.clone(), sku: data.product_id.clone().unwrap_or_default(), unit_price: data.amount, qty: data.quantity.into(), }) }) .collect::<Result<Vec<_>, _>>(), None => Err(report!(errors::ConnectorError::MissingRequiredField { field_name: "order_details", })), }?; let auth_type = AffirmAuthType::try_from(&item.router_data.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let public_api_key = auth_type.public_key; let merchant = Merchant { public_api_key, user_confirmation_url: request.get_complete_authorize_url()?, user_cancel_url: request.get_router_return_url()?, user_confirmation_url_action: None, use_vcn: None, name: None, }; Ok(Self { merchant, items, shipping, billing, total: item.amount, currency: request.currency, order_id: Some(item.router_data.connector_request_reference_id.clone()), }) } _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } pub struct AffirmAuthType { pub public_key: Secret<String>, pub private_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for AffirmAuthType { 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 { public_key: api_key.to_owned(), private_key: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } impl From<AffirmTransactionStatus> for common_enums::AttemptStatus { fn from(item: AffirmTransactionStatus) -> Self { match item { AffirmTransactionStatus::Authorized => Self::Authorized, AffirmTransactionStatus::AuthExpired => Self::Failure, AffirmTransactionStatus::Canceled => Self::Voided, AffirmTransactionStatus::Captured => Self::Charged, AffirmTransactionStatus::ConfirmationExpired => Self::Failure, AffirmTransactionStatus::Confirmed => Self::Authorized, AffirmTransactionStatus::Created => Self::Pending, AffirmTransactionStatus::Declined => Self::Failure, AffirmTransactionStatus::Disputed => Self::Unresolved, AffirmTransactionStatus::DisputeRefunded => Self::Unresolved, AffirmTransactionStatus::ExpiredAuthorization => Self::Failure, AffirmTransactionStatus::ExpiredConfirmation => Self::Failure, AffirmTransactionStatus::PartiallyCaptured => Self::Charged, AffirmTransactionStatus::Voided => Self::Voided, AffirmTransactionStatus::PartiallyVoided => Self::Voided, } } } impl From<AffirmRefundStatus> for common_enums::RefundStatus { fn from(item: AffirmRefundStatus) -> Self { match item { AffirmRefundStatus::PartiallyRefunded => Self::Success, AffirmRefundStatus::Refunded => Self::Success, } } } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct AffirmPaymentsResponse { checkout_id: String, redirect_url: String, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct AffirmCompleteAuthorizeResponse { pub id: String, pub status: AffirmTransactionStatus, pub amount: MinorUnit, pub amount_refunded: MinorUnit, pub authorization_expiration: String, pub checkout_id: String, pub created: String, pub currency: Currency, pub events: Vec<TransactionEvent>, pub settlement_transaction_id: Option<String>, pub transaction_id: String, pub order_id: String, pub shipping_carrier: Option<String>, pub shipping_confirmation: Option<String>, pub shipping: Option<Shipping>, pub agent_alias: Option<String>, pub merchant_transaction_id: Option<String>, pub provider_id: Option<i64>, pub remove_tax: Option<bool>, pub checkout: Option<Value>, pub refund_expires: Option<String>, pub remaining_capturable_amount: Option<i64>, pub loan_information: Option<LoanInformation>, pub user_id: Option<String>, pub platform: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct TransactionEvent { pub id: String, pub amount: MinorUnit, pub created: String, pub currency: Currency, pub fee: Option<i64>, pub fee_refunded: Option<MinorUnit>, pub reference_id: Option<String>, #[serde(rename = "type")] pub event_type: AffirmEventType, pub settlement_transaction_id: Option<String>, pub transaction_id: String, pub order_id: String, pub shipping_carrier: Option<String>, pub shipping_confirmation: Option<String>, pub shipping: Option<Shipping>, pub agent_alias: Option<String>, pub merchant_transaction_id: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct LoanInformation { pub fees: Option<LoanFees>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct LoanFees { pub amount: Option<MinorUnit>, pub description: Option<String>, } #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum AffirmTransactionStatus { Authorized, AuthExpired, Canceled, Captured, ConfirmationExpired, Confirmed, Created, Declined, Disputed, DisputeRefunded, ExpiredAuthorization, ExpiredConfirmation, PartiallyCaptured, Voided, PartiallyVoided, } #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum AffirmRefundStatus { PartiallyRefunded, Refunded, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct AffirmPSyncResponse { pub amount: MinorUnit, pub amount_refunded: MinorUnit, pub authorization_expiration: Option<String>, pub checkout_id: String, pub created: String, pub currency: Currency, pub events: Vec<TransactionEvent>, pub id: String, pub order_id: String, pub provider_id: Option<i64>, pub remove_tax: Option<bool>, pub status: AffirmTransactionStatus, pub checkout: Option<Value>, pub refund_expires: Option<String>, pub remaining_capturable_amount: Option<MinorUnit>, pub loan_information: Option<LoanInformation>, pub shipping_carrier: Option<String>, pub shipping_confirmation: Option<String>, pub shipping: Option<Shipping>, pub merchant_transaction_id: Option<String>, pub settlement_transaction_id: Option<String>, pub transaction_id: String, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct AffirmRsyncResponse { pub amount: MinorUnit, pub amount_refunded: MinorUnit, pub authorization_expiration: String, pub checkout_id: String, pub created: String, pub currency: Currency, pub events: Vec<TransactionEvent>, pub id: String, pub order_id: String, pub status: AffirmRefundStatus, pub refund_expires: Option<String>, pub remaining_capturable_amount: Option<MinorUnit>, pub shipping_carrier: Option<String>, pub shipping_confirmation: Option<String>, pub shipping: Option<Shipping>, pub merchant_transaction_id: Option<String>, pub settlement_transaction_id: Option<String>, pub transaction_id: String, } #[derive(Debug, Serialize, Deserialize)] #[serde(untagged)] pub enum AffirmResponseWrapper { Authorize(AffirmPaymentsResponse), Psync(Box<AffirmPSyncResponse>), } impl<F, T> TryFrom<ResponseRouterData<F, AffirmResponseWrapper, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, AffirmResponseWrapper, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { match &item.response { AffirmResponseWrapper::Authorize(resp) => { let redirection_data = url::Url::parse(&resp.redirect_url) .ok() .map(|url| RedirectForm::from((url, Method::Get))); Ok(Self { status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(resp.checkout_id.clone()), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, charges: None, incremental_authorization_allowed: None, }), ..item.data }) } AffirmResponseWrapper::Psync(resp) => { let status = enums::AttemptStatus::from(resp.status); Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(resp.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, charges: None, incremental_authorization_allowed: None, }), ..item.data }) } } } } impl<F, T> TryFrom<ResponseRouterData<F, AffirmCompleteAuthorizeResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, AffirmCompleteAuthorizeResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: common_enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.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 }) } } #[derive(Default, Debug, Serialize)] pub struct AffirmRefundRequest { pub amount: MinorUnit, #[serde(skip_serializing_if = "Option::is_none")] pub reference_id: Option<String>, } impl<F> TryFrom<&AffirmRouterData<&RefundsRouterData<F>>> for AffirmRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &AffirmRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { let reference_id = item.router_data.request.connector_transaction_id.clone(); Ok(Self { amount: item.amount.to_owned(), reference_id: Some(reference_id), }) } } #[allow(dead_code)] #[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct AffirmRefundResponse { pub id: String, pub amount: MinorUnit, pub created: String, pub currency: Currency, pub fee: Option<MinorUnit>, pub fee_refunded: Option<MinorUnit>, pub reference_id: Option<String>, #[serde(rename = "type")] pub event_type: AffirmEventType, pub settlement_transaction_id: Option<String>, pub transaction_id: String, pub order_id: String, pub shipping_carrier: Option<String>, pub shipping_confirmation: Option<String>, pub shipping: Option<Shipping>, pub agent_alias: Option<String>, pub merchant_transaction_id: Option<String>, } impl From<AffirmEventType> for enums::RefundStatus { fn from(event_type: AffirmEventType) -> Self { match event_type { AffirmEventType::Refund => Self::Success, _ => Self::Pending, } } } impl TryFrom<RefundsResponseRouterData<Execute, AffirmRefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, AffirmRefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.event_type), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, AffirmRsyncResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, AffirmRsyncResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct AffirmErrorResponse { pub status_code: u16, pub code: String, pub message: String, #[serde(rename = "type")] pub error_type: String, } #[derive(Debug, Serialize)] pub struct AffirmCaptureRequest { pub order_id: Option<String>, pub reference_id: Option<String>, pub amount: MinorUnit, pub shipping_carrier: Option<String>, pub shipping_confirmation: Option<String>, } impl TryFrom<&AffirmRouterData<&PaymentsCaptureRouterData>> for AffirmCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &AffirmRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> { let reference_id = match item.router_data.connector_request_reference_id.clone() { ref_id if ref_id.is_empty() => None, ref_id => Some(ref_id), }; let amount = item.amount; Ok(Self { reference_id, amount, order_id: None, shipping_carrier: None, shipping_confirmation: None, }) } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct AffirmCaptureResponse { pub id: String, pub amount: MinorUnit, pub created: String, pub currency: Currency, pub fee: Option<MinorUnit>, pub fee_refunded: Option<MinorUnit>, pub reference_id: Option<String>, #[serde(rename = "type")] pub event_type: AffirmEventType, pub settlement_transaction_id: Option<String>, pub transaction_id: String, pub order_id: String, pub shipping_carrier: Option<String>, pub shipping_confirmation: Option<String>, pub shipping: Option<Shipping>, pub agent_alias: Option<String>, pub merchant_transaction_id: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum AffirmEventType { Auth, AuthExpired, Capture, ChargeOff, Confirm, ConfirmationExpired, ExpireAuthorization, ExpireConfirmation, Refund, SplitCapture, Update, Void, PartialVoid, RefundVoided, } impl From<AffirmEventType> for enums::AttemptStatus { fn from(event_type: AffirmEventType) -> Self { match event_type { AffirmEventType::Auth => Self::Authorized, AffirmEventType::Capture | AffirmEventType::SplitCapture | AffirmEventType::Confirm => { Self::Charged } AffirmEventType::AuthExpired | AffirmEventType::ChargeOff | AffirmEventType::ConfirmationExpired | AffirmEventType::ExpireAuthorization | AffirmEventType::ExpireConfirmation => Self::Failure, AffirmEventType::Refund | AffirmEventType::RefundVoided => Self::AutoRefunded, AffirmEventType::Update => Self::Pending, AffirmEventType::Void | AffirmEventType::PartialVoid => Self::Voided, } } } impl<F> TryFrom<ResponseRouterData<F, AffirmCaptureResponse, PaymentsCaptureData, PaymentsResponseData>> for RouterData<F, PaymentsCaptureData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, AffirmCaptureResponse, PaymentsCaptureData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::from(item.response.event_type.clone()), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.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 }) } } impl TryFrom<&PaymentsCancelRouterData> for AffirmCancelRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { let request = &item.request; let reference_id = request.connector_transaction_id.clone(); let amount = item .request .amount .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "amount", })?; Ok(Self { reference_id: Some(reference_id), amount, merchant_transaction_id: None, }) } } #[derive(Debug, Serialize)] pub struct AffirmCancelRequest { pub reference_id: Option<String>, pub amount: i64, pub merchant_transaction_id: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct AffirmCancelResponse { pub id: String, pub amount: MinorUnit, pub created: String, pub currency: Currency, pub fee: Option<MinorUnit>, pub fee_refunded: Option<MinorUnit>, pub reference_id: Option<String>, #[serde(rename = "type")] pub event_type: AffirmEventType, pub settlement_transaction_id: Option<String>, pub transaction_id: String, pub order_id: String, pub shipping_carrier: Option<String>, pub shipping_confirmation: Option<String>, pub shipping: Option<Shipping>, pub agent_alias: Option<String>, pub merchant_transaction_id: Option<String>, } impl<F> TryFrom<ResponseRouterData<F, AffirmCancelResponse, PaymentsCancelData, PaymentsResponseData>> for RouterData<F, PaymentsCancelData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, AffirmCancelResponse, PaymentsCancelData, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::from(item.response.event_type.clone()), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.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 }) } }
crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs
hyperswitch_connectors
full_file
null
null
null
6,110
null
null
null
null
null
null
null
// Struct: ClientAuthCheckInfoResponse // File: crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ClientAuthCheckInfoResponse
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
hyperswitch_connectors
struct_definition
ClientAuthCheckInfoResponse
0
[]
53
null
null
null
null
null
null
null
// Struct: RoutingDictionaryRecord // File: crates/api_models/src/routing.rs // Module: api_models // Implementations: 0 pub struct RoutingDictionaryRecord
crates/api_models/src/routing.rs
api_models
struct_definition
RoutingDictionaryRecord
0
[]
36
null
null
null
null
null
null
null
// Struct: HipayMaintenanceRequest // File: crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct HipayMaintenanceRequest
crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs
hyperswitch_connectors
struct_definition
HipayMaintenanceRequest
0
[]
50
null
null
null
null
null
null
null
// Struct: GlobalpayCaptureRequest // File: crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct GlobalpayCaptureRequest
crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs
hyperswitch_connectors
struct_definition
GlobalpayCaptureRequest
0
[]
48
null
null
null
null
null
null
null
// Implementation: impl MandateSetup for for Threedsecureio // File: crates/hyperswitch_connectors/src/connectors/threedsecureio.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl MandateSetup for for Threedsecureio
crates/hyperswitch_connectors/src/connectors/threedsecureio.rs
hyperswitch_connectors
impl_block
null
null
null
61
null
Threedsecureio
MandateSetup for
0
0
null
null
// Function: get_card_details_from_locker // File: crates/router/src/core/payment_methods/cards.rs // Module: router pub fn get_card_details_from_locker( state: &routes::SessionState, pm: &domain::PaymentMethod, ) -> errors::RouterResult<api::CardDetailFromLocker>
crates/router/src/core/payment_methods/cards.rs
router
function_signature
null
null
null
68
get_card_details_from_locker
null
null
null
null
null
null
// Function: retrieve_file_and_provider_file_id_from_file_id // File: crates/router/src/core/files/helpers.rs // Module: router pub fn retrieve_file_and_provider_file_id_from_file_id( state: &SessionState, file_id: Option<String>, dispute_id: Option<String>, merchant_context: &domain::MerchantContext, is_connector_file_data_required: api::FileDataRequired, ) -> CustomResult<FileInfo, errors::ApiErrorResponse>
crates/router/src/core/files/helpers.rs
router
function_signature
null
null
null
97
retrieve_file_and_provider_file_id_from_file_id
null
null
null
null
null
null
// Function: set_debit_routing_savings // File: crates/hyperswitch_domain_models/src/payments/payment_attempt.rs // Module: hyperswitch_domain_models pub fn set_debit_routing_savings(&mut self, debit_routing_savings: Option<&MinorUnit>)
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
hyperswitch_domain_models
function_signature
null
null
null
57
set_debit_routing_savings
null
null
null
null
null
null
// Struct: NmiValidateRequest // File: crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct NmiValidateRequest
crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
hyperswitch_connectors
struct_definition
NmiValidateRequest
0
[]
49
null
null
null
null
null
null
null
// Struct: SignedKey // File: crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct SignedKey
crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
hyperswitch_connectors
struct_definition
SignedKey
0
[]
46
null
null
null
null
null
null
null
// Struct: ResponseIndicators // File: crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ResponseIndicators
crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
hyperswitch_connectors
struct_definition
ResponseIndicators
0
[]
48
null
null
null
null
null
null
null
// Implementation: impl api::ConnectorAccessToken for for Paypal // File: crates/hyperswitch_connectors/src/connectors/paypal.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::ConnectorAccessToken for for Paypal
crates/hyperswitch_connectors/src/connectors/paypal.rs
hyperswitch_connectors
impl_block
null
null
null
55
null
Paypal
api::ConnectorAccessToken for
0
0
null
null
// Function: get_default_global_tenant_id // File: crates/common_utils/src/id_type/tenant.rs // Module: common_utils // Documentation: Get the default global tenant ID pub fn get_default_global_tenant_id() -> Self
crates/common_utils/src/id_type/tenant.rs
common_utils
function_signature
null
null
null
50
get_default_global_tenant_id
null
null
null
null
null
null
// File: crates/hyperswitch_connectors/src/connectors/aci/transformers.rs // Module: hyperswitch_connectors // Public structs: 33 use std::str::FromStr; use common_enums::enums; use common_utils::{id_type, pii::Email, request::Method, types::StringMajorUnit}; use error_stack::report; use hyperswitch_domain_models::{ network_tokenization::NetworkTokenNumber, payment_method_data::{ BankRedirectData, Card, NetworkTokenData, PayLaterData, PaymentMethodData, WalletData, }, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::SetupMandate, router_request_types::{ PaymentsAuthorizeData, PaymentsCancelData, PaymentsSyncData, ResponseId, SetupMandateRequestData, }, router_response_types::{ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::errors; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use url::Url; use super::aci_result_codes::{FAILURE_CODES, PENDING_CODES, SUCCESSFUL_CODES}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ self, CardData, NetworkTokenData as NetworkTokenDataTrait, PaymentsAuthorizeRequestData, PhoneDetailsData, RouterData as _, }, }; type Error = error_stack::Report<errors::ConnectorError>; trait GetCaptureMethod { fn get_capture_method(&self) -> Option<enums::CaptureMethod>; } impl GetCaptureMethod for PaymentsAuthorizeData { fn get_capture_method(&self) -> Option<enums::CaptureMethod> { self.capture_method } } impl GetCaptureMethod for PaymentsSyncData { fn get_capture_method(&self) -> Option<enums::CaptureMethod> { self.capture_method } } impl GetCaptureMethod for PaymentsCancelData { fn get_capture_method(&self) -> Option<enums::CaptureMethod> { None } } #[derive(Debug, Serialize)] pub struct AciRouterData<T> { pub amount: StringMajorUnit, pub router_data: T, } impl<T> From<(StringMajorUnit, T)> for AciRouterData<T> { fn from((amount, item): (StringMajorUnit, T)) -> Self { Self { amount, router_data: item, } } } pub struct AciAuthType { pub api_key: Secret<String>, pub entity_id: Secret<String>, } impl TryFrom<&ConnectorAuthType> for AciAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &ConnectorAuthType) -> Result<Self, Self::Error> { if let ConnectorAuthType::BodyKey { api_key, key1 } = item { Ok(Self { api_key: api_key.to_owned(), entity_id: key1.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? } } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum AciRecurringType { Initial, Repeated, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AciPaymentsRequest { #[serde(flatten)] pub txn_details: TransactionDetails, #[serde(flatten)] pub payment_method: PaymentDetails, #[serde(flatten)] pub instruction: Option<Instruction>, pub shopper_result_url: Option<String>, #[serde(rename = "customParameters[3DS2_enrolled]")] pub three_ds_two_enrolled: Option<bool>, pub recurring_type: Option<AciRecurringType>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct TransactionDetails { pub entity_id: Secret<String>, pub amount: StringMajorUnit, pub currency: String, pub payment_type: AciPaymentType, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AciCancelRequest { pub entity_id: Secret<String>, pub payment_type: AciPaymentType, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AciMandateRequest { pub entity_id: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub payment_brand: Option<PaymentBrand>, #[serde(flatten)] pub payment_details: PaymentDetails, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AciMandateResponse { pub id: String, pub result: ResultCode, pub build_number: String, pub timestamp: String, } #[derive(Debug, Clone, Serialize)] #[serde(untagged)] pub enum PaymentDetails { #[serde(rename = "card")] AciCard(Box<CardDetails>), BankRedirect(Box<BankRedirectionPMData>), Wallet(Box<WalletPMData>), Klarna, Mandate, AciNetworkToken(Box<AciNetworkTokenData>), } impl TryFrom<(&WalletData, &PaymentsAuthorizeRouterData)> for PaymentDetails { type Error = Error; fn try_from(value: (&WalletData, &PaymentsAuthorizeRouterData)) -> Result<Self, Self::Error> { let (wallet_data, item) = value; let payment_data = match wallet_data { WalletData::MbWayRedirect(_) => { let phone_details = item.get_billing_phone()?; Self::Wallet(Box::new(WalletPMData { payment_brand: PaymentBrand::Mbway, account_id: Some(phone_details.get_number_with_hash_country_code()?), })) } WalletData::AliPayRedirect { .. } => Self::Wallet(Box::new(WalletPMData { payment_brand: PaymentBrand::AliPay, account_id: None, })), WalletData::AliPayHkRedirect(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::AmazonPay(_) | WalletData::ApplePay(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect { .. } | WalletData::GooglePay(_) | WalletData::BluecodeRedirect {} | WalletData::GooglePayThirdPartySdk(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect { .. } | WalletData::VippsRedirect { .. } | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::AliPayQr(_) | WalletData::ApplePayRedirect(_) | WalletData::GooglePayRedirect(_) | WalletData::Mifinity(_) | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( "Payment method".to_string(), ))?, }; Ok(payment_data) } } impl TryFrom<( &AciRouterData<&PaymentsAuthorizeRouterData>, &BankRedirectData, )> for PaymentDetails { type Error = Error; fn try_from( value: ( &AciRouterData<&PaymentsAuthorizeRouterData>, &BankRedirectData, ), ) -> Result<Self, Self::Error> { let (item, bank_redirect_data) = value; let payment_data = match bank_redirect_data { BankRedirectData::Eps { .. } => Self::BankRedirect(Box::new(BankRedirectionPMData { payment_brand: PaymentBrand::Eps, bank_account_country: Some(item.router_data.get_billing_country()?), bank_account_bank_name: None, bank_account_bic: None, bank_account_iban: None, billing_country: None, merchant_customer_id: None, merchant_transaction_id: None, customer_email: None, })), BankRedirectData::Eft { .. } => Self::BankRedirect(Box::new(BankRedirectionPMData { payment_brand: PaymentBrand::Eft, bank_account_country: Some(item.router_data.get_billing_country()?), bank_account_bank_name: None, bank_account_bic: None, bank_account_iban: None, billing_country: None, merchant_customer_id: None, merchant_transaction_id: None, customer_email: None, })), BankRedirectData::Giropay { bank_account_bic, bank_account_iban, .. } => Self::BankRedirect(Box::new(BankRedirectionPMData { payment_brand: PaymentBrand::Giropay, bank_account_country: Some(item.router_data.get_billing_country()?), bank_account_bank_name: None, bank_account_bic: bank_account_bic.clone(), bank_account_iban: bank_account_iban.clone(), billing_country: None, merchant_customer_id: None, merchant_transaction_id: None, customer_email: None, })), BankRedirectData::Ideal { bank_name, .. } => { Self::BankRedirect(Box::new(BankRedirectionPMData { payment_brand: PaymentBrand::Ideal, bank_account_country: Some(item.router_data.get_billing_country()?), bank_account_bank_name: Some(bank_name.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "ideal.bank_name", }, )?), bank_account_bic: None, bank_account_iban: None, billing_country: None, merchant_customer_id: None, merchant_transaction_id: None, customer_email: None, })) } BankRedirectData::Sofort { .. } => { Self::BankRedirect(Box::new(BankRedirectionPMData { payment_brand: PaymentBrand::Sofortueberweisung, bank_account_country: Some(item.router_data.get_billing_country()?), bank_account_bank_name: None, bank_account_bic: None, bank_account_iban: None, billing_country: None, merchant_customer_id: None, merchant_transaction_id: None, customer_email: None, })) } BankRedirectData::Przelewy24 { .. } => { Self::BankRedirect(Box::new(BankRedirectionPMData { payment_brand: PaymentBrand::Przelewy, bank_account_country: None, bank_account_bank_name: None, bank_account_bic: None, bank_account_iban: None, billing_country: None, merchant_customer_id: None, merchant_transaction_id: None, customer_email: Some(item.router_data.get_billing_email()?), })) } BankRedirectData::Interac { .. } => { Self::BankRedirect(Box::new(BankRedirectionPMData { payment_brand: PaymentBrand::InteracOnline, bank_account_country: Some(item.router_data.get_billing_country()?), bank_account_bank_name: None, bank_account_bic: None, bank_account_iban: None, billing_country: None, merchant_customer_id: None, merchant_transaction_id: None, customer_email: Some(item.router_data.get_billing_email()?), })) } BankRedirectData::Trustly { .. } => { Self::BankRedirect(Box::new(BankRedirectionPMData { payment_brand: PaymentBrand::Trustly, bank_account_country: None, bank_account_bank_name: None, bank_account_bic: None, bank_account_iban: None, billing_country: Some(item.router_data.get_billing_country()?), merchant_customer_id: Some(Secret::new(item.router_data.get_customer_id()?)), merchant_transaction_id: Some(Secret::new( item.router_data.connector_request_reference_id.clone(), )), customer_email: None, })) } BankRedirectData::Bizum { .. } | BankRedirectData::Blik { .. } | BankRedirectData::BancontactCard { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } | BankRedirectData::OnlineBankingFpx { .. } | BankRedirectData::OnlineBankingPoland { .. } | BankRedirectData::OnlineBankingSlovakia { .. } | BankRedirectData::OnlineBankingThailand { .. } | BankRedirectData::LocalBankRedirect {} | BankRedirectData::OpenBankingUk { .. } => Err( errors::ConnectorError::NotImplemented("Payment method".to_string()), )?, }; Ok(payment_data) } } fn get_aci_payment_brand( card_network: Option<common_enums::CardNetwork>, is_network_token_flow: bool, ) -> Result<PaymentBrand, Error> { match card_network { Some(common_enums::CardNetwork::Visa) => Ok(PaymentBrand::Visa), Some(common_enums::CardNetwork::Mastercard) => Ok(PaymentBrand::Mastercard), Some(common_enums::CardNetwork::AmericanExpress) => Ok(PaymentBrand::AmericanExpress), Some(common_enums::CardNetwork::JCB) => Ok(PaymentBrand::Jcb), Some(common_enums::CardNetwork::DinersClub) => Ok(PaymentBrand::DinersClub), Some(common_enums::CardNetwork::Discover) => Ok(PaymentBrand::Discover), Some(common_enums::CardNetwork::UnionPay) => Ok(PaymentBrand::UnionPay), Some(common_enums::CardNetwork::Maestro) => Ok(PaymentBrand::Maestro), Some(unsupported_network) => Err(errors::ConnectorError::NotSupported { message: format!("Card network {unsupported_network} is not supported by ACI"), connector: "ACI", })?, None => { if is_network_token_flow { Ok(PaymentBrand::Visa) } else { Err(errors::ConnectorError::MissingRequiredField { field_name: "card.card_network", } .into()) } } } } impl TryFrom<(Card, Option<Secret<String>>)> for PaymentDetails { type Error = Error; fn try_from( (card_data, card_holder_name): (Card, Option<Secret<String>>), ) -> Result<Self, Self::Error> { let card_expiry_year = card_data.get_expiry_year_4_digit(); let payment_brand = get_aci_payment_brand(card_data.card_network, false).ok(); Ok(Self::AciCard(Box::new(CardDetails { card_number: card_data.card_number, card_holder: card_holder_name.ok_or(errors::ConnectorError::MissingRequiredField { field_name: "card_holder_name", })?, card_expiry_month: card_data.card_exp_month.clone(), card_expiry_year, card_cvv: card_data.card_cvc, payment_brand, }))) } } impl TryFrom<( &AciRouterData<&PaymentsAuthorizeRouterData>, &NetworkTokenData, )> for PaymentDetails { type Error = Error; fn try_from( value: ( &AciRouterData<&PaymentsAuthorizeRouterData>, &NetworkTokenData, ), ) -> Result<Self, Self::Error> { let (_item, network_token_data) = value; let token_number = network_token_data.get_network_token(); let payment_brand = get_aci_payment_brand(network_token_data.card_network.clone(), true)?; let aci_network_token_data = AciNetworkTokenData { token_type: AciTokenAccountType::Network, token_number, token_expiry_month: network_token_data.get_network_token_expiry_month(), token_expiry_year: network_token_data.get_expiry_year_4_digit(), token_cryptogram: Some( network_token_data .get_cryptogram() .clone() .unwrap_or_default(), ), payment_brand, }; Ok(Self::AciNetworkToken(Box::new(aci_network_token_data))) } } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum AciTokenAccountType { Network, } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct AciNetworkTokenData { #[serde(rename = "tokenAccount.type")] pub token_type: AciTokenAccountType, #[serde(rename = "tokenAccount.number")] pub token_number: NetworkTokenNumber, #[serde(rename = "tokenAccount.expiryMonth")] pub token_expiry_month: Secret<String>, #[serde(rename = "tokenAccount.expiryYear")] pub token_expiry_year: Secret<String>, #[serde(rename = "tokenAccount.cryptogram")] pub token_cryptogram: Option<Secret<String>>, #[serde(rename = "paymentBrand")] pub payment_brand: PaymentBrand, } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct BankRedirectionPMData { payment_brand: PaymentBrand, #[serde(rename = "bankAccount.country")] bank_account_country: Option<api_models::enums::CountryAlpha2>, #[serde(rename = "bankAccount.bankName")] bank_account_bank_name: Option<common_enums::BankNames>, #[serde(rename = "bankAccount.bic")] bank_account_bic: Option<Secret<String>>, #[serde(rename = "bankAccount.iban")] bank_account_iban: Option<Secret<String>>, #[serde(rename = "billing.country")] billing_country: Option<api_models::enums::CountryAlpha2>, #[serde(rename = "customer.email")] customer_email: Option<Email>, #[serde(rename = "customer.merchantCustomerId")] merchant_customer_id: Option<Secret<id_type::CustomerId>>, merchant_transaction_id: Option<Secret<String>>, } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct WalletPMData { payment_brand: PaymentBrand, #[serde(rename = "virtualAccount.accountId")] account_id: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaymentBrand { Eps, Eft, Ideal, Giropay, Sofortueberweisung, InteracOnline, Przelewy, Trustly, Mbway, #[serde(rename = "ALIPAY")] AliPay, // Card network brands #[serde(rename = "VISA")] Visa, #[serde(rename = "MASTER")] Mastercard, #[serde(rename = "AMEX")] AmericanExpress, #[serde(rename = "JCB")] Jcb, #[serde(rename = "DINERS")] DinersClub, #[serde(rename = "DISCOVER")] Discover, #[serde(rename = "UNIONPAY")] UnionPay, #[serde(rename = "MAESTRO")] Maestro, } #[derive(Debug, Clone, Eq, PartialEq, Serialize)] pub struct CardDetails { #[serde(rename = "card.number")] pub card_number: cards::CardNumber, #[serde(rename = "card.holder")] pub card_holder: Secret<String>, #[serde(rename = "card.expiryMonth")] pub card_expiry_month: Secret<String>, #[serde(rename = "card.expiryYear")] pub card_expiry_year: Secret<String>, #[serde(rename = "card.cvv")] pub card_cvv: Secret<String>, #[serde(rename = "paymentBrand")] #[serde(skip_serializing_if = "Option::is_none")] pub payment_brand: Option<PaymentBrand>, } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum InstructionMode { Initial, Repeated, } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum InstructionType { Unscheduled, } #[derive(Debug, Clone, Serialize)] pub enum InstructionSource { #[serde(rename = "CIT")] CardholderInitiatedTransaction, #[serde(rename = "MIT")] MerchantInitiatedTransaction, } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct Instruction { #[serde(rename = "standingInstruction.mode")] mode: InstructionMode, #[serde(rename = "standingInstruction.type")] transaction_type: InstructionType, #[serde(rename = "standingInstruction.source")] source: InstructionSource, create_registration: Option<bool>, } #[derive(Debug, Clone, Eq, PartialEq, Serialize)] pub struct BankDetails { #[serde(rename = "bankAccount.holder")] pub account_holder: Secret<String>, } #[allow(dead_code)] #[derive(Debug, Default, Clone, Eq, PartialEq, Serialize, Deserialize)] pub enum AciPaymentType { #[serde(rename = "PA")] Preauthorization, #[default] #[serde(rename = "DB")] Debit, #[serde(rename = "CD")] Credit, #[serde(rename = "CP")] Capture, #[serde(rename = "RV")] Reversal, #[serde(rename = "RF")] Refund, } impl TryFrom<&AciRouterData<&PaymentsAuthorizeRouterData>> for AciPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &AciRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(ref card_data) => Self::try_from((item, card_data)), PaymentMethodData::NetworkToken(ref network_token_data) => { Self::try_from((item, network_token_data)) } PaymentMethodData::Wallet(ref wallet_data) => Self::try_from((item, wallet_data)), PaymentMethodData::PayLater(ref pay_later_data) => { Self::try_from((item, pay_later_data)) } PaymentMethodData::BankRedirect(ref bank_redirect_data) => { Self::try_from((item, bank_redirect_data)) } PaymentMethodData::MandatePayment => { let mandate_id = item.router_data.request.mandate_id.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "mandate_id", }, )?; Self::try_from((item, mandate_id)) } PaymentMethodData::Crypto(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Aci"), ))? } } } } impl TryFrom<(&AciRouterData<&PaymentsAuthorizeRouterData>, &WalletData)> for AciPaymentsRequest { type Error = Error; fn try_from( value: (&AciRouterData<&PaymentsAuthorizeRouterData>, &WalletData), ) -> Result<Self, Self::Error> { let (item, wallet_data) = value; let txn_details = get_transaction_details(item)?; let payment_method = PaymentDetails::try_from((wallet_data, item.router_data))?; Ok(Self { txn_details, payment_method, instruction: None, shopper_result_url: item.router_data.request.router_return_url.clone(), three_ds_two_enrolled: None, recurring_type: None, }) } } impl TryFrom<( &AciRouterData<&PaymentsAuthorizeRouterData>, &BankRedirectData, )> for AciPaymentsRequest { type Error = Error; fn try_from( value: ( &AciRouterData<&PaymentsAuthorizeRouterData>, &BankRedirectData, ), ) -> Result<Self, Self::Error> { let (item, bank_redirect_data) = value; let txn_details = get_transaction_details(item)?; let payment_method = PaymentDetails::try_from((item, bank_redirect_data))?; Ok(Self { txn_details, payment_method, instruction: None, shopper_result_url: item.router_data.request.router_return_url.clone(), three_ds_two_enrolled: None, recurring_type: None, }) } } impl TryFrom<(&AciRouterData<&PaymentsAuthorizeRouterData>, &PayLaterData)> for AciPaymentsRequest { type Error = Error; fn try_from( value: (&AciRouterData<&PaymentsAuthorizeRouterData>, &PayLaterData), ) -> Result<Self, Self::Error> { let (item, _pay_later_data) = value; let txn_details = get_transaction_details(item)?; let payment_method = PaymentDetails::Klarna; Ok(Self { txn_details, payment_method, instruction: None, shopper_result_url: item.router_data.request.router_return_url.clone(), three_ds_two_enrolled: None, recurring_type: None, }) } } impl TryFrom<(&AciRouterData<&PaymentsAuthorizeRouterData>, &Card)> for AciPaymentsRequest { type Error = Error; fn try_from( value: (&AciRouterData<&PaymentsAuthorizeRouterData>, &Card), ) -> Result<Self, Self::Error> { let (item, card_data) = value; let card_holder_name = item.router_data.get_optional_billing_full_name(); let txn_details = get_transaction_details(item)?; let payment_method = PaymentDetails::try_from((card_data.clone(), card_holder_name))?; let instruction = get_instruction_details(item); let recurring_type = get_recurring_type(item); let three_ds_two_enrolled = item .router_data .is_three_ds() .then_some(item.router_data.request.enrolled_for_3ds); Ok(Self { txn_details, payment_method, instruction, shopper_result_url: item.router_data.request.router_return_url.clone(), three_ds_two_enrolled, recurring_type, }) } } impl TryFrom<( &AciRouterData<&PaymentsAuthorizeRouterData>, &NetworkTokenData, )> for AciPaymentsRequest { type Error = Error; fn try_from( value: ( &AciRouterData<&PaymentsAuthorizeRouterData>, &NetworkTokenData, ), ) -> Result<Self, Self::Error> { let (item, network_token_data) = value; let txn_details = get_transaction_details(item)?; let payment_method = PaymentDetails::try_from((item, network_token_data))?; let instruction = get_instruction_details(item); Ok(Self { txn_details, payment_method, instruction, shopper_result_url: item.router_data.request.router_return_url.clone(), three_ds_two_enrolled: None, recurring_type: None, }) } } impl TryFrom<( &AciRouterData<&PaymentsAuthorizeRouterData>, api_models::payments::MandateIds, )> for AciPaymentsRequest { type Error = Error; fn try_from( value: ( &AciRouterData<&PaymentsAuthorizeRouterData>, api_models::payments::MandateIds, ), ) -> Result<Self, Self::Error> { let (item, _mandate_data) = value; let instruction = get_instruction_details(item); let txn_details = get_transaction_details(item)?; let recurring_type = get_recurring_type(item); Ok(Self { txn_details, payment_method: PaymentDetails::Mandate, instruction, shopper_result_url: item.router_data.request.router_return_url.clone(), three_ds_two_enrolled: None, recurring_type, }) } } fn get_transaction_details( item: &AciRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<TransactionDetails, error_stack::Report<errors::ConnectorError>> { let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?; let payment_type = if item.router_data.request.is_auto_capture()? { AciPaymentType::Debit } else { AciPaymentType::Preauthorization }; Ok(TransactionDetails { entity_id: auth.entity_id, amount: item.amount.to_owned(), currency: item.router_data.request.currency.to_string(), payment_type, }) } fn get_instruction_details( item: &AciRouterData<&PaymentsAuthorizeRouterData>, ) -> Option<Instruction> { if item.router_data.request.customer_acceptance.is_some() && item.router_data.request.setup_future_usage == Some(enums::FutureUsage::OffSession) { return Some(Instruction { mode: InstructionMode::Initial, transaction_type: InstructionType::Unscheduled, source: InstructionSource::CardholderInitiatedTransaction, create_registration: Some(true), }); } else if item.router_data.request.mandate_id.is_some() { return Some(Instruction { mode: InstructionMode::Repeated, transaction_type: InstructionType::Unscheduled, source: InstructionSource::MerchantInitiatedTransaction, create_registration: None, }); } None } fn get_recurring_type( item: &AciRouterData<&PaymentsAuthorizeRouterData>, ) -> Option<AciRecurringType> { if item.router_data.request.mandate_id.is_some() { Some(AciRecurringType::Repeated) } else if item.router_data.request.customer_acceptance.is_some() && item.router_data.request.setup_future_usage == Some(enums::FutureUsage::OffSession) { Some(AciRecurringType::Initial) } else { None } } impl TryFrom<&PaymentsCancelRouterData> for AciCancelRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { let auth = AciAuthType::try_from(&item.connector_auth_type)?; let aci_payment_request = Self { entity_id: auth.entity_id, payment_type: AciPaymentType::Reversal, }; Ok(aci_payment_request) } } impl TryFrom<&RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>> for AciMandateRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let auth = AciAuthType::try_from(&item.connector_auth_type)?; let (payment_brand, payment_details) = match &item.request.payment_method_data { PaymentMethodData::Card(card_data) => { let brand = get_aci_payment_brand(card_data.card_network.clone(), false).ok(); match brand.as_ref() { Some(PaymentBrand::Visa) | Some(PaymentBrand::Mastercard) | Some(PaymentBrand::AmericanExpress) => (), Some(_) => { return Err(errors::ConnectorError::NotSupported { message: "Payment method not supported for mandate setup".to_string(), connector: "ACI", } .into()); } None => (), }; let details = PaymentDetails::AciCard(Box::new(CardDetails { card_number: card_data.card_number.clone(), card_expiry_month: card_data.card_exp_month.clone(), card_expiry_year: card_data.get_expiry_year_4_digit(), card_cvv: card_data.card_cvc.clone(), card_holder: card_data.card_holder_name.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "card_holder_name", }, )?, payment_brand: brand.clone(), })); (brand, details) } _ => { return Err(errors::ConnectorError::NotSupported { message: "Payment method not supported for mandate setup".to_string(), connector: "ACI", } .into()); } }; Ok(Self { entity_id: auth.entity_id, payment_brand, payment_details, }) } } #[derive(Debug, Default, Clone, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum AciPaymentStatus { Succeeded, Failed, #[default] Pending, RedirectShopper, } fn map_aci_attempt_status(item: AciPaymentStatus, auto_capture: bool) -> enums::AttemptStatus { match item { AciPaymentStatus::Succeeded => { if auto_capture { enums::AttemptStatus::Charged } else { enums::AttemptStatus::Authorized } } AciPaymentStatus::Failed => enums::AttemptStatus::Failure, AciPaymentStatus::Pending => enums::AttemptStatus::Authorizing, AciPaymentStatus::RedirectShopper => enums::AttemptStatus::AuthenticationPending, } } impl FromStr for AciPaymentStatus { type Err = error_stack::Report<errors::ConnectorError>; fn from_str(s: &str) -> Result<Self, Self::Err> { if FAILURE_CODES.contains(&s) { Ok(Self::Failed) } else if PENDING_CODES.contains(&s) { Ok(Self::Pending) } else if SUCCESSFUL_CODES.contains(&s) { Ok(Self::Succeeded) } else { Err(report!(errors::ConnectorError::UnexpectedResponseError( bytes::Bytes::from(s.to_owned()) ))) } } } #[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct AciPaymentsResponse { id: String, registration_id: Option<Secret<String>>, ndc: String, timestamp: String, build_number: String, pub(super) result: ResultCode, pub(super) redirect: Option<AciRedirectionData>, } #[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct AciErrorResponse { ndc: String, timestamp: String, build_number: String, pub(super) result: ResultCode, } #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct AciRedirectionData { pub method: Option<Method>, pub parameters: Vec<Parameters>, pub url: Url, pub preconditions: Option<Vec<PreconditionData>>, } #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct PreconditionData { pub method: Option<Method>, pub parameters: Vec<Parameters>, pub url: Url, } #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] pub struct Parameters { pub name: String, pub value: String, } #[derive(Default, Debug, Clone, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct ResultCode { pub(super) code: String, pub(super) description: String, pub(super) parameter_errors: Option<Vec<ErrorParameters>>, } #[derive(Default, Debug, Clone, Deserialize, PartialEq, Eq, Serialize)] pub struct ErrorParameters { pub(super) name: String, pub(super) value: Option<String>, pub(super) message: String, } impl<F, Req> TryFrom<ResponseRouterData<F, AciPaymentsResponse, Req, PaymentsResponseData>> for RouterData<F, Req, PaymentsResponseData> where Req: GetCaptureMethod, { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, AciPaymentsResponse, Req, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let redirection_data = item.response.redirect.map(|data| { let mut form_fields = std::collections::HashMap::<_, _>::from_iter( data.parameters .iter() .map(|parameter| (parameter.name.clone(), parameter.value.clone())), ); if let Some(preconditions) = data.preconditions { if let Some(first_precondition) = preconditions.first() { for param in &first_precondition.parameters { form_fields.insert(param.name.clone(), param.value.clone()); } } } // If method is Get, parameters are appended to URL // If method is post, we http Post the method to URL RedirectForm::Form { endpoint: data.url.to_string(), // Handles method for Bank redirects currently.
crates/hyperswitch_connectors/src/connectors/aci/transformers.rs#chunk0
hyperswitch_connectors
chunk
null
null
null
8,191
null
null
null
null
null
null
null
// Struct: QrCodeData // File: crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct QrCodeData
crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
hyperswitch_connectors
struct_definition
QrCodeData
0
[]
50
null
null
null
null
null
null
null
// Struct: SdkEventsRequest // File: crates/api_models/src/analytics/sdk_events.rs // Module: api_models // Implementations: 0 pub struct SdkEventsRequest
crates/api_models/src/analytics/sdk_events.rs
api_models
struct_definition
SdkEventsRequest
0
[]
40
null
null
null
null
null
null
null
// Implementation: impl Memoization // File: crates/hyperswitch_constraint_graph/src/types.rs // Module: hyperswitch_constraint_graph // Methods: 1 total (1 public) impl Memoization
crates/hyperswitch_constraint_graph/src/types.rs
hyperswitch_constraint_graph
impl_block
null
null
null
42
null
Memoization
null
1
1
null
null
// Struct: InjectorResponse // File: crates/injector/src/types.rs // Module: injector // Implementations: 0 pub struct InjectorResponse
crates/injector/src/types.rs
injector
struct_definition
InjectorResponse
0
[]
33
null
null
null
null
null
null
null
// Struct: Fiservemea // File: crates/hyperswitch_connectors/src/connectors/fiservemea.rs // Module: hyperswitch_connectors // Implementations: 17 // Traits: api::Payment, api::PaymentSession, api::ConnectorAccessToken, api::MandateSetup, api::PaymentAuthorize, api::PaymentSync, api::PaymentCapture, api::PaymentVoid, api::Refund, api::RefundExecute, api::RefundSync, api::PaymentToken, ConnectorCommon, ConnectorValidation, webhooks::IncomingWebhook, ConnectorSpecifications pub struct Fiservemea
crates/hyperswitch_connectors/src/connectors/fiservemea.rs
hyperswitch_connectors
struct_definition
Fiservemea
17
[ "api::Payment", "api::PaymentSession", "api::ConnectorAccessToken", "api::MandateSetup", "api::PaymentAuthorize", "api::PaymentSync", "api::PaymentCapture", "api::PaymentVoid", "api::Refund", "api::RefundExecute", "api::RefundSync", "api::PaymentToken", "ConnectorCommon", "ConnectorValidation", "webhooks::IncomingWebhook", "ConnectorSpecifications" ]
134
null
null
null
null
null
null
null
// Implementation: impl WiseHttpStatus // File: crates/hyperswitch_connectors/src/connectors/wise/transformers.rs // Module: hyperswitch_connectors // Methods: 1 total (1 public) impl WiseHttpStatus
crates/hyperswitch_connectors/src/connectors/wise/transformers.rs
hyperswitch_connectors
impl_block
null
null
null
48
null
WiseHttpStatus
null
1
1
null
null
// Struct: PaymentLinkStatusData // File: crates/hyperswitch_domain_models/src/api.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct PaymentLinkStatusData
crates/hyperswitch_domain_models/src/api.rs
hyperswitch_domain_models
struct_definition
PaymentLinkStatusData
0
[]
43
null
null
null
null
null
null
null
// Implementation: impl DrainerSettings // File: crates/scheduler/src/settings.rs // Module: scheduler // Methods: 1 total (1 public) impl DrainerSettings
crates/scheduler/src/settings.rs
scheduler
impl_block
null
null
null
37
null
DrainerSettings
null
1
1
null
null
// Struct: PowertranzAuthType // File: crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PowertranzAuthType
crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs
hyperswitch_connectors
struct_definition
PowertranzAuthType
0
[]
52
null
null
null
null
null
null
null
// Implementation: impl api::PaymentCapture for for Tokenio // File: crates/hyperswitch_connectors/src/connectors/tokenio.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentCapture for for Tokenio
crates/hyperswitch_connectors/src/connectors/tokenio.rs
hyperswitch_connectors
impl_block
null
null
null
57
null
Tokenio
api::PaymentCapture for
0
0
null
null
// File: crates/hyperswitch_connectors/src/connectors/stax/transformers.rs // Module: hyperswitch_connectors // Public structs: 17 use common_enums::enums; use common_utils::pii::Email; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{BankDebitData, PaymentMethodData}, router_data::{ConnectorAuthType, PaymentMethodToken, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{ ConnectorCustomerResponseData, PaymentsResponseData, RefundsResponseData, }, types, }; use hyperswitch_interfaces::{api, errors}; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, unimplemented_payment_method, utils::{ self, missing_field_err, CardData as CardDataUtil, PaymentsAuthorizeRequestData, RouterData as _, }, }; #[derive(Debug, Serialize)] pub struct StaxRouterData<T> { pub amount: f64, pub router_data: T, } impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for StaxRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { let amount = utils::get_amount_as_f64(currency_unit, amount, currency)?; Ok(Self { amount, router_data: item, }) } } #[derive(Debug, Serialize)] pub struct StaxPaymentsRequestMetaData { tax: i64, } #[derive(Debug, Serialize)] pub struct StaxPaymentsRequest { payment_method_id: Secret<String>, total: f64, is_refundable: bool, pre_auth: bool, meta: StaxPaymentsRequestMetaData, idempotency_id: Option<String>, } impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &StaxRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { if item.router_data.request.currency != enums::Currency::USD { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Stax"), ))? } let total = item.amount; match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(_) => { let pm_token = item.router_data.get_payment_method_token()?; let pre_auth = !item.router_data.request.is_auto_capture()?; Ok(Self { meta: StaxPaymentsRequestMetaData { tax: 0 }, total, is_refundable: true, pre_auth, payment_method_id: match pm_token { PaymentMethodToken::Token(token) => token, PaymentMethodToken::ApplePayDecrypt(_) => Err( unimplemented_payment_method!("Apple Pay", "Simplified", "Stax"), )?, PaymentMethodToken::PazeDecrypt(_) => { Err(unimplemented_payment_method!("Paze", "Stax"))? } PaymentMethodToken::GooglePayDecrypt(_) => { Err(unimplemented_payment_method!("Google Pay", "Stax"))? } }, idempotency_id: Some(item.router_data.connector_request_reference_id.clone()), }) } PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { .. }) => { let pm_token = item.router_data.get_payment_method_token()?; let pre_auth = !item.router_data.request.is_auto_capture()?; Ok(Self { meta: StaxPaymentsRequestMetaData { tax: 0 }, total, is_refundable: true, pre_auth, payment_method_id: match pm_token { PaymentMethodToken::Token(token) => token, PaymentMethodToken::ApplePayDecrypt(_) => Err( unimplemented_payment_method!("Apple Pay", "Simplified", "Stax"), )?, PaymentMethodToken::PazeDecrypt(_) => { Err(unimplemented_payment_method!("Paze", "Stax"))? } PaymentMethodToken::GooglePayDecrypt(_) => { Err(unimplemented_payment_method!("Google Pay", "Stax"))? } }, idempotency_id: Some(item.router_data.connector_request_reference_id.clone()), }) } PaymentMethodData::BankDebit(_) | PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Upi(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Stax"), ))? } } } } // Auth Struct pub struct StaxAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for StaxAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Serialize)] pub struct StaxCustomerRequest { #[serde(skip_serializing_if = "Option::is_none")] email: Option<Email>, #[serde(skip_serializing_if = "Option::is_none")] firstname: Option<Secret<String>>, } impl TryFrom<&types::ConnectorCustomerRouterData> for StaxCustomerRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::ConnectorCustomerRouterData) -> Result<Self, Self::Error> { if item.request.email.is_none() && item.request.name.is_none() { Err(errors::ConnectorError::MissingRequiredField { field_name: "email or name", } .into()) } else { Ok(Self { email: item.request.email.to_owned(), firstname: item.request.name.to_owned(), }) } } } #[derive(Debug, Deserialize, Serialize)] pub struct StaxCustomerResponse { id: Secret<String>, } impl<F, T> TryFrom<ResponseRouterData<F, StaxCustomerResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, StaxCustomerResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(PaymentsResponseData::ConnectorCustomerResponse( ConnectorCustomerResponseData::new_with_customer_id(item.response.id.expose()), )), ..item.data }) } } #[derive(Debug, Serialize)] pub struct StaxTokenizeData { person_name: Secret<String>, card_number: cards::CardNumber, card_exp: Secret<String>, card_cvv: Secret<String>, customer_id: Secret<String>, } #[derive(Debug, Serialize)] pub struct StaxBankTokenizeData { person_name: Secret<String>, bank_account: Secret<String>, bank_routing: Secret<String>, bank_name: common_enums::BankNames, bank_type: common_enums::BankType, bank_holder_type: common_enums::BankHolderType, customer_id: Secret<String>, } #[derive(Debug, Serialize)] #[serde(tag = "method")] #[serde(rename_all = "lowercase")] pub enum StaxTokenRequest { Card(StaxTokenizeData), Bank(StaxBankTokenizeData), } impl TryFrom<&types::TokenizationRouterData> for StaxTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> { let customer_id = item.get_connector_customer_id()?; match item.request.payment_method_data.clone() { PaymentMethodData::Card(card_data) => { let stax_card_data = StaxTokenizeData { card_exp: card_data .get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?, person_name: item .get_optional_billing_full_name() .unwrap_or(Secret::new("".to_string())), card_number: card_data.card_number, card_cvv: card_data.card_cvc, customer_id: Secret::new(customer_id), }; Ok(Self::Card(stax_card_data)) } PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { account_number, routing_number, bank_name, bank_type, bank_holder_type, .. }) => { let stax_bank_data = StaxBankTokenizeData { person_name: item.get_billing_full_name()?, bank_account: account_number, bank_routing: routing_number, bank_name: bank_name.ok_or_else(missing_field_err("bank_name"))?, bank_type: bank_type.ok_or_else(missing_field_err("bank_type"))?, bank_holder_type: bank_holder_type .ok_or_else(missing_field_err("bank_holder_type"))?, customer_id: Secret::new(customer_id), }; Ok(Self::Bank(stax_bank_data)) } PaymentMethodData::BankDebit(_) | PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Upi(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Stax"), ))? } } } } #[derive(Debug, Deserialize, Serialize)] pub struct StaxTokenResponse { id: Secret<String>, } impl<F, T> TryFrom<ResponseRouterData<F, StaxTokenResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, StaxTokenResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(PaymentsResponseData::TokenizationResponse { token: item.response.id.expose(), }), ..item.data }) } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum StaxPaymentResponseTypes { Charge, PreAuth, } #[derive(Debug, Deserialize, Serialize)] pub struct StaxChildCapture { id: String, } #[derive(Debug, Deserialize, Serialize)] pub struct StaxPaymentsResponse { success: bool, id: String, is_captured: i8, is_voided: bool, child_captures: Vec<StaxChildCapture>, #[serde(rename = "type")] payment_response_type: StaxPaymentResponseTypes, idempotency_id: Option<String>, } #[derive(Debug, Deserialize, Serialize)] pub struct StaxMetaData { pub capture_id: String, } impl<F, T> TryFrom<ResponseRouterData<F, StaxPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, StaxPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let mut connector_metadata = None; let mut status = match item.response.success { true => match item.response.payment_response_type { StaxPaymentResponseTypes::Charge => enums::AttemptStatus::Charged, StaxPaymentResponseTypes::PreAuth => match item.response.is_captured { 0 => enums::AttemptStatus::Authorized, _ => { connector_metadata = item.response.child_captures.first().map(|child_captures| { serde_json::json!(StaxMetaData { capture_id: child_captures.id.clone() }) }); enums::AttemptStatus::Charged } }, }, false => enums::AttemptStatus::Failure, }; if item.response.is_voided { status = enums::AttemptStatus::Voided; } Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: Some( item.response.idempotency_id.unwrap_or(item.response.id), ), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct StaxCaptureRequest { total: Option<f64>, } impl TryFrom<&StaxRouterData<&types::PaymentsCaptureRouterData>> for StaxCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &StaxRouterData<&types::PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { let total = item.amount; Ok(Self { total: Some(total) }) } } // REFUND : // Type definition for RefundRequest #[derive(Debug, Serialize)] pub struct StaxRefundRequest { pub total: f64, } impl<F> TryFrom<&StaxRouterData<&types::RefundsRouterData<F>>> for StaxRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &StaxRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { total: item.amount }) } } #[derive(Debug, Deserialize, Serialize)] pub struct ChildTransactionsInResponse { id: String, success: bool, created_at: String, total: f64, } #[derive(Debug, Deserialize, Serialize)] pub struct RefundResponse { id: String, success: bool, child_transactions: Vec<ChildTransactionsInResponse>, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_amount = utils::to_currency_base_unit_asf64( item.data.request.refund_amount, item.data.request.currency, ) .change_context(errors::ConnectorError::ResponseHandlingFailed)?; let filtered_txn: Vec<&ChildTransactionsInResponse> = item .response .child_transactions .iter() .filter(|txn| txn.total == refund_amount) .collect(); let mut refund_txn = filtered_txn .first() .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; for child in filtered_txn.iter() { if child.created_at > refund_txn.created_at { refund_txn = child; } } let refund_status = match refund_txn.success { true => enums::RefundStatus::Success, false => enums::RefundStatus::Failure, }; Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: refund_txn.id.clone(), refund_status, }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = match item.response.success { true => enums::RefundStatus::Success, false => enums::RefundStatus::Failure, }; Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status, }), ..item.data }) } } #[derive(Debug, Deserialize)] #[serde(rename_all = "snake_case")] pub enum StaxWebhookEventType { PreAuth, Capture, Charge, Void, Refund, #[serde(other)] Unknown, } #[derive(Debug, Deserialize)] pub struct StaxWebhookBody { #[serde(rename = "type")] pub transaction_type: StaxWebhookEventType, pub id: String, pub auth_id: Option<String>, pub success: bool, }
crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
hyperswitch_connectors
full_file
null
null
null
3,976
null
null
null
null
null
null
null
// Implementation: impl IntermediateString // File: crates/external_services/src/email.rs // Module: external_services // Methods: 2 total (2 public) impl IntermediateString
crates/external_services/src/email.rs
external_services
impl_block
null
null
null
37
null
IntermediateString
null
2
2
null
null
// Struct: BankOfAmericaRsyncResponse // File: crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct BankOfAmericaRsyncResponse
crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
hyperswitch_connectors
struct_definition
BankOfAmericaRsyncResponse
0
[]
56
null
null
null
null
null
null
null
// Function: new // File: crates/diesel_models/src/subscription.rs // Module: diesel_models pub fn new( id: common_utils::id_type::SubscriptionId, status: String, billing_processor: Option<String>, payment_method_id: Option<String>, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, client_secret: Option<String>, connector_subscription_id: Option<String>, merchant_id: common_utils::id_type::MerchantId, customer_id: common_utils::id_type::CustomerId, metadata: Option<SecretSerdeValue>, profile_id: common_utils::id_type::ProfileId, merchant_reference_id: Option<String>, ) -> Self
crates/diesel_models/src/subscription.rs
diesel_models
function_signature
null
null
null
151
new
null
null
null
null
null
null
// Struct: TokenizedCard // File: crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct TokenizedCard
crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
hyperswitch_connectors
struct_definition
TokenizedCard
0
[]
50
null
null
null
null
null
null
null
// Function: to_field_value_pairs // File: crates/diesel_models/src/kv.rs // Module: diesel_models pub fn to_field_value_pairs( &self, request_id: String, global_id: String, ) -> crate::StorageResult<Vec<(&str, String)>>
crates/diesel_models/src/kv.rs
diesel_models
function_signature
null
null
null
63
to_field_value_pairs
null
null
null
null
null
null
// Implementation: impl api::MandateSetup for for Tesouro // File: crates/hyperswitch_connectors/src/connectors/tesouro.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::MandateSetup for for Tesouro
crates/hyperswitch_connectors/src/connectors/tesouro.rs
hyperswitch_connectors
impl_block
null
null
null
62
null
Tesouro
api::MandateSetup for
0
0
null
null
// Struct: Routing // File: crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct Routing
crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs
hyperswitch_connectors
struct_definition
Routing
0
[]
45
null
null
null
null
null
null
null
// Struct: PaymentAccountCardInformation // File: crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PaymentAccountCardInformation
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
hyperswitch_connectors
struct_definition
PaymentAccountCardInformation
0
[]
51
null
null
null
null
null
null
null
// Struct: ExternalVaultTokenData // File: crates/api_models/src/payment_methods.rs // Module: api_models // Implementations: 0 pub struct ExternalVaultTokenData
crates/api_models/src/payment_methods.rs
api_models
struct_definition
ExternalVaultTokenData
0
[]
38
null
null
null
null
null
null
null
// Implementation: impl api::PaymentAuthorize for for Paybox // File: crates/hyperswitch_connectors/src/connectors/paybox.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentAuthorize for for Paybox
crates/hyperswitch_connectors/src/connectors/paybox.rs
hyperswitch_connectors
impl_block
null
null
null
57
null
Paybox
api::PaymentAuthorize for
0
0
null
null
// Function: create_address // File: crates/diesel_models/src/address.rs // Module: diesel_models pub fn create_address(self, source: Address) -> Address
crates/diesel_models/src/address.rs
diesel_models
function_signature
null
null
null
35
create_address
null
null
null
null
null
null
// Implementation: impl GlobalCustomerId // File: crates/common_utils/src/id_type/global_id/customer.rs // Module: common_utils // Methods: 2 total (2 public) impl GlobalCustomerId
crates/common_utils/src/id_type/global_id/customer.rs
common_utils
impl_block
null
null
null
40
null
GlobalCustomerId
null
2
2
null
null
// Function: new_password_without_validation // File: crates/router/src/types/domain/user.rs // Module: router pub fn new_password_without_validation(password: Secret<String>) -> UserResult<Self>
crates/router/src/types/domain/user.rs
router
function_signature
null
null
null
40
new_password_without_validation
null
null
null
null
null
null
// Struct: AcceptDisputeRequestData // File: crates/hyperswitch_domain_models/src/router_request_types.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct AcceptDisputeRequestData
crates/hyperswitch_domain_models/src/router_request_types.rs
hyperswitch_domain_models
struct_definition
AcceptDisputeRequestData
0
[]
47
null
null
null
null
null
null
null
// Struct: TokenioAuthType // File: crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct TokenioAuthType
crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs
hyperswitch_connectors
struct_definition
TokenioAuthType
0
[]
49
null
null
null
null
null
null
null
// Implementation: impl BlackList for for AuthToken // File: crates/router/src/services/authentication/blacklist.rs // Module: router // Methods: 1 total (0 public) impl BlackList for for AuthToken
crates/router/src/services/authentication/blacklist.rs
router
impl_block
null
null
null
45
null
AuthToken
BlackList for
1
0
null
null
// Struct: ApiErrorResponse // File: crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ApiErrorResponse
crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
hyperswitch_connectors
struct_definition
ApiErrorResponse
0
[]
46
null
null
null
null
null
null
null
// Struct: BlikBankRedirectAdditionalData // File: crates/api_models/src/payments/additional_info.rs // Module: api_models // Implementations: 0 pub struct BlikBankRedirectAdditionalData
crates/api_models/src/payments/additional_info.rs
api_models
struct_definition
BlikBankRedirectAdditionalData
0
[]
45
null
null
null
null
null
null
null
// Implementation: impl super::payments::metrics::PaymentMetricAnalytics for for SqlxClient // File: crates/analytics/src/sqlx.rs // Module: analytics // Methods: 0 total (0 public) impl super::payments::metrics::PaymentMetricAnalytics for for SqlxClient
crates/analytics/src/sqlx.rs
analytics
impl_block
null
null
null
60
null
SqlxClient
super::payments::metrics::PaymentMetricAnalytics for
0
0
null
null
// Struct: GetParentGroupsInfoQueryParams // File: crates/api_models/src/user_role/role.rs // Module: api_models // Implementations: 0 pub struct GetParentGroupsInfoQueryParams
crates/api_models/src/user_role/role.rs
api_models
struct_definition
GetParentGroupsInfoQueryParams
0
[]
44
null
null
null
null
null
null
null
End of preview. Expand in Data Studio

Hyperswitch Rust Codebase Dataset

A comprehensive dataset extracted from the Hyperswitch open-source payment processing platform, containing 16,731 code samples across 37 modules with 6.99M tokens for training Rust code understanding and generation models.

πŸ“Š Dataset Overview

This dataset provides both file-level and granular code samples from Hyperswitch, a modern payment switch written in Rust. It's designed for training code models to understand payment processing patterns, Rust idioms, and large-scale system architecture.

Key Statistics

  • Total Samples: 16,731
  • Total Tokens: 6,991,792
  • File-level Samples: 2,120 complete files
  • Granular Samples: 14,611 extracted components
  • Modules: 37 distinct modules
  • License: Apache 2.0

πŸ—οΈ Dataset Structure

Sample Distribution by Type

Type Count Description
Struct Definitions 5,710 Data structures and models
Implementation Blocks 4,296 Method implementations
Function Signatures 4,121 Function definitions
Full Files 1,666 Complete source files
File Chunks 454 Large file segments
Module Structures 261 Module declarations
Trait Definitions 223 Interface definitions

File-level vs Granular Split

  • File-level (2,120): Complete files with full context
  • Granular (14,611): Extracted functions, structs, traits, and implementations

πŸ—‚οΈ Module Coverage

The dataset spans 37 modules covering different aspects of payment processing:

  • router - Payment routing logic
  • payment_methods - Payment method handling
  • hyperswitch_connectors - Payment gateway connectors
  • cards - Card processing utilities
  • api_models - API request/response models
  • diesel_models - Database models
  • storage_impl - Data persistence layer
  • redis_interface - Caching layer
  • currency_conversion - Multi-currency support
  • analytics - Payment analytics
  • events - Event handling system
  • scheduler - Background job processing
  • test_utils - Testing utilities
  • hsdev - Development tools
  • connector-template - Connector scaffolding
  • external_services - Third-party integrations
  • openapi - API documentation
  • euclid - Routing engine
  • smithy - Code generation

[Complete list of 37 modules included in dataset]

πŸ“‹ Data Format

Each sample in all_data.jsonl contains:

{
  "text": "// Rust code content",
  "file_path": "relative/path/to/file.rs",
  "module": "module_name",
  "type": "struct_definition|function_signature|full_file|...",
  "tokens": 150,
  "metadata": {
    "functions": ["func1", "func2"],
    "structs": ["Struct1", "Struct2"],
    "traits": ["Trait1"],
    "dependencies": ["use statements"]
  }
}

🎯 Use Cases

Primary Applications

  • Code Understanding: Train models to explain Rust code patterns
  • Code Generation: Generate payment processing logic
  • Documentation: Automatic code documentation
  • Code Review: Assist in code quality assessment
  • Developer Onboarding: Help new developers understand codebase

Specific Domains

  • Payment Processing: Understanding financial transaction flows
  • Rust Programming: Learning Rust idioms and patterns
  • Microservices Architecture: Understanding distributed system patterns
  • API Design: Learning REST API patterns
  • Database Integration: Understanding ORM patterns

πŸ› οΈ Dataset Creation

Extraction Process

  1. Repository Analysis: Scanned entire Hyperswitch codebase
  2. File Filtering: Included .rs files, excluded generated code
  3. Granular Extraction: Used regex patterns to extract:
    • Function definitions with context
    • Struct definitions with documentation
    • Trait definitions and implementations
    • Module declarations
  4. Chunk Processing: Large files split with 512-token overlap
  5. Metadata Generation: Extracted dependencies and cross-references

Quality Controls

  • Syntax Validation: All samples are valid Rust code
  • Context Preservation: Maintains import statements and dependencies
  • Documentation Included: Preserves /// and //! comments
  • Test Coverage: Includes test files for usage patterns

πŸ“ˆ Model Training

Recommended Usage

  • Context Window: 8,192 tokens (handles 95% of samples)
  • Training Split: 90% train, 10% validation
  • Token Distribution: Well-balanced across different code constructs
  • Batch Size: Adjust based on context window and hardware

Training Considerations

  • Code Completion: Use for next-token prediction
  • Code Understanding: Use for explanation tasks
  • Fine-tuning: Excellent for domain-specific adaptation
  • Evaluation: Test on payment processing concepts

πŸ” Sample Examples

Struct Definition

/// Payment connector configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectorConfig {
    pub connector_name: String,
    pub api_endpoint: Url,
    pub credentials: ConnectorCredentials,
    pub supported_payment_methods: Vec<PaymentMethod>,
}

Function Signature

/// Process payment through selected connector
pub async fn process_payment(
    state: &AppState,
    payment_data: PaymentData,
    connector: &dyn PaymentConnector,
) -> RouterResult<PaymentResponse>

Implementation Block

impl PaymentConnector for StripeConnector {
    async fn authorize_payment(
        &self,
        request: PaymentAuthorizeRequest,
    ) -> ConnectorResult<PaymentAuthorizeResponse> {
        // Implementation details...
    }
}

πŸ“Š Dataset Quality

Metrics

  • Syntax Validity: 100% (all samples compile)
  • Documentation Coverage: 85% have doc comments
  • Test Coverage: 15% are test files
  • Average Tokens per Sample: 418 tokens
  • Context Completeness: 95% have necessary imports

Validation

  • Automated Testing: All samples pass cargo check
  • Manual Review: Random sampling verified for quality
  • Deduplication: Identical code blocks removed
  • Privacy: No sensitive credentials or API keys

πŸš€ Getting Started

Download and Usage

# Load dataset
import json

samples = []
with open('all_data.jsonl', 'r') as f:
    for line in f:
        samples.append(json.loads(line))

print(f"Loaded {len(samples)} samples")
print(f"Sample types: {set(s['type'] for s in samples)}")

Training Example

from transformers import AutoTokenizer, AutoModelForCausalLM
from datasets import Dataset

# Load tokenizer
tokenizer = AutoTokenizer.from_pretrained("Kwaipilot/KAT-Dev")

# Prepare dataset
def tokenize_function(examples):
    return tokenizer(examples["text"], truncation=True, max_length=8192)

dataset = Dataset.from_list(samples)
tokenized_dataset = dataset.map(tokenize_function, batched=True)

πŸ™ Acknowledgments

  • Hyperswitch Team for building an excellent open-source payment platform
  • Rust Community for creating robust tooling and documentation standards
  • Juspay Technologies for open-sourcing this valuable codebase

πŸ“ž Citation

@dataset{HyperSwitch-Repo-CPT-Dataset,
  title={HyperSwitch-Repo-CPT-Dataset},
  author={Aditya Narayan},
  year={2024},
  publisher={Hugging Face},
  url={https://huggingface.co/datasets/AdityaNarayan/HyperSwitch-Repo-CPT-Dataset},
  note={Extracted from https://github.com/juspay/hyperswitch}
}

This dataset is part of ongoing research into domain-specific code model training for financial technology applications.

Downloads last month
19

Models trained or fine-tuned on AdityaNarayan/HyperSwitch-Repo-CPT-Dataset