text
string
file_path
string
module
string
type
string
tokens
int64
language
string
struct_name
string
type_name
string
trait_name
string
impl_type
string
function_name
string
source
string
section
string
keys
list
macro_type
string
url
string
title
string
chunk_index
int64
impl MerchantAccountInterface for KafkaStore { async fn insert_merchant( &self, state: &KeyManagerState, merchant_account: domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store .insert_merchant(state, merchant_account, key_store) .await } async fn find_merchant_account_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store .find_merchant_account_by_merchant_id(state, merchant_id, key_store) .await } async fn update_merchant( &self, state: &KeyManagerState, this: domain::MerchantAccount, merchant_account: storage::MerchantAccountUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store .update_merchant(state, this, merchant_account, key_store) .await } async fn update_specific_fields_in_merchant( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, merchant_account: storage::MerchantAccountUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store .update_specific_fields_in_merchant(state, merchant_id, merchant_account, key_store) .await } async fn update_all_merchant_account( &self, merchant_account: storage::MerchantAccountUpdate, ) -> CustomResult<usize, errors::StorageError> { self.diesel_store .update_all_merchant_account(merchant_account) .await } async fn find_merchant_account_by_publishable_key( &self, state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<(domain::MerchantAccount, domain::MerchantKeyStore), errors::StorageError> { self.diesel_store .find_merchant_account_by_publishable_key(state, publishable_key) .await } #[cfg(feature = "olap")] async fn list_merchant_accounts_by_organization_id( &self, state: &KeyManagerState, organization_id: &id_type::OrganizationId, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { self.diesel_store .list_merchant_accounts_by_organization_id(state, organization_id) .await } async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_merchant_account_by_merchant_id(merchant_id) .await } #[cfg(feature = "olap")] async fn list_multiple_merchant_accounts( &self, state: &KeyManagerState, merchant_ids: Vec<id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { self.diesel_store .list_multiple_merchant_accounts(state, merchant_ids) .await } #[cfg(feature = "olap")] async fn list_merchant_and_org_ids( &self, state: &KeyManagerState, limit: u32, offset: Option<u32>, ) -> CustomResult<Vec<(id_type::MerchantId, id_type::OrganizationId)>, errors::StorageError> { self.diesel_store .list_merchant_and_org_ids(state, limit, offset) .await } }
crates/router/src/db/kafka_store.rs
router
impl_block
856
rust
null
KafkaStore
MerchantAccountInterface for
impl MerchantAccountInterface for for KafkaStore
null
null
null
null
null
null
null
null
pub struct ZenWebhookEventType { #[serde(rename = "type")] pub transaction_type: ZenWebhookTxnType, pub transaction_id: String, pub status: ZenPaymentStatus, }
crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
hyperswitch_connectors
struct_definition
43
rust
ZenWebhookEventType
null
null
null
null
null
null
null
null
null
null
null
/// Routing Algorithm specific to merchants pub struct MerchantRoutingAlgorithm { #[schema(value_type = String)] pub id: common_utils::id_type::RoutingId, #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, pub name: String, pub description: String, pub algorithm: RoutingAlgorithmWrapper, pub created_at: i64, pub modified_at: i64, pub algorithm_for: TransactionType, }
crates/api_models/src/routing.rs
api_models
struct_definition
103
rust
MerchantRoutingAlgorithm
null
null
null
null
null
null
null
null
null
null
null
impl<'a> HeaderMapStruct<'a> { pub fn new(headers: &'a HeaderMap) -> Self { HeaderMapStruct { headers } } fn get_mandatory_header_value_by_key( &self, key: &str, ) -> Result<&str, error_stack::Report<errors::ApiErrorResponse>> { self.headers .get(key) .ok_or(errors::ApiErrorResponse::InvalidRequestData { message: format!("Missing header key: `{key}`"), }) .attach_printable(format!("Failed to find header key: {key}"))? .to_str() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "`{key}` in headers", }) .attach_printable(format!( "Failed to convert header value to string for header key: {key}", )) } /// Get the id type from the header /// This can be used to extract lineage ids from the headers pub fn get_id_type_from_header< T: TryFrom< std::borrow::Cow<'static, str>, Error = error_stack::Report<errors::ValidationError>, >, >( &self, key: &str, ) -> RouterResult<T> { self.get_mandatory_header_value_by_key(key) .map(|val| val.to_owned()) .and_then(|header_value| { T::try_from(std::borrow::Cow::Owned(header_value)).change_context( errors::ApiErrorResponse::InvalidRequestData { message: format!("`{key}` header is invalid"), }, ) }) } #[cfg(feature = "v2")] pub fn get_organization_id_from_header(&self) -> RouterResult<id_type::OrganizationId> { self.get_mandatory_header_value_by_key(headers::X_ORGANIZATION_ID) .map(|val| val.to_owned()) .and_then(|organization_id| { id_type::OrganizationId::try_from_string(organization_id).change_context( errors::ApiErrorResponse::InvalidRequestData { message: format!("`{}` header is invalid", headers::X_ORGANIZATION_ID), }, ) }) } pub fn get_auth_string_from_header(&self) -> RouterResult<&str> { self.headers .get(headers::AUTHORIZATION) .get_required_value(headers::AUTHORIZATION)? .to_str() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: headers::AUTHORIZATION, }) .attach_printable("Failed to convert authorization header to string") } pub fn get_id_type_from_header_if_present<T>(&self, key: &str) -> RouterResult<Option<T>> where T: TryFrom< std::borrow::Cow<'static, str>, Error = error_stack::Report<errors::ValidationError>, >, { self.headers .get(key) .map(|value| value.to_str()) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "`{key}` in headers", }) .attach_printable(format!( "Failed to convert header value to string for header key: {key}", ))? .map(|value| { T::try_from(std::borrow::Cow::Owned(value.to_owned())).change_context( errors::ApiErrorResponse::InvalidRequestData { message: format!("`{key}` header is invalid"), }, ) }) .transpose() } }
crates/router/src/services/authentication.rs
router
impl_block
756
rust
null
HeaderMapStruct
null
impl HeaderMapStruct
null
null
null
null
null
null
null
null
pub struct Discount { #[serde(rename = "type")] pub discount_type: DiscountType, pub discount_one: Option<DiscountObject>, pub discount_two: Option<DiscountObject>, pub discount_three: Option<DiscountObject>, }
crates/hyperswitch_connectors/src/connectors/santander/transformers.rs
hyperswitch_connectors
struct_definition
51
rust
Discount
null
null
null
null
null
null
null
null
null
null
null
impl api::PaymentCapture for Bluesnap {}
crates/hyperswitch_connectors/src/connectors/bluesnap.rs
hyperswitch_connectors
impl_block
9
rust
null
Bluesnap
api::PaymentCapture for
impl api::PaymentCapture for for Bluesnap
null
null
null
null
null
null
null
null
impl api::RefundSync for Hipay {}
crates/hyperswitch_connectors/src/connectors/hipay.rs
hyperswitch_connectors
impl_block
10
rust
null
Hipay
api::RefundSync for
impl api::RefundSync for for Hipay
null
null
null
null
null
null
null
null
impl api::PaymentVoid for Nmi {}
crates/hyperswitch_connectors/src/connectors/nmi.rs
hyperswitch_connectors
impl_block
9
rust
null
Nmi
api::PaymentVoid for
impl api::PaymentVoid for for Nmi
null
null
null
null
null
null
null
null
pub struct AuthenticationData { pub merchant_account: domain::MerchantAccount, pub platform_merchant_account: Option<domain::MerchantAccount>, pub key_store: domain::MerchantKeyStore, pub profile_id: Option<id_type::ProfileId>, }
crates/router/src/services/authentication.rs
router
struct_definition
54
rust
AuthenticationData
null
null
null
null
null
null
null
null
null
null
null
impl ConnectorSpecifications for Stax { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&STAX_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*STAX_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&STAX_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/stax.rs
hyperswitch_connectors
impl_block
105
rust
null
Stax
ConnectorSpecifications for
impl ConnectorSpecifications for for Stax
null
null
null
null
null
null
null
null
pub struct XenditSplitResponse { id: String, name: String, description: String, routes: Vec<XenditSplitRoute>, }
crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs
hyperswitch_connectors
struct_definition
34
rust
XenditSplitResponse
null
null
null
null
null
null
null
null
null
null
null
pub struct RefundsResponseData { pub connector_refund_id: String, pub refund_status: common_enums::RefundStatus, // pub amount_received: Option<i32>, // Calculation for amount received not in place yet }
crates/hyperswitch_domain_models/src/router_response_types.rs
hyperswitch_domain_models
struct_definition
51
rust
RefundsResponseData
null
null
null
null
null
null
null
null
null
null
null
impl Worldpayvantiv { pub fn new() -> &'static Self { &Self { amount_converter: &MinorUnitForConnector, } } }
crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
hyperswitch_connectors
impl_block
35
rust
null
Worldpayvantiv
null
impl Worldpayvantiv
null
null
null
null
null
null
null
null
pub struct EncryptionCreateRequest { #[serde(flatten)] pub identifier: Identifier, }
crates/common_utils/src/types/keymanager.rs
common_utils
struct_definition
19
rust
EncryptionCreateRequest
null
null
null
null
null
null
null
null
null
null
null
impl api::PaymentCapture for Moneris {}
crates/hyperswitch_connectors/src/connectors/moneris.rs
hyperswitch_connectors
impl_block
10
rust
null
Moneris
api::PaymentCapture for
impl api::PaymentCapture for for Moneris
null
null
null
null
null
null
null
null
pub async fn retrieve_customer( state: SessionState, merchant_context: domain::MerchantContext, _profile_id: Option<id_type::ProfileId>, customer_id: id_type::CustomerId, ) -> errors::CustomerResponse<customers::CustomerResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let response = db .find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( key_manager_state, &customer_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .switch()? .ok_or(errors::CustomersErrorResponse::CustomerNotFound)?; let address = match &response.address_id { Some(address_id) => Some(api_models::payments::AddressDetails::from( db.find_address_by_address_id( key_manager_state, address_id, merchant_context.get_merchant_key_store(), ) .await .switch()?, )), None => None, }; Ok(services::ApplicationResponse::Json( customers::CustomerResponse::foreign_from((response, address)), )) }
crates/router/src/core/customers.rs
router
function_signature
263
rust
null
null
null
null
retrieve_customer
null
null
null
null
null
null
null
pub async fn delete_disputes( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Vec<Dispute>> { let query = diesel::delete(<Dispute>::table()) .filter(dispute_dsl::merchant_id.eq(merchant_id.to_owned())) .filter(dispute_dsl::dispute_id.like("test_%")); logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while deleting disputes") .and_then(|result| match result.len() { n if n > 0 => { logger::debug!("{n} records deleted"); Ok(result) } 0 => Err(error_stack::report!(errors::DatabaseError::NotFound) .attach_printable("No records deleted")), _ => Ok(result), }) }
crates/diesel_models/src/query/user/sample_data.rs
diesel_models
function_signature
220
rust
null
null
null
null
delete_disputes
null
null
null
null
null
null
null
impl ConnectorSpecifications for Getnet { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&GETNET_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*GETNET_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&GETNET_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/getnet.rs
hyperswitch_connectors
impl_block
105
rust
null
Getnet
ConnectorSpecifications for
impl ConnectorSpecifications for for Getnet
null
null
null
null
null
null
null
null
pub struct PaypalThreeDsParams { pub liability_shift: LiabilityShift, pub three_d_secure: ThreeDsCheck, }
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
hyperswitch_connectors
struct_definition
26
rust
PaypalThreeDsParams
null
null
null
null
null
null
null
null
null
null
null
pub struct CoinbaseWebhookDetails { pub attempt_number: i64, pub event: Event, pub id: String, pub scheduled_for: String, }
crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
hyperswitch_connectors
struct_definition
36
rust
CoinbaseWebhookDetails
null
null
null
null
null
null
null
null
null
null
null
pub struct Sift { amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), }
crates/hyperswitch_connectors/src/connectors/sift.rs
hyperswitch_connectors
struct_definition
27
rust
Sift
null
null
null
null
null
null
null
null
null
null
null
pub struct ErrorResponse { #[serde(rename = "type")] #[schema( example = "invalid_request", value_type = &'static str )] pub error_type: &'static str, #[schema( example = "Missing required param: {param}", value_type = String )] pub message: String, #[schema( example = "IR_04", value_type = String )] pub code: String, #[serde(flatten)] pub extra: Option<Extra>, #[cfg(feature = "detailed_errors")] #[serde(skip_serializing_if = "Option::is_none")] pub stacktrace: Option<serde_json::Value>, }
crates/api_models/src/errors/types.rs
api_models
struct_definition
150
rust
ErrorResponse
null
null
null
null
null
null
null
null
null
null
null
pub async fn call_to_locker( state: &SessionState, payment_methods: Vec<domain::PaymentMethod>, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, merchant_context: &domain::MerchantContext, ) -> CustomResult<usize, errors::ApiErrorResponse> { let mut cards_moved = 0; for pm in payment_methods.into_iter().filter(|pm| { matches!( pm.get_payment_method_type(), Some(storage_enums::PaymentMethod::Card) ) }) { let card = cards::get_card_from_locker( state, customer_id, merchant_id, pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), ) .await; let card = match card { Ok(card) => card, Err(err) => { logger::error!("Failed to fetch card from Basilisk HS locker : {:?}", err); continue; } }; let card_details = api::CardDetail { card_number: card.card_number, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.name_on_card, nick_name: card.nick_name.map(masking::Secret::new), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, }; let pm_create = api::PaymentMethodCreate { payment_method: pm.get_payment_method_type(), payment_method_type: pm.get_payment_method_subtype(), payment_method_issuer: pm.payment_method_issuer, payment_method_issuer_code: pm.payment_method_issuer_code, card: Some(card_details.clone()), #[cfg(feature = "payouts")] wallet: None, #[cfg(feature = "payouts")] bank_transfer: None, metadata: pm.metadata, customer_id: Some(pm.customer_id), card_network: card.card_brand, client_secret: None, payment_method_data: None, billing: None, connector_mandate_details: None, network_transaction_id: None, }; let add_card_result = cards::PmCards{ state, merchant_context, }.add_card_hs( pm_create, &card_details, customer_id, api_enums::LockerChoice::HyperswitchCardVault, Some(pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id)), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!( "Card migration failed for merchant_id: {merchant_id:?}, customer_id: {customer_id:?}, payment_method_id: {} ", pm.payment_method_id )); let (_add_card_rs_resp, _is_duplicate) = match add_card_result { Ok(output) => output, Err(err) => { logger::error!("Failed to add card to Rust locker : {:?}", err); continue; } }; cards_moved += 1; logger::info!( "Card migrated for merchant_id: {merchant_id:?}, customer_id: {customer_id:?}, payment_method_id: {} ", pm.payment_method_id ); } Ok(cards_moved) }
crates/router/src/core/locker_migration.rs
router
function_signature
700
rust
null
null
null
null
call_to_locker
null
null
null
null
null
null
null
pub async fn fetch_merchant_account_for_network_token_webhooks( state: &SessionState, merchant_id: &id_type::MerchantId, ) -> RouterResult<domain::MerchantContext> { let db = &*state.store; let key_manager_state = &(state).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch merchant account for the merchant id")?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), key_store, ))); Ok(merchant_context) }
crates/router/src/core/webhooks/network_tokenization_incoming.rs
router
function_signature
241
rust
null
null
null
null
fetch_merchant_account_for_network_token_webhooks
null
null
null
null
null
null
null
impl api::PaymentSession for Datatrans {}
crates/hyperswitch_connectors/src/connectors/datatrans.rs
hyperswitch_connectors
impl_block
10
rust
null
Datatrans
api::PaymentSession for
impl api::PaymentSession for for Datatrans
null
null
null
null
null
null
null
null
impl api::RefundExecute for Vgs {}
crates/hyperswitch_connectors/src/connectors/vgs.rs
hyperswitch_connectors
impl_block
10
rust
null
Vgs
api::RefundExecute for
impl api::RefundExecute for for Vgs
null
null
null
null
null
null
null
null
pub struct CardData { name: Option<Secret<String>>, expiry_month: Option<Secret<String>>, expiry_year: Option<Secret<String>>, card_type: String, last_four: Secret<String>, card_bin: Option<Secret<String>>, avs_result: String, cvd_result: String, cavv_result: Option<String>, address_match: Option<i32>, postal_result: Option<i32>, avs: Option<AvsObject>, }
crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
hyperswitch_connectors
struct_definition
104
rust
CardData
null
null
null
null
null
null
null
null
null
null
null
impl api::PaymentCapture for Airwallex {}
crates/hyperswitch_connectors/src/connectors/airwallex.rs
hyperswitch_connectors
impl_block
10
rust
null
Airwallex
api::PaymentCapture for
impl api::PaymentCapture for for Airwallex
null
null
null
null
null
null
null
null
&auth::JWTAuth { permission: Permission::ProfileReportRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn generate_merchant_authentication_report( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<ReportRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GenerateAuthenticationReport; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { let user = UserInterface::find_user_by_id(&*state.global_store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; let user_email = UserEmail::from_pii_email(user.email) .change_context(AnalyticsError::UnknownError)? .get_secret(); let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let lambda_req = GenerateReportRequest { request: payload, merchant_id: Some(merchant_id.clone()), auth: AuthInfo::MerchantLevel { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }, email: user_email, }; let json_bytes = serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; invoke_lambda( &state.conf.report_download_config.authentication_function, &state.conf.report_download_config.region, &json_bytes, ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantReportRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn generate_org_authentication_report( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<ReportRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GenerateAuthenticationReport; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { let user = UserInterface::find_user_by_id(&*state.global_store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; let user_email = UserEmail::from_pii_email(user.email) .change_context(AnalyticsError::UnknownError)? .get_secret(); let org_id = auth.merchant_account.get_org_id(); let lambda_req = GenerateReportRequest { request: payload, merchant_id: None, auth: AuthInfo::OrgLevel { org_id: org_id.clone(), }, email: user_email, }; let json_bytes = serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; invoke_lambda( &state.conf.report_download_config.authentication_function, &state.conf.report_download_config.region, &json_bytes, ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::OrganizationReportRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn generate_profile_authentication_report( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<ReportRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GenerateAuthenticationReport; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { let user = UserInterface::find_user_by_id(&*state.global_store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; let user_email = UserEmail::from_pii_email(user.email) .change_context(AnalyticsError::UnknownError)? .get_secret(); let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let profile_id = auth .profile_id .ok_or(report!(UserErrors::JwtProfileIdMissing)) .change_context(AnalyticsError::AccessForbiddenError)?; let lambda_req = GenerateReportRequest { request: payload, merchant_id: Some(merchant_id.clone()), auth: AuthInfo::ProfileLevel { org_id: org_id.clone(), merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }, email: user_email, }; let json_bytes = serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; invoke_lambda( &state.conf.report_download_config.authentication_function, &state.conf.report_download_config.region, &json_bytes, ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileReportRead, }, api_locking::LockAction::NotApplicable, )) .await } /// # Panics /// /// Panics if `json_payload` array does not contain one `GetApiEventMetricRequest` element. pub async fn get_merchant_api_events_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetApiEventMetricRequest; 1]>, ) -> impl Responder { // safety: This shouldn't panic owing to the data type #[allow(clippy::expect_used)] let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetApiEventMetricRequest"); let flow = AnalyticsFlow::GetApiEventMetrics; Box::pin(api::server_wrap( flow, state.clone(), &req, payload, |state, auth: AuthenticationData, req, _| async move { analytics::api_event::get_api_event_metrics( &state.pool, auth.merchant_account.get_id(), req, ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_merchant_api_event_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<GetApiEventFiltersRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetApiEventFilters; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { analytics::api_event::get_filters(&state.pool, req, auth.merchant_account.get_id()) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_profile_connector_events( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Query<api_models::analytics::connector_events::ConnectorEventsRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetConnectorEvents; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { utils::check_if_profile_id_is_present_in_payment_intent( req.payment_id.clone(), &state, &auth, ) .await .change_context(AnalyticsError::AccessForbiddenError)?; connector_events_core(&state.pool, req, auth.merchant_account.get_id()) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_profile_routing_events( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Query<api_models::analytics::routing_events::RoutingEventsRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetRoutingEvents; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { utils::check_if_profile_id_is_present_in_payment_intent( req.payment_id.clone(), &state, &auth, ) .await .change_context(AnalyticsError::AccessForbiddenError)?; routing_events_core(&state.pool, req, auth.merchant_account.get_id()) .await .map(ApplicationResponse::Json) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } pub async fn get_global_search_results( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<GetGlobalSearchRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetGlobalSearchResults; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, auth: UserFromToken, req, _| async move { let role_id = auth.role_id; let role_info = RoleInfo::from_role_id_org_id_tenant_id( &state, &role_id, &auth.org_id, auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError) .change_context(OpenSearchError::UnknownError)?; let permission_groups = role_info.get_permission_groups(); if !permission_groups.contains(&common_enums::PermissionGroup::OperationsView) { return Err(OpenSearchError::AccessForbiddenError)?; } let user_roles: HashSet<UserRole> = match role_info.get_entity_type() { EntityType::Tenant => state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &auth.user_id, tenant_id: auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), org_id: None, merchant_id: None, profile_id: None, entity_id: None, version: None, status: None, limit: None, }) .await .change_context(UserErrors::InternalServerError) .change_context(OpenSearchError::UnknownError)? .into_iter() .collect(), EntityType::Organization | EntityType::Merchant | EntityType::Profile => state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &auth.user_id, tenant_id: auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), org_id: Some(&auth.org_id), merchant_id: None, profile_id: None, entity_id: None, version: None, status: None, limit: None, }) .await .change_context(UserErrors::InternalServerError) .change_context(OpenSearchError::UnknownError)? .into_iter() .collect(), }; let state = Arc::new(state); let role_info_map: HashMap<String, RoleInfo> = user_roles .iter() .map(|user_role| { let state = Arc::clone(&state); let role_id = user_role.role_id.clone(); let org_id = user_role.org_id.clone().unwrap_or_default(); let tenant_id = &user_role.tenant_id; async move { RoleInfo::from_role_id_org_id_tenant_id( &state, &role_id, &org_id, tenant_id, ) .await .change_context(UserErrors::InternalServerError) .change_context(OpenSearchError::UnknownError) .map(|role_info| (role_id, role_info)) } }) .collect::<FuturesUnordered<_>>() .collect::<Vec<_>>() .await .into_iter() .collect::<Result<HashMap<_, _>, _>>()?; let filtered_user_roles: Vec<&UserRole> = user_roles .iter() .filter(|user_role| { let user_role_id = &user_role.role_id; if let Some(role_info) = role_info_map.get(user_role_id) { let permissions = role_info.get_permission_groups(); permissions.contains(&common_enums::PermissionGroup::OperationsView) } else { false } }) .collect(); let search_params: Vec<AuthInfo> = filtered_user_roles .iter() .filter_map(|user_role| { user_role .get_entity_id_and_type() .and_then(|(_, entity_type)| match entity_type { EntityType::Profile => Some(AuthInfo::ProfileLevel { org_id: user_role.org_id.clone()?, merchant_id: user_role.merchant_id.clone()?, profile_ids: vec![user_role.profile_id.clone()?], }), EntityType::Merchant => Some(AuthInfo::MerchantLevel { org_id: user_role.org_id.clone()?, merchant_ids: vec![user_role.merchant_id.clone()?], }), EntityType::Organization => Some(AuthInfo::OrgLevel { org_id: user_role.org_id.clone()?, }), EntityType::Tenant => Some(AuthInfo::OrgLevel { org_id: auth.org_id.clone(), }), }) }) .collect(); analytics::search::msearch_results( state .opensearch_client .as_ref() .ok_or_else(|| error_stack::report!(OpenSearchError::NotEnabled))?, req, search_params, SEARCH_INDEXES.to_vec(), ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_search_results( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<GetSearchRequest>, index: web::Path<SearchIndex>, ) -> impl Responder { let index = index.into_inner(); let flow = AnalyticsFlow::GetSearchResults; let indexed_req = GetSearchRequestWithIndex { search_req: json_payload.into_inner(), index, }; Box::pin(api::server_wrap( flow, state.clone(), &req, indexed_req, |state, auth: UserFromToken, req, _| async move { let role_id = auth.role_id; let role_info = RoleInfo::from_role_id_org_id_tenant_id( &state, &role_id, &auth.org_id, auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError) .change_context(OpenSearchError::UnknownError)?; let permission_groups = role_info.get_permission_groups(); if !permission_groups.contains(&common_enums::PermissionGroup::OperationsView) { return Err(OpenSearchError::AccessForbiddenError)?; } let user_roles: HashSet<UserRole> = match role_info.get_entity_type() { EntityType::Tenant => state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &auth.user_id, tenant_id: auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), org_id: None, merchant_id: None, profile_id: None, entity_id: None, version: None, status: None, limit: None, }) .await .change_context(UserErrors::InternalServerError) .change_context(OpenSearchError::UnknownError)? .into_iter() .collect(), EntityType::Organization | EntityType::Merchant | EntityType::Profile => state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &auth.user_id, tenant_id: auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), org_id: Some(&auth.org_id), merchant_id: None, profile_id: None, entity_id: None, version: None, status: None, limit: None, }) .await .change_context(UserErrors::InternalServerError) .change_context(OpenSearchError::UnknownError)? .into_iter() .collect(), }; let state = Arc::new(state); let role_info_map: HashMap<String, RoleInfo> = user_roles .iter() .map(|user_role| { let state = Arc::clone(&state); let role_id = user_role.role_id.clone(); let org_id = user_role.org_id.clone().unwrap_or_default(); let tenant_id = &user_role.tenant_id; async move { RoleInfo::from_role_id_org_id_tenant_id( &state, &role_id, &org_id, tenant_id, ) .await .change_context(UserErrors::InternalServerError) .change_context(OpenSearchError::UnknownError) .map(|role_info| (role_id, role_info)) } }) .collect::<FuturesUnordered<_>>() .collect::<Vec<_>>() .await .into_iter() .collect::<Result<HashMap<_, _>, _>>()?; let filtered_user_roles: Vec<&UserRole> = user_roles .iter() .filter(|user_role| { let user_role_id = &user_role.role_id; if let Some(role_info) = role_info_map.get(user_role_id) { let permissions = role_info.get_permission_groups(); permissions.contains(&common_enums::PermissionGroup::OperationsView) } else { false } }) .collect(); let search_params: Vec<AuthInfo> = filtered_user_roles .iter() .filter_map(|user_role| { user_role .get_entity_id_and_type() .and_then(|(_, entity_type)| match entity_type { EntityType::Profile => Some(AuthInfo::ProfileLevel { org_id: user_role.org_id.clone()?, merchant_id: user_role.merchant_id.clone()?, profile_ids: vec![user_role.profile_id.clone()?], }), EntityType::Merchant => Some(AuthInfo::MerchantLevel { org_id: user_role.org_id.clone()?, merchant_ids: vec![user_role.merchant_id.clone()?], }), EntityType::Organization => Some(AuthInfo::OrgLevel { org_id: user_role.org_id.clone()?, }), EntityType::Tenant => Some(AuthInfo::OrgLevel { org_id: auth.org_id.clone(), }), }) }) .collect(); analytics::search::search_results( state .opensearch_client .as_ref() .ok_or_else(|| error_stack::report!(OpenSearchError::NotEnabled))?, req, search_params, ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_merchant_dispute_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<api_models::analytics::GetDisputeFilterRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetDisputeFilters; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let auth: AuthInfo = AuthInfo::MerchantLevel { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; analytics::disputes::get_filters(&state.pool, req, &auth) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_profile_dispute_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<api_models::analytics::GetDisputeFilterRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetDisputeFilters; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let profile_id = auth .profile_id .ok_or(report!(UserErrors::JwtProfileIdMissing)) .change_context(AnalyticsError::AccessForbiddenError)?; let auth: AuthInfo = AuthInfo::ProfileLevel { org_id: org_id.clone(), merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; analytics::disputes::get_filters(&state.pool, req, &auth) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_org_dispute_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<api_models::analytics::GetDisputeFilterRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetDisputeFilters; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; analytics::disputes::get_filters(&state.pool, req, &auth) .await .map(ApplicationResponse::Json) }, auth::auth_type( &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: false, organization_id: None, }, &auth::JWTAuth { permission: Permission::OrganizationAnalyticsRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// # Panics /// /// Panics if `json_payload` array does not contain one `GetDisputeMetricRequest` element. pub async fn get_merchant_dispute_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetDisputeMetricRequest; 1]>, ) -> impl Responder { // safety: This shouldn't panic owing to the data type #[allow(clippy::expect_used)] let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetDisputeMetricRequest"); let flow = AnalyticsFlow::GetDisputeMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let auth: AuthInfo = AuthInfo::MerchantLevel { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; analytics::disputes::get_metrics(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// # Panics /// /// Panics if `json_payload` array does not contain one `GetDisputeMetricRequest` element. pub async fn get_profile_dispute_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetDisputeMetricRequest; 1]>, ) -> impl Responder { // safety: This shouldn't panic owing to the data type #[allow(clippy::expect_used)] let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetDisputeMetricRequest"); let flow = AnalyticsFlow::GetDisputeMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let profile_id = auth .profile_id .ok_or(report!(UserErrors::JwtProfileIdMissing)) .change_context(AnalyticsError::AccessForbiddenError)?; let auth: AuthInfo = AuthInfo::ProfileLevel { org_id: org_id.clone(), merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; analytics::disputes::get_metrics(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// # Panics /// /// Panics if `json_payload` array does not contain one `GetDisputeMetricRequest` element. pub async fn get_org_dispute_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetDisputeMetricRequest; 1]>, ) -> impl Responder { // safety: This shouldn't panic owing to the data type #[allow(clippy::expect_used)] let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetDisputeMetricRequest"); let flow = AnalyticsFlow::GetDisputeMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; analytics::disputes::get_metrics(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, auth::auth_type( &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: false, organization_id: None, }, &auth::JWTAuth { permission: Permission::OrganizationAnalyticsRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } pub async fn get_merchant_sankey( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<TimeRange>, ) -> impl Responder { let flow = AnalyticsFlow::GetSankey; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let auth: AuthInfo = AuthInfo::MerchantLevel { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; analytics::payment_intents::get_sankey(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_merchant_auth_event_sankey( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<TimeRange>, ) -> impl Responder { let flow = AnalyticsFlow::GetSankey; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let auth: AuthInfo = AuthInfo::MerchantLevel { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; analytics::auth_events::get_sankey(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_org_auth_event_sankey( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<TimeRange>, ) -> impl Responder { let flow = AnalyticsFlow::GetSankey; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; analytics::auth_events::get_sankey(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, auth::auth_type( &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: false, organization_id: None, }, &auth::JWTAuth { permission: Permission::OrganizationAnalyticsRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_profile_auth_event_sankey( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<TimeRange>, ) -> impl Responder { let flow = AnalyticsFlow::GetSankey; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let profile_id = auth .profile_id .ok_or(report!(UserErrors::JwtProfileIdMissing)) .change_context(AnalyticsError::AccessForbiddenError)?; let auth: AuthInfo = AuthInfo::ProfileLevel { org_id: org_id.clone(), merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; analytics::auth_events::get_sankey(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_org_sankey( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<TimeRange>, ) -> impl Responder { let flow = AnalyticsFlow::GetSankey; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; analytics::payment_intents::get_sankey(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, auth::auth_type( &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: false, organization_id: None, }, &auth::JWTAuth { permission: Permission::OrganizationAnalyticsRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_profile_sankey( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<TimeRange>, ) -> impl Responder { let flow = AnalyticsFlow::GetSankey; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state: crate::routes::SessionState, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let profile_id = auth .profile_id .ok_or(report!(UserErrors::JwtProfileIdMissing)) .change_context(AnalyticsError::AccessForbiddenError)?; let auth: AuthInfo = AuthInfo::ProfileLevel { org_id: org_id.clone(), merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; analytics::payment_intents::get_sankey(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } }
crates/router/src/analytics.rs#chunk2
router
chunk
7,809
null
null
null
null
null
null
null
null
null
null
null
null
null
File: crates/router/tests/connectors/checkout.rs use masking::Secret; use router::types::{self, domain, storage::enums}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct CheckoutTest; impl ConnectorActions for CheckoutTest {} impl utils::Connector for CheckoutTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Checkout; utils::construct_connector_data_old( Box::new(Checkout::new()), types::Connector::Checkout, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .checkout .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "checkout".to_string() } } static CONNECTOR: CheckoutTest = CheckoutTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[serial_test::serial] #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[serial_test::serial] #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[serial_test::serial] #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[serial_test::serial] #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[serial_test::serial] #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[serial_test::serial] #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[serial_test::serial] #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector Error, needs to be looked into and fixed"] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[serial_test::serial] #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[serial_test::serial] #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[serial_test::serial] #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[serial_test::serial] #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[serial_test::serial] #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector Error, needs to be looked into and fixed"] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); tokio::time::sleep(std::time::Duration::from_secs(5)).await; let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[serial_test::serial] #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "cvv_invalid".to_string(), ); } // Creates a payment with incorrect expiry month. #[serial_test::serial] #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "card_expiry_month_invalid".to_string(), ); } // Creates a payment with incorrect expiry year. #[serial_test::serial] #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "card_expired".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[serial_test::serial] #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!(void_response.response.unwrap_err().status_code, 403); } // Captures a payment using invalid connector payment id. #[serial_test::serial] #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!(capture_response.response.unwrap_err().status_code, 404); } // Refunds a payment with refund amount higher than payment amount. #[serial_test::serial] #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "refund_amount_exceeds_balance", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
crates/router/tests/connectors/checkout.rs
router
full_file
3,015
null
null
null
null
null
null
null
null
null
null
null
null
null
pub async fn create_pm_collect_db_entry( state: &SessionState, merchant_context: &domain::MerchantContext, pm_collect_link_data: &PaymentMethodCollectLinkData, return_url: Option<String>, ) -> RouterResult<PaymentMethodCollectLink> { let db: &dyn StorageInterface = &*state.store; let link_data = serde_json::to_value(pm_collect_link_data) .map_err(|_| report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable("Failed to convert PaymentMethodCollectLinkData to Value")?; let pm_collect_link = GenericLinkNew { link_id: pm_collect_link_data.pm_collect_link_id.to_string(), primary_reference: pm_collect_link_data .customer_id .get_string_repr() .to_string(), merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), link_type: common_enums::GenericLinkType::PaymentMethodCollect, link_data, url: pm_collect_link_data.link.clone(), return_url, expiry: common_utils::date_time::now() + Duration::seconds(pm_collect_link_data.session_expiry.into()), ..Default::default() }; db.insert_pm_collect_link(pm_collect_link) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: "payment method collect link already exists".to_string(), }) }
crates/router/src/core/payment_methods.rs
router
function_signature
297
rust
null
null
null
null
create_pm_collect_db_entry
null
null
null
null
null
null
null
pub async fn find_by_merchant_id_payment_id_connector_dispute_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, connector_dispute_id: &str, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())) .and(dsl::connector_dispute_id.eq(connector_dispute_id.to_owned())), ) .await }
crates/diesel_models/src/query/dispute.rs
diesel_models
function_signature
149
rust
null
null
null
null
find_by_merchant_id_payment_id_connector_dispute_id
null
null
null
null
null
null
null
impl api::Payment for Hyperwallet {}
crates/hyperswitch_connectors/src/connectors/hyperwallet.rs
hyperswitch_connectors
impl_block
8
rust
null
Hyperwallet
api::Payment for
impl api::Payment for for Hyperwallet
null
null
null
null
null
null
null
null
pub fn inner(&self) -> &T { &self.0 }
crates/hyperswitch_domain_models/src/type_encryption.rs
hyperswitch_domain_models
function_signature
18
rust
null
null
null
null
inner
null
null
null
null
null
null
null
pub struct StripeCard { pub number: cards::CardNumber, pub exp_month: masking::Secret<String>, pub exp_year: masking::Secret<String>, pub cvc: masking::Secret<String>, pub holder_name: Option<masking::Secret<String>>, }
crates/router/src/compatibility/stripe/payment_intents/types.rs
router
struct_definition
58
rust
StripeCard
null
null
null
null
null
null
null
null
null
null
null
state, req_state, merchant_context, &profile, operation, payment_sync_request, get_tracker_response, call_connector_action, HeaderPayload::default(), )) .await?; Ok(router_types::RedirectPaymentFlowResponse { payment_data, profile, }) } fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, ) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>> { let payment_intent = &payment_flow_response.payment_data.payment_intent; let profile = &payment_flow_response.profile; let return_url = payment_intent .return_url .as_ref() .or(profile.return_url.as_ref()) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("return url not found in payment intent and profile")? .to_owned(); let return_url = return_url .add_query_params(("id", payment_intent.id.get_string_repr())) .add_query_params(("status", &payment_intent.status.to_string())); let return_url_str = return_url.into_inner().to_string(); Ok(services::ApplicationResponse::JsonForRedirection( api::RedirectionResponse { return_url_with_query_params: return_url_str, }, )) } fn get_payment_action(&self) -> services::PaymentAction { services::PaymentAction::PSync } } #[derive(Clone, Debug)] pub struct PaymentAuthenticateCompleteAuthorize; #[cfg(feature = "v1")] #[async_trait::async_trait] impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize { type PaymentFlowResponse = router_types::AuthenticatePaymentFlowResponse; #[allow(clippy::too_many_arguments)] async fn call_payment_flow( &self, state: &SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, req: PaymentsRedirectResponseData, connector_action: CallConnectorAction, connector: String, payment_id: id_type::PaymentId, ) -> RouterResult<Self::PaymentFlowResponse> { let merchant_id = merchant_context.get_merchant_account().get_id().clone(); let key_manager_state = &state.into(); let payment_intent = state .store .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, &merchant_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_attempt = state .store .find_payment_attempt_by_attempt_id_merchant_id( &payment_intent.active_attempt.get_id(), &merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let authentication_id = payment_attempt .authentication_id .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing authentication_id in payment_attempt")?; let authentication = state .store .find_authentication_by_merchant_id_authentication_id(&merchant_id, &authentication_id) .await .to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound { id: authentication_id.get_string_repr().to_string(), })?; // Fetching merchant_connector_account to check if pull_mechanism is enabled for 3ds connector let authentication_merchant_connector_account = helpers::get_merchant_connector_account( state, &merchant_id, None, merchant_context.get_merchant_key_store(), &payment_intent .profile_id .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing profile_id in payment_intent")?, &payment_attempt .authentication_connector .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing authentication connector in payment_intent")?, None, ) .await?; let is_pull_mechanism_enabled = utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata( authentication_merchant_connector_account .get_metadata() .map(|metadata| metadata.expose()), ); let response = if is_pull_mechanism_enabled || authentication.authentication_type != Some(common_enums::DecoupledAuthenticationType::Challenge) { let payment_confirm_req = api::PaymentsRequest { payment_id: Some(req.resource_id.clone()), merchant_id: req.merchant_id.clone(), feature_metadata: Some(api_models::payments::FeatureMetadata { redirect_response: Some(api_models::payments::RedirectResponse { param: req.param.map(Secret::new), json_payload: Some( req.json_payload.unwrap_or(serde_json::json!({})).into(), ), }), search_tags: None, apple_pay_recurring_details: None, }), ..Default::default() }; Box::pin(payments_core::< api::Authorize, api::PaymentsResponse, _, _, _, _, >( state.clone(), req_state, merchant_context.clone(), None, PaymentConfirm, payment_confirm_req, services::api::AuthFlow::Merchant, connector_action, None, HeaderPayload::with_source(enums::PaymentSource::ExternalAuthenticator), )) .await? } else { let payment_sync_req = api::PaymentsRetrieveRequest { resource_id: req.resource_id, merchant_id: req.merchant_id, param: req.param, force_sync: req.force_sync, connector: req.connector, merchant_connector_details: req.creds_identifier.map(|creds_id| { api::MerchantConnectorDetailsWrap { creds_identifier: creds_id, encoded_data: None, } }), client_secret: None, expand_attempts: None, expand_captures: None, all_keys_required: None, }; Box::pin( payments_core::<api::PSync, api::PaymentsResponse, _, _, _, _>( state.clone(), req_state, merchant_context.clone(), None, PaymentStatus, payment_sync_req, services::api::AuthFlow::Merchant, connector_action, None, HeaderPayload::default(), ), ) .await? }; let payments_response = match response { services::ApplicationResponse::Json(response) => Ok(response), services::ApplicationResponse::JsonWithHeaders((response, _)) => Ok(response), _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the response in json"), }?; // When intent status is RequiresCustomerAction, Set poll_id in redis to allow the fetch status of poll through retrieve_poll_status api from client if payments_response.status == common_enums::IntentStatus::RequiresCustomerAction { let req_poll_id = core_utils::get_external_authentication_request_poll_id(&payment_id); let poll_id = core_utils::get_poll_id(&merchant_id, req_poll_id.clone()); let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; redis_conn .set_key_with_expiry( &poll_id.into(), api_models::poll::PollStatus::Pending.to_string(), consts::POLL_ID_TTL, ) .await .change_context(errors::StorageError::KVError) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add poll_id in redis")?; }; let default_poll_config = router_types::PollConfig::default(); let default_config_str = default_poll_config .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while stringifying default poll config")?; let poll_config = state .store .find_config_by_key_unwrap_or( &router_types::PollConfig::get_poll_config_key(connector), Some(default_config_str), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("The poll config was not found in the DB")?; let poll_config: router_types::PollConfig = poll_config .config .parse_struct("PollConfig") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while parsing PollConfig")?; let profile_id = payments_response .profile_id .as_ref() .get_required_value("profile_id")?; let business_profile = state .store .find_business_profile_by_profile_id( key_manager_state, merchant_context.get_merchant_key_store(), profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(router_types::AuthenticatePaymentFlowResponse { payments_response, poll_config, business_profile, }) } fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, payment_id: id_type::PaymentId, connector: String, ) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>> { let payments_response = &payment_flow_response.payments_response; let redirect_response = helpers::get_handle_response_url( payment_id.clone(), &payment_flow_response.business_profile, payments_response, connector.clone(), )?; // html script to check if inside iframe, then send post message to parent for redirection else redirect self to return_url let html = core_utils::get_html_redirect_response_for_external_authentication( redirect_response.return_url_with_query_params, payments_response, payment_id, &payment_flow_response.poll_config, )?; Ok(services::ApplicationResponse::Form(Box::new( services::RedirectionFormData { redirect_form: services::RedirectForm::Html { html_data: html }, payment_method_data: None, amount: payments_response.amount.to_string(), currency: payments_response.currency.clone(), }, ))) } fn get_payment_action(&self) -> services::PaymentAction { services::PaymentAction::PaymentAuthenticateCompleteAuthorize } } #[cfg(feature = "v1")] pub async fn get_decrypted_wallet_payment_method_token<F, Req, D>( operation: &BoxedOperation<'_, F, Req, D>, state: &SessionState, merchant_context: &domain::MerchantContext, payment_data: &mut D, connector_call_type_optional: Option<&ConnectorCallType>, ) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse> where F: Send + Clone + Sync, D: OperationSessionGetters<F> + Send + Sync + Clone, { if is_operation_confirm(operation) && payment_data.get_payment_attempt().payment_method == Some(storage_enums::PaymentMethod::Wallet) { let wallet_type = payment_data .get_payment_attempt() .payment_method_type .get_required_value("payment_method_type")?; let wallet: Box<dyn WalletFlow<F, D>> = match wallet_type { storage_enums::PaymentMethodType::ApplePay => Box::new(ApplePayWallet), storage_enums::PaymentMethodType::Paze => Box::new(PazeWallet), storage_enums::PaymentMethodType::GooglePay => Box::new(GooglePayWallet), _ => return Ok(None), }; // Check if the wallet has already decrypted the token from the payment data. // If a pre-decrypted token is available, use it directly to avoid redundant decryption. if let Some(predecrypted_token) = wallet.check_predecrypted_token(payment_data)? { logger::debug!("Using predecrypted token for wallet"); return Ok(Some(predecrypted_token)); } let merchant_connector_account = get_merchant_connector_account_for_wallet_decryption_flow::<F, D>( state, merchant_context, payment_data, connector_call_type_optional, ) .await?; let decide_wallet_flow = &wallet .decide_wallet_flow(state, payment_data, &merchant_connector_account) .attach_printable("Failed to decide wallet flow")? .async_map(|payment_price_data| async move { wallet .decrypt_wallet_token(&payment_price_data, payment_data) .await }) .await .transpose() .attach_printable("Failed to decrypt Wallet token")?; Ok(decide_wallet_flow.clone()) } else { Ok(None) } } #[cfg(feature = "v1")] pub async fn get_merchant_connector_account_for_wallet_decryption_flow<F, D>( state: &SessionState, merchant_context: &domain::MerchantContext, payment_data: &mut D, connector_call_type_optional: Option<&ConnectorCallType>, ) -> RouterResult<helpers::MerchantConnectorAccountType> where F: Send + Clone + Sync, D: OperationSessionGetters<F> + Send + Sync + Clone, { let connector_call_type = connector_call_type_optional .get_required_value("connector_call_type") .change_context(errors::ApiErrorResponse::InternalServerError)?; let connector_routing_data = match connector_call_type { ConnectorCallType::PreDetermined(connector_routing_data) => connector_routing_data, ConnectorCallType::Retryable(connector_routing_data) => connector_routing_data .first() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Found no connector routing data in retryable call")?, ConnectorCallType::SessionMultiple(_session_connector_data) => { return Err(errors::ApiErrorResponse::InternalServerError).attach_printable( "SessionMultiple connector call type is invalid in confirm calls", ); } }; construct_profile_id_and_get_mca( state, merchant_context, payment_data, &connector_routing_data .connector_data .connector_name .to_string(), connector_routing_data .connector_data .merchant_connector_id .as_ref(), false, ) .await } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>( state: &SessionState, req_state: ReqState, merchant_context: &domain::MerchantContext, connector: api::ConnectorData, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, customer: &Option<domain::Customer>, call_connector_action: CallConnectorAction, validate_result: &operations::ValidateResult, schedule_time: Option<time::PrimitiveDateTime>, header_payload: HeaderPayload, frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &domain::Profile, is_retry_payment: bool, return_raw_connector_response: Option<bool>, merchant_connector_account: helpers::MerchantConnectorAccountType, mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>, tokenization_action: TokenizationAction, ) -> RouterResult<( RouterData<F, RouterDReq, router_types::PaymentsResponseData>, helpers::MerchantConnectorAccountType, )> where F: Send + Clone + Sync, RouterDReq: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { let add_access_token_result = router_data .add_access_token( state, &connector, merchant_context, payment_data.get_creds_identifier(), ) .await?; router_data = router_data.add_session_token(state, &connector).await?; let should_continue_further = access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &call_connector_action, ); let should_continue_further = match router_data .create_order_at_connector(state, &connector, should_continue_further) .await? { Some(create_order_response) => { if let Ok(order_id) = create_order_response.clone().create_order_result { payment_data.set_connector_response_reference_id(Some(order_id.clone())) } // Set the response in routerdata response to carry forward router_data .update_router_data_with_create_order_response(create_order_response.clone()); create_order_response.create_order_result.ok().is_some() } // If create order is not required, then we can proceed with further processing None => true, }; let updated_customer = call_create_connector_customer_if_required( state, customer, merchant_context, &merchant_connector_account, payment_data, router_data.access_token.as_ref(), ) .await?; #[cfg(feature = "v1")] if let Some(connector_customer_id) = payment_data.get_connector_customer_id() { router_data.connector_customer = Some(connector_customer_id); } router_data.payment_method_token = payment_data.get_payment_method_token().cloned(); let payment_method_token_response = router_data .add_payment_method_token( state, &connector, &tokenization_action, should_continue_further, ) .await?; let mut should_continue_further = tokenization::update_router_data_with_payment_method_token_result( payment_method_token_response, &mut router_data, is_retry_payment, should_continue_further, ); (router_data, should_continue_further) = complete_preprocessing_steps_if_required( state, &connector, payment_data, router_data, operation, should_continue_further, ) .await?; if let Ok(router_types::PaymentsResponseData::PreProcessingResponse { session_token: Some(session_token), .. }) = router_data.response.to_owned() { payment_data.push_sessions_token(session_token); }; // In case of authorize flow, pre-task and post-tasks are being called in build request // if we do not want to proceed further, then the function will return Ok(None, false) let (connector_request, should_continue_further) = if should_continue_further { // Check if the actual flow specific request can be built with available data router_data .build_flow_specific_connector_request(state, &connector, call_connector_action.clone()) .await? } else { (None, false) }; if should_add_task_to_process_tracker(payment_data) { operation .to_domain()? .add_task_to_process_tracker( state, payment_data.get_payment_attempt(), validate_result.requeue, schedule_time, ) .await .map_err(|error| logger::error!(process_tracker_error=?error)) .ok(); } // Update the payment trackers just before calling the connector // Since the request is already built in the previous step, // there should be no error in request construction from hyperswitch end (_, *payment_data) = operation .to_update_tracker()? .update_trackers( state, req_state, payment_data.clone(), customer.clone(), merchant_context.get_merchant_account().storage_scheme, updated_customer, merchant_context.get_merchant_key_store(), frm_suggestion, header_payload.clone(), ) .await?; let router_data = if should_continue_further { // The status of payment_attempt and intent will be updated in the previous step // update this in router_data. // This is added because few connector integrations do not update the status, // and rely on previous status set in router_data router_data.status = payment_data.get_payment_attempt().status; router_data .decide_flows( state, &connector, call_connector_action, connector_request, business_profile, header_payload.clone(), return_raw_connector_response, ) .await } else { Ok(router_data) }?; Ok((router_data, merchant_connector_account)) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn call_connector_service_prerequisites<F, RouterDReq, ApiRequest, D>( state: &SessionState, merchant_context: &domain::MerchantContext, connector: api::ConnectorData, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, customer: &Option<domain::Customer>, validate_result: &operations::ValidateResult, business_profile: &domain::Profile, should_retry_with_pan: bool, routing_decision: Option<routing_helpers::RoutingDecisionData>, ) -> RouterResult<( helpers::MerchantConnectorAccountType, RouterData<F, RouterDReq, router_types::PaymentsResponseData>, TokenizationAction, )> where F: Send + Clone + Sync, RouterDReq: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { let merchant_connector_account = construct_profile_id_and_get_mca( state, merchant_context, payment_data, &connector.connector_name.to_string(), connector.merchant_connector_id.as_ref(), false, ) .await?; let customer_acceptance = payment_data .get_payment_attempt() .customer_acceptance .clone(); if is_pre_network_tokenization_enabled( state, business_profile, customer_acceptance, connector.connector_name, ) { let payment_method_data = payment_data.get_payment_method_data(); let customer_id = payment_data.get_payment_intent().customer_id.clone(); if let (Some(domain::PaymentMethodData::Card(card_data)), Some(customer_id)) = (payment_method_data, customer_id) { let vault_operation = get_vault_operation_for_pre_network_tokenization(state, customer_id, card_data) .await; match vault_operation { payments::VaultOperation::SaveCardAndNetworkTokenData( card_and_network_token_data, ) => { payment_data.set_vault_operation( payments::VaultOperation::SaveCardAndNetworkTokenData(Box::new( *card_and_network_token_data.clone(), )), ); payment_data.set_payment_method_data(Some( domain::PaymentMethodData::NetworkToken( card_and_network_token_data .network_token .network_token_data .clone(), ), )); } payments::VaultOperation::SaveCardData(card_data_for_vault) => payment_data .set_vault_operation(payments::VaultOperation::SaveCardData( card_data_for_vault.clone(), )), payments::VaultOperation::ExistingVaultData(_) => (), } } } if payment_data .get_payment_attempt() .merchant_connector_id .is_none() { payment_data.set_merchant_connector_id_in_attempt(merchant_connector_account.get_mca_id()); } operation .to_domain()? .populate_payment_data( state, payment_data, merchant_context, business_profile, &connector, ) .await?; let (pd, tokenization_action) = get_connector_tokenization_action_when_confirm_true( state, operation, payment_data, validate_result, merchant_context.get_merchant_key_store(), customer, business_profile, should_retry_with_pan, ) .await?; *payment_data = pd; // This is used to apply any kind of routing decision to the required data, // before the call to `connector` is made. routing_decision.map(|decision| decision.apply_routing_decision(payment_data)); // Validating the blocklist guard and generate the fingerprint blocklist_guard(state, merchant_context, operation, payment_data).await?; let merchant_recipient_data = payment_data .get_merchant_recipient_data( state, merchant_context, &merchant_connector_account, &connector, ) .await?; let router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_context, customer, &merchant_connector_account, merchant_recipient_data, None, ) .await?; let connector_request_reference_id = router_data.connector_request_reference_id.clone(); payment_data .set_connector_request_reference_id_in_payment_attempt(connector_request_reference_id); Ok((merchant_connector_account, router_data, tokenization_action)) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn decide_unified_connector_service_call<F, RouterDReq, ApiRequest, D>( state: &SessionState, req_state: ReqState, merchant_context: &domain::MerchantContext, connector: api::ConnectorData, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, customer: &Option<domain::Customer>, call_connector_action: CallConnectorAction, validate_result: &operations::ValidateResult, schedule_time: Option<time::PrimitiveDateTime>, header_payload: HeaderPayload, frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &domain::Profile, is_retry_payment: bool, all_keys_required: Option<bool>, merchant_connector_account: helpers::MerchantConnectorAccountType, mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>, tokenization_action: TokenizationAction, ) -> RouterResult<( RouterData<F, RouterDReq, router_types::PaymentsResponseData>, helpers::MerchantConnectorAccountType, )> where F: Send + Clone + Sync, RouterDReq: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { record_time_taken_with(|| async { if !matches!( call_connector_action, CallConnectorAction::UCSHandleResponse(_) ) && !matches!( call_connector_action, CallConnectorAction::HandleResponse(_), ) && should_call_unified_connector_service( state, merchant_context, &router_data, Some(payment_data), ) .await? { router_env::logger::info!( "Processing payment through UCS gateway system - payment_id={}, attempt_id={}", payment_data .get_payment_intent() .payment_id .get_string_repr(), payment_data.get_payment_attempt().attempt_id ); if should_add_task_to_process_tracker(payment_data) { operation .to_domain()? .add_task_to_process_tracker( state, payment_data.get_payment_attempt(), validate_result.requeue, schedule_time, ) .await .map_err(|error| logger::error!(process_tracker_error=?error)) .ok(); } // Update feature metadata to track UCS usage for stickiness update_gateway_system_in_feature_metadata( payment_data, GatewaySystem::UnifiedConnectorService, )?; (_, *payment_data) = operation .to_update_tracker()? .update_trackers( state, req_state, payment_data.clone(), customer.clone(), merchant_context.get_merchant_account().storage_scheme, None, merchant_context.get_merchant_key_store(), frm_suggestion, header_payload.clone(), ) .await?; router_data .call_unified_connector_service( state, merchant_connector_account.clone(), merchant_context, ) .await?; Ok((router_data, merchant_connector_account)) } else { router_env::logger::info!( "Processing payment through Direct gateway system - payment_id={}, attempt_id={}", payment_data .get_payment_intent() .payment_id .get_string_repr(), payment_data.get_payment_attempt().attempt_id ); // Update feature metadata to track Direct routing usage for stickiness update_gateway_system_in_feature_metadata(payment_data, GatewaySystem::Direct)?; call_connector_service( state, req_state, merchant_context, connector, operation, payment_data, customer, call_connector_action, validate_result, schedule_time, header_payload, frm_suggestion, business_profile, is_retry_payment, all_keys_required, merchant_connector_account, router_data, tokenization_action, ) .await } }) .await } async fn record_time_taken_with<F, Fut, R>(f: F) -> RouterResult<R> where F: FnOnce() -> Fut, Fut: future::Future<Output = RouterResult<R>>, { let stime = Instant::now(); let result = f().await; let etime = Instant::now(); let duration = etime.saturating_duration_since(stime); tracing::info!(duration = format!("Duration taken: {}", duration.as_millis())); result } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>( state: &SessionState, req_state: ReqState, merchant_context: &domain::MerchantContext, connector: api::ConnectorData, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, customer: &Option<domain::Customer>, call_connector_action: CallConnectorAction, schedule_time: Option<time::PrimitiveDateTime>, header_payload: HeaderPayload, frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &domain::Profile, is_retry_payment: bool, should_retry_with_pan: bool, return_raw_connector_response: Option<bool>, merchant_connector_account_type_details: domain::MerchantConnectorAccountTypeDetails, mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>, updated_customer: Option<storage::CustomerUpdate>, ) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, RouterDReq: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { let add_access_token_result = router_data .add_access_token( state, &connector, merchant_context, payment_data.get_creds_identifier(), ) .await?; router_data = router_data.add_session_token(state, &connector).await?; let should_continue_further = access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &call_connector_action, ); let should_continue = match router_data .create_order_at_connector(state, &connector, should_continue_further) .await? { Some(create_order_response) => { if let Ok(order_id) = create_order_response.clone().create_order_result { payment_data.set_connector_response_reference_id(Some(order_id)) } // Set the response in routerdata response to carry forward router_data .update_router_data_with_create_order_response(create_order_response.clone()); create_order_response.create_order_result.ok().map(|_| ()) } // If create order is not required, then we can proceed with further processing None => Some(()), }; // In case of authorize flow, pre-task and post-tasks are being called in build request // if we do not want to proceed further, then the function will return Ok(None, false) let (connector_request, should_continue_further) = match should_continue { Some(_) => { router_data .build_flow_specific_connector_request( state, &connector, call_connector_action.clone(), ) .await? } None => (None, false), }; // Update the payment trackers just before calling the connector // Since the request is already built in the previous step, // there should be no error in request construction from hyperswitch end (_, *payment_data) = operation .to_update_tracker()? .update_trackers( state, req_state, payment_data.clone(), customer.clone(), merchant_context.get_merchant_account().storage_scheme, updated_customer, merchant_context.get_merchant_key_store(), frm_suggestion, header_payload.clone(), ) .await?; let router_data = if should_continue_further { // The status of payment_attempt and intent will be updated in the previous step // update this in router_data. // This is added because few connector integrations do not update the status, // and rely on previous status set in router_data // TODO: status is already set when constructing payment data, why should this be done again? // router_data.status = payment_data.get_payment_attempt().status; router_data .decide_flows( state, &connector, call_connector_action, connector_request, business_profile, header_payload.clone(), return_raw_connector_response, ) .await } else { Ok(router_data) }?; Ok(router_data) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] #[allow(clippy::type_complexity)] #[instrument(skip_all)] pub async fn call_connector_service_prerequisites<F, RouterDReq, ApiRequest, D>( state: &SessionState, req_state: ReqState, merchant_context: &domain::MerchantContext, connector: api::ConnectorData, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, customer: &Option<domain::Customer>, call_connector_action: CallConnectorAction, schedule_time: Option<time::PrimitiveDateTime>, header_payload: HeaderPayload, frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &domain::Profile, is_retry_payment: bool, should_retry_with_pan: bool, all_keys_required: Option<bool>, ) -> RouterResult<( domain::MerchantConnectorAccountTypeDetails, Option<storage::CustomerUpdate>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>, )> where F: Send + Clone + Sync, RouterDReq: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { let merchant_connector_account_type_details = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new( helpers::get_merchant_connector_account_v2( state, merchant_context.get_merchant_key_store(), connector.merchant_connector_id.as_ref(), ) .await?, )); operation .to_domain()? .populate_payment_data( state, payment_data, merchant_context, business_profile, &connector, ) .await?; let updated_customer = call_create_connector_customer_if_required( state, customer, merchant_context, &merchant_connector_account_type_details, payment_data, ) .await?; let router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_context, customer, &merchant_connector_account_type_details, None, None, ) .await?; Ok(( merchant_connector_account_type_details, updated_customer, router_data, )) }
crates/router/src/core/payments.rs#chunk3
router
chunk
8,191
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct PlacetopayError { pub status: PlacetopayErrorStatus, pub message: String, pub reason: String, }
crates/hyperswitch_connectors/src/connectors/placetopay/transformers.rs
hyperswitch_connectors
struct_definition
32
rust
PlacetopayError
null
null
null
null
null
null
null
null
null
null
null
pub struct MifinityRouterData<T> { pub amount: StringMajorUnit, pub router_data: T, }
crates/hyperswitch_connectors/src/connectors/mifinity/transformers.rs
hyperswitch_connectors
struct_definition
26
rust
MifinityRouterData
null
null
null
null
null
null
null
null
null
null
null
pub fn is_key_deleted(&self) -> bool { matches!(self, Self::KeyDeleted) }
crates/redis_interface/src/types.rs
redis_interface
function_signature
23
rust
null
null
null
null
is_key_deleted
null
null
null
null
null
null
null
File: crates/router/src/locale.rs use rust_i18n::i18n; i18n!("locales", fallback = "en");
crates/router/src/locale.rs
router
full_file
32
null
null
null
null
null
null
null
null
null
null
null
null
null
/// Returns customer_user_agent_extended with customer_user_agent as fallback pub fn get_user_agent_extended(&self) -> Option<String> { self.customer_user_agent_extended .clone() .or_else(|| self.customer_user_agent.clone()) }
crates/diesel_models/src/mandate.rs
diesel_models
function_signature
52
rust
null
null
null
null
get_user_agent_extended
null
null
null
null
null
null
null
pub fn add_negative_filter_clause( &mut self, key: impl ToSql<T>, value: impl ToSql<T>, ) -> QueryResult<()> { self.add_custom_filter_clause(key, value, FilterTypes::NotEqual) }
crates/analytics/src/query.rs
analytics
function_signature
53
rust
null
null
null
null
add_negative_filter_clause
null
null
null
null
null
null
null
pub const fn new() -> &'static Self { &Self { amount_converter: &StringMajorUnitForConnector, amount_converter_webhooks: &StringMinorUnitForConnector, } }
crates/hyperswitch_connectors/src/connectors/braintree.rs
hyperswitch_connectors
function_signature
42
rust
null
null
null
null
new
null
null
null
null
null
null
null
pub fn get_merchant_id(&self) -> id_type::MerchantId { self.merchant_id.clone() }
crates/router/src/types/domain/user.rs
router
function_signature
25
rust
null
null
null
null
get_merchant_id
null
null
null
null
null
null
null
impl MandateNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Mandate> { generics::generic_insert(conn, self).await } }
crates/diesel_models/src/query/mandate.rs
diesel_models
impl_block
42
rust
null
MandateNew
null
impl MandateNew
null
null
null
null
null
null
null
null
pub async fn call_update_gateway_score_open_router( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<api_models::open_router::UpdateScorePayload>, ) -> impl Responder { let flow = Flow::DecisionEngineGatewayFeedbackCall; Box::pin(oss_api::server_wrap( flow, state, &req, payload.clone(), |state, _auth, payload, _| { routing::update_gateway_score_open_router(state.clone(), payload) }, &auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/routing.rs
router
function_signature
152
rust
null
null
null
null
call_update_gateway_score_open_router
null
null
null
null
null
null
null
impl Shift4AuthorizePreprocessingCommon for PaymentsAuthorizeData { fn get_email_optional(&self) -> Option<pii::Email> { self.email.clone() } fn get_complete_authorize_url(&self) -> Option<String> { self.complete_authorize_url.clone() } fn get_currency_required( &self, ) -> Result<enums::Currency, error_stack::Report<errors::ConnectorError>> { Ok(self.currency) } fn get_payment_method_data_required( &self, ) -> Result<PaymentMethodData, error_stack::Report<errors::ConnectorError>> { Ok(self.payment_method_data.clone()) } fn is_automatic_capture(&self) -> Result<bool, Error> { self.is_auto_capture() } fn get_router_return_url(&self) -> Option<String> { self.router_return_url.clone() } fn get_metadata( &self, ) -> Result<Option<serde_json::Value>, error_stack::Report<errors::ConnectorError>> { Ok(self.metadata.clone()) } }
crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
hyperswitch_connectors
impl_block
226
rust
null
PaymentsAuthorizeData
Shift4AuthorizePreprocessingCommon for
impl Shift4AuthorizePreprocessingCommon for for PaymentsAuthorizeData
null
null
null
null
null
null
null
null
impl api::PaymentToken for Authorizedotnet {}
crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs
hyperswitch_connectors
impl_block
10
rust
null
Authorizedotnet
api::PaymentToken for
impl api::PaymentToken for for Authorizedotnet
null
null
null
null
null
null
null
null
pub struct ApplePayTokenizedCard { transaction_type: TransactionType, }
crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
hyperswitch_connectors
struct_definition
16
rust
ApplePayTokenizedCard
null
null
null
null
null
null
null
null
null
null
null
impl ConnectorValidation for Inespay { //TODO: implement functions when support enabled }
crates/hyperswitch_connectors/src/connectors/inespay.rs
hyperswitch_connectors
impl_block
19
rust
null
Inespay
ConnectorValidation for
impl ConnectorValidation for for Inespay
null
null
null
null
null
null
null
null
File: crates/connector_configs/src/connector.rs Public functions: 5 Public structs: 9 use std::collections::HashMap; #[cfg(feature = "payouts")] use api_models::enums::PayoutConnectors; use api_models::{ enums::{AuthenticationConnectors, Connector, PmAuthConnectors, TaxConnectors}, payments, }; use serde::{Deserialize, Serialize}; use toml; use crate::common_config::{CardProvider, InputData, Provider, ZenApplePay}; #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct PayloadCurrencyAuthKeyType { pub api_key: String, pub processing_account_id: String, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct Classic { pub password_classic: String, pub username_classic: String, pub merchant_id_classic: String, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct Evoucher { pub password_evoucher: String, pub username_evoucher: String, pub merchant_id_evoucher: String, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct CashtoCodeCurrencyAuthKeyType { pub classic: Classic, pub evoucher: Evoucher, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum CurrencyAuthValue { CashtoCode(CashtoCodeCurrencyAuthKeyType), Payload(PayloadCurrencyAuthKeyType), } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub enum ConnectorAuthType { HeaderKey { api_key: String, }, BodyKey { api_key: String, key1: String, }, SignatureKey { api_key: String, key1: String, api_secret: String, }, MultiAuthKey { api_key: String, key1: String, api_secret: String, key2: String, }, CurrencyAuthKey { auth_key_map: HashMap<String, CurrencyAuthValue>, }, CertificateAuth { certificate: String, private_key: String, }, #[default] NoKey, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, Serialize, Clone)] #[serde(untagged)] pub enum ApplePayTomlConfig { Standard(Box<payments::ApplePayMetadata>), Zen(ZenApplePay), } #[serde_with::skip_serializing_none] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum KlarnaEndpoint { Europe, NorthAmerica, Oceania, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, Serialize, Clone)] pub struct ConfigMerchantAdditionalDetails { pub open_banking_recipient_data: Option<InputData>, pub account_data: Option<InputData>, pub iban: Option<Vec<InputData>>, pub bacs: Option<Vec<InputData>>, pub connector_recipient_id: Option<InputData>, pub wallet_id: Option<InputData>, pub faster_payments: Option<Vec<InputData>>, pub sepa: Option<Vec<InputData>>, pub sepa_instant: Option<Vec<InputData>>, pub elixir: Option<Vec<InputData>>, pub bankgiro: Option<Vec<InputData>>, pub plusgiro: Option<Vec<InputData>>, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, Serialize, Clone)] pub struct ConfigMetadata { pub merchant_config_currency: Option<InputData>, pub merchant_account_id: Option<InputData>, pub account_name: Option<InputData>, pub account_type: Option<InputData>, pub terminal_id: Option<InputData>, pub google_pay: Option<Vec<InputData>>, pub apple_pay: Option<Vec<InputData>>, pub merchant_id: Option<InputData>, pub endpoint_prefix: Option<InputData>, pub mcc: Option<InputData>, pub merchant_country_code: Option<InputData>, pub merchant_name: Option<InputData>, pub acquirer_bin: Option<InputData>, pub acquirer_merchant_id: Option<InputData>, pub acquirer_country_code: Option<InputData>, pub three_ds_requestor_name: Option<InputData>, pub three_ds_requestor_id: Option<InputData>, pub pull_mechanism_for_external_3ds_enabled: Option<InputData>, pub klarna_region: Option<InputData>, pub pricing_type: Option<InputData>, pub source_balance_account: Option<InputData>, pub brand_id: Option<InputData>, pub destination_account_number: Option<InputData>, pub dpa_id: Option<InputData>, pub dpa_name: Option<InputData>, pub locale: Option<InputData>, pub card_brands: Option<InputData>, pub merchant_category_code: Option<InputData>, pub merchant_configuration_id: Option<InputData>, pub currency_id: Option<InputData>, pub platform_id: Option<InputData>, pub ledger_account_id: Option<InputData>, pub tenant_id: Option<InputData>, pub platform_url: Option<InputData>, pub report_group: Option<InputData>, pub proxy_url: Option<InputData>, pub shop_name: Option<InputData>, pub merchant_funding_source: Option<InputData>, pub account_id: Option<String>, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, Serialize, Clone)] pub struct ConnectorWalletDetailsConfig { pub samsung_pay: Option<Vec<InputData>>, pub paze: Option<Vec<InputData>>, pub google_pay: Option<Vec<InputData>>, pub amazon_pay: Option<Vec<InputData>>, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, Serialize, Clone)] pub struct ConnectorTomlConfig { pub connector_auth: Option<ConnectorAuthType>, pub connector_webhook_details: Option<api_models::admin::MerchantConnectorWebhookDetails>, pub metadata: Option<Box<ConfigMetadata>>, pub connector_wallets_details: Option<Box<ConnectorWalletDetailsConfig>>, pub additional_merchant_data: Option<Box<ConfigMerchantAdditionalDetails>>, pub credit: Option<Vec<CardProvider>>, pub debit: Option<Vec<CardProvider>>, pub bank_transfer: Option<Vec<Provider>>, pub bank_redirect: Option<Vec<Provider>>, pub bank_debit: Option<Vec<Provider>>, pub open_banking: Option<Vec<Provider>>, pub pay_later: Option<Vec<Provider>>, pub wallet: Option<Vec<Provider>>, pub crypto: Option<Vec<Provider>>, pub reward: Option<Vec<Provider>>, pub upi: Option<Vec<Provider>>, pub voucher: Option<Vec<Provider>>, pub gift_card: Option<Vec<Provider>>, pub card_redirect: Option<Vec<Provider>>, pub is_verifiable: Option<bool>, pub real_time_payment: Option<Vec<Provider>>, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, Serialize, Clone)] pub struct ConnectorConfig { pub authipay: Option<ConnectorTomlConfig>, pub juspaythreedsserver: Option<ConnectorTomlConfig>, pub katapult: Option<ConnectorTomlConfig>, pub aci: Option<ConnectorTomlConfig>, pub adyen: Option<ConnectorTomlConfig>, pub affirm: Option<ConnectorTomlConfig>, #[cfg(feature = "payouts")] pub adyen_payout: Option<ConnectorTomlConfig>, #[cfg(feature = "payouts")] pub adyenplatform_payout: Option<ConnectorTomlConfig>, pub airwallex: Option<ConnectorTomlConfig>, pub amazonpay: Option<ConnectorTomlConfig>, pub archipel: Option<ConnectorTomlConfig>, pub authorizedotnet: Option<ConnectorTomlConfig>, pub bamboraapac: Option<ConnectorTomlConfig>, pub bankofamerica: Option<ConnectorTomlConfig>, pub barclaycard: Option<ConnectorTomlConfig>, pub billwerk: Option<ConnectorTomlConfig>, pub bitpay: Option<ConnectorTomlConfig>, pub blackhawknetwork: Option<ConnectorTomlConfig>, pub bluecode: Option<ConnectorTomlConfig>, pub bluesnap: Option<ConnectorTomlConfig>, pub boku: Option<ConnectorTomlConfig>, pub braintree: Option<ConnectorTomlConfig>, pub breadpay: Option<ConnectorTomlConfig>, pub cashtocode: Option<ConnectorTomlConfig>, pub celero: Option<ConnectorTomlConfig>, pub chargebee: Option<ConnectorTomlConfig>, pub custombilling: Option<ConnectorTomlConfig>, pub checkbook: Option<ConnectorTomlConfig>, pub checkout: Option<ConnectorTomlConfig>, pub coinbase: Option<ConnectorTomlConfig>, pub coingate: Option<ConnectorTomlConfig>, pub cryptopay: Option<ConnectorTomlConfig>, pub ctp_visa: Option<ConnectorTomlConfig>, pub cybersource: Option<ConnectorTomlConfig>, #[cfg(feature = "payouts")] pub cybersource_payout: Option<ConnectorTomlConfig>, pub iatapay: Option<ConnectorTomlConfig>, pub itaubank: Option<ConnectorTomlConfig>, pub opennode: Option<ConnectorTomlConfig>, pub bambora: Option<ConnectorTomlConfig>, pub datatrans: Option<ConnectorTomlConfig>, pub deutschebank: Option<ConnectorTomlConfig>, pub digitalvirgo: Option<ConnectorTomlConfig>, pub dlocal: Option<ConnectorTomlConfig>, pub dwolla: Option<ConnectorTomlConfig>, pub ebanx_payout: Option<ConnectorTomlConfig>, pub elavon: Option<ConnectorTomlConfig>, pub facilitapay: Option<ConnectorTomlConfig>, pub fiserv: Option<ConnectorTomlConfig>, pub fiservemea: Option<ConnectorTomlConfig>, pub fiuu: Option<ConnectorTomlConfig>, pub flexiti: Option<ConnectorTomlConfig>, pub forte: Option<ConnectorTomlConfig>, pub getnet: Option<ConnectorTomlConfig>, pub globalpay: Option<ConnectorTomlConfig>, pub globepay: Option<ConnectorTomlConfig>, pub gocardless: Option<ConnectorTomlConfig>, pub gpayments: Option<ConnectorTomlConfig>, pub hipay: Option<ConnectorTomlConfig>, pub helcim: Option<ConnectorTomlConfig>, pub hyperswitch_vault: Option<ConnectorTomlConfig>, pub hyperwallet: Option<ConnectorTomlConfig>, pub inespay: Option<ConnectorTomlConfig>, pub jpmorgan: Option<ConnectorTomlConfig>, pub klarna: Option<ConnectorTomlConfig>, pub mifinity: Option<ConnectorTomlConfig>, pub mollie: Option<ConnectorTomlConfig>, pub moneris: Option<ConnectorTomlConfig>, pub mpgs: Option<ConnectorTomlConfig>, pub multisafepay: Option<ConnectorTomlConfig>, pub nexinets: Option<ConnectorTomlConfig>, pub nexixpay: Option<ConnectorTomlConfig>, pub nmi: Option<ConnectorTomlConfig>, pub nomupay_payout: Option<ConnectorTomlConfig>, pub noon: Option<ConnectorTomlConfig>, pub nordea: Option<ConnectorTomlConfig>, pub novalnet: Option<ConnectorTomlConfig>, pub nuvei: Option<ConnectorTomlConfig>, pub paybox: Option<ConnectorTomlConfig>, pub payload: Option<ConnectorTomlConfig>, pub payme: Option<ConnectorTomlConfig>, #[cfg(feature = "payouts")] pub payone_payout: Option<ConnectorTomlConfig>, pub paypal: Option<ConnectorTomlConfig>, pub paysafe: Option<ConnectorTomlConfig>, #[cfg(feature = "payouts")] pub paypal_payout: Option<ConnectorTomlConfig>, pub paystack: Option<ConnectorTomlConfig>, pub paytm: Option<ConnectorTomlConfig>, pub payu: Option<ConnectorTomlConfig>, pub phonepe: Option<ConnectorTomlConfig>, pub placetopay: Option<ConnectorTomlConfig>, pub plaid: Option<ConnectorTomlConfig>, pub powertranz: Option<ConnectorTomlConfig>, pub prophetpay: Option<ConnectorTomlConfig>, pub razorpay: Option<ConnectorTomlConfig>, pub recurly: Option<ConnectorTomlConfig>, pub riskified: Option<ConnectorTomlConfig>, pub rapyd: Option<ConnectorTomlConfig>, pub redsys: Option<ConnectorTomlConfig>, pub santander: Option<ConnectorTomlConfig>, pub shift4: Option<ConnectorTomlConfig>, pub sift: Option<ConnectorTomlConfig>, pub silverflow: Option<ConnectorTomlConfig>, pub stripe: Option<ConnectorTomlConfig>, #[cfg(feature = "payouts")] pub stripe_payout: Option<ConnectorTomlConfig>, pub stripebilling: Option<ConnectorTomlConfig>, pub signifyd: Option<ConnectorTomlConfig>, pub tokenio: Option<ConnectorTomlConfig>, pub trustpay: Option<ConnectorTomlConfig>, pub trustpayments: Option<ConnectorTomlConfig>, pub threedsecureio: Option<ConnectorTomlConfig>, pub netcetera: Option<ConnectorTomlConfig>, pub tsys: Option<ConnectorTomlConfig>, pub vgs: Option<ConnectorTomlConfig>, pub volt: Option<ConnectorTomlConfig>, pub wellsfargo: Option<ConnectorTomlConfig>, #[cfg(feature = "payouts")] pub wise_payout: Option<ConnectorTomlConfig>, pub worldline: Option<ConnectorTomlConfig>, pub worldpay: Option<ConnectorTomlConfig>, pub worldpayvantiv: Option<ConnectorTomlConfig>, pub worldpayxml: Option<ConnectorTomlConfig>, pub xendit: Option<ConnectorTomlConfig>, pub square: Option<ConnectorTomlConfig>, pub stax: Option<ConnectorTomlConfig>, pub dummy_connector: Option<ConnectorTomlConfig>, pub stripe_test: Option<ConnectorTomlConfig>, pub paypal_test: Option<ConnectorTomlConfig>, pub zen: Option<ConnectorTomlConfig>, pub zsl: Option<ConnectorTomlConfig>, pub taxjar: Option<ConnectorTomlConfig>, pub ctp_mastercard: Option<ConnectorTomlConfig>, pub unified_authentication_service: Option<ConnectorTomlConfig>, } impl ConnectorConfig { fn new() -> Result<Self, String> { let config_str = if cfg!(feature = "production") { include_str!("../toml/production.toml") } else if cfg!(feature = "sandbox") { include_str!("../toml/sandbox.toml") } else { include_str!("../toml/development.toml") }; let config = toml::from_str::<Self>(config_str); match config { Ok(data) => Ok(data), Err(err) => Err(err.to_string()), } } #[cfg(feature = "payouts")] pub fn get_payout_connector_config( connector: PayoutConnectors, ) -> Result<Option<ConnectorTomlConfig>, String> { let connector_data = Self::new()?; match connector { PayoutConnectors::Adyen => Ok(connector_data.adyen_payout), PayoutConnectors::Adyenplatform => Ok(connector_data.adyenplatform_payout), PayoutConnectors::Cybersource => Ok(connector_data.cybersource_payout), PayoutConnectors::Ebanx => Ok(connector_data.ebanx_payout), PayoutConnectors::Nomupay => Ok(connector_data.nomupay_payout), PayoutConnectors::Payone => Ok(connector_data.payone_payout), PayoutConnectors::Paypal => Ok(connector_data.paypal_payout), PayoutConnectors::Stripe => Ok(connector_data.stripe_payout), PayoutConnectors::Wise => Ok(connector_data.wise_payout), } } pub fn get_authentication_connector_config( connector: AuthenticationConnectors, ) -> Result<Option<ConnectorTomlConfig>, String> { let connector_data = Self::new()?; match connector { AuthenticationConnectors::Threedsecureio => Ok(connector_data.threedsecureio), AuthenticationConnectors::Netcetera => Ok(connector_data.netcetera), AuthenticationConnectors::Gpayments => Ok(connector_data.gpayments), AuthenticationConnectors::CtpMastercard => Ok(connector_data.ctp_mastercard), AuthenticationConnectors::CtpVisa => Ok(connector_data.ctp_visa), AuthenticationConnectors::UnifiedAuthenticationService => { Ok(connector_data.unified_authentication_service) } AuthenticationConnectors::Juspaythreedsserver => Ok(connector_data.juspaythreedsserver), } } pub fn get_tax_processor_config( connector: TaxConnectors, ) -> Result<Option<ConnectorTomlConfig>, String> { let connector_data = Self::new()?; match connector { TaxConnectors::Taxjar => Ok(connector_data.taxjar), } } pub fn get_pm_authentication_processor_config( connector: PmAuthConnectors, ) -> Result<Option<ConnectorTomlConfig>, String> { let connector_data = Self::new()?; match connector { PmAuthConnectors::Plaid => Ok(connector_data.plaid), } } pub fn get_connector_config( connector: Connector, ) -> Result<Option<ConnectorTomlConfig>, String> { let connector_data = Self::new()?; match connector { Connector::Aci => Ok(connector_data.aci), Connector::Authipay => Ok(connector_data.authipay), Connector::Adyen => Ok(connector_data.adyen), Connector::Affirm => Ok(connector_data.affirm), Connector::Adyenplatform => Err("Use get_payout_connector_config".to_string()), Connector::Airwallex => Ok(connector_data.airwallex), Connector::Amazonpay => Ok(connector_data.amazonpay), Connector::Archipel => Ok(connector_data.archipel), Connector::Authorizedotnet => Ok(connector_data.authorizedotnet), Connector::Bamboraapac => Ok(connector_data.bamboraapac), Connector::Bankofamerica => Ok(connector_data.bankofamerica), Connector::Barclaycard => Ok(connector_data.barclaycard), Connector::Billwerk => Ok(connector_data.billwerk), Connector::Bitpay => Ok(connector_data.bitpay), Connector::Bluesnap => Ok(connector_data.bluesnap), Connector::Bluecode => Ok(connector_data.bluecode), Connector::Blackhawknetwork => Ok(connector_data.blackhawknetwork), Connector::Boku => Ok(connector_data.boku), Connector::Braintree => Ok(connector_data.braintree), Connector::Breadpay => Ok(connector_data.breadpay), Connector::Cashtocode => Ok(connector_data.cashtocode), Connector::Celero => Ok(connector_data.celero), Connector::Chargebee => Ok(connector_data.chargebee), Connector::Checkbook => Ok(connector_data.checkbook), Connector::Checkout => Ok(connector_data.checkout), Connector::Coinbase => Ok(connector_data.coinbase), Connector::Coingate => Ok(connector_data.coingate), Connector::Cryptopay => Ok(connector_data.cryptopay), Connector::CtpVisa => Ok(connector_data.ctp_visa), Connector::Custombilling => Ok(connector_data.custombilling), Connector::Cybersource => Ok(connector_data.cybersource), #[cfg(feature = "dummy_connector")] Connector::DummyBillingConnector => Ok(connector_data.dummy_connector), Connector::Iatapay => Ok(connector_data.iatapay), Connector::Itaubank => Ok(connector_data.itaubank), Connector::Opennode => Ok(connector_data.opennode), Connector::Bambora => Ok(connector_data.bambora), Connector::Datatrans => Ok(connector_data.datatrans), Connector::Deutschebank => Ok(connector_data.deutschebank), Connector::Digitalvirgo => Ok(connector_data.digitalvirgo), Connector::Dlocal => Ok(connector_data.dlocal), Connector::Dwolla => Ok(connector_data.dwolla), Connector::Ebanx => Ok(connector_data.ebanx_payout), Connector::Elavon => Ok(connector_data.elavon), Connector::Facilitapay => Ok(connector_data.facilitapay), Connector::Fiserv => Ok(connector_data.fiserv), Connector::Fiservemea => Ok(connector_data.fiservemea), Connector::Fiuu => Ok(connector_data.fiuu), Connector::Flexiti => Ok(connector_data.flexiti), Connector::Forte => Ok(connector_data.forte), Connector::Getnet => Ok(connector_data.getnet), Connector::Globalpay => Ok(connector_data.globalpay), Connector::Globepay => Ok(connector_data.globepay), Connector::Gocardless => Ok(connector_data.gocardless), Connector::Gpayments => Ok(connector_data.gpayments), Connector::Hipay => Ok(connector_data.hipay), Connector::HyperswitchVault => Ok(connector_data.hyperswitch_vault), Connector::Helcim => Ok(connector_data.helcim), Connector::Inespay => Ok(connector_data.inespay), Connector::Jpmorgan => Ok(connector_data.jpmorgan), Connector::Juspaythreedsserver => Ok(connector_data.juspaythreedsserver), Connector::Klarna => Ok(connector_data.klarna), Connector::Mifinity => Ok(connector_data.mifinity), Connector::Mollie => Ok(connector_data.mollie), Connector::Moneris => Ok(connector_data.moneris), Connector::Multisafepay => Ok(connector_data.multisafepay), Connector::Nexinets => Ok(connector_data.nexinets), Connector::Nexixpay => Ok(connector_data.nexixpay), Connector::Prophetpay => Ok(connector_data.prophetpay), Connector::Nmi => Ok(connector_data.nmi), Connector::Nordea => Ok(connector_data.nordea), Connector::Nomupay => Err("Use get_payout_connector_config".to_string()), Connector::Novalnet => Ok(connector_data.novalnet), Connector::Noon => Ok(connector_data.noon), Connector::Nuvei => Ok(connector_data.nuvei), Connector::Paybox => Ok(connector_data.paybox), Connector::Payload => Ok(connector_data.payload), Connector::Payme => Ok(connector_data.payme), Connector::Payone => Err("Use get_payout_connector_config".to_string()), Connector::Paypal => Ok(connector_data.paypal), Connector::Paysafe => Ok(connector_data.paysafe), Connector::Paystack => Ok(connector_data.paystack), Connector::Payu => Ok(connector_data.payu), Connector::Placetopay => Ok(connector_data.placetopay), Connector::Plaid => Ok(connector_data.plaid), Connector::Powertranz => Ok(connector_data.powertranz), Connector::Razorpay => Ok(connector_data.razorpay), Connector::Rapyd => Ok(connector_data.rapyd), Connector::Recurly => Ok(connector_data.recurly), Connector::Redsys => Ok(connector_data.redsys), Connector::Riskified => Ok(connector_data.riskified), Connector::Santander => Ok(connector_data.santander), Connector::Shift4 => Ok(connector_data.shift4), Connector::Signifyd => Ok(connector_data.signifyd), Connector::Silverflow => Ok(connector_data.silverflow), Connector::Square => Ok(connector_data.square), Connector::Stax => Ok(connector_data.stax), Connector::Stripe => Ok(connector_data.stripe), Connector::Stripebilling => Ok(connector_data.stripebilling), Connector::Tokenio => Ok(connector_data.tokenio), Connector::Trustpay => Ok(connector_data.trustpay), Connector::Threedsecureio => Ok(connector_data.threedsecureio), Connector::Taxjar => Ok(connector_data.taxjar), Connector::Tsys => Ok(connector_data.tsys), Connector::Vgs => Ok(connector_data.vgs), Connector::Volt => Ok(connector_data.volt), Connector::Wellsfargo => Ok(connector_data.wellsfargo), Connector::Wise => Err("Use get_payout_connector_config".to_string()), Connector::Worldline => Ok(connector_data.worldline), Connector::Worldpay => Ok(connector_data.worldpay), Connector::Worldpayvantiv => Ok(connector_data.worldpayvantiv), Connector::Worldpayxml => Ok(connector_data.worldpayxml), Connector::Zen => Ok(connector_data.zen), Connector::Zsl => Ok(connector_data.zsl), #[cfg(feature = "dummy_connector")] Connector::DummyConnector1 => Ok(connector_data.dummy_connector), #[cfg(feature = "dummy_connector")] Connector::DummyConnector2 => Ok(connector_data.dummy_connector), #[cfg(feature = "dummy_connector")] Connector::DummyConnector3 => Ok(connector_data.dummy_connector), #[cfg(feature = "dummy_connector")] Connector::DummyConnector4 => Ok(connector_data.stripe_test), #[cfg(feature = "dummy_connector")] Connector::DummyConnector5 => Ok(connector_data.dummy_connector), #[cfg(feature = "dummy_connector")] Connector::DummyConnector6 => Ok(connector_data.dummy_connector), #[cfg(feature = "dummy_connector")] Connector::DummyConnector7 => Ok(connector_data.paypal_test), Connector::Netcetera => Ok(connector_data.netcetera), Connector::CtpMastercard => Ok(connector_data.ctp_mastercard), Connector::Xendit => Ok(connector_data.xendit), Connector::Paytm => Ok(connector_data.paytm), Connector::Phonepe => Ok(connector_data.phonepe), } } }
crates/connector_configs/src/connector.rs
connector_configs
full_file
5,775
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct NmiCompleteResponse { pub response: Response, pub responsetext: String, pub authcode: Option<String>, pub transactionid: String, pub avsresponse: Option<String>, pub cvvresponse: Option<String>, pub orderid: String, pub response_code: String, customer_vault_id: Option<Secret<String>>, }
crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
hyperswitch_connectors
struct_definition
81
rust
NmiCompleteResponse
null
null
null
null
null
null
null
null
null
null
null
impl api::PaymentAuthorize for Facilitapay {}
crates/hyperswitch_connectors/src/connectors/facilitapay.rs
hyperswitch_connectors
impl_block
11
rust
null
Facilitapay
api::PaymentAuthorize for
impl api::PaymentAuthorize for for Facilitapay
null
null
null
null
null
null
null
null
File: crates/hyperswitch_connectors/src/connectors/opayo.rs Public functions: 1 Public structs: 1 mod transformers; use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ 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::{ PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, RefundExecuteType, RefundSyncType, Response, }, webhooks, }; use masking::{ExposeInterface, Mask}; use transformers as opayo; use crate::{constants::headers, types::ResponseRouterData, utils::convert_amount}; #[derive(Clone)] pub struct Opayo { amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), } impl Opayo { pub fn new() -> &'static Self { &Self { amount_converter: &MinorUnitForConnector, } } } impl api::Payment for Opayo {} impl api::PaymentSession for Opayo {} impl api::ConnectorAccessToken for Opayo {} impl api::MandateSetup for Opayo {} impl api::PaymentAuthorize for Opayo {} impl api::PaymentSync for Opayo {} impl api::PaymentCapture for Opayo {} impl api::PaymentVoid for Opayo {} impl api::Refund for Opayo {} impl api::RefundExecute for Opayo {} impl api::RefundSync for Opayo {} impl api::PaymentToken for Opayo {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Opayo { } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Opayo 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 content_type = ConnectorCommon::common_get_content_type(self); let mut common_headers = self.get_auth_header(&req.connector_auth_type)?; common_headers.push(( headers::CONTENT_TYPE.to_string(), content_type.to_string().into(), )); Ok(common_headers) } } impl ConnectorCommon for Opayo { fn id(&self) -> &'static str { "opayo" } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.opayo.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = opayo::OpayoAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), auth.api_key.expose().into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: opayo::OpayoErrorResponse = res.response .parse_struct("OpayoErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: 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 Opayo { fn validate_connector_against_payment_request( &self, capture_method: Option<enums::CaptureMethod>, _payment_method: enums::PaymentMethod, _pmt: Option<enums::PaymentMethodType>, ) -> CustomResult<(), errors::ConnectorError> { let capture_method = capture_method.unwrap_or_default(); match capture_method { enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual | enums::CaptureMethod::SequentialAutomatic => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( crate::utils::construct_not_supported_error_report(capture_method, self.id()), ), } } } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Opayo { //TODO: implement sessions flow } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Opayo {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Opayo { fn build_request( &self, _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Opayo".to_string()) .into(), ) } } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Opayo { 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 = convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = opayo::OpayoRouterData::from((amount, req)); let connector_req = opayo::OpayoPaymentsRequest::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(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: opayo::OpayoPaymentsResponse = res .response .parse_struct("Opayo 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 Opayo { 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(&PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(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: opayo::OpayoPaymentsResponse = res .response .parse_struct("opayo 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 Opayo { 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(&PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsCaptureType::get_headers(self, req, connectors)?) .set_body(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: opayo::OpayoPaymentsResponse = res .response .parse_struct("Opayo 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 Opayo {} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Opayo { 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 = convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = opayo::OpayoRouterData::from((refund_amount, req)); let connector_req = opayo::OpayoRefundRequest::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(&RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(RefundExecuteType::get_headers(self, req, connectors)?) .set_body(RefundExecuteType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: opayo::RefundResponse = res .response .parse_struct("opayo 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 Opayo { 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(&RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(RefundSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: opayo::RefundResponse = res .response .parse_struct("opayo 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 Opayo { 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 Opayo {}
crates/hyperswitch_connectors/src/connectors/opayo.rs
hyperswitch_connectors
full_file
4,395
null
null
null
null
null
null
null
null
null
null
null
null
null
OpenAPI Block Path: components.schemas.BacsBankTransferAdditionalData { "type": "object", "description": "Masked payout method details for bacs bank transfer payout method", "required": [ "bank_sort_code", "bank_account_number" ], "properties": { "bank_sort_code": { "type": "string", "description": "Partially masked sort code for Bacs payment method", "example": "108800" }, "bank_account_number": { "type": "string", "description": "Bank account's owner name", "example": "0001****3456" }, "bank_name": { "type": "string", "description": "Bank name", "example": "Deutsche Bank", "nullable": true }, "bank_country_code": { "allOf": [ { "$ref": "#/components/schemas/CountryAlpha2" } ], "nullable": true }, "bank_city": { "type": "string", "description": "Bank city", "example": "California", "nullable": true } } }
./hyperswitch/api-reference/v1/openapi_spec_v1.json
null
openapi_block
269
.json
null
null
null
null
null
openapi_spec
components
[ "schemas", "BacsBankTransferAdditionalData" ]
null
null
null
null
OpenAPI Block Path: components.schemas.ListBlocklistQuery { "type": "object", "required": [ "data_kind" ], "properties": { "data_kind": { "$ref": "#/components/schemas/BlocklistDataKind" }, "limit": { "type": "integer", "format": "int32", "minimum": 0 }, "offset": { "type": "integer", "format": "int32", "minimum": 0 } } }
./hyperswitch/api-reference/v1/openapi_spec_v1.json
null
openapi_block
124
.json
null
null
null
null
null
openapi_spec
components
[ "schemas", "ListBlocklistQuery" ]
null
null
null
null
pub fn new() -> &'static Self { &Self { amount_converter: &StringMajorUnitForConnector, } }
crates/hyperswitch_connectors/src/connectors/barclaycard.rs
hyperswitch_connectors
function_signature
28
rust
null
null
null
null
new
null
null
null
null
null
null
null
pub async fn add_api_key( state: &SessionState, api_key: Secret<String>, merchant_id: common_utils::id_type::MerchantId, key_id: common_utils::id_type::ApiKeyId, expiry: Option<u64>, ) -> CustomResult<(), ApiClientError> { let decision_config = if let Some(config) = &state.conf.decision { config } else { return Ok(()); }; let rule = RuleRequest { tag: state.tenant.schema.clone(), expiry, variant: AuthRuleType::ApiKey { api_key, identifiers: Identifiers::ApiKey { merchant_id, key_id, }, }, }; call_decision_service(state, decision_config, rule, RULE_ADD_METHOD).await }
crates/router/src/services/authentication/decision.rs
router
function_signature
168
rust
null
null
null
null
add_api_key
null
null
null
null
null
null
null
pub struct BillingInformation { first_name: Secret<String>, last_name: Secret<String>, address_1: Secret<String>, address_2: Secret<String>, city: Secret<String>, postal_code: Secret<String>, province: Secret<String>, }
crates/hyperswitch_connectors/src/connectors/flexiti/transformers.rs
hyperswitch_connectors
struct_definition
55
rust
BillingInformation
null
null
null
null
null
null
null
null
null
null
null
pub trait VerifyConnector { async fn verify( state: &SessionState, connector_data: VerifyConnectorData, ) -> errors::RouterResponse<()> { let authorize_data = connector_data.get_payment_authorize_data(); let access_token = Self::get_access_token(state, connector_data.clone()).await?; let router_data = connector_data.get_router_data(state, authorize_data, access_token); let request = connector_data .connector .get_connector_integration() .build_request(&router_data, &state.conf.connectors) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Payment request cannot be built".to_string(), })? .ok_or(errors::ApiErrorResponse::InternalServerError)?; let response = services::call_connector_api(&state.to_owned(), request, "verify_connector_request") .await .change_context(errors::ApiErrorResponse::InternalServerError)?; match response { Ok(_) => Ok(services::ApplicationResponse::StatusOk), Err(error_response) => { Self::handle_payment_error_response::< api::Authorize, types::PaymentFlowData, types::PaymentsAuthorizeData, types::PaymentsResponseData, >( connector_data.connector.get_connector_integration(), error_response, ) .await } } } async fn get_access_token( _state: &SessionState, _connector_data: VerifyConnectorData, ) -> errors::CustomResult<Option<types::AccessToken>, errors::ApiErrorResponse> { // AccessToken is None for the connectors without the AccessToken Flow. // If a connector has that, then it should override this implementation. Ok(None) } async fn handle_payment_error_response<F, ResourceCommonData, Req, Resp>( // connector: &(dyn api::Connector + Sync), connector: BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>, error_response: types::Response, ) -> errors::RouterResponse<()> { let error = connector .get_error_response(error_response, None) .change_context(errors::ApiErrorResponse::InternalServerError)?; Err(errors::ApiErrorResponse::InvalidRequestData { message: error.reason.unwrap_or(error.message), } .into()) } async fn handle_access_token_error_response<F, ResourceCommonData, Req, Resp>( connector: BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>, error_response: types::Response, ) -> errors::RouterResult<Option<types::AccessToken>> { let error = connector .get_error_response(error_response, None) .change_context(errors::ApiErrorResponse::InternalServerError)?; Err(errors::ApiErrorResponse::InvalidRequestData { message: error.reason.unwrap_or(error.message), } .into()) } }
crates/router/src/types/api/verify_connector.rs
router
trait_definition
590
rust
null
null
VerifyConnector
null
null
null
null
null
null
null
null
null
pub struct HyperwalletCard { number: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Secret<String>, complete: bool, }
crates/hyperswitch_connectors/src/connectors/hyperwallet/transformers.rs
hyperswitch_connectors
struct_definition
41
rust
HyperwalletCard
null
null
null
null
null
null
null
null
null
null
null
impl Braintree { pub const fn new() -> &'static Self { &Self { amount_converter: &StringMajorUnitForConnector, amount_converter_webhooks: &StringMinorUnitForConnector, } } }
crates/hyperswitch_connectors/src/connectors/braintree.rs
hyperswitch_connectors
impl_block
48
rust
null
Braintree
null
impl Braintree
null
null
null
null
null
null
null
null
/// Default constructor. pub fn new() -> Result<Self, config::ConfigError> { Self::new_with_config_path(None) }
crates/router_env/src/logger/config.rs
router_env
function_signature
30
rust
null
null
null
null
new
null
null
null
null
null
null
null
pub async fn terminate_auth_select( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<user_api::AuthSelectRequest>, ) -> HttpResponse { let flow = Flow::AuthSelect; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, user, req, _| user_core::terminate_auth_select(state, user, req), &auth::SinglePurposeJWTAuth(TokenPurpose::AuthSelect), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/user.rs
router
function_signature
129
rust
null
null
null
null
terminate_auth_select
null
null
null
null
null
null
null
pub fn calculate_signature( signature_data: String, ) -> Result<Secret<String>, Report<errors::ConnectorError>> { let message = signature_data.as_bytes(); let encoded_data = hex::encode( crypto::Md5 .generate_digest(message) .change_context(errors::ConnectorError::RequestEncodingFailed)?, ); Ok(Secret::new(encoded_data)) }
crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
hyperswitch_connectors
function_signature
82
rust
null
null
null
null
calculate_signature
null
null
null
null
null
null
null
pub async fn get_domain_info( domain: AnalyticsDomain, ) -> crate::errors::AnalyticsResult<GetInfoResponse> { let info = match domain { AnalyticsDomain::Payments => GetInfoResponse { metrics: utils::get_payment_metrics_info(), download_dimensions: None, dimensions: utils::get_payment_dimensions(), }, AnalyticsDomain::PaymentIntents => GetInfoResponse { metrics: utils::get_payment_intent_metrics_info(), download_dimensions: None, dimensions: utils::get_payment_intent_dimensions(), }, AnalyticsDomain::Refunds => GetInfoResponse { metrics: utils::get_refund_metrics_info(), download_dimensions: None, dimensions: utils::get_refund_dimensions(), }, AnalyticsDomain::Frm => GetInfoResponse { metrics: utils::get_frm_metrics_info(), download_dimensions: None, dimensions: utils::get_frm_dimensions(), }, AnalyticsDomain::SdkEvents => GetInfoResponse { metrics: utils::get_sdk_event_metrics_info(), download_dimensions: None, dimensions: utils::get_sdk_event_dimensions(), }, AnalyticsDomain::AuthEvents => GetInfoResponse { metrics: utils::get_auth_event_metrics_info(), download_dimensions: None, dimensions: utils::get_auth_event_dimensions(), }, AnalyticsDomain::ApiEvents => GetInfoResponse { metrics: utils::get_api_event_metrics_info(), download_dimensions: None, dimensions: utils::get_api_event_dimensions(), }, AnalyticsDomain::Dispute => GetInfoResponse { metrics: utils::get_dispute_metrics_info(), download_dimensions: None, dimensions: utils::get_dispute_dimensions(), }, AnalyticsDomain::Routing => GetInfoResponse { metrics: utils::get_payment_metrics_info(), download_dimensions: None, dimensions: utils::get_payment_dimensions(), }, }; Ok(info) }
crates/analytics/src/core.rs
analytics
function_signature
394
rust
null
null
null
null
get_domain_info
null
null
null
null
null
null
null
impl<Req> RoutingEventsWrapper<Req> where Req: Serialize + Clone, { #[allow(clippy::too_many_arguments)] pub fn new( tenant_id: id_type::TenantId, request_id: Option<RequestId>, payment_id: String, profile_id: id_type::ProfileId, merchant_id: id_type::MerchantId, flow: String, request: Option<Req>, parse_response: bool, log_event: bool, ) -> Self { Self { tenant_id, request_id, payment_id, profile_id, merchant_id, flow, request, parse_response, log_event, routing_event: None, } } pub fn construct_event_builder( self, url: String, routing_engine: routing_events::RoutingEngine, method: routing_events::ApiMethod, ) -> RoutingResult<Self> { let mut wrapper = self; let request = wrapper .request .clone() .ok_or(errors::RoutingError::RoutingEventsError { message: "Request body is missing".to_string(), status_code: 400, })?; let serialized_request = serde_json::to_value(&request) .change_context(errors::RoutingError::RoutingEventsError { message: "Failed to serialize RoutingRequest".to_string(), status_code: 500, }) .attach_printable("Failed to serialize request body")?; let routing_event = routing_events::RoutingEvent::new( wrapper.tenant_id.clone(), "".to_string(), &wrapper.flow, serialized_request, url, method, wrapper.payment_id.clone(), wrapper.profile_id.clone(), wrapper.merchant_id.clone(), wrapper.request_id, routing_engine, ); wrapper.set_routing_event(routing_event); Ok(wrapper) } pub async fn trigger_event<Res, F, Fut>( self, state: &SessionState, func: F, ) -> RoutingResult<RoutingEventsResponse<Res>> where F: FnOnce() -> Fut + Send, Res: Serialize + serde::de::DeserializeOwned + Clone, Fut: futures::Future<Output = RoutingResult<Option<Res>>> + Send, { let mut routing_event = self.routing_event .ok_or(errors::RoutingError::RoutingEventsError { message: "Routing event is missing".to_string(), status_code: 500, })?; let mut response = RoutingEventsResponse::new(None, None); let resp = func().await; match resp { Ok(ok_resp) => { if let Some(resp) = ok_resp { routing_event.set_response_body(&resp); // routing_event // .set_routable_connectors(ok_resp.get_routable_connectors().unwrap_or_default()); // routing_event.set_payment_connector(ok_resp.get_payment_connector()); routing_event.set_status_code(200); response.set_response(resp.clone()); self.log_event .then(|| state.event_handler().log_event(&routing_event)); } } Err(err) => { // Need to figure out a generic way to log errors routing_event .set_error(serde_json::json!({"error": err.current_context().to_string()})); match err.current_context() { errors::RoutingError::RoutingEventsError { status_code, .. } => { routing_event.set_status_code(*status_code); } _ => { routing_event.set_status_code(500); } } state.event_handler().log_event(&routing_event) } } response.set_event(routing_event); Ok(response) } pub fn set_log_event(&mut self, log_event: bool) { self.log_event = log_event; } pub fn set_request_body(&mut self, request: Req) { self.request = Some(request); } pub fn set_routing_event(&mut self, routing_event: routing_events::RoutingEvent) { self.routing_event = Some(routing_event); } }
crates/router/src/core/payments/routing/utils.rs
router
impl_block
884
rust
null
RoutingEventsWrapper
null
impl RoutingEventsWrapper
null
null
null
null
null
null
null
null
pub struct ExternalSchemeDetails { transaction_id: Secret<String>, // This is sensitive information brand: Option<CardNetwork>, }
crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
hyperswitch_connectors
struct_definition
27
rust
ExternalSchemeDetails
null
null
null
null
null
null
null
null
null
null
null
impl MerchantAccountUpdateInternal { pub fn apply_changeset(self, source: MerchantAccount) -> MerchantAccount { let Self { merchant_name, merchant_details, return_url, webhook_details, sub_merchants_enabled, parent_merchant_id, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post, publishable_key, storage_scheme, locker_id, metadata, routing_algorithm, primary_business_details, modified_at, intent_fulfillment_time, frm_routing_algorithm, payout_routing_algorithm, organization_id, is_recon_enabled, default_profile, recon_status, payment_link_config, pm_collect_link_config, is_platform_account, product_type, } = self; MerchantAccount { merchant_id: source.merchant_id, return_url: return_url.or(source.return_url), enable_payment_response_hash: enable_payment_response_hash .unwrap_or(source.enable_payment_response_hash), payment_response_hash_key: payment_response_hash_key .or(source.payment_response_hash_key), redirect_to_merchant_with_http_post: redirect_to_merchant_with_http_post .unwrap_or(source.redirect_to_merchant_with_http_post), merchant_name: merchant_name.or(source.merchant_name), merchant_details: merchant_details.or(source.merchant_details), webhook_details: webhook_details.or(source.webhook_details), sub_merchants_enabled: sub_merchants_enabled.or(source.sub_merchants_enabled), parent_merchant_id: parent_merchant_id.or(source.parent_merchant_id), publishable_key: publishable_key.or(source.publishable_key), storage_scheme: storage_scheme.unwrap_or(source.storage_scheme), locker_id: locker_id.or(source.locker_id), metadata: metadata.or(source.metadata), routing_algorithm: routing_algorithm.or(source.routing_algorithm), primary_business_details: primary_business_details .unwrap_or(source.primary_business_details), intent_fulfillment_time: intent_fulfillment_time.or(source.intent_fulfillment_time), created_at: source.created_at, modified_at, frm_routing_algorithm: frm_routing_algorithm.or(source.frm_routing_algorithm), payout_routing_algorithm: payout_routing_algorithm.or(source.payout_routing_algorithm), organization_id: organization_id.unwrap_or(source.organization_id), is_recon_enabled: is_recon_enabled.unwrap_or(source.is_recon_enabled), default_profile: default_profile.unwrap_or(source.default_profile), recon_status: recon_status.unwrap_or(source.recon_status), payment_link_config: payment_link_config.or(source.payment_link_config), pm_collect_link_config: pm_collect_link_config.or(source.pm_collect_link_config), version: source.version, is_platform_account: is_platform_account.unwrap_or(source.is_platform_account), id: source.id, product_type: product_type.or(source.product_type), merchant_account_type: source.merchant_account_type, } } }
crates/diesel_models/src/merchant_account.rs
diesel_models
impl_block
611
rust
null
MerchantAccountUpdateInternal
null
impl MerchantAccountUpdateInternal
null
null
null
null
null
null
null
null
impl ApiKeys { pub fn server(state: AppState) -> Scope { web::scope("/v2/api-keys") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(api_keys::api_key_create))) .service(web::resource("/list").route(web::get().to(api_keys::api_key_list))) .service( web::resource("/{key_id}") .route(web::get().to(api_keys::api_key_retrieve)) .route(web::put().to(api_keys::api_key_update)) .route(web::delete().to(api_keys::api_key_revoke)), ) } }
crates/router/src/routes/app.rs
router
impl_block
142
rust
null
ApiKeys
null
impl ApiKeys
null
null
null
null
null
null
null
null
pub struct PaypalVault { store_in_vault: StoreInVault, usage_type: UsageType, }
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
hyperswitch_connectors
struct_definition
23
rust
PaypalVault
null
null
null
null
null
null
null
null
null
null
null
pub struct BillingConnectorPaymentDetails { /// Payment Processor Token to process the Revenue Recovery Payment pub payment_processor_token: String, /// Billing Connector's Customer Id pub connector_customer_id: String, }
crates/diesel_models/src/types.rs
diesel_models
struct_definition
44
rust
BillingConnectorPaymentDetails
null
null
null
null
null
null
null
null
null
null
null
- Add logging to the response for stripe compatibility layer ([#1470](https://github.com/juspay/hyperswitch/pull/1470)) ([`96c71e1`](https://github.com/juspay/hyperswitch/commit/96c71e1b1bbf2b67a6e2c87478b98bcbb7cdb3ef)) - **router:** - Implement `CardsInfoInterface` for `MockDB` ([#1262](https://github.com/juspay/hyperswitch/pull/1262)) ([`cbff605`](https://github.com/juspay/hyperswitch/commit/cbff605f2af257f4f0ba45c1afe276ce902680ab)) - Add mandate connector to payment data ([#1392](https://github.com/juspay/hyperswitch/pull/1392)) ([`7933e98`](https://github.com/juspay/hyperswitch/commit/7933e98c8cadfa27154b5a7ba5d7d12b33272ec6)) - [Bluesnap] add kount frms session_id support for bluesnap connector ([#1403](https://github.com/juspay/hyperswitch/pull/1403)) ([`fbaecdc`](https://github.com/juspay/hyperswitch/commit/fbaecdc352e653f81bcc036ce0aabc222c91e92d)) - Add caching for MerchantKeyStore ([#1409](https://github.com/juspay/hyperswitch/pull/1409)) ([`fda3fb4`](https://github.com/juspay/hyperswitch/commit/fda3fb4d2bc69297a8b8220e44798c4ca9dea9c2)) - Use subscriber client for subscription in pubsub ([#1297](https://github.com/juspay/hyperswitch/pull/1297)) ([`864d855`](https://github.com/juspay/hyperswitch/commit/864d85534fbc174d8e989493c3231497f5c79fe5)) - Encrypt PII fields before saving it in the database ([#1043](https://github.com/juspay/hyperswitch/pull/1043)) ([`fa392c4`](https://github.com/juspay/hyperswitch/commit/fa392c40a86b2589a55c3adf1de5b862a544dbe9)) - Add error type for empty connector list ([#1363](https://github.com/juspay/hyperswitch/pull/1363)) ([`b2da920`](https://github.com/juspay/hyperswitch/commit/b2da9202809089e6725405351f51d81837b08667)) - Add new error response for 403 ([#1330](https://github.com/juspay/hyperswitch/pull/1330)) ([`49d5ad7`](https://github.com/juspay/hyperswitch/commit/49d5ad7b3c24fc9c9847b473fda370398e3c7e38)) - Applepay through trustpay ([#1422](https://github.com/juspay/hyperswitch/pull/1422)) ([`8032e02`](https://github.com/juspay/hyperswitch/commit/8032e0290b0a0ee33a640740b3bd4567a939712c)) ### Bug Fixes - **api_models:** Fix bank namings ([#1315](https://github.com/juspay/hyperswitch/pull/1315)) ([`a8f2494`](https://github.com/juspay/hyperswitch/commit/a8f2494a87a7731deb104fe2eda548fbccdac895)) - **config:** Fix docker compose local setup ([#1372](https://github.com/juspay/hyperswitch/pull/1372)) ([`d21fcc7`](https://github.com/juspay/hyperswitch/commit/d21fcc7bfc3bdf672b9cfbc5a234a3f3d03771c8)) - **connector:** - [Authorizedotnet] Fix webhooks ([#1261](https://github.com/juspay/hyperswitch/pull/1261)) ([`776c833`](https://github.com/juspay/hyperswitch/commit/776c833de706dcd8e93786d1fa294769669303cd)) - [Checkout] Fix error message in error handling ([#1221](https://github.com/juspay/hyperswitch/pull/1221)) ([`22b2fa3`](https://github.com/juspay/hyperswitch/commit/22b2fa30610ad5ca97cd53df187ccd994411f4e2)) - [coinbase] remove non-mandatory fields ([#1252](https://github.com/juspay/hyperswitch/pull/1252)) ([`bfd7dad`](https://github.com/juspay/hyperswitch/commit/bfd7dad2f1d694bbdc0a18782732ff95ee7730f6)) - [Rapyd] Fix payment response structure ([#1258](https://github.com/juspay/hyperswitch/pull/1258)) ([`3af3a3c`](https://github.com/juspay/hyperswitch/commit/3af3a3cb39641633aecc2d4fc120ece13a6ee72a)) - [Adyen] Address Internal Server Error when calling PSync without redirection ([#1311](https://github.com/juspay/hyperswitch/pull/1311)) ([`b966525`](https://github.com/juspay/hyperswitch/commit/b96652507a6ab37f3c75aeb0cf715fd6454b9f32)) - [opennode] webhook url fix ([#1364](https://github.com/juspay/hyperswitch/pull/1364)) ([`e484193`](https://github.com/juspay/hyperswitch/commit/e484193101ffdc693044fd43c130b12821256111)) - [Zen] fix additional base url required for Zen apple pay checkout integration ([#1394](https://github.com/juspay/hyperswitch/pull/1394)) ([`7955007`](https://github.com/juspay/hyperswitch/commit/795500797d1061630b5ca493187a4e19d98d26c0)) - [Bluesnap] Throw proper error message for redirection scenario ([#1367](https://github.com/juspay/hyperswitch/pull/1367)) ([`4a8de77`](https://github.com/juspay/hyperswitch/commit/4a8de7741d43da07e655bc7382927c68e8ac1eb5)) - [coinbase][opennode][bitpay] handle error response ([#1406](https://github.com/juspay/hyperswitch/pull/1406)) ([`301c3dc`](https://github.com/juspay/hyperswitch/commit/301c3dc44bb740709a0c5c54ee95fc811c2897ed)) - [Zen][ACI] Error handling and Mapping ([#1436](https://github.com/juspay/hyperswitch/pull/1436)) ([`8a4f4a4`](https://github.com/juspay/hyperswitch/commit/8a4f4a4c307d75dee8a1fac8f029091a7d49d432)) - [Bluesnap] fix expiry year ([#1426](https://github.com/juspay/hyperswitch/pull/1426)) ([`92c8222`](https://github.com/juspay/hyperswitch/commit/92c822257e3780fce11f7f0df9a0db48ae1b86e0)) - [Shift4]Add Refund webhooks ([#1307](https://github.com/juspay/hyperswitch/pull/1307)) ([`1691bea`](https://github.com/juspay/hyperswitch/commit/1691beacc3a1c604ce6a1f4cf236f5f7932ed7ae)) - [Shift4] validate pretask for threeds cards ([#1428](https://github.com/juspay/hyperswitch/pull/1428)) ([`2c1dcff`](https://github.com/juspay/hyperswitch/commit/2c1dcff046407aa9053b96c549ab578988b5c618)) - Fix trustpay error response for transaction status api ([#1445](https://github.com/juspay/hyperswitch/pull/1445)) ([`7db94a6`](https://github.com/juspay/hyperswitch/commit/7db94a620882d7b4d14ac97f35f6ced06ae529d7)) - Fix for sending refund_amount in connectors refund request ([#1278](https://github.com/juspay/hyperswitch/pull/1278)) ([`016857f`](https://github.com/juspay/hyperswitch/commit/016857fff0681058f3321a7952c7bd917442293a)) - Use reference as payment_id in trustpay ([#1444](https://github.com/juspay/hyperswitch/pull/1444)) ([`3645c49`](https://github.com/juspay/hyperswitch/commit/3645c49b3830e6dc9e23d91b3ac66213727dca9f)) - Implement ConnectorErrorExt for error_stack::Result<T, ConnectorError> ([#1382](https://github.com/juspay/hyperswitch/pull/1382)) ([`3ef1d29`](https://github.com/juspay/hyperswitch/commit/3ef1d2935e32a8b581e4d2d7f328d970ade4b7f9)) - [Adyen] fix charged status for Auto capture payment ([#1462](https://github.com/juspay/hyperswitch/pull/1462)) ([`6c818ef`](https://github.com/juspay/hyperswitch/commit/6c818ef3366e9f094d39523334199a9a3abb78e9)) - [Adyen] fix unit test ([#1469](https://github.com/juspay/hyperswitch/pull/1469)) ([`6e581c6`](https://github.com/juspay/hyperswitch/commit/6e581c6060423af9984375ad4169a1fec94d4585)) - [Airwallex] Fix refunds ([#1468](https://github.com/juspay/hyperswitch/pull/1468)) ([`1b2841b`](https://github.com/juspay/hyperswitch/commit/1b2841be5997083cd2e414fc698d3d39f9c24c04)) - [Zen] Convert the amount to base denomination in order_details ([#1477](https://github.com/juspay/hyperswitch/pull/1477)) ([`7ca62d3`](https://github.com/juspay/hyperswitch/commit/7ca62d3c7c04997c7eed6e82ec02dc39ea046b2f)) - [Shift4] Fix incorrect deserialization of webhook event type ([#1463](https://github.com/juspay/hyperswitch/pull/1463)) ([`b44f35d`](https://github.com/juspay/hyperswitch/commit/b44f35d4d9ddf4fcd725f0e0a5d51fa9eb7f7e3f)) - [Trustpay] add missing failure status ([#1485](https://github.com/juspay/hyperswitch/pull/1485)) ([`ecf16b0`](https://github.com/juspay/hyperswitch/commit/ecf16b0c7437fefa3550db7275ca2f73d1499b72)) - [Trustpay] add reason to all the error responses ([#1482](https://github.com/juspay/hyperswitch/pull/1482)) ([`1d216db`](https://github.com/juspay/hyperswitch/commit/1d216db5ceeac3dc61d672de89a921501dcaee45)) - **core:** - Remove `missing_required_field_error` being thrown in `should_add_task_to_process_tracker` function ([#1239](https://github.com/juspay/hyperswitch/pull/1239)) ([`3857d06`](https://github.com/juspay/hyperswitch/commit/3857d06627d4c1b85b2e5b9687d80298acf82c14)) - Return an empty array when the customer does not have any payment methods ([#1431](https://github.com/juspay/hyperswitch/pull/1431)) ([`6563587`](https://github.com/juspay/hyperswitch/commit/6563587564a6de579888a751b8c21e832060d728)) - Fix amount capturable in payments response ([#1437](https://github.com/juspay/hyperswitch/pull/1437)) ([`5bc1aab`](https://github.com/juspay/hyperswitch/commit/5bc1aaba5945bd829bc2dffcef59db074fa523a7)) - Save payment_method_type when creating a record in the payment_method table ([#1378](https://github.com/juspay/hyperswitch/pull/1378)) ([`76cb15e`](https://github.com/juspay/hyperswitch/commit/76cb15e01de748f9328d57968d6ddee9831720aa)) - Add validation for card expiry month, expiry year and card cvc ([#1416](https://github.com/juspay/hyperswitch/pull/1416)) ([`c40617a`](https://github.com/juspay/hyperswitch/commit/c40617aea66eb3c14ad47efbce28374cd28626e0)) - **currency:** Add RON and TRY currencies ([#1455](https://github.com/juspay/hyperswitch/pull/1455)) ([`495a98f`](https://github.com/juspay/hyperswitch/commit/495a98f0454787ae322f63f2adc3e3a6b6e0b515)) - **error:** Propagate MissingRequiredFields api_error ([#1244](https://github.com/juspay/hyperswitch/pull/1244)) ([`798881a`](https://github.com/juspay/hyperswitch/commit/798881ab5b0e7a095daad9e920a29c36961ec13d)) - **kms:** Add metrics to external_services kms ([#1237](https://github.com/juspay/hyperswitch/pull/1237)) ([`28f0d1f`](https://github.com/juspay/hyperswitch/commit/28f0d1f5351f0d3f6abd982ebe99bc15a74797c2)) - **list:** Add mandate type in payment_method_list ([#1238](https://github.com/juspay/hyperswitch/pull/1238)) ([`9341191`](https://github.com/juspay/hyperswitch/commit/9341191e39627b661b9d105d65a869e8348c81ed)) - **locker:** Remove unnecessary assertions for locker_id on BasiliskLocker when saving cards ([#1337](https://github.com/juspay/hyperswitch/pull/1337)) ([`23458bc`](https://github.com/juspay/hyperswitch/commit/23458bc42776e6440e76d324d37f36b65c393451)) - **logging:** Fix traces export through opentelemetry ([#1355](https://github.com/juspay/hyperswitch/pull/1355)) ([`b2b9dc0`](https://github.com/juspay/hyperswitch/commit/b2b9dc0b58d737ea114d078fe02271a10accaefa)) - **payments:** Do not delete client secret on payment failure ([#1226](https://github.com/juspay/hyperswitch/pull/1226)) ([`c1b631b`](https://github.com/juspay/hyperswitch/commit/c1b631bd1e0025452f2cf37345996ea789810839)) - **refund:** Change amount to refund_amount ([#1268](https://github.com/juspay/hyperswitch/pull/1268)) ([`24c3a42`](https://github.com/juspay/hyperswitch/commit/24c3a42898a37dccf3f99a9fcc259127606598dd)) - **router:** - Subscriber return type ([#1292](https://github.com/juspay/hyperswitch/pull/1292)) ([`55bb117`](https://github.com/juspay/hyperswitch/commit/55bb117e1ddc147d7309823dc593bd1a05fe69a9)) - Hotfixes for stripe webhook event mapping and reference id retrieval ([#1368](https://github.com/juspay/hyperswitch/pull/1368)) ([`5c2232b`](https://github.com/juspay/hyperswitch/commit/5c2232b737f5430a68fdf6cba9aa5f4c1d6cf3e2)) - [Trustpay] fix email & user-agent information as mandatory fields in trustpay card payment request ([#1414](https://github.com/juspay/hyperswitch/pull/1414)) ([`7ef011a`](https://github.com/juspay/hyperswitch/commit/7ef011ad737257fc83f7a43d16f1bf4ac54336ae)) - [Trustpay] fix email & user-agent information as mandatory fields in trustpay card payment request ([#1418](https://github.com/juspay/hyperswitch/pull/1418)) ([`c596d12`](https://github.com/juspay/hyperswitch/commit/c596d121a846e6c0fa399b8f28ffe4ab6124651a)) - Fix payment status updation for 2xx error responses ([#1457](https://github.com/juspay/hyperswitch/pull/1457)) ([`a7ac4af`](https://github.com/juspay/hyperswitch/commit/a7ac4af5d916ff1e7965be35f347ce0e13407747)) - **router/webhooks:** - Use api error response for returning errors from webhooks core ([#1305](https://github.com/juspay/hyperswitch/pull/1305)) ([`cd0cf40`](https://github.com/juspay/hyperswitch/commit/cd0cf40fe29358700f92c1520475934752bb4b30)) - Correct webhook error mapping and make source verification optional for all connectors ([#1333](https://github.com/juspay/hyperswitch/pull/1333)) ([`7131509`](https://github.com/juspay/hyperswitch/commit/71315097dd01ee675b0e4df3087b930637de416c)) - Map webhook event type not found errors to 422 ([#1340](https://github.com/juspay/hyperswitch/pull/1340)) ([`61bacd8`](https://github.com/juspay/hyperswitch/commit/61bacd8c9590a78a6d5067e378bfed6301d64d07)) - **session_token:** Log error only when it occurs ([#1136](https://github.com/juspay/hyperswitch/pull/1136)) ([`ebf3de4`](https://github.com/juspay/hyperswitch/commit/ebf3de41018f131f7501b17936e58c05276ead77)) - **stripe:** Fix logs on stripe connector integration ([#1448](https://github.com/juspay/hyperswitch/pull/1448)) ([`c42b436`](https://github.com/juspay/hyperswitch/commit/c42b436abe1ed980d9b861dd4ba56324c8361a5a)) - Remove multiple call to locker ([#1230](https://github.com/juspay/hyperswitch/pull/1230)) ([`b3c6b1f`](https://github.com/juspay/hyperswitch/commit/b3c6b1f0aacb9950d225779aa7de1ac49fe148d2)) - Populate meta_data in payment_intent ([#1240](https://github.com/juspay/hyperswitch/pull/1240)) ([`1ac3eb0`](https://github.com/juspay/hyperswitch/commit/1ac3eb0a36030412ef51ec2664e8af43c9c2fc54)) - Merchant webhook config should be looked up in config table instead of redis ([#1241](https://github.com/juspay/hyperswitch/pull/1241)) ([`48e5375`](https://github.com/juspay/hyperswitch/commit/48e537568debccdcd01c78eabce0b480a96beda2)) - Invalidation of in-memory cache ([#1270](https://github.com/juspay/hyperswitch/pull/1270)) ([`e78b3a6`](https://github.com/juspay/hyperswitch/commit/e78b3a65d45429357adf3534b6028798d1f68620)) - Customer id is not mandatory during confirm ([#1317](https://github.com/juspay/hyperswitch/pull/1317)) ([`1261791`](https://github.com/juspay/hyperswitch/commit/1261791d9f70794b3d6426ff35f4eb0fc1076be0)) - Certificate decode failed when creating the session token for applepay ([#1385](https://github.com/juspay/hyperswitch/pull/1385)) ([`8497c55`](https://github.com/juspay/hyperswitch/commit/8497c55283d548c04b3a01560b06d9594e7d634c)) - Update customer data if passed in payments ([#1402](https://github.com/juspay/hyperswitch/pull/1402)) ([`86f679a`](https://github.com/juspay/hyperswitch/commit/86f679abc1549b59239ece4a1123b60e40c26b96)) - Fix some fields not being updated during payments create, update and confirm ([#1451](https://github.com/juspay/hyperswitch/pull/1451)) ([`1764085`](https://github.com/juspay/hyperswitch/commit/17640858eabb5d5a56a17c9e0a52e5773a0c592f)) ### Refactors - **api_models:** Follow naming convention for wallets & paylater payment method data enums ([#1338](https://github.com/juspay/hyperswitch/pull/1338)) ([`6c0d136`](https://github.com/juspay/hyperswitch/commit/6c0d136cee106fc25fbcf63e4bbc01b28baa1519)) - **auth_type:** Updated auth type in `update tracker` and also changed the default flow to `non-3ds` from `3ds` ([#1424](https://github.com/juspay/hyperswitch/pull/1424)) ([`1616051`](https://github.com/juspay/hyperswitch/commit/1616051145c1e276fdd7d0f85cda76baaeaa0023)) - **compatibility:** Map connector to routing in payments request for backward compatibility ([#1339](https://github.com/juspay/hyperswitch/pull/1339)) ([`166688a`](https://github.com/juspay/hyperswitch/commit/166688a5906a2fcbb034c40a113452f6dc2e7160)) - **compatibility, connector:** Add holder name and change trust pay merchant_ref id to payment_id ([`d091549`](https://github.com/juspay/hyperswitch/commit/d091549576676c87f855e06678544704339d82e4)) - **configs:** Make kms module and KmsDecrypt pub ([#1274](https://github.com/juspay/hyperswitch/pull/1274)) ([`f0db993`](https://github.com/juspay/hyperswitch/commit/f0db9937c7b33858a1ff3e17eaecba094ca4c18c)) - **connector:** - Update error handling for Nexinets, Cybersource ([#1151](https://github.com/juspay/hyperswitch/pull/1151)) ([`2ede8ad`](https://github.com/juspay/hyperswitch/commit/2ede8ade8cff56443d8712518c64de7d952f4a0c)) - [Zen] refactor connector_meta_data for zen connector applepay session data ([#1390](https://github.com/juspay/hyperswitch/pull/1390)) ([`0575b26`](https://github.com/juspay/hyperswitch/commit/0575b26b4fc229e92aef179146dfd561a9ee7f27)) - **connector_customer:** Incorrect mapping of connector customer ([#1275](https://github.com/juspay/hyperswitch/pull/1275)) ([`ebdfde7`](https://github.com/juspay/hyperswitch/commit/ebdfde75ecc1c39720396ad7c18062f5c108b8d3)) - **core:** - Generate response hash key if not specified in create merchant account request ([#1232](https://github.com/juspay/hyperswitch/pull/1232)) ([`7b74cab`](https://github.com/juspay/hyperswitch/commit/7b74cab385db68e510d2d513083a725a4f945ae3)) - Add 'redirect_response' field to CompleteAuthorizeData ([#1222](https://github.com/juspay/hyperswitch/pull/1222)) ([`77e60c8`](https://github.com/juspay/hyperswitch/commit/77e60c82fa123ef780485a8507ce779f2f41e166)) - Use HMAC-SHA512 to calculate payments response hash ([#1302](https://github.com/juspay/hyperswitch/pull/1302)) ([`7032ea8`](https://github.com/juspay/hyperswitch/commit/7032ea849416cb740c892360d21e436d2675fbe4)) - Accept customer data in customer object ([#1447](https://github.com/juspay/hyperswitch/pull/1447)) ([`cff1ce6`](https://github.com/juspay/hyperswitch/commit/cff1ce61f0347665d18040486cfbbcd93139950b)) - Move update trackers after build request ([#1472](https://github.com/juspay/hyperswitch/pull/1472)) ([`6114fb6`](https://github.com/juspay/hyperswitch/commit/6114fb634063a9a6d732af38e2a9e343d940a15e)) - Update trackers for preprocessing steps ([#1481](https://github.com/juspay/hyperswitch/pull/1481)) ([`8fffc16`](https://github.com/juspay/hyperswitch/commit/8fffc161ea909fb29a81090f97ee9f811431d539)) - **disputes:** Resolve incorrect 5xx error mappings for disputes ([#1360](https://github.com/juspay/hyperswitch/pull/1360)) ([`c9b400e`](https://github.com/juspay/hyperswitch/commit/c9b400e186731b7de6073fece662fd0fcbbfc953)) - **errors:** - Remove RedisErrorExt ([#1389](https://github.com/juspay/hyperswitch/pull/1389)) ([`5d51505`](https://github.com/juspay/hyperswitch/commit/5d515050cf77705e3bf8c4b83f81ee51a8bff052))
CHANGELOG.md#chunk59
null
doc_chunk
8,118
doc
null
null
null
null
null
null
null
null
null
null
null
null
File: crates/hyperswitch_connectors/src/connectors/payu/transformers.rs Public structs: 25 use base64::Engine; use common_enums::enums; use common_utils::{ consts::BASE64_ENGINE, pii::{Email, IpAddress}, types::MinorUnit, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{PaymentMethodData, WalletData}, router_data::{AccessToken, ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RefundsResponseData}, types, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::AccessTokenRequestInfo as _, }; const WALLET_IDENTIFIER: &str = "PBL"; #[derive(Debug, Serialize)] pub struct PayuRouterData<T> { pub amount: MinorUnit, pub router_data: T, } impl<T> TryFrom<(MinorUnit, T)> for PayuRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data: item, }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PayuPaymentsRequest { customer_ip: Secret<String, IpAddress>, merchant_pos_id: Secret<String>, total_amount: MinorUnit, currency_code: enums::Currency, description: String, pay_methods: PayuPaymentMethod, continue_url: Option<String>, ext_order_id: Option<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct PayuPaymentMethod { pay_method: PayuPaymentMethodData, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum PayuPaymentMethodData { Card(PayuCard), Wallet(PayuWallet), } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub enum PayuCard { #[serde(rename_all = "camelCase")] Card { number: cards::CardNumber, expiration_month: Secret<String>, expiration_year: Secret<String>, cvv: Secret<String>, }, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct PayuWallet { pub value: PayuWalletCode, #[serde(rename = "type")] pub wallet_type: String, pub authorization_code: Secret<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "lowercase")] pub enum PayuWalletCode { Ap, Jp, } impl TryFrom<&PayuRouterData<&types::PaymentsAuthorizeRouterData>> for PayuPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PayuRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let auth_type = PayuAuthType::try_from(&item.router_data.connector_auth_type)?; let payment_method = match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(ccard) => Ok(PayuPaymentMethod { pay_method: PayuPaymentMethodData::Card(PayuCard::Card { number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, cvv: ccard.card_cvc, }), }), PaymentMethodData::Wallet(wallet_data) => match wallet_data { WalletData::GooglePay(data) => Ok(PayuPaymentMethod { pay_method: PayuPaymentMethodData::Wallet({ PayuWallet { value: PayuWalletCode::Ap, wallet_type: WALLET_IDENTIFIER.to_string(), authorization_code: Secret::new( BASE64_ENGINE.encode( data.tokenization_data .get_encrypted_google_pay_token() .change_context( errors::ConnectorError::MissingRequiredField { field_name: "gpay wallet_token", }, )?, ), ), } }), }), WalletData::ApplePay(apple_pay_data) => { let apple_pay_encrypted_data = apple_pay_data .payment_data .get_encrypted_apple_pay_payment_data_mandatory() .change_context(errors::ConnectorError::MissingRequiredField { field_name: "Apple pay encrypted data", })?; Ok(PayuPaymentMethod { pay_method: PayuPaymentMethodData::Wallet({ PayuWallet { value: PayuWalletCode::Jp, wallet_type: WALLET_IDENTIFIER.to_string(), authorization_code: Secret::new( apple_pay_encrypted_data.to_string(), ), } }), }) } _ => Err(errors::ConnectorError::NotImplemented( "Unknown Wallet in Payment Method".to_string(), )), }, _ => Err(errors::ConnectorError::NotImplemented( "Unknown payment method".to_string(), )), }?; let browser_info = item.router_data.request.browser_info.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "browser_info", }, )?; Ok(Self { customer_ip: Secret::new( browser_info .ip_address .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "browser_info.ip_address", })? .to_string(), ), merchant_pos_id: auth_type.merchant_pos_id, ext_order_id: Some(item.router_data.connector_request_reference_id.clone()), total_amount: item.amount.to_owned(), currency_code: item.router_data.request.currency, description: item.router_data.description.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "item.description", }, )?, pay_methods: payment_method, continue_url: None, }) } } pub struct PayuAuthType { pub(super) api_key: Secret<String>, pub(super) merchant_pos_id: Secret<String>, } impl TryFrom<&ConnectorAuthType> for PayuAuthType { 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 { api_key: api_key.to_owned(), merchant_pos_id: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, } } } #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PayuPaymentStatus { Success, WarningContinueRedirect, #[serde(rename = "WARNING_CONTINUE_3DS")] WarningContinue3ds, WarningContinueCvv, #[default] Pending, } impl From<PayuPaymentStatus> for enums::AttemptStatus { fn from(item: PayuPaymentStatus) -> Self { match item { PayuPaymentStatus::Success => Self::Pending, PayuPaymentStatus::WarningContinue3ds => Self::Pending, PayuPaymentStatus::WarningContinueCvv => Self::Pending, PayuPaymentStatus::WarningContinueRedirect => Self::Pending, PayuPaymentStatus::Pending => Self::Pending, } } } #[derive(Debug, Clone, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct PayuPaymentsResponse { pub status: PayuPaymentStatusData, pub redirect_uri: String, pub iframe_allowed: Option<bool>, pub three_ds_protocol_version: Option<String>, pub order_id: String, pub ext_order_id: Option<String>, } impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PayuPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::from(item.response.status.status_code), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item .response .ext_order_id .or(Some(item.response.order_id)), incremental_authorization_allowed: None, charges: None, }), amount_captured: None, ..item.data }) } } #[derive(Default, Debug, Clone, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PayuPaymentsCaptureRequest { order_id: String, order_status: OrderStatus, } impl TryFrom<&types::PaymentsCaptureRouterData> for PayuPaymentsCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { Ok(Self { order_id: item.request.connector_transaction_id.clone(), order_status: OrderStatus::Completed, }) } } #[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct PayuPaymentsCaptureResponse { status: PayuPaymentStatusData, } impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsCaptureResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PayuPaymentsCaptureResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::from(item.response.status.status_code.clone()), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, 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, }), amount_captured: None, ..item.data }) } } #[derive(Debug, Clone, Serialize, PartialEq)] pub struct PayuAuthUpdateRequest { grant_type: String, client_id: Secret<String>, client_secret: Secret<String>, } impl TryFrom<&types::RefreshTokenRouterData> for PayuAuthUpdateRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::RefreshTokenRouterData) -> Result<Self, Self::Error> { Ok(Self { grant_type: "client_credentials".to_string(), client_id: item.get_request_id()?, client_secret: item.request.app_id.clone(), }) } } #[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct PayuAuthUpdateResponse { pub access_token: Secret<String>, pub token_type: String, pub expires_in: i64, pub grant_type: String, } impl<F, T> TryFrom<ResponseRouterData<F, PayuAuthUpdateResponse, T, AccessToken>> for RouterData<F, T, AccessToken> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PayuAuthUpdateResponse, T, AccessToken>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(AccessToken { token: item.response.access_token, expires: item.response.expires_in, }), ..item.data }) } } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PayuPaymentsCancelResponse { pub order_id: String, pub ext_order_id: Option<String>, pub status: PayuPaymentStatusData, } impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsCancelResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PayuPaymentsCancelResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::from(item.response.status.status_code.clone()), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item .response .ext_order_id .or(Some(item.response.order_id)), incremental_authorization_allowed: None, charges: None, }), amount_captured: None, ..item.data }) } } #[allow(dead_code)] #[derive(Debug, Serialize, Eq, PartialEq, Default, Deserialize, Clone)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum OrderStatus { New, Canceled, Completed, WaitingForConfirmation, #[default] Pending, } impl From<OrderStatus> for enums::AttemptStatus { fn from(item: OrderStatus) -> Self { match item { OrderStatus::New => Self::PaymentMethodAwaited, OrderStatus::Canceled => Self::Voided, OrderStatus::Completed => Self::Charged, OrderStatus::Pending => Self::Pending, OrderStatus::WaitingForConfirmation => Self::Authorized, } } } #[derive(Debug, Serialize, Default, Deserialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PayuPaymentStatusData { status_code: PayuPaymentStatus, severity: Option<String>, status_desc: Option<String>, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PayuProductData { name: String, unit_price: String, quantity: String, #[serde(rename = "virtual")] virtually: Option<bool>, listing_date: Option<String>, } #[derive(Debug, Clone, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct PayuOrderResponseData { order_id: String, ext_order_id: Option<String>, order_create_date: String, notify_url: Option<String>, customer_ip: Secret<String, IpAddress>, merchant_pos_id: Secret<String>, description: String, validity_time: Option<String>, currency_code: enums::Currency, total_amount: String, buyer: Option<PayuOrderResponseBuyerData>, pay_method: Option<PayuOrderResponsePayMethod>, products: Option<Vec<PayuProductData>>, status: OrderStatus, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PayuOrderResponseBuyerData { ext_customer_id: Option<String>, email: Option<Email>, phone: Option<Secret<String>>, first_name: Option<Secret<String>>, last_name: Option<Secret<String>>, #[serde(rename = "nin")] national_identification_number: Option<Secret<String>>, language: Option<String>, delivery: Option<String>, customer_id: Option<String>, } #[derive(Debug, Clone, Deserialize, PartialEq, Serialize)] #[serde(tag = "type", rename_all = "SCREAMING_SNAKE_CASE")] pub enum PayuOrderResponsePayMethod { CardToken, Pbl, Installemnts, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PayuOrderResponseProperty { name: String, value: String, } #[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct PayuPaymentsSyncResponse { orders: Vec<PayuOrderResponseData>, status: PayuPaymentStatusData, properties: Option<Vec<PayuOrderResponseProperty>>, } impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsSyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PayuPaymentsSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let order = match item.response.orders.first() { Some(order) => order, _ => Err(errors::ConnectorError::ResponseHandlingFailed)?, }; Ok(Self { status: enums::AttemptStatus::from(order.status.clone()), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(order.order_id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: order .ext_order_id .clone() .or(Some(order.order_id.clone())), incremental_authorization_allowed: None, charges: None, }), amount_captured: Some( order .total_amount .parse::<i64>() .change_context(errors::ConnectorError::ResponseDeserializationFailed)?, ), ..item.data }) } } #[derive(Default, Debug, Serialize)] pub struct PayuRefundRequestData { description: String, amount: Option<MinorUnit>, } #[derive(Default, Debug, Serialize)] pub struct PayuRefundRequest { refund: PayuRefundRequestData, } impl<F> TryFrom<&PayuRouterData<&types::RefundsRouterData<F>>> for PayuRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PayuRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { refund: PayuRefundRequestData { description: item.router_data.request.reason.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "item.request.reason", }, )?, amount: None, }, }) } } // Type definition for Refund Response #[allow(dead_code)] #[derive(Debug, Serialize, Eq, PartialEq, Default, Deserialize, Clone)] #[serde(rename_all = "UPPERCASE")] pub enum RefundStatus { Finalized, Completed, Canceled, #[default] Pending, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Finalized | RefundStatus::Completed => Self::Success, RefundStatus::Canceled => Self::Failure, RefundStatus::Pending => Self::Pending, } } } #[derive(Default, Debug, Clone, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PayuRefundResponseData { refund_id: String, ext_refund_id: String, amount: String, currency_code: enums::Currency, description: String, creation_date_time: String, status: RefundStatus, status_date_time: Option<String>, } #[derive(Default, Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct RefundResponse { refund: PayuRefundResponseData, } 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_status = enums::RefundStatus::from(item.response.refund.status); Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.refund.refund_id, refund_status, }), ..item.data }) } } #[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct RefundSyncResponse { refunds: Vec<PayuRefundResponseData>, } impl TryFrom<RefundsResponseRouterData<RSync, RefundSyncResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundSyncResponse>, ) -> Result<Self, Self::Error> { let refund = match item.response.refunds.first() { Some(refund) => refund, _ => Err(errors::ConnectorError::ResponseHandlingFailed)?, }; Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: refund.refund_id.clone(), refund_status: enums::RefundStatus::from(refund.status.clone()), }), ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PayuErrorData { pub status_code: String, pub code: Option<String>, pub code_literal: Option<String>, pub status_desc: String, } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct PayuErrorResponse { pub status: PayuErrorData, } #[derive(Deserialize, Debug, Serialize)] pub struct PayuAccessTokenErrorResponse { pub error: String, pub error_description: String, }
crates/hyperswitch_connectors/src/connectors/payu/transformers.rs
hyperswitch_connectors
full_file
4,782
null
null
null
null
null
null
null
null
null
null
null
null
null
/// Generate Authentication Id from prefix pub fn generate_authentication_id(prefix: &'static str) -> Self { Self(crate::generate_ref_id_with_default_length(prefix)) }
crates/common_utils/src/id_type/authentication.rs
common_utils
function_signature
36
rust
null
null
null
null
generate_authentication_id
null
null
null
null
null
null
null
pub struct GetnetAuthType { pub username: Secret<String>, pub password: Secret<String>, pub merchant_id: Secret<String>, }
crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs
hyperswitch_connectors
struct_definition
30
rust
GetnetAuthType
null
null
null
null
null
null
null
null
null
null
null
pub struct SubsequentAuthInformation { original_network_trans_id: Secret<String>, // original_auth_amount: String, Required for Discover, Diners Club, JCB, and China Union Pay transactions. reason: Reason, }
crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
hyperswitch_connectors
struct_definition
47
rust
SubsequentAuthInformation
null
null
null
null
null
null
null
null
null
null
null
pub fn get_secret(&self) -> Secret<String> { self.0.clone() }
crates/router/src/types/domain/user.rs
router
function_signature
20
rust
null
null
null
null
get_secret
null
null
null
null
null
null
null
File: crates/router/tests/utils.rs Public functions: 10 Public structs: 12 #![allow( dead_code, clippy::expect_used, clippy::missing_panics_doc, clippy::unwrap_used )] use actix_http::{body::MessageBody, Request}; use actix_web::{ dev::{Service, ServiceResponse}, test::{call_and_read_body_json, TestRequest}, }; use derive_deref::Deref; use router::{configs::settings::Settings, routes::AppState, services}; use router_env::tracing::Instrument; use serde::{de::DeserializeOwned, Deserialize}; use serde_json::{json, Value}; use tokio::sync::{oneshot, OnceCell}; static SERVER: OnceCell<bool> = OnceCell::const_new(); async fn spawn_server() -> bool { let conf = Settings::new().expect("invalid settings"); let server = Box::pin(router::start_server(conf)) .await .expect("failed to create server"); let _server = tokio::spawn(server.in_current_span()); true } pub async fn setup() { Box::pin(SERVER.get_or_init(spawn_server)).await; } const STRIPE_MOCK: &str = "http://localhost:12111/"; async fn stripemock() -> Option<String> { // not working: https://github.com/stripe/stripe-mock/issues/231 None } pub async fn mk_service( ) -> impl Service<Request, Response = ServiceResponse<impl MessageBody>, Error = actix_web::Error> { let mut conf = Settings::new().unwrap(); let request_body_limit = conf.server.request_body_limit; if let Some(url) = stripemock().await { conf.connectors.stripe.base_url = url; } let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(AppState::with_storage( conf, router::db::StorageImpl::Mock, tx, Box::new(services::MockApiClient), )) .await; actix_web::test::init_service(router::mk_app(app_state, request_body_limit)).await } pub struct Guest; pub struct Admin { authkey: String, } pub struct User { authkey: String, } #[allow(dead_code)] pub struct AppClient<T> { state: T, } impl AppClient<Guest> { pub fn guest() -> Self { Self { state: Guest } } } impl AppClient<Admin> { pub async fn create_merchant_account<T: DeserializeOwned, S, B>( &self, app: &S, merchant_id: impl Into<Option<String>>, ) -> T where S: Service<Request, Response = ServiceResponse<B>, Error = actix_web::Error>, B: MessageBody, { let request = TestRequest::post() .uri("/accounts") .append_header(("api-key".to_owned(), self.state.authkey.clone())) .set_json(mk_merchant_account(merchant_id.into())) .to_request(); call_and_read_body_json(app, request).await } pub async fn create_connector<T: DeserializeOwned, S, B>( &self, app: &S, merchant_id: &common_utils::id_type::MerchantId, connector_name: &str, api_key: &str, ) -> T where S: Service<Request, Response = ServiceResponse<B>, Error = actix_web::Error>, B: MessageBody, { let request = TestRequest::post() .uri(&format!( "/account/{}/connectors", merchant_id.get_string_repr() )) .append_header(("api-key".to_owned(), self.state.authkey.clone())) .set_json(mk_connector(connector_name, api_key)) .to_request(); call_and_read_body_json(app, request).await } } impl AppClient<User> { pub async fn create_payment<T: DeserializeOwned, S, B>( &self, app: &S, amount: i64, amount_to_capture: i32, ) -> T where S: Service<Request, Response = ServiceResponse<B>, Error = actix_web::Error>, B: MessageBody, { let request = TestRequest::post() .uri("/payments") .append_header(("api-key".to_owned(), self.state.authkey.clone())) .set_json(mk_payment(amount, amount_to_capture)) .to_request(); call_and_read_body_json(app, request).await } pub async fn create_refund<T: DeserializeOwned, S, B>( &self, app: &S, payment_id: &common_utils::id_type::PaymentId, amount: usize, ) -> T where S: Service<Request, Response = ServiceResponse<B>, Error = actix_web::Error>, B: MessageBody, { let request = TestRequest::post() .uri("/refunds") .append_header(("api-key".to_owned(), self.state.authkey.clone())) .set_json(mk_refund(payment_id, amount)) .to_request(); call_and_read_body_json(app, request).await } } impl<T> AppClient<T> { pub fn admin(&self, authkey: &str) -> AppClient<Admin> { AppClient { state: Admin { authkey: authkey.to_string(), }, } } pub fn user(&self, authkey: &str) -> AppClient<User> { AppClient { state: User { authkey: authkey.to_string(), }, } } pub async fn health<S, B>(&self, app: &S) -> String where S: Service<Request, Response = ServiceResponse<B>, Error = actix_web::Error>, B: MessageBody, { let request = TestRequest::get().uri("/health").to_request(); let bytes = actix_web::test::call_and_read_body(app, request).await; String::from_utf8(bytes.to_vec()).unwrap() } } fn mk_merchant_account(merchant_id: Option<String>) -> Value { let merchant_id = merchant_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); json!({ "merchant_id": merchant_id, "merchant_name": "NewAge Retailer", "merchant_details": { "primary_contact_person": "John Test", "primary_email": "JohnTest@test.com", "primary_phone": "sunt laborum", "secondary_contact_person": "John Test2", "secondary_email": "JohnTest2@test.com", "secondary_phone": "cillum do dolor id", "website": "www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "line1": "Juspay Router", "line2": "Koramangala", "line3": "Stallion", "city": "Bangalore", "state": "Karnataka", "zip": "560095", "country": "IN" } }, "return_url": "www.example.com/success", "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", }, "routing_algorithm": { "type": "single", "data": "stripe" }, "sub_merchants_enabled": false, "metadata": { "city": "NY", "unit": "245" } }) } fn mk_payment(amount: i64, amount_to_capture: i32) -> Value { json!({ "amount": amount, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-10-10T10:11:12Z", "amount_to_capture": amount_to_capture, "customer_id": "cus_udst2tfldj6upmye2reztkmm4i", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "35", "card_holder_name": "John Doe", "card_cvc": "123" } }, "statement_descriptor_name": "Hyperswitch", "statement_descriptor_suffix": "Hyperswitch", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }) } fn mk_connector(connector_name: &str, api_key: &str) -> Value { json!({ "connector_type": "fiz_operations", "connector_name": connector_name, "connector_account_details": { "auth_type": "HeaderKey", "api_key": api_key, }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "wallet", "payment_method_types": [ "upi_collect", "upi_intent" ], "payment_method_issuers": [ "labore magna ipsum", "aute" ], "payment_schemes": [ "Discover", "Discover" ], "accepted_currencies": [ "AED", "AED" ], "accepted_countries": [ "in", "us" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ], "metadata": { "city": "NY", "unit": "245" } }) } fn _mk_payment_confirm() -> Value { json!({ "return_url": "http://example.com/payments", "setup_future_usage": "on_session", "authentication_type": "no_three_ds", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "35", "card_holder_name": "John Doe", "card_cvc": "123" } }, "shipping": {}, "billing": {} }) } fn mk_refund(payment_id: &common_utils::id_type::PaymentId, amount: usize) -> Value { let timestamp = common_utils::date_time::now().to_string(); json!({ "payment_id": payment_id, "refund_id": timestamp.get(23..), "amount": amount, "reason": "Customer returned product", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }) } pub struct HNil; impl<'de> Deserialize<'de> for HNil { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_any(serde::de::IgnoredAny)?; Ok(Self) } } #[derive(Deserialize)] pub struct HCons<H, T> { #[serde(flatten)] pub head: H, #[serde(flatten)] pub tail: T, } #[macro_export] macro_rules! HList { () => { $crate::utils::HNil }; ($head:ty $(, $rest:ty)* $(,)?) => { $crate::utils::HCons<$head, HList![$($rest),*]> }; } #[macro_export] macro_rules! hlist_pat { () => { $crate::utils::HNil }; ($head:pat $(, $rest:pat)* $(,)?) => { $crate::utils::HCons { head: $head, tail: hlist_pat!($($rest),*) } }; } #[derive(Deserialize, Deref)] pub struct MerchantId { merchant_id: common_utils::id_type::MerchantId, } #[derive(Deserialize, Deref)] pub struct ApiKey { api_key: String, } #[derive(Deserialize)] pub struct Error { pub message: Message, } #[derive(Deserialize, Deref)] pub struct Message { message: String, } #[derive(Deserialize, Deref)] pub struct PaymentId { payment_id: common_utils::id_type::PaymentId, } #[derive(Deserialize, Deref)] pub struct Status { status: String, }
crates/router/tests/utils.rs
router
full_file
2,963
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct PlainCardDetails { #[serde(rename = "type")] pub res_type: String, pub number: cards::CardNumber, pub expiry_month: Secret<String>, pub expiry_year: Secret<String>, pub cvv: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "3D")] pub three_ds: Option<ThreeDSecureData>, }
crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs
hyperswitch_connectors
struct_definition
90
rust
PlainCardDetails
null
null
null
null
null
null
null
null
null
null
null
pub async fn create_card_info( state: routes::SessionState, card_info_request: cards_info_api_types::CardInfoCreateRequest, ) -> RouterResponse<cards_info_api_types::CardInfoResponse> { let db = state.store.as_ref(); cards_info::CardsInfoInterface::add_card_info(db, card_info_request.foreign_into()) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: "CardInfo with given key already exists in our records".to_string(), }) .map(|card_info| ApplicationResponse::Json(card_info.foreign_into())) }
crates/router/src/core/cards_info.rs
router
function_signature
130
rust
null
null
null
null
create_card_info
null
null
null
null
null
null
null
Documentation: api-reference/v1/payment-methods/paymentmethods--create.mdx # Type: Doc File --- openapi: post /payment_methods ---
api-reference/v1/payment-methods/paymentmethods--create.mdx
null
doc_file
32
doc
null
null
null
null
null
null
null
null
null
null
null
null
pub struct StaxTokenizeData { person_name: Secret<String>, card_number: cards::CardNumber, card_exp: Secret<String>, card_cvv: Secret<String>, customer_id: Secret<String>, }
crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
hyperswitch_connectors
struct_definition
47
rust
StaxTokenizeData
null
null
null
null
null
null
null
null
null
null
null
pub fn get_id(&self) -> id_type::MerchantConnectorAccountId { self.id.clone() }
crates/diesel_models/src/merchant_connector_account.rs
diesel_models
function_signature
22
rust
null
null
null
null
get_id
null
null
null
null
null
null
null
Documentation: api-reference/v2/payment-method-session/payment-method-session--confirm-a-payment-method-session.mdx # Type: Doc File --- openapi: post /v2/payment-method-sessions/{id}/confirm ---
api-reference/v2/payment-method-session/payment-method-session--confirm-a-payment-method-session.mdx
null
doc_file
45
doc
null
null
null
null
null
null
null
null
null
null
null
null
File: crates/analytics/src/payment_intents.rs pub mod accumulator; mod core; pub mod filters; pub mod metrics; pub mod sankey; pub mod types; pub use accumulator::{PaymentIntentMetricAccumulator, PaymentIntentMetricsAccumulator}; pub trait PaymentIntentAnalytics: metrics::PaymentIntentMetricAnalytics + filters::PaymentIntentFilterAnalytics { } pub use self::core::{get_filters, get_metrics, get_sankey};
crates/analytics/src/payment_intents.rs
analytics
full_file
92
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct MerchantAccount { pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub publishable_key: Option<String>, pub storage_scheme: storage_enums::MerchantStorageScheme, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub organization_id: common_utils::id_type::OrganizationId, pub recon_status: storage_enums::ReconStatus, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub id: common_utils::id_type::MerchantId, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: Option<common_enums::MerchantAccountType>, }
crates/diesel_models/src/merchant_account.rs
diesel_models
struct_definition
169
rust
MerchantAccount
null
null
null
null
null
null
null
null
null
null
null
pub fn open_router_config_default() -> Self { Self { elimination_analyser_config: None, params: None, decision_engine_configs: Some(open_router::DecisionEngineEliminationData { threshold: DEFAULT_ELIMINATION_THRESHOLD, }), } }
crates/api_models/src/routing.rs
api_models
function_signature
57
rust
null
null
null
null
open_router_config_default
null
null
null
null
null
null
null
impl api::PayoutFulfill for Ebanx {}
crates/hyperswitch_connectors/src/connectors/ebanx.rs
hyperswitch_connectors
impl_block
12
rust
null
Ebanx
api::PayoutFulfill for
impl api::PayoutFulfill for for Ebanx
null
null
null
null
null
null
null
null
pub struct Dwolla { amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), }
crates/hyperswitch_connectors/src/connectors/dwolla.rs
hyperswitch_connectors
struct_definition
27
rust
Dwolla
null
null
null
null
null
null
null
null
null
null
null
pub struct ConnectorEvent { tenant_id: common_utils::id_type::TenantId, connector_name: String, flow: String, request: String, masked_response: Option<String>, error: Option<String>, url: String, method: String, payment_id: String, merchant_id: common_utils::id_type::MerchantId, created_at: i128, /// Connector Event Request ID pub request_id: String, latency: u128, refund_id: Option<String>, dispute_id: Option<String>, status_code: u16, }
crates/hyperswitch_interfaces/src/events/connector_api_logs.rs
hyperswitch_interfaces
struct_definition
130
rust
ConnectorEvent
null
null
null
null
null
null
null
null
null
null
null
pub async fn retrieve_card_info( state: routes::SessionState, merchant_context: domain::MerchantContext, request: cards_info_api_types::CardsInfoRequest, ) -> RouterResponse<cards_info_api_types::CardInfoResponse> { let db = state.store.as_ref(); verify_iin_length(&request.card_iin)?; helpers::verify_payment_intent_time_and_client_secret( &state, &merchant_context, request.client_secret, ) .await?; let card_info = db .get_card_info(&request.card_iin) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve card information")? .ok_or(report!(errors::ApiErrorResponse::InvalidCardIin))?; Ok(ApplicationResponse::Json( cards_info_api_types::CardInfoResponse::foreign_from(card_info), )) }
crates/router/src/core/cards_info.rs
router
function_signature
190
rust
null
null
null
null
retrieve_card_info
null
null
null
null
null
null
null
pub async fn list_merchants_for_user_in_org( state: SessionState, user_from_token: auth::UserFromToken, ) -> UserResponse<Vec<user_api::UserMerchantAccountResponse>> { let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; if role_info.is_internal() { return Err(UserErrors::InvalidRoleOperationWithMessage( "Internal roles are not allowed for this operation".to_string(), ) .into()); } let merchant_accounts = match role_info.get_entity_type() { EntityType::Tenant | EntityType::Organization => state .store .list_merchant_accounts_by_organization_id(&(&state).into(), &user_from_token.org_id) .await .change_context(UserErrors::InternalServerError)?, EntityType::Merchant | EntityType::Profile => { let merchant_ids = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: user_from_token.user_id.as_str(), tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: Some(&user_from_token.org_id), merchant_id: None, profile_id: None, entity_id: None, version: None, status: Some(UserStatus::Active), limit: None, }) .await .change_context(UserErrors::InternalServerError)? .into_iter() .filter_map(|user_role| user_role.merchant_id) .collect::<HashSet<_>>() .into_iter() .collect(); state .store .list_multiple_merchant_accounts(&(&state).into(), merchant_ids) .await .change_context(UserErrors::InternalServerError)? } }; // TODO: Add a check to see if merchant accounts are empty, and handle accordingly, when a single route will be used instead // of having two separate routes. Ok(ApplicationResponse::Json( merchant_accounts .into_iter() .map(|merchant_account| user_api::UserMerchantAccountResponse { merchant_name: merchant_account.merchant_name.clone(), merchant_id: merchant_account.get_id().to_owned(), product_type: merchant_account.product_type, merchant_account_type: merchant_account.merchant_account_type, version: merchant_account.version, }) .collect::<Vec<_>>(), )) }
crates/router/src/core/user.rs
router
function_signature
581
rust
null
null
null
null
list_merchants_for_user_in_org
null
null
null
null
null
null
null
impl ExchangeRates { pub fn new(base_currency: Currency, conversion: HashMap<Currency, CurrencyFactors>) -> Self { Self { base_currency, conversion, } } /// The flow here is from_currency -> base_currency -> to_currency /// from to_currency -> base currency pub fn forward_conversion( &self, amt: Decimal, from_currency: Currency, ) -> Result<Decimal, CurrencyConversionError> { let from_factor = self .conversion .get(&from_currency) .ok_or_else(|| { CurrencyConversionError::ConversionNotSupported(from_currency.to_string()) })? .from_factor; amt.checked_mul(from_factor) .ok_or(CurrencyConversionError::DecimalMultiplicationFailed) } /// from base_currency -> to_currency pub fn backward_conversion( &self, amt: Decimal, to_currency: Currency, ) -> Result<Decimal, CurrencyConversionError> { let to_factor = self .conversion .get(&to_currency) .ok_or_else(|| { CurrencyConversionError::ConversionNotSupported(to_currency.to_string()) })? .to_factor; amt.checked_mul(to_factor) .ok_or(CurrencyConversionError::DecimalMultiplicationFailed) } }
crates/currency_conversion/src/types.rs
currency_conversion
impl_block
277
rust
null
ExchangeRates
null
impl ExchangeRates
null
null
null
null
null
null
null
null
impl<T, I> Serialize for StrongSecret<T, I> where T: SerializableSecret + Serialize + ZeroizableSecret + Sized, I: Strategy<T>, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { pii_serializer::pii_serialize(self, serializer) } }
crates/masking/src/serde.rs
masking
impl_block
80
rust
null
StrongSecret
Serialize for
impl Serialize for for StrongSecret
null
null
null
null
null
null
null
null
pub async fn connector_retrieve( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantConnectorAccountId>, ) -> HttpResponse { let flow = Flow::MerchantConnectorsRetrieve; let id = path.into_inner(); let payload = web::Json(admin::MerchantConnectorId { id: id.clone() }).into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth::AuthenticationData { merchant_account, key_store, .. }, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(merchant_account, key_store), )); retrieve_connector(state, merchant_context, req.id.clone()) }, auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantConnectorRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/admin.rs
router
function_signature
242
rust
null
null
null
null
connector_retrieve
null
null
null
null
null
null
null
impl Capturable for PaymentsSyncData { #[cfg(feature = "v1")] fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { payment_data .payment_attempt .amount_to_capture .or(payment_data.payment_intent.amount_captured) .or_else(|| Some(payment_data.payment_attempt.get_total_amount())) .map(|amt| amt.get_amount_as_i64()) } #[cfg(feature = "v2")] fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { // TODO: add a getter for this payment_data .payment_attempt .amount_details .get_amount_to_capture() .or_else(|| Some(payment_data.payment_attempt.get_total_amount())) .map(|amt| amt.get_amount_as_i64()) } #[cfg(feature = "v1")] fn get_amount_capturable<F>( &self, payment_data: &PaymentData<F>, amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { if attempt_status.is_terminal_status() { Some(0) } else { amount_capturable.or(Some(MinorUnit::get_amount_as_i64( payment_data.payment_attempt.amount_capturable, ))) } } #[cfg(feature = "v2")] fn get_amount_capturable<F>( &self, payment_data: &PaymentData<F>, amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { if attempt_status.is_terminal_status() { Some(0) } else { None } } }
crates/router/src/types.rs
router
impl_block
465
rust
null
PaymentsSyncData
Capturable for
impl Capturable for for PaymentsSyncData
null
null
null
null
null
null
null
null
pub struct PaymentLink { pub href: String, }
crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
hyperswitch_connectors
struct_definition
12
rust
PaymentLink
null
null
null
null
null
null
null
null
null
null
null
impl api::RefundSync for Stax {}
crates/hyperswitch_connectors/src/connectors/stax.rs
hyperswitch_connectors
impl_block
10
rust
null
Stax
api::RefundSync for
impl api::RefundSync for for Stax
null
null
null
null
null
null
null
null
pub fn parse_csv( merchant_id: &id_type::MerchantId, data: &[u8], ) -> csv::Result<Vec<payment_methods_api::CardNetworkTokenizeRequest>> { let mut csv_reader = csv::ReaderBuilder::new() .has_headers(true) .from_reader(data); let mut records = Vec::new(); let mut id_counter = 0; for (i, result) in csv_reader .deserialize::<domain::CardNetworkTokenizeRecord>() .enumerate() { match result { Ok(mut record) => { logger::info!("Parsed Record (line {}): {:?}", i + 1, record); id_counter += 1; record.line_number = Some(id_counter); record.merchant_id = Some(merchant_id.clone()); match payment_methods_api::CardNetworkTokenizeRequest::foreign_try_from(record) { Ok(record) => { records.push(record); } Err(err) => { logger::error!("Error parsing line {}: {}", i + 1, err.to_string()); } } } Err(e) => logger::error!("Error parsing line {}: {}", i + 1, e), } } Ok(records) }
crates/router/src/core/payment_methods/tokenize.rs
router
function_signature
263
rust
null
null
null
null
parse_csv
null
null
null
null
null
null
null