text
stringlengths
65
57.3k
file_path
stringlengths
22
92
module
stringclasses
38 values
type
stringclasses
7 values
struct_name
stringlengths
3
60
impl_count
int64
0
60
traits
listlengths
0
59
tokens
int64
16
8.19k
function_name
stringlengths
3
85
type_name
stringlengths
1
67
trait_name
stringclasses
573 values
method_count
int64
0
31
public_method_count
int64
0
19
submodule_count
int64
0
56
export_count
int64
0
9
// Implementation: impl api::PaymentVoid for for Helcim // File: crates/hyperswitch_connectors/src/connectors/helcim.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentVoid for for Helcim
crates/hyperswitch_connectors/src/connectors/helcim.rs
hyperswitch_connectors
impl_block
null
null
null
61
null
Helcim
api::PaymentVoid for
0
0
null
null
// File: crates/router/src/compatibility/stripe.rs // Module: router // Public functions: 1 // Public structs: 1 pub mod app; pub mod customers; pub mod payment_intents; pub mod refunds; pub mod setup_intents; pub mod webhooks; #[cfg(feature = "v1")] use actix_web::{web, Scope}; pub mod errors; #[cfg(feature = "v1")] use crate::routes; #[cfg(feature = "v1")] pub struct StripeApis; #[cfg(feature = "v1")] impl StripeApis { pub fn server(state: routes::AppState) -> Scope { let max_depth = 10; let strict = false; web::scope("/vs/v1") .app_data(web::Data::new(serde_qs::Config::new(max_depth, strict))) .service(app::SetupIntents::server(state.clone())) .service(app::PaymentIntents::server(state.clone())) .service(app::Refunds::server(state.clone())) .service(app::Customers::server(state.clone())) .service(app::Webhooks::server(state.clone())) .service(app::Mandates::server(state)) } }
crates/router/src/compatibility/stripe.rs
router
full_file
null
null
null
254
null
null
null
null
null
null
null
// Function: authentication_sync_core // File: crates/router/src/core/unified_authentication_service.rs // Module: router pub fn authentication_sync_core( state: SessionState, merchant_context: domain::MerchantContext, auth_flow: AuthFlow, req: AuthenticationSyncRequest, ) -> RouterResponse<AuthenticationSyncResponse>
crates/router/src/core/unified_authentication_service.rs
router
function_signature
null
null
null
69
authentication_sync_core
null
null
null
null
null
null
// Struct: ApplePayPaymentInformation // File: crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ApplePayPaymentInformation
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
hyperswitch_connectors
struct_definition
ApplePayPaymentInformation
0
[]
51
null
null
null
null
null
null
null
// File: crates/analytics/src/types.rs // Module: analytics // Public structs: 1 use std::{fmt::Display, str::FromStr}; use common_utils::{ errors::{CustomResult, ErrorSwitch, ParsingError}, events::{ApiEventMetric, ApiEventsType}, impl_api_event_type, }; use error_stack::{report, Report, ResultExt}; use super::query::QueryBuildingError; use crate::errors::AnalyticsError; #[derive(serde::Deserialize, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AnalyticsDomain { Payments, Refunds, Frm, PaymentIntents, AuthEvents, SdkEvents, ApiEvents, Dispute, Routing, } #[derive(Debug, strum::AsRefStr, strum::Display, Clone, Copy)] pub enum AnalyticsCollection { Payment, PaymentSessionized, Refund, RefundSessionized, FraudCheck, SdkEvents, SdkEventsAnalytics, ApiEvents, PaymentIntent, PaymentIntentSessionized, ConnectorEvents, OutgoingWebhookEvent, Authentications, Dispute, DisputeSessionized, ApiEventsAnalytics, ActivePaymentsAnalytics, RoutingEvents, } #[allow(dead_code)] #[derive(Debug)] pub enum TableEngine { CollapsingMergeTree { sign: &'static str }, BasicTree, } #[derive(Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, Hash)] #[serde(transparent)] pub struct DBEnumWrapper<T: FromStr + Display>(pub T); impl<T: FromStr + Display> AsRef<T> for DBEnumWrapper<T> { fn as_ref(&self) -> &T { &self.0 } } impl<T: FromStr + Display + Default> Default for DBEnumWrapper<T> { fn default() -> Self { Self(T::default()) } } impl<T> FromStr for DBEnumWrapper<T> where T: FromStr + Display, { type Err = Report<ParsingError>; fn from_str(s: &str) -> Result<Self, Self::Err> { T::from_str(s) .map_err(|_er| report!(ParsingError::EnumParseFailure(std::any::type_name::<T>()))) .map(DBEnumWrapper) .attach_printable_lazy(|| format!("raw_value: {s}")) } } #[async_trait::async_trait] pub trait AnalyticsDataSource where Self: Sized + Sync + Send, { type Row; async fn load_results<T>(&self, query: &str) -> CustomResult<Vec<T>, QueryExecutionError> where Self: LoadRow<T>; fn get_table_engine(_table: AnalyticsCollection) -> TableEngine { TableEngine::BasicTree } } pub trait LoadRow<T> where Self: AnalyticsDataSource, T: Sized, { fn load_row(row: Self::Row) -> CustomResult<T, QueryExecutionError>; } #[derive(thiserror::Error, Debug)] pub enum MetricsError { #[error("Error building query")] QueryBuildingError, #[error("Error running Query")] QueryExecutionFailure, #[error("Error processing query results")] PostProcessingFailure, #[allow(dead_code)] #[error("Not Implemented")] NotImplemented, } #[derive(Debug, thiserror::Error)] pub enum QueryExecutionError { #[error("Failed to extract domain rows")] RowExtractionFailure, #[error("Database error")] DatabaseError, } pub type MetricsResult<T> = CustomResult<T, MetricsError>; impl ErrorSwitch<MetricsError> for QueryBuildingError { fn switch(&self) -> MetricsError { MetricsError::QueryBuildingError } } pub type FiltersResult<T> = CustomResult<T, FiltersError>; #[derive(thiserror::Error, Debug)] pub enum FiltersError { #[error("Error building query")] QueryBuildingError, #[error("Error running Query")] QueryExecutionFailure, #[allow(dead_code)] #[error("Not Implemented: {0}")] NotImplemented(&'static str), } impl ErrorSwitch<FiltersError> for QueryBuildingError { fn switch(&self) -> FiltersError { FiltersError::QueryBuildingError } } impl ErrorSwitch<AnalyticsError> for FiltersError { fn switch(&self) -> AnalyticsError { match self { Self::QueryBuildingError | Self::QueryExecutionFailure => AnalyticsError::UnknownError, Self::NotImplemented(a) => AnalyticsError::NotImplemented(a), } } } impl_api_event_type!(Miscellaneous, (AnalyticsDomain));
crates/analytics/src/types.rs
analytics
full_file
null
null
null
997
null
null
null
null
null
null
null
// Implementation: impl api::PaymentsPostAuthenticate for for Cybersource // File: crates/hyperswitch_connectors/src/connectors/cybersource.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentsPostAuthenticate for for Cybersource
crates/hyperswitch_connectors/src/connectors/cybersource.rs
hyperswitch_connectors
impl_block
null
null
null
63
null
Cybersource
api::PaymentsPostAuthenticate for
0
0
null
null
// Function: fetch_disputes // File: crates/router/src/routes/disputes.rs // Module: router pub fn fetch_disputes( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, json_payload: web::Query<dispute_types::DisputeFetchQueryData>, ) -> HttpResponse
crates/router/src/routes/disputes.rs
router
function_signature
null
null
null
75
fetch_disputes
null
null
null
null
null
null
// Implementation: impl CardsInfoInterface for for KafkaStore // File: crates/router/src/db/kafka_store.rs // Module: router // Methods: 3 total (0 public) impl CardsInfoInterface for for KafkaStore
crates/router/src/db/kafka_store.rs
router
impl_block
null
null
null
47
null
KafkaStore
CardsInfoInterface for
3
0
null
null
// Function: create_user_theme // File: crates/router/src/core/user/theme.rs // Module: router pub fn create_user_theme( state: SessionState, user_from_token: UserFromToken, request: theme_api::CreateUserThemeRequest, ) -> UserResponse<theme_api::GetThemeResponse>
crates/router/src/core/user/theme.rs
router
function_signature
null
null
null
67
create_user_theme
null
null
null
null
null
null
// Struct: QrRequestData // File: crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct QrRequestData
crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
hyperswitch_connectors
struct_definition
QrRequestData
0
[]
50
null
null
null
null
null
null
null
// Function: perform_surcharge_decision_management_for_payment_method_list // File: crates/router/src/core/payment_methods/surcharge_decision_configs.rs // Module: router pub fn perform_surcharge_decision_management_for_payment_method_list( state: &SessionState, algorithm_ref: routing::RoutingAlgorithmRef, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, billing_address: Option<hyperswitch_domain_models::address::Address>, response_payment_method_types: &mut [api_models::payment_methods::ResponsePaymentMethodsEnabled], ) -> ConditionalConfigResult<( types::SurchargeMetadata, surcharge_decision_configs::MerchantSurchargeConfigs, )>
crates/router/src/core/payment_methods/surcharge_decision_configs.rs
router
function_signature
null
null
null
145
perform_surcharge_decision_management_for_payment_method_list
null
null
null
null
null
null
// Implementation: impl behaviour::Conversion for for PaymentIntent // File: crates/hyperswitch_domain_models/src/payments/payment_intent.rs // Module: hyperswitch_domain_models // Methods: 3 total (0 public) impl behaviour::Conversion for for PaymentIntent
crates/hyperswitch_domain_models/src/payments/payment_intent.rs
hyperswitch_domain_models
impl_block
null
null
null
55
null
PaymentIntent
behaviour::Conversion for
3
0
null
null
// Function: update // File: crates/api_models/src/routing.rs // Module: api_models pub fn update(&mut self, new: Self)
crates/api_models/src/routing.rs
api_models
function_signature
null
null
null
33
update
null
null
null
null
null
null
// Struct: BluesnapRefundRequest // File: crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct BluesnapRefundRequest
crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
hyperswitch_connectors
struct_definition
BluesnapRefundRequest
0
[]
52
null
null
null
null
null
null
null
merchant_key_store.key.get_inner(), ) .await?; add_delete_tokenized_data_task(&*state.store, &lookup_key, pm).await?; metrics::TOKENIZED_DATA_COUNT.add(1, &[]); Ok(lookup_key) } #[cfg(feature = "payouts")] #[instrument(skip_all)] pub async fn get_payout_method_data_from_temporary_locker( state: &routes::SessionState, lookup_key: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> RouterResult<(Option<api::PayoutMethodData>, SupplementaryVaultData)> { let de_tokenize = get_tokenized_data(state, lookup_key, true, merchant_key_store.key.get_inner()).await?; let (payout_method, supp_data) = api::PayoutMethodData::from_values(de_tokenize.value1, de_tokenize.value2) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error parsing Payout Method from Values")?; Ok((Some(payout_method), supp_data)) } #[cfg(feature = "payouts")] #[instrument(skip_all)] pub async fn store_payout_method_data_in_locker( state: &routes::SessionState, token_id: Option<String>, payout_method: &api::PayoutMethodData, customer_id: Option<id_type::CustomerId>, merchant_key_store: &domain::MerchantKeyStore, ) -> RouterResult<String> { let value1 = payout_method .get_value1(customer_id.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error getting Value1 for locker")?; let value2 = payout_method .get_value2(customer_id) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error getting Value2 for locker")?; let lookup_key = token_id.unwrap_or_else(|| generate_id_with_default_len("temporary_token")); let lookup_key = create_tokenize( state, value1, Some(value2), lookup_key, merchant_key_store.key.get_inner(), ) .await?; // add_delete_tokenized_data_task(&*state.store, &lookup_key, pm).await?; // scheduler_metrics::TOKENIZED_DATA_COUNT.add(1, &[]); Ok(lookup_key) } #[instrument(skip_all)] pub async fn delete_locker_payment_method_by_lookup_key( state: &routes::SessionState, lookup_key: &Option<String>, ) { if let Some(lookup_key) = lookup_key { delete_tokenized_data(state, lookup_key) .await .map(|_| logger::info!("Card From locker deleted Successfully")) .map_err(|err| logger::error!("Error: Deleting Card From Redis Locker : {:?}", err)) .ok(); } } } //------------------------------------------------TokenizeService------------------------------------------------ #[inline(always)] fn get_redis_locker_key(lookup_key: &str) -> String { format!("{}_{}", consts::LOCKER_REDIS_PREFIX, lookup_key) } #[instrument(skip(state, value1, value2))] pub async fn create_tokenize( state: &routes::SessionState, value1: String, value2: Option<String>, lookup_key: String, encryption_key: &masking::Secret<Vec<u8>>, ) -> RouterResult<String> { let redis_key = get_redis_locker_key(lookup_key.as_str()); let func = || async { metrics::CREATED_TOKENIZED_CARD.add(1, &[]); let payload_to_be_encrypted = api::TokenizePayloadRequest { value1: value1.clone(), value2: value2.clone().unwrap_or_default(), lookup_key: lookup_key.clone(), service_name: VAULT_SERVICE_NAME.to_string(), }; let payload = payload_to_be_encrypted .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError)?; let encrypted_payload = GcmAes256 .encode_message(encryption_key.peek().as_ref(), payload.as_bytes()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode redis temp locker data")?; let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; redis_conn .set_key_if_not_exists_with_expiry( &redis_key.as_str().into(), bytes::Bytes::from(encrypted_payload), Some(i64::from(consts::LOCKER_REDIS_EXPIRY_SECONDS)), ) .await .map(|_| lookup_key.clone()) .inspect_err(|error| { metrics::TEMP_LOCKER_FAILURES.add(1, &[]); logger::error!(?error, "Failed to store tokenized data in Redis"); }) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error from redis locker") }; match func().await { Ok(s) => { logger::info!( "Insert payload in redis locker successful with lookup key: {:?}", redis_key ); Ok(s) } Err(err) => { logger::error!("Redis Temp locker Failed: {:?}", err); Err(err) } } } #[instrument(skip(state))] pub async fn get_tokenized_data( state: &routes::SessionState, lookup_key: &str, _should_get_value2: bool, encryption_key: &masking::Secret<Vec<u8>>, ) -> RouterResult<api::TokenizePayloadRequest> { let redis_key = get_redis_locker_key(lookup_key); let func = || async { metrics::GET_TOKENIZED_CARD.add(1, &[]); let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let response = redis_conn .get_key::<bytes::Bytes>(&redis_key.as_str().into()) .await; match response { Ok(resp) => { let decrypted_payload = GcmAes256 .decode_message( encryption_key.peek().as_ref(), masking::Secret::new(resp.into()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to decode redis temp locker data")?; let get_response: api::TokenizePayloadRequest = bytes::Bytes::from(decrypted_payload) .parse_struct("TokenizePayloadRequest") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Error getting TokenizePayloadRequest from tokenize response", )?; Ok(get_response) } Err(err) => { metrics::TEMP_LOCKER_FAILURES.add(1, &[]); Err(err).change_context(errors::ApiErrorResponse::UnprocessableEntity { message: "Token is invalid or expired".into(), }) } } }; match func().await { Ok(s) => { logger::info!( "Fetch payload in redis locker successful with lookup key: {:?}", redis_key ); Ok(s) } Err(err) => { logger::error!("Redis Temp locker Failed: {:?}", err); Err(err) } } } #[instrument(skip(state))] pub async fn delete_tokenized_data( state: &routes::SessionState, lookup_key: &str, ) -> RouterResult<()> { let redis_key = get_redis_locker_key(lookup_key); let func = || async { metrics::DELETED_TOKENIZED_CARD.add(1, &[]); let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let response = redis_conn.delete_key(&redis_key.as_str().into()).await; match response { Ok(redis_interface::DelReply::KeyDeleted) => Ok(()), Ok(redis_interface::DelReply::KeyNotDeleted) => { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Token invalid or expired") } Err(err) => { metrics::TEMP_LOCKER_FAILURES.add(1, &[]); Err(errors::ApiErrorResponse::InternalServerError).attach_printable_lazy(|| { format!("Failed to delete from redis locker: {err:?}") }) } } }; match func().await { Ok(s) => { logger::info!( "Delete payload in redis locker successful with lookup key: {:?}", redis_key ); Ok(s) } Err(err) => { logger::error!("Redis Temp locker Failed: {:?}", err); Err(err) } } } #[cfg(feature = "v2")] async fn create_vault_request<R: pm_types::VaultingInterface>( jwekey: &settings::Jwekey, locker: &settings::Locker, payload: Vec<u8>, tenant_id: id_type::TenantId, ) -> CustomResult<request::Request, errors::VaultError> { let private_key = jwekey.vault_private_key.peek().as_bytes(); let jws = services::encryption::jws_sign_payload( &payload, &locker.locker_signing_key_id, private_key, ) .await .change_context(errors::VaultError::RequestEncryptionFailed)?; let jwe_payload = pm_transforms::create_jwe_body_for_vault(jwekey, &jws).await?; let mut url = locker.host.to_owned(); url.push_str(R::get_vaulting_request_url()); let mut request = request::Request::new(services::Method::Post, &url); request.add_header( headers::CONTENT_TYPE, consts::VAULT_HEADER_CONTENT_TYPE.into(), ); request.add_header( headers::X_TENANT_ID, tenant_id.get_string_repr().to_owned().into(), ); request.set_body(request::RequestContent::Json(Box::new(jwe_payload))); Ok(request) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn call_to_vault<V: pm_types::VaultingInterface>( state: &routes::SessionState, payload: Vec<u8>, ) -> CustomResult<String, errors::VaultError> { let locker = &state.conf.locker; let jwekey = state.conf.jwekey.get_inner(); let request = create_vault_request::<V>(jwekey, locker, payload, state.tenant.tenant_id.to_owned()) .await?; let response = services::call_connector_api(state, request, V::get_vaulting_flow_name()) .await .change_context(errors::VaultError::VaultAPIError); let jwe_body: services::JweBody = response .get_response_inner("JweBody") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Failed to get JweBody from vault response")?; let decrypted_payload = pm_transforms::get_decrypted_vault_response_payload( jwekey, jwe_body, locker.decryption_scheme.clone(), ) .await .change_context(errors::VaultError::ResponseDecryptionFailed) .attach_printable("Error getting decrypted vault response payload")?; Ok(decrypted_payload) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn get_fingerprint_id_from_vault<D: domain::VaultingDataInterface + serde::Serialize>( state: &routes::SessionState, data: &D, key: String, ) -> CustomResult<String, errors::VaultError> { let data = serde_json::to_string(data) .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode Vaulting data to string")?; let payload = pm_types::VaultFingerprintRequest { key, data } .encode_to_vec() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode VaultFingerprintRequest")?; let resp = call_to_vault::<pm_types::GetVaultFingerprint>(state, payload) .await .change_context(errors::VaultError::VaultAPIError) .attach_printable("Call to vault failed")?; let fingerprint_resp: pm_types::VaultFingerprintResponse = resp .parse_struct("VaultFingerprintResponse") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Failed to parse data into VaultFingerprintResponse")?; Ok(fingerprint_resp.fingerprint_id) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn add_payment_method_to_vault( state: &routes::SessionState, merchant_context: &domain::MerchantContext, pmd: &domain::PaymentMethodVaultingData, existing_vault_id: Option<domain::VaultId>, customer_id: &id_type::GlobalCustomerId, ) -> CustomResult<pm_types::AddVaultResponse, errors::VaultError> { let payload = pm_types::AddVaultRequest { entity_id: customer_id.to_owned(), vault_id: existing_vault_id .unwrap_or(domain::VaultId::generate(uuid::Uuid::now_v7().to_string())), data: pmd, ttl: state.conf.locker.ttl_for_storage_in_secs, } .encode_to_vec() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode AddVaultRequest")?; let resp = call_to_vault::<pm_types::AddVault>(state, payload) .await .change_context(errors::VaultError::VaultAPIError) .attach_printable("Call to vault failed")?; let stored_pm_resp: pm_types::AddVaultResponse = resp .parse_struct("AddVaultResponse") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Failed to parse data into AddVaultResponse")?; Ok(stored_pm_resp) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn retrieve_payment_method_from_vault_internal( state: &routes::SessionState, merchant_context: &domain::MerchantContext, vault_id: &domain::VaultId, customer_id: &id_type::GlobalCustomerId, ) -> CustomResult<pm_types::VaultRetrieveResponse, errors::VaultError> { let payload = pm_types::VaultRetrieveRequest { entity_id: customer_id.to_owned(), vault_id: vault_id.to_owned(), } .encode_to_vec() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode VaultRetrieveRequest")?; let resp = call_to_vault::<pm_types::VaultRetrieve>(state, payload) .await .change_context(errors::VaultError::VaultAPIError) .attach_printable("Call to vault failed")?; let stored_pm_resp: pm_types::VaultRetrieveResponse = resp .parse_struct("VaultRetrieveResponse") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Failed to parse data into VaultRetrieveResponse")?; Ok(stored_pm_resp) } #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[instrument(skip_all)] pub async fn retrieve_value_from_vault( state: &routes::SessionState, request: pm_types::VaultRetrieveRequest, ) -> CustomResult<serde_json::value::Value, errors::VaultError> { let payload = request .encode_to_vec() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode VaultRetrieveRequest")?; let resp = call_to_vault::<pm_types::VaultRetrieve>(state, payload) .await .change_context(errors::VaultError::VaultAPIError) .attach_printable("Call to vault failed")?; let stored_resp: serde_json::Value = resp .parse_struct("VaultRetrieveResponse") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Failed to parse data into VaultRetrieveResponse")?; Ok(stored_resp) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn retrieve_payment_method_from_vault_external( state: &routes::SessionState, merchant_account: &domain::MerchantAccount, pm: &domain::PaymentMethod, merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, ) -> RouterResult<pm_types::VaultRetrieveResponse> { let connector_vault_id = pm .locker_id .clone() .map(|id| id.get_string_repr().to_owned()); let merchant_connector_account = match &merchant_connector_account { domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(mca) => { Ok(mca.as_ref()) } domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => { Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("MerchantConnectorDetails not supported for vault operations")) } }?; let router_data = core_utils::construct_vault_router_data( state, merchant_account.get_id(), merchant_connector_account, None, connector_vault_id, None, ) .await?; let mut old_router_data = VaultConnectorFlowData::to_old_router_data(router_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Cannot construct router data for making the external vault retrieve api call", )?; let connector_name = merchant_connector_account.get_connector_name_as_string(); // always get the connector name from this call let connector_data = api::ConnectorData::get_external_vault_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, Some(merchant_connector_account.get_id()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector data")?; let connector_integration: services::BoxedVaultConnectorIntegrationInterface< ExternalVaultRetrieveFlow, types::VaultRequestData, types::VaultResponseData, > = connector_data.connector.get_connector_integration(); let router_data_resp = services::execute_connector_processing_step( state, connector_integration, &old_router_data, payments_core::CallConnectorAction::Trigger, None, None, ) .await .to_vault_failed_response()?; get_vault_response_for_retrieve_payment_method_data::<ExternalVaultRetrieveFlow>( router_data_resp, ) } #[cfg(feature = "v2")] pub fn get_vault_response_for_retrieve_payment_method_data<F>( router_data: VaultRouterData<F>, ) -> RouterResult<pm_types::VaultRetrieveResponse> { match router_data.response { Ok(response) => match response { types::VaultResponseData::ExternalVaultRetrieveResponse { vault_data } => { Ok(pm_types::VaultRetrieveResponse { data: vault_data }) } types::VaultResponseData::ExternalVaultInsertResponse { .. } | types::VaultResponseData::ExternalVaultDeleteResponse { .. } | types::VaultResponseData::ExternalVaultCreateResponse { .. } => { Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid Vault Response")) } }, Err(err) => Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve payment method")), } } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn retrieve_payment_method_from_vault_using_payment_token( state: &routes::SessionState, merchant_context: &domain::MerchantContext, profile: &domain::Profile, payment_token: &String, payment_method_type: &common_enums::PaymentMethod, ) -> RouterResult<(domain::PaymentMethod, domain::PaymentMethodVaultingData)> { let pm_token_data = utils::retrieve_payment_token_data( state, payment_token.to_string(), Some(payment_method_type), ) .await?; let payment_method_id = match pm_token_data { storage::PaymentTokenData::PermanentCard(card_token_data) => { card_token_data.payment_method_id } storage::PaymentTokenData::TemporaryGeneric(_) => { Err(errors::ApiErrorResponse::NotImplemented { message: errors::NotImplementedMessage::Reason( "TemporaryGeneric Token not implemented".to_string(), ), })? } storage::PaymentTokenData::AuthBankDebit(_) => { Err(errors::ApiErrorResponse::NotImplemented { message: errors::NotImplementedMessage::Reason( "AuthBankDebit Token not implemented".to_string(), ), })? } }; let db = &*state.store; let key_manager_state = &state.into(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_method = db .find_payment_method( key_manager_state, merchant_context.get_merchant_key_store(), &payment_method_id, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let vault_data = retrieve_payment_method_from_vault(state, merchant_context, profile, &payment_method) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve payment method from vault")? .data; Ok((payment_method, vault_data)) } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct TemporaryVaultCvc { card_cvc: masking::Secret<String>, } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn insert_cvc_using_payment_token( state: &routes::SessionState, payment_token: &String, payment_method_data: api_models::payment_methods::PaymentMethodCreateData, payment_method: common_enums::PaymentMethod, fulfillment_time: i64, encryption_key: &masking::Secret<Vec<u8>>, ) -> RouterResult<()> { let card_cvc = domain::PaymentMethodVaultingData::try_from(payment_method_data)? .get_card() .and_then(|card| card.card_cvc.clone()); if let Some(card_cvc) = card_cvc { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let key = format!("pm_token_{payment_token}_{payment_method}_hyperswitch_cvc"); let payload_to_be_encrypted = TemporaryVaultCvc { card_cvc }; let payload = payload_to_be_encrypted .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError)?; // Encrypt the CVC and store it in Redis let encrypted_payload = GcmAes256 .encode_message(encryption_key.peek().as_ref(), payload.as_bytes()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode TemporaryVaultCvc for vault")?; redis_conn .set_key_if_not_exists_with_expiry( &key.as_str().into(), bytes::Bytes::from(encrypted_payload), Some(fulfillment_time), ) .await .change_context(errors::StorageError::KVError) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add token in redis")?; }; Ok(()) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn retrieve_and_delete_cvc_from_payment_token( state: &routes::SessionState, payment_token: &String, payment_method: common_enums::PaymentMethod, encryption_key: &masking::Secret<Vec<u8>>, ) -> RouterResult<masking::Secret<String>> { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let key = format!("pm_token_{payment_token}_{payment_method}_hyperswitch_cvc",); let data = redis_conn .get_key::<bytes::Bytes>(&key.clone().into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch the token from redis")?; // decrypt the cvc data let decrypted_payload = GcmAes256 .decode_message( encryption_key.peek().as_ref(), masking::Secret::new(data.into()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to decode TemporaryVaultCvc from vault")?; let cvc_data: TemporaryVaultCvc = bytes::Bytes::from(decrypted_payload) .parse_struct("TemporaryVaultCvc") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize TemporaryVaultCvc")?; // delete key after retrieving the cvc redis_conn.delete_key(&key.into()).await.map_err(|err| { logger::error!("Failed to delete token from redis: {:?}", err); }); Ok(cvc_data.card_cvc) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn delete_payment_token( state: &routes::SessionState, key_for_token: &str, intent_status: enums::IntentStatus, ) -> RouterResult<()> { if ![ enums::IntentStatus::RequiresCustomerAction, enums::IntentStatus::RequiresMerchantAction, ] .contains(&intent_status) { utils::delete_payment_token_data(state, key_for_token) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to delete payment_token")?; } Ok(()) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn retrieve_payment_method_from_vault( state: &routes::SessionState, merchant_context: &domain::MerchantContext, profile: &domain::Profile, pm: &domain::PaymentMethod, ) -> RouterResult<pm_types::VaultRetrieveResponse> { let is_external_vault_enabled = profile.is_external_vault_enabled(); match is_external_vault_enabled { true => { let external_vault_source = pm.external_vault_source.as_ref(); let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new( payments_core::helpers::get_merchant_connector_account_v2( state, merchant_context.get_merchant_key_store(), external_vault_source, ) .await .attach_printable( "failed to fetch merchant connector account for external vault retrieve", )?, )); retrieve_payment_method_from_vault_external( state, merchant_context.get_merchant_account(), pm, merchant_connector_account, ) .await } false => { let vault_id = pm .locker_id .clone() .ok_or(errors::VaultError::MissingRequiredField { field_name: "locker_id", }) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Missing locker_id for VaultRetrieveRequest")?; retrieve_payment_method_from_vault_internal( state, merchant_context, &vault_id, &pm.customer_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve payment method from vault") } } } #[cfg(feature = "v2")] pub async fn delete_payment_method_data_from_vault_internal( state: &routes::SessionState, merchant_context: &domain::MerchantContext, vault_id: domain::VaultId, customer_id: &id_type::GlobalCustomerId, ) -> CustomResult<pm_types::VaultDeleteResponse, errors::VaultError> { let payload = pm_types::VaultDeleteRequest { entity_id: customer_id.to_owned(), vault_id, } .encode_to_vec() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode VaultDeleteRequest")?; let resp = call_to_vault::<pm_types::VaultDelete>(state, payload) .await .change_context(errors::VaultError::VaultAPIError) .attach_printable("Call to vault failed")?; let stored_pm_resp: pm_types::VaultDeleteResponse = resp .parse_struct("VaultDeleteResponse") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Failed to parse data into VaultDeleteResponse")?; Ok(stored_pm_resp) } #[cfg(feature = "v2")] pub async fn delete_payment_method_data_from_vault_external( state: &routes::SessionState, merchant_account: &domain::MerchantAccount, merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, vault_id: domain::VaultId, customer_id: &id_type::GlobalCustomerId, ) -> RouterResult<pm_types::VaultDeleteResponse> { let connector_vault_id = vault_id.get_string_repr().to_owned(); // Extract MerchantConnectorAccount from the enum let merchant_connector_account = match &merchant_connector_account { domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(mca) => { Ok(mca.as_ref()) } domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => { Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("MerchantConnectorDetails not supported for vault operations")) } }?; let router_data = core_utils::construct_vault_router_data( state, merchant_account.get_id(), merchant_connector_account, None, Some(connector_vault_id), None, ) .await?; let mut old_router_data = VaultConnectorFlowData::to_old_router_data(router_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Cannot construct router data for making the external vault delete api call", )?; let connector_name = merchant_connector_account.get_connector_name_as_string(); // always get the connector name from this call let connector_data = api::ConnectorData::get_external_vault_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, Some(merchant_connector_account.get_id()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector data")?; let connector_integration: services::BoxedVaultConnectorIntegrationInterface< ExternalVaultDeleteFlow, types::VaultRequestData, types::VaultResponseData, > = connector_data.connector.get_connector_integration(); let router_data_resp = services::execute_connector_processing_step( state, connector_integration, &old_router_data, payments_core::CallConnectorAction::Trigger, None, None, ) .await .to_vault_failed_response()?; get_vault_response_for_delete_payment_method_data::<ExternalVaultDeleteFlow>( router_data_resp, customer_id.to_owned(), ) } #[cfg(feature = "v2")] pub fn get_vault_response_for_delete_payment_method_data<F>( router_data: VaultRouterData<F>, customer_id: id_type::GlobalCustomerId, ) -> RouterResult<pm_types::VaultDeleteResponse> { match router_data.response { Ok(response) => match response { types::VaultResponseData::ExternalVaultDeleteResponse { connector_vault_id } => { Ok(pm_types::VaultDeleteResponse { vault_id: domain::VaultId::generate(connector_vault_id), // converted to VaultId type entity_id: customer_id, }) } types::VaultResponseData::ExternalVaultInsertResponse { .. } | types::VaultResponseData::ExternalVaultRetrieveResponse { .. } | types::VaultResponseData::ExternalVaultCreateResponse { .. } => { Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid Vault Response")) } }, Err(err) => Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve payment method")), } } #[cfg(feature = "v2")] pub async fn delete_payment_method_data_from_vault( state: &routes::SessionState, merchant_context: &domain::MerchantContext, profile: &domain::Profile, pm: &domain::PaymentMethod, ) -> RouterResult<pm_types::VaultDeleteResponse> { let is_external_vault_enabled = profile.is_external_vault_enabled(); let vault_id = pm .locker_id .clone() .get_required_value("locker_id") .attach_printable("Missing locker_id in PaymentMethod")?; match is_external_vault_enabled { true => { let external_vault_source = pm.external_vault_source.as_ref(); let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new( payments_core::helpers::get_merchant_connector_account_v2( state, merchant_context.get_merchant_key_store(), external_vault_source, ) .await .attach_printable( "failed to fetch merchant connector account for external vault delete", )?, )); delete_payment_method_data_from_vault_external( state, merchant_context.get_merchant_account(), merchant_connector_account, vault_id.clone(), &pm.customer_id, ) .await } false => delete_payment_method_data_from_vault_internal( state, merchant_context, vault_id, &pm.customer_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to delete payment method from vault"), } } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn retrieve_payment_method_from_vault_external_v1( state: &routes::SessionState, merchant_id: &id_type::MerchantId, pm: &domain::PaymentMethod, merchant_connector_account: hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, ) -> RouterResult<hyperswitch_domain_models::vault::PaymentMethodVaultingData> { let connector_vault_id = pm.locker_id.clone().map(|id| id.to_string()); let router_data = core_utils::construct_vault_router_data( state, merchant_id, &merchant_connector_account, None, connector_vault_id, None, ) .await?; let old_router_data = VaultConnectorFlowData::to_old_router_data(router_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Cannot construct router data for making the external vault retrieve api call", )?; let connector_name = merchant_connector_account.get_connector_name_as_string(); let connector_data = api::ConnectorData::get_external_vault_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, Some(merchant_connector_account.get_id()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector data")?; let connector_integration: services::BoxedVaultConnectorIntegrationInterface< hyperswitch_domain_models::router_flow_types::ExternalVaultRetrieveFlow, types::VaultRequestData, types::VaultResponseData, > = connector_data.connector.get_connector_integration(); let router_data_resp = services::execute_connector_processing_step( state, connector_integration, &old_router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_vault_failed_response()?; get_vault_response_for_retrieve_payment_method_data_v1(router_data_resp) } pub fn get_vault_response_for_retrieve_payment_method_data_v1<F>( router_data: VaultRouterData<F>, ) -> RouterResult<hyperswitch_domain_models::vault::PaymentMethodVaultingData> { match router_data.response { Ok(response) => match response { types::VaultResponseData::ExternalVaultRetrieveResponse { vault_data } => { Ok(vault_data) } types::VaultResponseData::ExternalVaultInsertResponse { .. } | types::VaultResponseData::ExternalVaultDeleteResponse { .. } | types::VaultResponseData::ExternalVaultCreateResponse { .. } => { Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid Vault Response")) } }, Err(err) => { logger::error!( "Failed to retrieve payment method from external vault: {:?}", err ); Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve payment method from external vault")) } } } // ********************************************** PROCESS TRACKER ********************************************** pub async fn add_delete_tokenized_data_task( db: &dyn db::StorageInterface, lookup_key: &str, pm: enums::PaymentMethod, ) -> RouterResult<()> { let runner = storage::ProcessTrackerRunner::DeleteTokenizeDataWorkflow; let process_tracker_id = format!("{runner}_{lookup_key}"); let task = runner.to_string(); let tag = ["BASILISK-V3"]; let tracking_data = storage::TokenizeCoreWorkflow { lookup_key: lookup_key.to_owned(),
crates/router/src/core/payment_methods/vault.rs#chunk1
router
chunk
null
null
null
8,190
null
null
null
null
null
null
null
// Struct: BreadpayRouterData // File: crates/hyperswitch_connectors/src/connectors/breadpay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct BreadpayRouterData<T>
crates/hyperswitch_connectors/src/connectors/breadpay/transformers.rs
hyperswitch_connectors
struct_definition
BreadpayRouterData
0
[]
52
null
null
null
null
null
null
null
utils::flatten_join_error(payment_attempt_fut) )?; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] { if payment_intent.status.is_in_terminal_state() && business_profile.dynamic_routing_algorithm.is_some() { let dynamic_routing_algo_ref: api_models::routing::DynamicRoutingAlgorithmRef = business_profile .dynamic_routing_algorithm .clone() .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")? .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("DynamicRoutingAlgorithmRef not found in profile")?; let state = state.clone(); let profile_id = business_profile.get_id().to_owned(); let payment_attempt = payment_attempt.clone(); let dynamic_routing_config_params_interpolator = routing_helpers::DynamicRoutingConfigParamsInterpolator::new( payment_attempt.payment_method, payment_attempt.payment_method_type, payment_attempt.authentication_type, payment_attempt.currency, payment_data .address .get_payment_billing() .and_then(|address| address.clone().address) .and_then(|address| address.country), payment_attempt .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|card| card.get("card")) .and_then(|data| data.as_object()) .and_then(|card| card.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()), payment_attempt .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|card| card.get("card")) .and_then(|data| data.as_object()) .and_then(|card| card.get("card_isin")) .and_then(|card_isin| card_isin.as_str()) .map(|card_isin| card_isin.to_string()), ); tokio::spawn( async move { let should_route_to_open_router = state.conf.open_router.dynamic_routing_enabled; let is_success_rate_based = matches!( payment_attempt.routing_approach, Some(enums::RoutingApproach::SuccessRateExploitation) | Some(enums::RoutingApproach::SuccessRateExploration) ); if should_route_to_open_router && is_success_rate_based { routing_helpers::update_gateway_score_helper_with_open_router( &state, &payment_attempt, &profile_id, dynamic_routing_algo_ref.clone(), ) .await .map_err(|e| logger::error!(open_router_update_gateway_score_err=?e)) .ok(); } else { routing_helpers::push_metrics_with_update_window_for_success_based_routing( &state, &payment_attempt, routable_connectors.clone(), &profile_id, dynamic_routing_algo_ref.clone(), dynamic_routing_config_params_interpolator.clone(), ) .await .map_err(|e| logger::error!(success_based_routing_metrics_error=?e)) .ok(); if let Some(gsm_error_category) = gsm_error_category { if gsm_error_category.should_perform_elimination_routing() { logger::info!("Performing update window for elimination routing"); routing_helpers::update_window_for_elimination_routing( &state, &payment_attempt, &profile_id, dynamic_routing_algo_ref.clone(), dynamic_routing_config_params_interpolator.clone(), gsm_error_category, ) .await .map_err(|e| logger::error!(dynamic_routing_metrics_error=?e)) .ok(); }; }; routing_helpers::push_metrics_with_update_window_for_contract_based_routing( &state, &payment_attempt, routable_connectors, &profile_id, dynamic_routing_algo_ref, dynamic_routing_config_params_interpolator, ) .await .map_err(|e| logger::error!(contract_based_routing_metrics_error=?e)) .ok(); } } .in_current_span(), ); } } payment_data.payment_intent = payment_intent; payment_data.payment_attempt = payment_attempt; router_data.payment_method_status.and_then(|status| { payment_data .payment_method_info .as_mut() .map(|info| info.status = status) }); if payment_data.payment_attempt.status == enums::AttemptStatus::Failure { let _ = card_testing_guard_utils::increment_blocked_count_in_cache( state, payment_data.card_testing_guard_data.clone(), ) .await; } match router_data.integrity_check { Ok(()) => Ok(payment_data), Err(err) => { metrics::INTEGRITY_CHECK_FAILED.add( 1, router_env::metric_attributes!( ( "connector", payment_data .payment_attempt .connector .clone() .unwrap_or_default(), ), ( "merchant_id", payment_data.payment_attempt.merchant_id.clone(), ) ), ); Err(error_stack::Report::new( errors::ApiErrorResponse::IntegrityCheckFailed { connector_transaction_id: payment_data .payment_attempt .get_connector_payment_id() .map(ToString::to_string), reason: payment_data .payment_attempt .error_message .unwrap_or_default(), field_names: err.field_names, }, )) } } } #[cfg(feature = "v2")] async fn update_payment_method_status_and_ntid<F: Clone>( state: &SessionState, key_store: &domain::MerchantKeyStore, payment_data: &mut PaymentData<F>, attempt_status: common_enums::AttemptStatus, payment_response: Result<types::PaymentsResponseData, ErrorResponse>, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<()> { todo!() } #[cfg(feature = "v1")] async fn update_payment_method_status_and_ntid<F: Clone>( state: &SessionState, key_store: &domain::MerchantKeyStore, payment_data: &mut PaymentData<F>, attempt_status: common_enums::AttemptStatus, payment_response: Result<types::PaymentsResponseData, ErrorResponse>, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<()> { // If the payment_method is deleted then ignore the error related to retrieving payment method // This should be handled when the payment method is soft deleted if let Some(id) = &payment_data.payment_attempt.payment_method_id { let payment_method = match state .store .find_payment_method(&(state.into()), key_store, id, storage_scheme) .await { Ok(payment_method) => payment_method, Err(error) => { if error.current_context().is_db_not_found() { logger::info!( "Payment Method not found in db and skipping payment method update {:?}", error ); return Ok(()); } else { Err(error) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error retrieving payment method from db in update_payment_method_status_and_ntid")? } } }; let pm_resp_network_transaction_id = payment_response .map(|resp| if let types::PaymentsResponseData::TransactionResponse { network_txn_id: network_transaction_id, .. } = resp { network_transaction_id } else {None}) .map_err(|err| { logger::error!(error=?err, "Failed to obtain the network_transaction_id from payment response"); }) .ok() .flatten(); let network_transaction_id = if payment_data.payment_intent.setup_future_usage == Some(diesel_models::enums::FutureUsage::OffSession) { if pm_resp_network_transaction_id.is_some() { pm_resp_network_transaction_id } else { logger::info!("Skip storing network transaction id"); None } } else { None }; let pm_update = if payment_method.status != common_enums::PaymentMethodStatus::Active && payment_method.status != attempt_status.into() { let updated_pm_status = common_enums::PaymentMethodStatus::from(attempt_status); payment_data .payment_method_info .as_mut() .map(|info| info.status = updated_pm_status); storage::PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate { network_transaction_id, status: Some(updated_pm_status), } } else { storage::PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate { network_transaction_id, status: None, } }; state .store .update_payment_method( &(state.into()), key_store, payment_method, pm_update, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; }; Ok(()) } #[cfg(feature = "v2")] impl<F: Send + Clone> Operation<F, types::PaymentsAuthorizeData> for &PaymentResponse { type Data = PaymentConfirmData<F>; fn to_post_update_tracker( &self, ) -> RouterResult< &(dyn PostUpdateTracker<F, Self::Data, types::PaymentsAuthorizeData> + Send + Sync), > { Ok(*self) } } #[cfg(feature = "v2")] impl<F: Send + Clone> Operation<F, types::PaymentsAuthorizeData> for PaymentResponse { type Data = PaymentConfirmData<F>; fn to_post_update_tracker( &self, ) -> RouterResult< &(dyn PostUpdateTracker<F, Self::Data, types::PaymentsAuthorizeData> + Send + Sync), > { Ok(self) } } #[cfg(feature = "v2")] impl<F: Send + Clone> Operation<F, types::PaymentsCaptureData> for PaymentResponse { type Data = hyperswitch_domain_models::payments::PaymentCaptureData<F>; fn to_post_update_tracker( &self, ) -> RouterResult< &(dyn PostUpdateTracker<F, Self::Data, types::PaymentsCaptureData> + Send + Sync), > { Ok(self) } } #[cfg(feature = "v2")] #[async_trait] impl<F: Clone> PostUpdateTracker< F, hyperswitch_domain_models::payments::PaymentCaptureData<F>, types::PaymentsCaptureData, > for PaymentResponse { async fn update_tracker<'b>( &'b self, state: &'b SessionState, mut payment_data: hyperswitch_domain_models::payments::PaymentCaptureData<F>, response: types::RouterData<F, types::PaymentsCaptureData, types::PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<hyperswitch_domain_models::payments::PaymentCaptureData<F>> where F: 'b + Send + Sync, types::RouterData<F, types::PaymentsCaptureData, types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects< F, types::PaymentsCaptureData, hyperswitch_domain_models::payments::PaymentCaptureData<F>, >, { use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects; let db = &*state.store; let key_manager_state = &state.into(); let response_router_data = response; let payment_intent_update = response_router_data.get_payment_intent_update(&payment_data, storage_scheme); let payment_attempt_update = response_router_data.get_payment_attempt_update(&payment_data, storage_scheme); let updated_payment_intent = db .update_payment_intent( key_manager_state, payment_data.payment_intent, payment_intent_update, key_store, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment intent")?; let updated_payment_attempt = db .update_payment_attempt( key_manager_state, key_store, payment_data.payment_attempt, payment_attempt_update, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment attempt")?; payment_data.payment_intent = updated_payment_intent; payment_data.payment_attempt = updated_payment_attempt; Ok(payment_data) } } #[cfg(feature = "v2")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::PaymentsAuthorizeData> for PaymentResponse { async fn update_tracker<'b>( &'b self, state: &'b SessionState, mut payment_data: PaymentConfirmData<F>, response: types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<PaymentConfirmData<F>> where F: 'b + Send + Sync, types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects< F, types::PaymentsAuthorizeData, PaymentConfirmData<F>, >, { use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects; let db = &*state.store; let key_manager_state = &state.into(); let response_router_data = response; let payment_intent_update = response_router_data.get_payment_intent_update(&payment_data, storage_scheme); let payment_attempt_update = response_router_data.get_payment_attempt_update(&payment_data, storage_scheme); let updated_payment_intent = db .update_payment_intent( key_manager_state, payment_data.payment_intent, payment_intent_update, key_store, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment intent")?; let updated_payment_attempt = db .update_payment_attempt( key_manager_state, key_store, payment_data.payment_attempt, payment_attempt_update, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment attempt")?; let attempt_status = updated_payment_attempt.status; payment_data.payment_intent = updated_payment_intent; payment_data.payment_attempt = updated_payment_attempt; if let Some(payment_method) = &payment_data.payment_method { match attempt_status { common_enums::AttemptStatus::AuthenticationFailed | common_enums::AttemptStatus::RouterDeclined | common_enums::AttemptStatus::AuthorizationFailed | common_enums::AttemptStatus::Voided | common_enums::AttemptStatus::VoidedPostCharge | common_enums::AttemptStatus::VoidInitiated | common_enums::AttemptStatus::CaptureFailed | common_enums::AttemptStatus::VoidFailed | common_enums::AttemptStatus::AutoRefunded | common_enums::AttemptStatus::Unresolved | common_enums::AttemptStatus::Pending | common_enums::AttemptStatus::Failure | common_enums::AttemptStatus::Expired => (), common_enums::AttemptStatus::Started | common_enums::AttemptStatus::AuthenticationPending | common_enums::AttemptStatus::AuthenticationSuccessful | common_enums::AttemptStatus::Authorized | common_enums::AttemptStatus::PartiallyAuthorized | common_enums::AttemptStatus::Charged | common_enums::AttemptStatus::Authorizing | common_enums::AttemptStatus::CodInitiated | common_enums::AttemptStatus::PartialCharged | common_enums::AttemptStatus::PartialChargedAndChargeable | common_enums::AttemptStatus::CaptureInitiated | common_enums::AttemptStatus::PaymentMethodAwaited | common_enums::AttemptStatus::ConfirmationAwaited | common_enums::AttemptStatus::DeviceDataCollectionPending | common_enums::AttemptStatus::IntegrityFailure => { let pm_update_status = enums::PaymentMethodStatus::Active; // payment_methods microservice call payment_methods::update_payment_method_status_internal( state, key_store, storage_scheme, pm_update_status, payment_method.get_id(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method status")?; } } } Ok(payment_data) } } #[cfg(feature = "v2")] impl<F: Send + Clone> Operation<F, types::PaymentsSyncData> for PaymentResponse { type Data = PaymentStatusData<F>; fn to_post_update_tracker( &self, ) -> RouterResult<&(dyn PostUpdateTracker<F, Self::Data, types::PaymentsSyncData> + Send + Sync)> { Ok(self) } } #[cfg(feature = "v2")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentStatusData<F>, types::PaymentsSyncData> for PaymentResponse { async fn update_tracker<'b>( &'b self, state: &'b SessionState, mut payment_data: PaymentStatusData<F>, response: types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<PaymentStatusData<F>> where F: 'b + Send + Sync, types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects< F, types::PaymentsSyncData, PaymentStatusData<F>, >, { use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects; let db = &*state.store; let key_manager_state = &state.into(); let response_router_data = response; let payment_intent_update = response_router_data.get_payment_intent_update(&payment_data, storage_scheme); let payment_attempt_update = response_router_data.get_payment_attempt_update(&payment_data, storage_scheme); let payment_attempt = payment_data.payment_attempt; let updated_payment_intent = db .update_payment_intent( key_manager_state, payment_data.payment_intent, payment_intent_update, key_store, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment intent")?; let updated_payment_attempt = db .update_payment_attempt( key_manager_state, key_store, payment_attempt, payment_attempt_update, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment attempt")?; payment_data.payment_intent = updated_payment_intent; payment_data.payment_attempt = updated_payment_attempt; Ok(payment_data) } } #[cfg(feature = "v2")] impl<F: Send + Clone> Operation<F, types::SetupMandateRequestData> for &PaymentResponse { type Data = PaymentConfirmData<F>; fn to_post_update_tracker( &self, ) -> RouterResult< &(dyn PostUpdateTracker<F, Self::Data, types::SetupMandateRequestData> + Send + Sync), > { Ok(*self) } } #[cfg(feature = "v2")] impl<F: Send + Clone> Operation<F, types::SetupMandateRequestData> for PaymentResponse { type Data = PaymentConfirmData<F>; fn to_post_update_tracker( &self, ) -> RouterResult< &(dyn PostUpdateTracker<F, Self::Data, types::SetupMandateRequestData> + Send + Sync), > { Ok(self) } } #[cfg(feature = "v2")] impl Operation< hyperswitch_domain_models::router_flow_types::ExternalVaultProxy, hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData, > for PaymentResponse { type Data = PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>; fn to_post_update_tracker( &self, ) -> RouterResult< &(dyn PostUpdateTracker< hyperswitch_domain_models::router_flow_types::ExternalVaultProxy, Self::Data, hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData, > + Send + Sync), > { Ok(self) } } #[cfg(feature = "v2")] impl Operation< hyperswitch_domain_models::router_flow_types::ExternalVaultProxy, hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData, > for &PaymentResponse { type Data = PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>; fn to_post_update_tracker( &self, ) -> RouterResult< &(dyn PostUpdateTracker< hyperswitch_domain_models::router_flow_types::ExternalVaultProxy, Self::Data, hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData, > + Send + Sync), > { Ok(*self) } } #[cfg(feature = "v2")] #[async_trait] impl PostUpdateTracker< hyperswitch_domain_models::router_flow_types::ExternalVaultProxy, PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>, hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData, > for PaymentResponse { async fn update_tracker<'b>( &'b self, state: &'b SessionState, mut payment_data: PaymentConfirmData< hyperswitch_domain_models::router_flow_types::ExternalVaultProxy, >, response: types::RouterData< hyperswitch_domain_models::router_flow_types::ExternalVaultProxy, hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData, types::PaymentsResponseData, >, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult< PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>, > where types::RouterData< hyperswitch_domain_models::router_flow_types::ExternalVaultProxy, hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData, types::PaymentsResponseData, >: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects< hyperswitch_domain_models::router_flow_types::ExternalVaultProxy, hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData, PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>, >, { use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects; let db = &*state.store; let key_manager_state = &state.into(); let response_router_data = response; let payment_intent_update = response_router_data.get_payment_intent_update(&payment_data, storage_scheme); let payment_attempt_update = response_router_data.get_payment_attempt_update(&payment_data, storage_scheme); let updated_payment_intent = db .update_payment_intent( key_manager_state, payment_data.payment_intent, payment_intent_update, key_store, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment intent")?; let updated_payment_attempt = db .update_payment_attempt( key_manager_state, key_store, payment_data.payment_attempt, payment_attempt_update, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment attempt")?; payment_data.payment_intent = updated_payment_intent; payment_data.payment_attempt = updated_payment_attempt; // TODO: Add external vault specific post-update logic if needed Ok(payment_data) } } #[cfg(feature = "v2")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::SetupMandateRequestData> for PaymentResponse { async fn update_tracker<'b>( &'b self, state: &'b SessionState, mut payment_data: PaymentConfirmData<F>, response: types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<PaymentConfirmData<F>> where F: 'b + Send + Sync, types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects< F, types::SetupMandateRequestData, PaymentConfirmData<F>, >, { use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects; let db = &*state.store; let key_manager_state = &state.into(); let response_router_data = response; let payment_intent_update = response_router_data.get_payment_intent_update(&payment_data, storage_scheme); let payment_attempt_update = response_router_data.get_payment_attempt_update(&payment_data, storage_scheme); let updated_payment_intent = db .update_payment_intent( key_manager_state, payment_data.payment_intent, payment_intent_update, key_store, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment intent")?; let updated_payment_attempt = db .update_payment_attempt( key_manager_state, key_store, payment_data.payment_attempt, payment_attempt_update, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment attempt")?; payment_data.payment_intent = updated_payment_intent; payment_data.payment_attempt = updated_payment_attempt; Ok(payment_data) } async fn save_pm_and_mandate<'b>( &self, state: &SessionState, router_data: &types::RouterData< F, types::SetupMandateRequestData, types::PaymentsResponseData, >, merchant_context: &domain::MerchantContext, payment_data: &mut PaymentConfirmData<F>, business_profile: &domain::Profile, ) -> CustomResult<(), errors::ApiErrorResponse> where F: 'b + Clone + Send + Sync, { // If we received a payment_method_id from connector in the router data response // Then we either update the payment method or create a new payment method // The case for updating the payment method is when the payment is created from the payment method service let Ok(payments_response) = &router_data.response else { // In case there was an error response from the connector // We do not take any action related to the payment method return Ok(()); }; let connector_request_reference_id = payment_data .payment_attempt .connector_token_details .as_ref() .and_then(|token_details| token_details.get_connector_token_request_reference_id()); let connector_token = payments_response.get_updated_connector_token_details(connector_request_reference_id); let payment_method_id = payment_data.payment_attempt.payment_method_id.clone(); // TODO: check what all conditions we will need to see if card need to be saved match ( connector_token .as_ref() .and_then(|connector_token| connector_token.connector_mandate_id.clone()), payment_method_id, ) { (Some(token), Some(payment_method_id)) => { if !matches!( router_data.status, enums::AttemptStatus::Charged | enums::AttemptStatus::Authorized ) { return Ok(()); } let connector_id = payment_data .payment_attempt .merchant_connector_id .clone() .get_required_value("merchant_connector_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing connector id")?; let net_amount = payment_data.payment_attempt.amount_details.get_net_amount(); let currency = payment_data.payment_intent.amount_details.currency; let connector_token_details_for_payment_method_update = api_models::payment_methods::ConnectorTokenDetails { connector_id, status: common_enums::ConnectorTokenStatus::Active, connector_token_request_reference_id: connector_token .and_then(|details| details.connector_token_request_reference_id), original_payment_authorized_amount: Some(net_amount), original_payment_authorized_currency: Some(currency), metadata: None, token: masking::Secret::new(token), token_type: common_enums::TokenizationType::MultiUse, }; let payment_method_update_request = api_models::payment_methods::PaymentMethodUpdate { payment_method_data: None, connector_token_details: Some( connector_token_details_for_payment_method_update, ), }; payment_methods::update_payment_method_core( state, merchant_context, business_profile, payment_method_update_request, &payment_method_id, ) .await .attach_printable("Failed to update payment method")?; } (Some(_), None) => { // TODO: create a new payment method } (None, Some(_)) | (None, None) => {} } Ok(()) } } #[cfg(feature = "v1")] fn update_connector_mandate_details_for_the_flow<F: Clone>( connector_mandate_id: Option<String>, mandate_metadata: Option<masking::Secret<serde_json::Value>>, connector_mandate_request_reference_id: Option<String>, payment_data: &mut PaymentData<F>, ) -> RouterResult<()> { let mut original_connector_mandate_reference_id = payment_data .payment_attempt .connector_mandate_detail .as_ref() .map(|detail| ConnectorMandateReferenceId::foreign_from(detail.clone())); let connector_mandate_reference_id = if connector_mandate_id.is_some() { if let Some(ref mut record) = original_connector_mandate_reference_id { record.update( connector_mandate_id, None, None, mandate_metadata, connector_mandate_request_reference_id, ); Some(record.clone()) } else { Some(ConnectorMandateReferenceId::new( connector_mandate_id, None, None, mandate_metadata, connector_mandate_request_reference_id, )) } } else { original_connector_mandate_reference_id }; payment_data.payment_attempt.connector_mandate_detail = connector_mandate_reference_id .clone() .map(ForeignFrom::foreign_from); payment_data.set_mandate_id(api_models::payments::MandateIds { mandate_id: None, mandate_reference_id: connector_mandate_reference_id.map(|connector_mandate_id| { MandateReferenceId::ConnectorMandateId(connector_mandate_id) }), }); Ok(()) } fn response_to_capture_update( multiple_capture_data: &MultipleCaptureData, response_list: HashMap<String, CaptureSyncResponse>, ) -> RouterResult<Vec<(storage::Capture, storage::CaptureUpdate)>> { let mut capture_update_list = vec![]; let mut unmapped_captures = vec![]; for (connector_capture_id, capture_sync_response) in response_list { let capture = multiple_capture_data.get_capture_by_connector_capture_id(&connector_capture_id); if let Some(capture) = capture { capture_update_list.push(( capture.clone(), storage::CaptureUpdate::foreign_try_from(capture_sync_response)?, )) } else { // connector_capture_id may not be populated in the captures table in some case // if so, we try to map the unmapped capture response and captures in DB. unmapped_captures.push(capture_sync_response) } } capture_update_list.extend(get_capture_update_for_unmapped_capture_responses( unmapped_captures, multiple_capture_data, )?); Ok(capture_update_list) } fn get_capture_update_for_unmapped_capture_responses( unmapped_capture_sync_response_list: Vec<CaptureSyncResponse>, multiple_capture_data: &MultipleCaptureData, ) -> RouterResult<Vec<(storage::Capture, storage::CaptureUpdate)>> { let mut result = Vec::new(); let captures_without_connector_capture_id: Vec<_> = multiple_capture_data .get_pending_captures_without_connector_capture_id() .into_iter() .cloned() .collect(); for capture_sync_response in unmapped_capture_sync_response_list { if let Some(capture) = captures_without_connector_capture_id .iter() .find(|capture| { capture_sync_response.get_connector_response_reference_id() == Some(capture.capture_id.clone()) || capture_sync_response.get_amount_captured() == Some(capture.amount) }) { result.push(( capture.clone(), storage::CaptureUpdate::foreign_try_from(capture_sync_response)?, )) } } Ok(result) } fn get_total_amount_captured<F: Clone, T: types::Capturable>( request: &T, amount_captured: Option<MinorUnit>, router_data_status: enums::AttemptStatus, payment_data: &PaymentData<F>, ) -> Option<MinorUnit> { match &payment_data.multiple_capture_data { Some(multiple_capture_data) => { //multiple capture Some(multiple_capture_data.get_total_blocked_amount()) } None => { //Non multiple capture let amount = request .get_captured_amount( amount_captured.map(MinorUnit::get_amount_as_i64), payment_data, ) .map(MinorUnit::new); amount_captured.or_else(|| { if router_data_status == enums::AttemptStatus::Charged { amount } else { None } }) } } } #[cfg(feature = "v2")] impl<F: Send + Clone + Sync> Operation<F, types::PaymentsCancelData> for PaymentResponse { type Data = hyperswitch_domain_models::payments::PaymentCancelData<F>; fn to_post_update_tracker( &self, ) -> RouterResult< &(dyn PostUpdateTracker<F, Self::Data, types::PaymentsCancelData> + Send + Sync), > { Ok(self) } } #[cfg(feature = "v2")] #[async_trait] impl<F: Clone + Send + Sync> PostUpdateTracker< F, hyperswitch_domain_models::payments::PaymentCancelData<F>, types::PaymentsCancelData, > for PaymentResponse { async fn update_tracker<'b>( &'b self, state: &'b SessionState, mut payment_data: hyperswitch_domain_models::payments::PaymentCancelData<F>, router_data: types::RouterData<F, types::PaymentsCancelData, types::PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<hyperswitch_domain_models::payments::PaymentCancelData<F>> where F: 'b + Send + Sync, types::RouterData<F, types::PaymentsCancelData, types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects< F, types::PaymentsCancelData, hyperswitch_domain_models::payments::PaymentCancelData<F>, >, { let db = &*state.store; let key_manager_state = &state.into(); use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects; let payment_intent_update = router_data.get_payment_intent_update(&payment_data, storage_scheme); let updated_payment_intent = db .update_payment_intent( key_manager_state, payment_data.payment_intent.clone(), payment_intent_update, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Error while updating the payment_intent")?; let payment_attempt_update = router_data.get_payment_attempt_update(&payment_data, storage_scheme); let updated_payment_attempt = db .update_payment_attempt( key_manager_state, key_store, payment_data.payment_attempt.clone(), payment_attempt_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Error while updating the payment_attempt")?; payment_data.set_payment_intent(updated_payment_intent); payment_data.set_payment_attempt(updated_payment_attempt); Ok(payment_data) } }
crates/router/src/core/payments/operations/payment_response.rs#chunk2
router
chunk
null
null
null
8,074
null
null
null
null
null
null
null
// Implementation: impl webhooks::IncomingWebhook for for Paystack // File: crates/hyperswitch_connectors/src/connectors/paystack.rs // Module: hyperswitch_connectors // Methods: 6 total (0 public) impl webhooks::IncomingWebhook for for Paystack
crates/hyperswitch_connectors/src/connectors/paystack.rs
hyperswitch_connectors
impl_block
null
null
null
61
null
Paystack
webhooks::IncomingWebhook for
6
0
null
null
// Struct: PaypalSyncBatchResponse // File: crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PaypalSyncBatchResponse
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
hyperswitch_connectors
struct_definition
PaypalSyncBatchResponse
0
[]
49
null
null
null
null
null
null
null
// Function: new // File: crates/router/src/events/api_logs.rs // Module: router pub fn new( tenant_id: common_utils::id_type::TenantId, merchant_id: Option<common_utils::id_type::MerchantId>, api_flow: &impl FlowMetric, request_id: &RequestId, latency: u128, status_code: i64, request: serde_json::Value, response: Option<serde_json::Value>, hs_latency: Option<u128>, auth_type: AuthenticationType, error: Option<serde_json::Value>, event_type: ApiEventsType, http_req: &HttpRequest, http_method: &http::Method, infra_components: Option<serde_json::Value>, ) -> Self
crates/router/src/events/api_logs.rs
router
function_signature
null
null
null
169
new
null
null
null
null
null
null
// File: crates/router/tests/connectors/square.rs // Module: router use std::{str::FromStr, time::Duration}; use masking::Secret; use router::types::{self, storage::enums, PaymentsResponseData}; use test_utils::connector_auth::ConnectorAuthentication; use crate::utils::{self, get_connector_transaction_id, Connector, ConnectorActions}; #[derive(Clone, Copy)] struct SquareTest; impl ConnectorActions for SquareTest {} impl Connector for SquareTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Square; utils::construct_connector_data_old( Box::new(&Square), types::Connector::Square, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( ConnectorAuthentication::new() .square .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "square".to_string() } } static CONNECTOR: SquareTest = SquareTest {}; fn get_default_payment_info(payment_method_token: Option<String>) -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: None, auth_type: None, access_token: None, connector_meta_data: None, connector_customer: None, payment_method_token, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] currency: None, }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } fn token_details() -> Option<types::PaymentMethodTokenizationData> { Some(types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("04".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("100".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, split_payments: None, mandate_id: None, setup_future_usage: None, customer_acceptance: None, setup_mandate_details: None, }) } async fn create_token() -> Option<String> { let token_response = CONNECTOR .create_connector_pm_token(token_details(), get_default_payment_info(None)) .await .expect("Authorize payment response"); match token_response.response.unwrap() { PaymentsResponseData::TokenizationResponse { token } => Some(token), _ => None, } } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), None, get_default_payment_info(create_token().await), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector does not support partial capture"] 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(create_token().await), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .expect("Authorize payment response"); let txn_id = 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(None), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(create_token().await), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(create_token().await), ) .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(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(create_token().await), ) .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(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(create_token().await), ) .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(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = 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(None), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), None, get_default_payment_info(create_token().await), ) .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(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(create_token().await), ) .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(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { //make a successful payment let response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .unwrap(); let refund_data = Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }); //try refund for previous payment let transaction_id = get_connector_transaction_id(response.response).unwrap(); for _x in 0..2 { tokio::time::sleep(Duration::from_secs(CONNECTOR.get_request_interval())).await; // to avoid 404 error let refund_response = CONNECTOR .refund_payment( transaction_id.clone(), refund_data.clone(), get_default_payment_info(None), ) .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(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), None, get_default_payment_info(create_token().await), ) .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(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("11".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, split_payments: None, mandate_id: None, setup_future_usage: None, customer_acceptance: None, setup_mandate_details: None, }), get_default_payment_info(None), ) .await .expect("Authorize payment response"); assert_eq!( token_response .response .unwrap_err() .reason .unwrap_or("".to_string()), "Missing required parameter.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("20".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, split_payments: None, mandate_id: None, setup_future_usage: None, customer_acceptance: None, setup_mandate_details: None, }), get_default_payment_info(None), ) .await .expect("Authorize payment response"); assert_eq!( token_response .response .unwrap_err() .reason .unwrap_or("".to_string()), "Invalid card expiration date.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("11".to_string()), card_exp_year: Secret::new("2000".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, split_payments: None, mandate_id: None, setup_future_usage: None, customer_acceptance: None, setup_mandate_details: None, }), get_default_payment_info(None), ) .await .expect("Authorize payment response"); assert_eq!( token_response .response .unwrap_err() .reason .unwrap_or("".to_string()), "Invalid card expiration date.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment( txn_id.clone().unwrap(), None, get_default_payment_info(None), ) .await .unwrap(); let connector_transaction_id = txn_id.unwrap(); assert_eq!( void_response.response.unwrap_err().reason.unwrap_or("".to_string()), format!("Payment {connector_transaction_id} is in inflight state COMPLETED, which is invalid for the requested operation") ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment( "123456789".to_string(), None, get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!( capture_response .response .unwrap_err() .reason .unwrap_or("".to_string()), String::from("Could not find payment with id: 123456789") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!( response .response .unwrap_err() .reason .unwrap_or("".to_string()), "The requested refund amount exceeds the amount available to refund.", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
crates/router/tests/connectors/square.rs
router
full_file
null
null
null
4,300
null
null
null
null
null
null
null
// Struct: SignUpWithMerchantIdRequest // File: crates/api_models/src/user.rs // Module: api_models // Implementations: 0 pub struct SignUpWithMerchantIdRequest
crates/api_models/src/user.rs
api_models
struct_definition
SignUpWithMerchantIdRequest
0
[]
39
null
null
null
null
null
null
null
// Struct: DwollaFundingSourceRequest // File: crates/hyperswitch_connectors/src/connectors/dwolla/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct DwollaFundingSourceRequest
crates/hyperswitch_connectors/src/connectors/dwolla/transformers.rs
hyperswitch_connectors
struct_definition
DwollaFundingSourceRequest
0
[]
54
null
null
null
null
null
null
null
// Function: event_types // File: crates/common_enums/src/enums.rs // Module: common_enums pub fn event_types(self) -> HashSet<EventType>
crates/common_enums/src/enums.rs
common_enums
function_signature
null
null
null
36
event_types
null
null
null
null
null
null
// Function: get_email // File: crates/router/src/types/domain/user.rs // Module: router pub fn get_email(&self) -> UserEmail
crates/router/src/types/domain/user.rs
router
function_signature
null
null
null
32
get_email
null
null
null
null
null
null
// Function: enum_value_string // File: crates/euclid/src/frontend/ast/parser.rs // Module: euclid pub fn enum_value_string(input: &str) -> ParseResult<&str, String>
crates/euclid/src/frontend/ast/parser.rs
euclid
function_signature
null
null
null
45
enum_value_string
null
null
null
null
null
null
// Implementation: impl api::PaymentCapture for for Finix // File: crates/hyperswitch_connectors/src/connectors/finix.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentCapture for for Finix
crates/hyperswitch_connectors/src/connectors/finix.rs
hyperswitch_connectors
impl_block
null
null
null
58
null
Finix
api::PaymentCapture for
0
0
null
null
// File: crates/hyperswitch_connectors/src/connectors/riskified.rs // Module: hyperswitch_connectors // Public functions: 2 // Public structs: 1 pub mod transformers; #[cfg(feature = "frm")] use api_models::webhooks::{ConnectorWebhookSecrets, IncomingWebhookEvent, ObjectReferenceId}; #[cfg(feature = "frm")] use base64::Engine; #[cfg(feature = "frm")] use common_utils::types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}; #[cfg(feature = "frm")] use common_utils::{ consts::BASE64_ENGINE, request::{Method, RequestBuilder}, types::MinorUnit, }; #[cfg(feature = "frm")] use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; use common_utils::{errors::CustomResult, request::Request}; #[cfg(feature = "frm")] use error_stack::ResultExt; #[cfg(feature = "frm")] use hyperswitch_domain_models::{ router_data::ErrorResponse, router_flow_types::{Checkout, Fulfillment, RecordReturn, Sale, Transaction}, router_request_types::fraud_check::{ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, FraudCheckSaleData, FraudCheckTransactionData, }, router_response_types::fraud_check::FraudCheckResponseData, }; use hyperswitch_domain_models::{ router_data::{AccessToken, RouterData}, router_flow_types::{ AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session, SetupMandate, Void, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, }, }; use hyperswitch_interfaces::{ api::{ ConnectorAccessToken, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, MandateSetup, Payment, PaymentAuthorize, PaymentCapture, PaymentSession, PaymentSync, PaymentToken, PaymentVoid, Refund, RefundExecute, RefundSync, }, configs::Connectors, errors::ConnectorError, }; #[cfg(feature = "frm")] use hyperswitch_interfaces::{ api::{ FraudCheck, FraudCheckCheckout, FraudCheckFulfillment, FraudCheckRecordReturn, FraudCheckSale, FraudCheckTransaction, }, events::connector_api_logs::ConnectorEvent, types::Response, webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; #[cfg(feature = "frm")] use masking::Maskable; #[cfg(feature = "frm")] use masking::{ExposeInterface, Mask, PeekInterface, Secret}; #[cfg(feature = "frm")] use ring::hmac; #[cfg(feature = "frm")] use transformers as riskified; #[cfg(feature = "frm")] use crate::constants::headers; #[cfg(feature = "frm")] use crate::utils::convert_amount; #[cfg(feature = "frm")] use crate::{ types::{ FrmCheckoutRouterData, FrmCheckoutType, FrmFulfillmentRouterData, FrmFulfillmentType, FrmTransactionRouterData, FrmTransactionType, ResponseRouterData, }, utils::FrmTransactionRouterDataRequest, }; #[derive(Clone)] pub struct Riskified { #[cfg(feature = "frm")] amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), } impl Riskified { pub fn new() -> &'static Self { &Self { #[cfg(feature = "frm")] amount_converter: &StringMajorUnitForConnector, } } #[cfg(feature = "frm")] pub fn generate_authorization_signature( &self, auth: &riskified::RiskifiedAuthType, payload: &str, ) -> CustomResult<String, ConnectorError> { let key = hmac::Key::new( hmac::HMAC_SHA256, auth.secret_token.clone().expose().as_bytes(), ); let signature_value = hmac::sign(&key, payload.as_bytes()); let digest = signature_value.as_ref(); Ok(hex::encode(digest)) } } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Riskified where Self: ConnectorIntegration<Flow, Request, Response>, { #[cfg(feature = "frm")] fn build_headers( &self, req: &RouterData<Flow, Request, Response>, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let auth: riskified::RiskifiedAuthType = riskified::RiskifiedAuthType::try_from(&req.connector_auth_type)?; let riskified_req = self.get_request_body(req, connectors)?; let binding = riskified_req.get_inner_value(); let payload = binding.peek(); let digest = self .generate_authorization_signature(&auth, payload) .change_context(ConnectorError::RequestEncodingFailed)?; let header = vec![ ( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), ), ( "X-RISKIFIED-SHOP-DOMAIN".to_string(), auth.domain_name.clone().into(), ), ( "X-RISKIFIED-HMAC-SHA256".to_string(), Mask::into_masked(digest), ), ( "Accept".to_string(), "application/vnd.riskified.com; version=2".into(), ), ]; Ok(header) } } impl ConnectorCommon for Riskified { fn id(&self) -> &'static str { "riskified" } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.riskified.base_url.as_ref() } #[cfg(feature = "frm")] fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { use hyperswitch_interfaces::consts::NO_ERROR_CODE; let response: riskified::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(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, attempt_status: None, code: NO_ERROR_CODE.to_string(), message: response.error.message.clone(), reason: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } #[cfg(feature = "frm")] impl ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseData> for Riskified { fn get_headers( &self, req: &FrmCheckoutRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &FrmCheckoutRouterData, connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "/decide")) } fn get_request_body( &self, req: &FrmCheckoutRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, ConnectorError> { let amount = convert_amount( self.amount_converter, MinorUnit::new(req.request.amount), req.request .currency .ok_or(ConnectorError::MissingRequiredField { field_name: "currency", })?, )?; let req_data = riskified::RiskifiedRouterData::from((amount, req)); let req_obj = riskified::RiskifiedPaymentsCheckoutRequest::try_from(&req_data)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &FrmCheckoutRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&FrmCheckoutType::get_url(self, req, connectors)?) .attach_default_headers() .headers(FrmCheckoutType::get_headers(self, req, connectors)?) .set_body(FrmCheckoutType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &FrmCheckoutRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<FrmCheckoutRouterData, ConnectorError> { let response: riskified::RiskifiedPaymentsResponse = res .response .parse_struct("RiskifiedPaymentsResponse Checkout") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); <FrmCheckoutRouterData>::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } impl Payment for Riskified {} impl PaymentAuthorize for Riskified {} impl PaymentSync for Riskified {} impl PaymentVoid for Riskified {} impl PaymentCapture for Riskified {} impl MandateSetup for Riskified {} impl ConnectorAccessToken for Riskified {} impl PaymentToken for Riskified {} impl Refund for Riskified {} impl RefundExecute for Riskified {} impl RefundSync for Riskified {} impl ConnectorValidation for Riskified {} #[cfg(feature = "frm")] impl ConnectorIntegration<Sale, FraudCheckSaleData, FraudCheckResponseData> for Riskified {} #[cfg(feature = "frm")] impl ConnectorIntegration<Transaction, FraudCheckTransactionData, FraudCheckResponseData> for Riskified { fn get_headers( &self, req: &FrmTransactionRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &FrmTransactionRouterData, connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { match req.is_payment_successful() { Some(false) => Ok(format!( "{}{}", self.base_url(connectors), "/checkout_denied" )), _ => Ok(format!("{}{}", self.base_url(connectors), "/decision")), } } fn get_request_body( &self, req: &FrmTransactionRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, ConnectorError> { match req.is_payment_successful() { Some(false) => { let req_obj = riskified::TransactionFailedRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } _ => { let amount = convert_amount( self.amount_converter, MinorUnit::new(req.request.amount), req.request .currency .ok_or(ConnectorError::MissingRequiredField { field_name: "currency", })?, )?; let req_data = riskified::RiskifiedRouterData::from((amount, req)); let req_obj = riskified::TransactionSuccessRequest::try_from(&req_data)?; Ok(RequestContent::Json(Box::new(req_obj))) } } } fn build_request( &self, req: &FrmTransactionRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&FrmTransactionType::get_url(self, req, connectors)?) .attach_default_headers() .headers(FrmTransactionType::get_headers(self, req, connectors)?) .set_body(FrmTransactionType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &FrmTransactionRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<FrmTransactionRouterData, ConnectorError> { let response: riskified::RiskifiedTransactionResponse = res .response .parse_struct("RiskifiedPaymentsResponse Transaction") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); match response { riskified::RiskifiedTransactionResponse::FailedResponse(response_data) => { <FrmTransactionRouterData>::try_from(ResponseRouterData { response: response_data, data: data.clone(), http_code: res.status_code, }) } riskified::RiskifiedTransactionResponse::SuccessResponse(response_data) => { <FrmTransactionRouterData>::try_from(ResponseRouterData { response: response_data, data: data.clone(), http_code: res.status_code, }) } } } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "frm")] impl ConnectorIntegration<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData> for Riskified { fn get_headers( &self, req: &FrmFulfillmentRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &FrmFulfillmentRouterData, connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "/fulfill")) } fn get_request_body( &self, req: &FrmFulfillmentRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, ConnectorError> { let req_obj = riskified::RiskifiedFulfillmentRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &FrmFulfillmentRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&FrmFulfillmentType::get_url(self, req, connectors)?) .attach_default_headers() .headers(FrmFulfillmentType::get_headers(self, req, connectors)?) .set_body(FrmFulfillmentType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &FrmFulfillmentRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<FrmFulfillmentRouterData, ConnectorError> { let response: riskified::RiskifiedFulfilmentResponse = res .response .parse_struct("RiskifiedFulfilmentResponse fulfilment") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); FrmFulfillmentRouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "frm")] impl ConnectorIntegration<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData> for Riskified { } impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Riskified { } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Riskified {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Riskified { fn build_request( &self, _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Err(ConnectorError::NotImplemented("Setup Mandate flow for Riskified".to_string()).into()) } } impl PaymentSession for Riskified {} impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Riskified {} impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Riskified {} impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Riskified {} impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Riskified {} impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Riskified {} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Riskified {} impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Riskified {} #[cfg(feature = "frm")] impl FraudCheck for Riskified {} #[cfg(feature = "frm")] impl FraudCheckSale for Riskified {} #[cfg(feature = "frm")] impl FraudCheckCheckout for Riskified {} #[cfg(feature = "frm")] impl FraudCheckTransaction for Riskified {} #[cfg(feature = "frm")] impl FraudCheckFulfillment for Riskified {} #[cfg(feature = "frm")] impl FraudCheckRecordReturn for Riskified {} #[cfg(feature = "frm")] #[async_trait::async_trait] impl IncomingWebhook for Riskified { fn get_webhook_source_verification_algorithm( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, request: &IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, ConnectorError> { let header_value = crate::utils::get_header_key_value("x-riskified-hmac-sha256", request.headers)?; Ok(header_value.as_bytes().to_vec()) } async fn verify_webhook_source( &self, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, ) -> CustomResult<bool, ConnectorError> { let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( merchant_id, connector_label, connector_webhook_details, ) .await .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let signature = self .get_webhook_source_verification_signature(request, &connector_webhook_secrets) .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let message = self .get_webhook_source_verification_message( request, merchant_id, &connector_webhook_secrets, ) .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &connector_webhook_secrets.secret); let signed_message = hmac::sign(&signing_key, &message); let payload_sign = BASE64_ENGINE.encode(signed_message.as_ref()); Ok(payload_sign.as_bytes().eq(&signature)) } fn get_webhook_source_verification_message( &self, request: &IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, ConnectorError> { Ok(request.body.to_vec()) } fn get_webhook_object_reference_id( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<ObjectReferenceId, ConnectorError> { let resource: riskified::RiskifiedWebhookBody = request .body .parse_struct("RiskifiedWebhookBody") .change_context(ConnectorError::WebhookReferenceIdNotFound)?; Ok(ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PaymentAttemptId(resource.id), )) } fn get_webhook_event_type( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { let resource: riskified::RiskifiedWebhookBody = request .body .parse_struct("RiskifiedWebhookBody") .change_context(ConnectorError::WebhookEventTypeNotFound)?; Ok(IncomingWebhookEvent::from(resource.status)) } fn get_webhook_resource_object( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { let resource: riskified::RiskifiedWebhookBody = request .body .parse_struct("RiskifiedWebhookBody") .change_context(ConnectorError::WebhookResourceObjectNotFound)?; Ok(Box::new(resource)) } } static RISKIFIED_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Riskified", description: "Riskified fraud and risk management provider with guaranteed real-time decisions and machine learning-powered ecommerce fraud prevention", connector_type: common_enums::HyperswitchConnectorCategory::FraudAndRiskManagementProvider, integration_status: common_enums::ConnectorIntegrationStatus::Sandbox, }; impl ConnectorSpecifications for Riskified { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&RISKIFIED_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { None } fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> { None } }
crates/hyperswitch_connectors/src/connectors/riskified.rs
hyperswitch_connectors
full_file
null
null
null
5,101
null
null
null
null
null
null
null
// File: crates/api_models/src/analytics/disputes.rs // Module: api_models // Public functions: 1 // Public structs: 4 use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; use super::{ForexMetric, NameDescription, TimeRange}; use crate::enums::{Currency, DisputeStage}; #[derive( Clone, Debug, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIter, strum::AsRefStr, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum DisputeMetrics { DisputeStatusMetric, TotalAmountDisputed, TotalDisputeLostAmount, SessionizedDisputeStatusMetric, SessionizedTotalAmountDisputed, SessionizedTotalDisputeLostAmount, } impl ForexMetric for DisputeMetrics { fn is_forex_metric(&self) -> bool { matches!( self, Self::TotalAmountDisputed | Self::TotalDisputeLostAmount ) } } #[derive( Debug, serde::Serialize, serde::Deserialize, strum::AsRefStr, PartialEq, PartialOrd, Eq, Ord, strum::Display, strum::EnumIter, Clone, Copy, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeDimensions { // Do not change the order of these enums // Consult the Dashboard FE folks since these also affects the order of metrics on FE Connector, DisputeStage, Currency, } impl From<DisputeDimensions> for NameDescription { fn from(value: DisputeDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } } impl From<DisputeMetrics> for NameDescription { fn from(value: DisputeMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } } #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct DisputeFilters { #[serde(default)] pub dispute_stage: Vec<DisputeStage>, #[serde(default)] pub connector: Vec<String>, #[serde(default)] pub currency: Vec<Currency>, } #[derive(Debug, serde::Serialize, Eq)] pub struct DisputeMetricsBucketIdentifier { pub dispute_stage: Option<DisputeStage>, pub connector: Option<String>, pub currency: Option<Currency>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, #[serde(rename = "time_bucket")] #[serde(with = "common_utils::custom_serde::iso8601custom")] pub start_time: time::PrimitiveDateTime, } impl Hash for DisputeMetricsBucketIdentifier { fn hash<H: Hasher>(&self, state: &mut H) { self.dispute_stage.hash(state); self.connector.hash(state); self.currency.hash(state); self.time_bucket.hash(state); } } impl PartialEq for DisputeMetricsBucketIdentifier { fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } } impl DisputeMetricsBucketIdentifier { pub fn new( dispute_stage: Option<DisputeStage>, connector: Option<String>, currency: Option<Currency>, normalized_time_range: TimeRange, ) -> Self { Self { dispute_stage, connector, currency, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } } #[derive(Debug, serde::Serialize)] pub struct DisputeMetricsBucketValue { pub disputes_challenged: Option<u64>, pub disputes_won: Option<u64>, pub disputes_lost: Option<u64>, pub disputed_amount: Option<u64>, pub dispute_lost_amount: Option<u64>, pub total_dispute: Option<u64>, } #[derive(Debug, serde::Serialize)] pub struct DisputeMetricsBucketResponse { #[serde(flatten)] pub values: DisputeMetricsBucketValue, #[serde(flatten)] pub dimensions: DisputeMetricsBucketIdentifier, }
crates/api_models/src/analytics/disputes.rs
api_models
full_file
null
null
null
968
null
null
null
null
null
null
null
// Implementation: impl ConnectorSpecifications for for Wellsfargopayout // File: crates/hyperswitch_connectors/src/connectors/wellsfargopayout.rs // Module: hyperswitch_connectors // Methods: 3 total (0 public) impl ConnectorSpecifications for for Wellsfargopayout
crates/hyperswitch_connectors/src/connectors/wellsfargopayout.rs
hyperswitch_connectors
impl_block
null
null
null
63
null
Wellsfargopayout
ConnectorSpecifications for
3
0
null
null
// Struct: PayPalOnboardingDone // File: crates/api_models/src/connector_onboarding.rs // Module: api_models // Implementations: 0 pub struct PayPalOnboardingDone
crates/api_models/src/connector_onboarding.rs
api_models
struct_definition
PayPalOnboardingDone
0
[]
40
null
null
null
null
null
null
null
// Struct: ChargebeeGetPlanPriceList // File: crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ChargebeeGetPlanPriceList
crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs
hyperswitch_connectors
struct_definition
ChargebeeGetPlanPriceList
0
[]
54
null
null
null
null
null
null
null
// Function: get_token_from_tokenization_service // File: crates/router/src/core/payment_methods/network_tokenization.rs // Module: router pub fn get_token_from_tokenization_service( state: &routes::SessionState, network_token_requestor_ref_id: String, pm_data: &domain::PaymentMethod, ) -> errors::RouterResult<domain::NetworkTokenData>
crates/router/src/core/payment_methods/network_tokenization.rs
router
function_signature
null
null
null
80
get_token_from_tokenization_service
null
null
null
null
null
null
// Function: is_failed // File: crates/common_enums/src/enums.rs // Module: common_enums pub fn is_failed(self) -> bool
crates/common_enums/src/enums.rs
common_enums
function_signature
null
null
null
33
is_failed
null
null
null
null
null
null
// Function: execute_payment_task_response_handler // File: crates/router/src/core/revenue_recovery/types.rs // Module: router pub fn execute_payment_task_response_handler( &self, state: &SessionState, payment_intent: &PaymentIntent, execute_task_process: &storage::ProcessTracker, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata, ) -> Result<(), errors::ProcessTrackerError>
crates/router/src/core/revenue_recovery/types.rs
router
function_signature
null
null
null
108
execute_payment_task_response_handler
null
null
null
null
null
null
// Function: try_get_enum_variant // File: crates/router_derive/src/lib.rs // Module: router_derive pub fn try_get_enum_variant(input: proc_macro::TokenStream) -> proc_macro::TokenStream
crates/router_derive/src/lib.rs
router_derive
function_signature
null
null
null
46
try_get_enum_variant
null
null
null
null
null
null
// Function: permission_groups_to_parent_group_info // File: crates/router/src/utils/user_role.rs // Module: router pub fn permission_groups_to_parent_group_info( permission_groups: &[PermissionGroup], entity_type: EntityType, ) -> Vec<role_api::ParentGroupInfo>
crates/router/src/utils/user_role.rs
router
function_signature
null
null
null
60
permission_groups_to_parent_group_info
null
null
null
null
null
null
// Implementation: impl api::MandateSetup for for Itaubank // File: crates/hyperswitch_connectors/src/connectors/itaubank.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::MandateSetup for for Itaubank
crates/hyperswitch_connectors/src/connectors/itaubank.rs
hyperswitch_connectors
impl_block
null
null
null
65
null
Itaubank
api::MandateSetup for
0
0
null
null
// Implementation: impl api::Payment for for Stripebilling // File: crates/hyperswitch_connectors/src/connectors/stripebilling.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::Payment for for Stripebilling
crates/hyperswitch_connectors/src/connectors/stripebilling.rs
hyperswitch_connectors
impl_block
null
null
null
56
null
Stripebilling
api::Payment for
0
0
null
null
// File: crates/openapi/src/routes/proxy.rs // Module: openapi // Public functions: 1 #[cfg(feature = "v2")] ///Proxy /// /// Create a proxy request #[utoipa::path( post, path = "/proxy", request_body( content = ProxyRequest, examples(( "Create a proxy request" = ( value = json!({ "request_body": { "source": { "type": "card", "number": "{{$card_number}}", "expiry_month": "{{$card_exp_month}}", "expiry_year": "{{$card_exp_year}}", "billing_address": { "address_line1": "123 High St.", "city": "London", "country": "GB" } }, "amount": 6540, "currency": "USD", "reference": "ORD-5023-4E89", "capture": true }, "destination_url": "https://api.example.com/payments", "headers": { "Content-Type": "application/json", "Authorization": "Bearer sk_test_example" }, "token": "pm_0196ea5a42a67583863d5b1253d62931", "token_type": "PaymentMethodId", "method": "POST" }) ) )) ), responses( (status = 200, description = "Proxy request", body = ProxyResponse), (status = 400, description = "Invalid data") ), params( ("X-Profile-Id" = String, Header, description = "Profile ID for authentication"), ), tag = "Proxy", operation_id = "Proxy Request", security(("api_key" = [])) )] pub async fn proxy_core() {}
crates/openapi/src/routes/proxy.rs
openapi
full_file
null
null
null
418
null
null
null
null
null
null
null
// Struct: DwollaPaymentLinks // File: crates/hyperswitch_connectors/src/connectors/dwolla/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct DwollaPaymentLinks
crates/hyperswitch_connectors/src/connectors/dwolla/transformers.rs
hyperswitch_connectors
struct_definition
DwollaPaymentLinks
0
[]
50
null
null
null
null
null
null
null
// Function: find_subscription // File: crates/router/src/core/subscription.rs // Module: router pub fn find_subscription( &self, subscription_id: String, ) -> errors::RouterResult<SubscriptionWithHandler<'_>>
crates/router/src/core/subscription.rs
router
function_signature
null
null
null
51
find_subscription
null
null
null
null
null
null
// Struct: ExchangeTokenCreateRequest // File: crates/api_models/src/pm_auth.rs // Module: api_models // Implementations: 0 pub struct ExchangeTokenCreateRequest
crates/api_models/src/pm_auth.rs
api_models
struct_definition
ExchangeTokenCreateRequest
0
[]
38
null
null
null
null
null
null
null
// Implementation: impl api::RefundSync for for Helcim // File: crates/hyperswitch_connectors/src/connectors/helcim.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::RefundSync for for Helcim
crates/hyperswitch_connectors/src/connectors/helcim.rs
hyperswitch_connectors
impl_block
null
null
null
63
null
Helcim
api::RefundSync for
0
0
null
null
// Trait: ResourceExt // File: crates/router_derive/src/macros/generate_permissions.rs // Module: router_derive pub trait ResourceExt
crates/router_derive/src/macros/generate_permissions.rs
router_derive
trait_definition
null
null
null
32
null
null
ResourceExt
null
null
null
null
// File: crates/router/src/routes/pm_auth.rs // Module: router // Public functions: 2 use actix_web::{web, HttpRequest, Responder}; use api_models as api_types; use router_env::{instrument, tracing, types::Flow}; use crate::{ core::api_locking, routes::AppState, services::{api, authentication as auth}, types::transformers::ForeignTryFrom, }; #[instrument(skip_all, fields(flow = ?Flow::PmAuthLinkTokenCreate))] pub async fn link_token_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_types::pm_auth::LinkTokenCreateRequest>, ) -> impl Responder { let payload = json_payload.into_inner(); let flow = Flow::PmAuthLinkTokenCreate; let api_auth = auth::ApiKeyAuth::default(); let (auth, _) = match crate::services::authentication::check_client_secret_and_get_auth( req.headers(), &payload, api_auth, ) { Ok((auth, _auth_flow)) => (auth, _auth_flow), Err(e) => return api::log_and_return_error_response(e), }; let header_payload = match hyperswitch_domain_models::payments::HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth, payload, _| { let merchant_context = crate::types::domain::MerchantContext::NormalMerchant(Box::new( crate::types::domain::Context(auth.merchant_account, auth.key_store), )); crate::core::pm_auth::create_link_token( state, merchant_context, payload, Some(header_payload.clone()), ) }, &*auth, api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::PmAuthExchangeToken))] pub async fn exchange_token( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_types::pm_auth::ExchangeTokenCreateRequest>, ) -> impl Responder { let payload = json_payload.into_inner(); let flow = Flow::PmAuthExchangeToken; let api_auth = auth::ApiKeyAuth::default(); let (auth, _) = match crate::services::authentication::check_client_secret_and_get_auth( req.headers(), &payload, api_auth, ) { Ok((auth, _auth_flow)) => (auth, _auth_flow), Err(e) => return api::log_and_return_error_response(e), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth, payload, _| { let merchant_context = crate::types::domain::MerchantContext::NormalMerchant(Box::new( crate::types::domain::Context(auth.merchant_account, auth.key_store), )); crate::core::pm_auth::exchange_token_core(state, merchant_context, payload) }, &*auth, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/pm_auth.rs
router
full_file
null
null
null
716
null
null
null
null
null
null
null
// Function: is_verified // File: crates/router/src/types/domain/user.rs // Module: router pub fn is_verified(&self) -> bool
crates/router/src/types/domain/user.rs
router
function_signature
null
null
null
31
is_verified
null
null
null
null
null
null
// Struct: GatewayStatusMappingUpdate // File: crates/diesel_models/src/gsm.rs // Module: diesel_models // Implementations: 0 pub struct GatewayStatusMappingUpdate
crates/diesel_models/src/gsm.rs
diesel_models
struct_definition
GatewayStatusMappingUpdate
0
[]
39
null
null
null
null
null
null
null
// File: crates/router/tests/connectors/forte.rs // Module: router use std::{str::FromStr, time::Duration}; use cards::CardNumber; use common_utils::types::MinorUnit; use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails}; use masking::Secret; use router::types::{self, api, domain, storage::enums}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct ForteTest; impl ConnectorActions for ForteTest {} impl utils::Connector for ForteTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Forte; utils::construct_connector_data_old( Box::new(Forte::new()), types::Connector::Forte, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .forte .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "forte".to_string() } } static CONNECTOR: ForteTest = ForteTest {}; fn get_payment_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: CardNumber::from_str("4111111111111111").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }) } fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(types::PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::IN), ..Default::default() }), phone: Some(PhoneDetails { number: Some(Secret::new("9123456789".to_string())), country_code: Some("+91".to_string()), }), email: None, }), None, None, )), ..Default::default() }) } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(get_payment_data(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); let connector_meta = utils::get_connector_metadata(authorize_response.response); let response = CONNECTOR .capture_payment( txn_id, Some(types::PaymentsCaptureData { connector_meta, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); //Status of the Payments is always in Pending State, Forte has to settle the sandbox transaction manually assert_eq!(response.status, enums::AttemptStatus::Pending); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); let connector_meta = utils::get_connector_metadata(authorize_response.response); let response = CONNECTOR .capture_payment( txn_id, Some(types::PaymentsCaptureData { connector_meta, amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); //Status of the Payments is always in Pending State, Forte has to settle the sandbox transactions manually assert_eq!(response.status, enums::AttemptStatus::Pending); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), 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(), ), encoded_data: None, capture_method: None, sync_type: types::SyncRequestType::SinglePaymentSync, connector_meta: None, mandate_id: None, payment_method_type: None, currency: enums::Currency::USD, payment_experience: None, integrity_object: None, amount: MinorUnit::new(100), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); let connector_meta = utils::get_connector_metadata(authorize_response.response); let response = CONNECTOR .void_payment( txn_id, Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), connector_meta, ..Default::default() }), None, ) .await .expect("Void payment response"); //Forte doesnot send status in response, so setting it to pending so later it will be synced assert_eq!(response.status, enums::AttemptStatus::Pending); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore = "Since Payment status is always in pending, cannot refund"] async fn should_refund_manually_captured_payment() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), None) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); let capture_connector_meta = utils::get_connector_metadata(authorize_response.response); let capture_response = CONNECTOR .capture_payment( txn_id.clone(), Some(types::PaymentsCaptureData { connector_meta: capture_connector_meta, ..utils::PaymentCaptureType::default().0 }), None, ) .await .expect("Capture payment response"); let refund_connector_metadata = utils::get_connector_metadata(capture_response.response); let response = CONNECTOR .refund_payment( txn_id, Some(types::RefundsData { connector_metadata: refund_connector_metadata, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore = "Since Payment status is always in pending, cannot refund"] async fn should_partially_refund_manually_captured_payment() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), None) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); let capture_connector_meta = utils::get_connector_metadata(authorize_response.response); let capture_response = CONNECTOR .capture_payment( txn_id.clone(), Some(types::PaymentsCaptureData { connector_meta: capture_connector_meta, ..utils::PaymentCaptureType::default().0 }), None, ) .await .expect("Capture payment response"); let refund_connector_metadata = utils::get_connector_metadata(capture_response.response); let response = CONNECTOR .refund_payment( txn_id, Some(types::RefundsData { connector_metadata: refund_connector_metadata, refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .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 = "Since Payment status is always in pending, cannot refund"] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund(None, None, None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let response = CONNECTOR .make_payment(get_payment_data(), get_default_payment_info()) .await .unwrap(); //Status of the Payments is always in Pending State, Forte has to settle the sandbox transaction manually assert_eq!(response.status, enums::AttemptStatus::Pending); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(get_payment_data(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); 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(), ), encoded_data: None, capture_method: None, ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); //Status of the Payments is always in Pending State, Forte has to settle the sandbox transaction manually assert_eq!(response.status, enums::AttemptStatus::Pending,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] #[ignore = "Since Payment status is always in pending, cannot refund"] async fn should_refund_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(get_payment_data(), get_default_payment_info()) .await .unwrap(); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); tokio::time::sleep(Duration::from_secs(10)).await; let refund_connector_metadata = utils::get_connector_metadata(authorize_response.response); let response = CONNECTOR .refund_payment( txn_id, Some(types::RefundsData { connector_metadata: refund_connector_metadata, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] #[ignore = "Since Payment status is always in pending, cannot refund"] async fn should_partially_refund_succeeded_payment() { let authorize_response = CONNECTOR .make_payment(get_payment_data(), get_default_payment_info()) .await .unwrap(); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); tokio::time::sleep(Duration::from_secs(10)).await; let refund_connector_metadata = utils::get_connector_metadata(authorize_response.response); let response = CONNECTOR .refund_payment( txn_id, Some(types::RefundsData { refund_amount: 50, connector_metadata: refund_connector_metadata, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] #[ignore = "Since Payment status is always in pending, cannot refund"] async fn should_refund_succeeded_payment_multiple_times() { let authorize_response = CONNECTOR .make_payment(get_payment_data(), get_default_payment_info()) .await .unwrap(); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); tokio::time::sleep(Duration::from_secs(10)).await; let refund_connector_metadata = utils::get_connector_metadata(authorize_response.response); for _x in 0..2 { let refund_response = CONNECTOR .refund_payment( txn_id.clone(), Some(types::RefundsData { connector_metadata: refund_connector_metadata.clone(), refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] #[ignore = "Since Payment status is always in pending, cannot refund"] async fn should_sync_refund() { let authorize_response = CONNECTOR .make_payment(get_payment_data(), get_default_payment_info()) .await .unwrap(); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); tokio::time::sleep(Duration::from_secs(10)).await; let refund_connector_metadata = utils::get_connector_metadata(authorize_response.response); let refund_response = CONNECTOR .refund_payment( txn_id, Some(types::RefundsData { connector_metadata: refund_connector_metadata, ..utils::PaymentRefundType::default().0 }), 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::Pending, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "INVALID CVV DATA".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "INVALID EXPIRATION DATE".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] #[ignore] 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 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); let capture_connector_meta = utils::get_connector_metadata(authorize_response.response); let capture_response = CONNECTOR .capture_payment( txn_id, Some(types::PaymentsCaptureData { connector_meta: capture_connector_meta, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); let txn_id = utils::get_connector_transaction_id(capture_response.clone().response).unwrap(); let connector_meta = utils::get_connector_metadata(capture_response.response); let void_response = CONNECTOR .void_payment( txn_id, Some(types::PaymentsCancelData { cancellation_reason: Some("requested_by_customer".to_string()), connector_meta, ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!( void_response.response.unwrap_err().message, "ORIG TRANS NOT FOUND" ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let connector_meta = Some(serde_json::json!({ "auth_id": "56YH8TZ", })); let capture_response = CONNECTOR .capture_payment( "123456789".to_string(), Some(types::PaymentsCaptureData { connector_meta, ..utils::PaymentCaptureType::default().0 }), None, ) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, "Error[1]: The value for field transaction_id is invalid. Check for possible formatting issues. Error[2]: The value for field transaction_id is invalid. Check for possible formatting issues.", ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] #[ignore] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let authorize_response = CONNECTOR .make_payment(get_payment_data(), None) .await .unwrap(); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); tokio::time::sleep(Duration::from_secs(10)).await; let refund_connector_metadata = utils::get_connector_metadata(authorize_response.response); let response = CONNECTOR .refund_payment( txn_id, Some(types::RefundsData { refund_amount: 1500, connector_metadata: refund_connector_metadata, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests // Cards Negative scenarios // Creates a payment with incorrect card issuer. #[actix_web::test] async fn should_throw_not_implemented_for_unsupported_issuer() { let authorize_data = Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: CardNumber::from_str("6759649826438453").unwrap(), ..utils::CCardType::default().0 }), capture_method: Some(enums::CaptureMethod::Automatic), ..utils::PaymentAuthorizeType::default().0 }); let response = CONNECTOR.make_payment(authorize_data, None).await; assert_eq!( *response.unwrap_err().current_context(), router::core::errors::ConnectorError::NotSupported { message: "Maestro".to_string(), connector: "Forte", } ) }
crates/router/tests/connectors/forte.rs
router
full_file
null
null
null
4,972
null
null
null
null
null
null
null
// File: crates/router/src/db/subscription.rs // Module: router use error_stack::report; use router_env::{instrument, tracing}; use storage_impl::MockDb; use super::Store; use crate::{ connection, core::errors::{self, CustomResult}, db::kafka_store::KafkaStore, types::storage, }; #[async_trait::async_trait] pub trait SubscriptionInterface { async fn insert_subscription_entry( &self, subscription_new: storage::subscription::SubscriptionNew, ) -> CustomResult<storage::Subscription, errors::StorageError>; async fn find_by_merchant_id_subscription_id( &self, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, ) -> CustomResult<storage::Subscription, errors::StorageError>; async fn update_subscription_entry( &self, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, data: storage::SubscriptionUpdate, ) -> CustomResult<storage::Subscription, errors::StorageError>; } #[async_trait::async_trait] impl SubscriptionInterface for Store { #[instrument(skip_all)] async fn insert_subscription_entry( &self, subscription_new: storage::subscription::SubscriptionNew, ) -> CustomResult<storage::Subscription, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; subscription_new .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_by_merchant_id_subscription_id( &self, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, ) -> CustomResult<storage::Subscription, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Subscription::find_by_merchant_id_subscription_id( &conn, merchant_id, subscription_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_subscription_entry( &self, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, data: storage::SubscriptionUpdate, ) -> CustomResult<storage::Subscription, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Subscription::update_subscription_entry(&conn, merchant_id, subscription_id, data) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl SubscriptionInterface for MockDb { #[instrument(skip_all)] async fn insert_subscription_entry( &self, _subscription_new: storage::subscription::SubscriptionNew, ) -> CustomResult<storage::Subscription, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_by_merchant_id_subscription_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _subscription_id: String, ) -> CustomResult<storage::Subscription, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_subscription_entry( &self, _merchant_id: &common_utils::id_type::MerchantId, _subscription_id: String, _data: storage::SubscriptionUpdate, ) -> CustomResult<storage::Subscription, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } #[async_trait::async_trait] impl SubscriptionInterface for KafkaStore { #[instrument(skip_all)] async fn insert_subscription_entry( &self, subscription_new: storage::subscription::SubscriptionNew, ) -> CustomResult<storage::Subscription, errors::StorageError> { self.diesel_store .insert_subscription_entry(subscription_new) .await } #[instrument(skip_all)] async fn find_by_merchant_id_subscription_id( &self, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, ) -> CustomResult<storage::Subscription, errors::StorageError> { self.diesel_store .find_by_merchant_id_subscription_id(merchant_id, subscription_id) .await } #[instrument(skip_all)] async fn update_subscription_entry( &self, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, data: storage::SubscriptionUpdate, ) -> CustomResult<storage::Subscription, errors::StorageError> { self.diesel_store .update_subscription_entry(merchant_id, subscription_id, data) .await } }
crates/router/src/db/subscription.rs
router
full_file
null
null
null
1,031
null
null
null
null
null
null
null
// Function: retrieve_default_fallback_algorithm_for_profile // File: crates/router/src/core/routing.rs // Module: router pub fn retrieve_default_fallback_algorithm_for_profile( state: SessionState, merchant_context: domain::MerchantContext, profile_id: common_utils::id_type::ProfileId, ) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>>
crates/router/src/core/routing.rs
router
function_signature
null
null
null
80
retrieve_default_fallback_algorithm_for_profile
null
null
null
null
null
null
// Function: insert // File: crates/diesel_models/src/query/payout_attempt.rs // Module: diesel_models pub fn insert(self, conn: &PgPooledConn) -> StorageResult<PayoutAttempt>
crates/diesel_models/src/query/payout_attempt.rs
diesel_models
function_signature
null
null
null
45
insert
null
null
null
null
null
null
// File: crates/analytics/src/payments/metrics/payment_success_count.rs // Module: analytics use std::collections::HashSet; use api_models::analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::PaymentMetricRow; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(super) struct PaymentSuccessCount; #[async_trait::async_trait] impl<T> super::PaymentMetric<T> for PaymentSuccessCount where T: AnalyticsDataSource + super::PaymentMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Payment); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(Aggregate::Count { field: None, alias: Some("count"), }) .switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; auth.set_filter_clause(&mut query_builder).switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; for dim in dimensions.iter() { query_builder .add_group_by_clause(dim) .attach_printable("Error grouping by dimensions") .switch()?; } if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } query_builder .add_filter_clause( PaymentDimensions::PaymentStatus, storage_enums::AttemptStatus::Charged, ) .switch()?; query_builder .execute_query::<PaymentMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( PaymentMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), None, i.connector.clone(), i.authentication_type.as_ref().map(|i| i.0), i.payment_method.clone(), i.payment_method_type.clone(), i.client_source.clone(), i.client_version.clone(), i.profile_id.clone(), i.card_network.clone(), i.merchant_id.clone(), i.card_last_4.clone(), i.card_issuer.clone(), i.error_reason.clone(), i.routing_approach.as_ref().map(|i| i.0.clone()), i.signature_network.clone(), i.is_issuer_regulated, i.is_debit_routed, TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result< HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/payments/metrics/payment_success_count.rs
analytics
full_file
null
null
null
980
null
null
null
null
null
null
null
// Implementation: impl api::PaymentSync for for Stripebilling // File: crates/hyperswitch_connectors/src/connectors/stripebilling.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentSync for for Stripebilling
crates/hyperswitch_connectors/src/connectors/stripebilling.rs
hyperswitch_connectors
impl_block
null
null
null
58
null
Stripebilling
api::PaymentSync for
0
0
null
null
// Struct: ApplePayTokenPaymentInformation // File: crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ApplePayTokenPaymentInformation
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
hyperswitch_connectors
struct_definition
ApplePayTokenPaymentInformation
0
[]
53
null
null
null
null
null
null
null
// Struct: InvoiceRecordBackData // File: crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct InvoiceRecordBackData
crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
hyperswitch_domain_models
struct_definition
InvoiceRecordBackData
0
[]
50
null
null
null
null
null
null
null
// Function: set_cargo_workspace_members_env // File: crates/router_env/src/cargo_workspace.rs // Module: router_env pub fn set_cargo_workspace_members_env()
crates/router_env/src/cargo_workspace.rs
router_env
function_signature
null
null
null
37
set_cargo_workspace_members_env
null
null
null
null
null
null
// Struct: CardSpecificFeatures // File: crates/api_models/src/feature_matrix.rs // Module: api_models // Implementations: 0 pub struct CardSpecificFeatures
crates/api_models/src/feature_matrix.rs
api_models
struct_definition
CardSpecificFeatures
0
[]
37
null
null
null
null
null
null
null
// Function: generate_signature // File: crates/hyperswitch_connectors/src/connectors/bankofamerica.rs // Module: hyperswitch_connectors pub fn generate_signature( &self, auth: bankofamerica::BankOfAmericaAuthType, host: String, resource: &str, payload: &String, date: OffsetDateTime, http_method: Method, ) -> CustomResult<String, errors::ConnectorError>
crates/hyperswitch_connectors/src/connectors/bankofamerica.rs
hyperswitch_connectors
function_signature
null
null
null
98
generate_signature
null
null
null
null
null
null
// Struct: AuthipayTransactionProcessingDetails // File: crates/hyperswitch_connectors/src/connectors/authipay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct AuthipayTransactionProcessingDetails
crates/hyperswitch_connectors/src/connectors/authipay/transformers.rs
hyperswitch_connectors
struct_definition
AuthipayTransactionProcessingDetails
0
[]
51
null
null
null
null
null
null
null
// File: crates/router/tests/connectors/powertranz.rs // Module: router use masking::Secret; use router::types::{self, domain, storage::enums}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct PowertranzTest; impl ConnectorActions for PowertranzTest {} impl utils::Connector for PowertranzTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Powertranz; utils::construct_connector_data_old( Box::new(&Powertranz), types::Connector::Powertranz, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .powertranz .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "powertranz".to_string() } } static CONNECTOR: PowertranzTest = PowertranzTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector does not support partial capture"] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector does not support payment sync"] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector does not support payment sync"] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector does not support payment sync"] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector does not support multiple refund"] 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 does not support refund sync"] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Field is invalid: CardCvv".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Field is invalid: CardExpiration".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Failure,); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!(void_response.status, enums::AttemptStatus::VoidFailed); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("Original auth not found") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.response.unwrap_err().message, "Invalid amount"); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
crates/router/tests/connectors/powertranz.rs
router
full_file
null
null
null
2,943
null
null
null
null
null
null
null
Ok(transformers::get_payapl_webhooks_event( payload.event_type, outcome, )) } fn get_webhook_resource_object( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let details: paypal::PaypalWebhooksBody = request .body .parse_struct("PaypalWebhooksBody") .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; Ok(match details.resource { paypal::PaypalResource::PaypalCardWebhooks(resource) => Box::new( paypal::PaypalPaymentsSyncResponse::try_from((*resource, details.event_type))?, ), paypal::PaypalResource::PaypalRedirectsWebhooks(resource) => Box::new( paypal::PaypalOrdersResponse::try_from((*resource, details.event_type))?, ), paypal::PaypalResource::PaypalRefundWebhooks(resource) => Box::new( paypal::RefundSyncResponse::try_from((*resource, details.event_type))?, ), paypal::PaypalResource::PaypalDisputeWebhooks(_) => Box::new(details), #[cfg(feature = "payouts")] paypal::PaypalResource::PaypalBatchPayoutWebhooks(resource) => { Box::new(paypal::PaypalPayoutSyncResponse::try_from(*resource)?) } #[cfg(feature = "payouts")] paypal::PaypalResource::PaypalItemPayoutWebhooks(resource) => Box::new( paypal::PaypalPayoutSyncResponse::try_from((*resource, details.event_type))?, ), }) } fn get_dispute_details( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<disputes::DisputePayload, errors::ConnectorError> { let webhook_payload: paypal::PaypalWebhooksBody = request .body .parse_struct("PaypalWebhooksBody") .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; match webhook_payload.resource { transformers::PaypalResource::PaypalCardWebhooks(_) | transformers::PaypalResource::PaypalRedirectsWebhooks(_) | transformers::PaypalResource::PaypalRefundWebhooks(_) => { Err(errors::ConnectorError::ResponseDeserializationFailed) .attach_printable("Expected Dispute webhooks,but found other webhooks")? } #[cfg(feature = "payouts")] transformers::PaypalResource::PaypalBatchPayoutWebhooks(_) | transformers::PaypalResource::PaypalItemPayoutWebhooks(_) => { Err(errors::ConnectorError::ResponseDeserializationFailed) .attach_printable("Expected Dispute webhooks,but found other webhooks")? } transformers::PaypalResource::PaypalDisputeWebhooks(payload) => { let amt = connector_utils::convert_back_amount_to_minor_units( self.amount_converter, payload.dispute_amount.value, payload.dispute_amount.currency_code, )?; Ok(disputes::DisputePayload { amount: connector_utils::convert_amount( self.amount_converter_webhooks, amt, payload.dispute_amount.currency_code, )?, currency: payload.dispute_amount.currency_code, dispute_stage: api_models::enums::DisputeStage::from( payload.dispute_life_cycle_stage.clone(), ), connector_status: payload.status.to_string(), connector_dispute_id: payload.dispute_id, connector_reason: payload.reason.clone(), connector_reason_code: payload.reason, challenge_required_by: None, created_at: payload.create_time, updated_at: payload.update_time, }) } } } } impl ConnectorRedirectResponse for Paypal { fn get_flow_type( &self, _query_params: &str, _json_payload: Option<serde_json::Value>, action: PaymentAction, ) -> CustomResult<CallConnectorAction, errors::ConnectorError> { match action { PaymentAction::PSync | PaymentAction::CompleteAuthorize | PaymentAction::PaymentAuthenticateCompleteAuthorize => { Ok(CallConnectorAction::Trigger) } } } } impl ConnectorErrorTypeMapping for Paypal { fn get_connector_error_type( &self, error_code: String, _error_message: String, ) -> ConnectorErrorType { match error_code.as_str() { "CANNOT_BE_NEGATIVE" => ConnectorErrorType::UserError, "CANNOT_BE_ZERO_OR_NEGATIVE" => ConnectorErrorType::UserError, "CARD_EXPIRED" => ConnectorErrorType::UserError, "DECIMAL_PRECISION" => ConnectorErrorType::UserError, "DUPLICATE_INVOICE_ID" => ConnectorErrorType::UserError, "INSTRUMENT_DECLINED" => ConnectorErrorType::BusinessError, "INTERNAL_SERVER_ERROR" => ConnectorErrorType::TechnicalError, "INVALID_ACCOUNT_STATUS" => ConnectorErrorType::BusinessError, "INVALID_CURRENCY_CODE" => ConnectorErrorType::UserError, "INVALID_PARAMETER_SYNTAX" => ConnectorErrorType::UserError, "INVALID_PARAMETER_VALUE" => ConnectorErrorType::UserError, "INVALID_RESOURCE_ID" => ConnectorErrorType::UserError, "INVALID_STRING_LENGTH" => ConnectorErrorType::UserError, "MISSING_REQUIRED_PARAMETER" => ConnectorErrorType::UserError, "PAYER_ACCOUNT_LOCKED_OR_CLOSED" => ConnectorErrorType::BusinessError, "PAYER_ACCOUNT_RESTRICTED" => ConnectorErrorType::BusinessError, "PAYER_CANNOT_PAY" => ConnectorErrorType::BusinessError, "PERMISSION_DENIED" => ConnectorErrorType::BusinessError, "INVALID_ARRAY_MAX_ITEMS" => ConnectorErrorType::UserError, "INVALID_ARRAY_MIN_ITEMS" => ConnectorErrorType::UserError, "INVALID_COUNTRY_CODE" => ConnectorErrorType::UserError, "NOT_SUPPORTED" => ConnectorErrorType::BusinessError, "PAYPAL_REQUEST_ID_REQUIRED" => ConnectorErrorType::UserError, "MALFORMED_REQUEST_JSON" => ConnectorErrorType::UserError, "PERMISSION_DENIED_FOR_DONATION_ITEMS" => ConnectorErrorType::BusinessError, "MALFORMED_REQUEST" => ConnectorErrorType::TechnicalError, "AMOUNT_MISMATCH" => ConnectorErrorType::UserError, "BILLING_ADDRESS_INVALID" => ConnectorErrorType::UserError, "CITY_REQUIRED" => ConnectorErrorType::UserError, "DONATION_ITEMS_NOT_SUPPORTED" => ConnectorErrorType::BusinessError, "DUPLICATE_REFERENCE_ID" => ConnectorErrorType::UserError, "INVALID_PAYER_ID" => ConnectorErrorType::UserError, "ITEM_TOTAL_REQUIRED" => ConnectorErrorType::UserError, "MAX_VALUE_EXCEEDED" => ConnectorErrorType::UserError, "MISSING_PICKUP_ADDRESS" => ConnectorErrorType::UserError, "MULTI_CURRENCY_ORDER" => ConnectorErrorType::BusinessError, "MULTIPLE_ITEM_CATEGORIES" => ConnectorErrorType::UserError, "MULTIPLE_SHIPPING_ADDRESS_NOT_SUPPORTED" => ConnectorErrorType::UserError, "MULTIPLE_SHIPPING_TYPE_NOT_SUPPORTED" => ConnectorErrorType::BusinessError, "PAYEE_ACCOUNT_INVALID" => ConnectorErrorType::UserError, "PAYEE_ACCOUNT_LOCKED_OR_CLOSED" => ConnectorErrorType::UserError, "REFERENCE_ID_REQUIRED" => ConnectorErrorType::UserError, "PAYMENT_SOURCE_CANNOT_BE_USED" => ConnectorErrorType::BusinessError, "PAYMENT_SOURCE_DECLINED_BY_PROCESSOR" => ConnectorErrorType::BusinessError, "PAYMENT_SOURCE_INFO_CANNOT_BE_VERIFIED" => ConnectorErrorType::BusinessError, "POSTAL_CODE_REQUIRED" => ConnectorErrorType::UserError, "SHIPPING_ADDRESS_INVALID" => ConnectorErrorType::UserError, "TAX_TOTAL_MISMATCH" => ConnectorErrorType::UserError, "TAX_TOTAL_REQUIRED" => ConnectorErrorType::UserError, "UNSUPPORTED_INTENT" => ConnectorErrorType::BusinessError, "UNSUPPORTED_PAYMENT_INSTRUCTION" => ConnectorErrorType::UserError, "SHIPPING_TYPE_NOT_SUPPORTED_FOR_CLIENT" => ConnectorErrorType::BusinessError, "UNSUPPORTED_SHIPPING_TYPE" => ConnectorErrorType::BusinessError, "PREFERRED_SHIPPING_OPTION_AMOUNT_MISMATCH" => ConnectorErrorType::UserError, "CARD_CLOSED" => ConnectorErrorType::BusinessError, "ORDER_CANNOT_BE_SAVED" => ConnectorErrorType::BusinessError, "SAVE_ORDER_NOT_SUPPORTED" => ConnectorErrorType::BusinessError, "FIELD_NOT_PATCHABLE" => ConnectorErrorType::UserError, "AMOUNT_NOT_PATCHABLE" => ConnectorErrorType::UserError, "INVALID_PATCH_OPERATION" => ConnectorErrorType::UserError, "PAYEE_ACCOUNT_NOT_SUPPORTED" => ConnectorErrorType::UserError, "PAYEE_ACCOUNT_NOT_VERIFIED" => ConnectorErrorType::UserError, "PAYEE_NOT_CONSENTED" => ConnectorErrorType::UserError, "INVALID_JSON_POINTER_FORMAT" => ConnectorErrorType::BusinessError, "INVALID_PARAMETER" => ConnectorErrorType::UserError, "NOT_PATCHABLE" => ConnectorErrorType::BusinessError, "PATCH_VALUE_REQUIRED" => ConnectorErrorType::UserError, "PATCH_PATH_REQUIRED" => ConnectorErrorType::UserError, "REFERENCE_ID_NOT_FOUND" => ConnectorErrorType::UserError, "SHIPPING_OPTION_NOT_SELECTED" => ConnectorErrorType::UserError, "SHIPPING_OPTIONS_NOT_SUPPORTED" => ConnectorErrorType::BusinessError, "MULTIPLE_SHIPPING_OPTION_SELECTED" => ConnectorErrorType::UserError, "ORDER_ALREADY_COMPLETED" => ConnectorErrorType::BusinessError, "ACTION_DOES_NOT_MATCH_INTENT" => ConnectorErrorType::BusinessError, "AGREEMENT_ALREADY_CANCELLED" => ConnectorErrorType::BusinessError, "BILLING_AGREEMENT_NOT_FOUND" => ConnectorErrorType::BusinessError, "DOMESTIC_TRANSACTION_REQUIRED" => ConnectorErrorType::BusinessError, "ORDER_NOT_APPROVED" => ConnectorErrorType::UserError, "MAX_NUMBER_OF_PAYMENT_ATTEMPTS_EXCEEDED" => ConnectorErrorType::TechnicalError, "PAYEE_BLOCKED_TRANSACTION" => ConnectorErrorType::BusinessError, "TRANSACTION_LIMIT_EXCEEDED" => ConnectorErrorType::UserError, "TRANSACTION_RECEIVING_LIMIT_EXCEEDED" => ConnectorErrorType::BusinessError, "TRANSACTION_REFUSED" => ConnectorErrorType::TechnicalError, "ORDER_ALREADY_AUTHORIZED" => ConnectorErrorType::BusinessError, "AUTH_CAPTURE_NOT_ENABLED" => ConnectorErrorType::BusinessError, "AMOUNT_CANNOT_BE_SPECIFIED" => ConnectorErrorType::BusinessError, "AUTHORIZATION_AMOUNT_EXCEEDED" => ConnectorErrorType::UserError, "AUTHORIZATION_CURRENCY_MISMATCH" => ConnectorErrorType::UserError, "MAX_AUTHORIZATION_COUNT_EXCEEDED" => ConnectorErrorType::BusinessError, "ORDER_COMPLETED_OR_VOIDED" => ConnectorErrorType::BusinessError, "ORDER_EXPIRED" => ConnectorErrorType::BusinessError, "INVALID_PICKUP_ADDRESS" => ConnectorErrorType::UserError, "CONSENT_NEEDED" => ConnectorErrorType::UserError, "COMPLIANCE_VIOLATION" => ConnectorErrorType::BusinessError, "REDIRECT_PAYER_FOR_ALTERNATE_FUNDING" => ConnectorErrorType::TechnicalError, "ORDER_ALREADY_CAPTURED" => ConnectorErrorType::UserError, "TRANSACTION_BLOCKED_BY_PAYEE" => ConnectorErrorType::BusinessError, "NOT_ENABLED_FOR_CARD_PROCESSING" => ConnectorErrorType::BusinessError, "PAYEE_NOT_ENABLED_FOR_CARD_PROCESSING" => ConnectorErrorType::BusinessError, _ => ConnectorErrorType::UnknownError, } } } static PAYPAL_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, enums::CaptureMethod::SequentialAutomatic, ]; let supported_capture_methods_bank_redirect = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::SequentialAutomatic, ]; let supported_card_network = vec![ common_enums::CardNetwork::Mastercard, common_enums::CardNetwork::Visa, common_enums::CardNetwork::Interac, common_enums::CardNetwork::AmericanExpress, common_enums::CardNetwork::JCB, common_enums::CardNetwork::DinersClub, common_enums::CardNetwork::Discover, common_enums::CardNetwork::CartesBancaires, common_enums::CardNetwork::UnionPay, ]; let mut paypal_supported_payment_methods = SupportedPaymentMethods::new(); paypal_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Credit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::Supported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); paypal_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Debit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::Supported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network, } }), ), }, ); paypal_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::Paypal, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); paypal_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Eps, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods_bank_redirect.clone(), specific_features: None, }, ); paypal_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Giropay, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods_bank_redirect.clone(), specific_features: None, }, ); paypal_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Ideal, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods_bank_redirect.clone(), specific_features: None, }, ); paypal_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Sofort, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods_bank_redirect.clone(), specific_features: None, }, ); paypal_supported_payment_methods }); static PAYPAL_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Paypal", description: "PayPal is a global online payment system that enables individuals and businesses to send and receive money electronically.", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Live, }; static PAYPAL_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 3] = [ enums::EventClass::Payments, enums::EventClass::Refunds, enums::EventClass::Disputes, ]; impl ConnectorSpecifications for Paypal { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&PAYPAL_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*PAYPAL_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&PAYPAL_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/paypal.rs#chunk2
hyperswitch_connectors
chunk
null
null
null
3,662
null
null
null
null
null
null
null
// Struct: DummyConnectorRefundResponse // File: crates/router/src/routes/dummy_connector/types.rs // Module: router // Implementations: 1 pub struct DummyConnectorRefundResponse
crates/router/src/routes/dummy_connector/types.rs
router
struct_definition
DummyConnectorRefundResponse
1
[]
41
null
null
null
null
null
null
null
// Implementation: impl ConnectorCommon for for Bamboraapac // File: crates/hyperswitch_connectors/src/connectors/bamboraapac.rs // Module: hyperswitch_connectors // Methods: 5 total (0 public) impl ConnectorCommon for for Bamboraapac
crates/hyperswitch_connectors/src/connectors/bamboraapac.rs
hyperswitch_connectors
impl_block
null
null
null
62
null
Bamboraapac
ConnectorCommon for
5
0
null
null
// Implementation: impl EventBuilder // File: crates/events/src/lib.rs // Module: events // Methods: 3 total (3 public) impl EventBuilder
crates/events/src/lib.rs
events
impl_block
null
null
null
34
null
EventBuilder
null
3
3
null
null
// Struct: FiuuWebhooksPaymentResponse // File: crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct FiuuWebhooksPaymentResponse
crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
hyperswitch_connectors
struct_definition
FiuuWebhooksPaymentResponse
0
[]
56
null
null
null
null
null
null
null
// Function: reset_password // File: crates/router/src/routes/user.rs // Module: router pub fn reset_password( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<user_api::ResetPasswordRequest>, ) -> HttpResponse
crates/router/src/routes/user.rs
router
function_signature
null
null
null
57
reset_password
null
null
null
null
null
null
// Function: add_negative_filter_clause // File: crates/analytics/src/query.rs // Module: analytics pub fn add_negative_filter_clause( &mut self, key: impl ToSql<T>, value: impl ToSql<T>, ) -> QueryResult<()>
crates/analytics/src/query.rs
analytics
function_signature
null
null
null
57
add_negative_filter_clause
null
null
null
null
null
null
// Function: attach_default_headers // File: crates/common_utils/src/request.rs // Module: common_utils pub fn attach_default_headers(mut self) -> Self
crates/common_utils/src/request.rs
common_utils
function_signature
null
null
null
33
attach_default_headers
null
null
null
null
null
null
// Implementation: impl EventsConfig // File: crates/router/src/events.rs // Module: router // Methods: 2 total (1 public) impl EventsConfig
crates/router/src/events.rs
router
impl_block
null
null
null
34
null
EventsConfig
null
2
1
null
null
#[cfg(test)] mod test { #![allow(clippy::expect_used)] use rustc_hash::FxHashMap; use strum::IntoEnumIterator; use super::*; #[test] fn test_consistent_dir_key_naming() { let mut key_names: FxHashMap<DirKeyKind, String> = FxHashMap::default(); for key in DirKeyKind::iter() { if matches!(key, DirKeyKind::Connector) { continue; } let json_str = if let DirKeyKind::MetaData = key { r#""metadata""#.to_string() } else { serde_json::to_string(&key).expect("JSON Serialization") }; let display_str = key.to_string(); assert_eq!( json_str.get(1..json_str.len() - 1).expect("Value metadata"), display_str ); key_names.insert(key, display_str); } let values = vec![ dirval!(PaymentMethod = Card), dirval!(CardBin s= "123456"), dirval!(CardType = Credit), dirval!(CardNetwork = Visa), dirval!(PayLaterType = Klarna), dirval!(WalletType = Paypal), dirval!(BankRedirectType = Sofort), dirval!(BankDebitType = Bacs), dirval!(CryptoType = CryptoCurrency), dirval!("" = "metadata"), dirval!(PaymentAmount = 100), dirval!(PaymentCurrency = USD), dirval!(CardRedirectType = Benefit), dirval!(AuthenticationType = ThreeDs), dirval!(CaptureMethod = Manual), dirval!(BillingCountry = UnitedStatesOfAmerica), dirval!(BusinessCountry = France), ]; for val in values { let json_val = serde_json::to_value(&val).expect("JSON Value Serialization"); let json_key = json_val .as_object() .expect("Serialized Object") .get("key") .expect("Object Key"); let value_str = json_key.as_str().expect("Value string"); let dir_key = val.get_key(); let key_name = key_names.get(&dir_key.kind).expect("Key name"); assert_eq!(key_name, value_str); } } #[cfg(feature = "ast_parser")] #[test] fn test_allowed_dir_keys() { use crate::types::DummyOutput; let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { payment_method = card } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let out = ast::lowering::lower_program::<DummyOutput>(program); assert!(out.is_ok()) } #[cfg(feature = "ast_parser")] #[test] fn test_not_allowed_dir_keys() { use crate::types::DummyOutput; let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { bank_debit = ach } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let out = ast::lowering::lower_program::<DummyOutput>(program); assert!(out.is_err()) } }
crates/euclid/src/frontend/dir.rs#chunk1
euclid
chunk
null
null
null
751
null
null
null
null
null
null
null
// Struct: NewUser // File: crates/router/src/types/domain/user.rs // Module: router // Implementations: 1 pub struct NewUser
crates/router/src/types/domain/user.rs
router
struct_definition
NewUser
1
[]
33
null
null
null
null
null
null
null
// File: crates/router/tests/connectors/opennode.rs // Module: router use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails}; use masking::Secret; use router::types::{self, api, domain, storage::enums}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct OpennodeTest; impl ConnectorActions for OpennodeTest {} impl utils::Connector for OpennodeTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Opennode; utils::construct_connector_data_old( Box::new(Opennode::new()), types::Connector::Opennode, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .opennode .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "opennode".to_string() } } static CONNECTOR: OpennodeTest = OpennodeTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(types::PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::IN), ..Default::default() }), phone: Some(PhoneDetails { number: Some(Secret::new("9123456789".to_string())), country_code: Some("+91".to_string()), }), email: None, }), None, None, )), ..Default::default() }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { amount: 1, currency: enums::Currency::USD, payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData { pay_currency: None, network: None, }), confirm: true, statement_descriptor_suffix: None, statement_descriptor: None, setup_future_usage: None, mandate_id: None, off_session: None, setup_mandate_details: None, // capture_method: Some(capture_method), browser_info: None, order_details: None, order_category: None, email: None, customer_name: None, payment_experience: None, payment_method_type: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None, router_return_url: Some(String::from("https://google.com/")), webhook_url: Some(String::from("https://google.com/")), complete_authorize_url: None, capture_method: None, customer_id: None, surcharge_details: None, request_incremental_authorization: false, metadata: None, authentication_data: None, customer_acceptance: None, ..utils::PaymentAuthorizeType::default().0 }) } // Creates a payment using the manual capture flow #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending); let resp = response.response.ok().unwrap(); let endpoint = match resp { types::PaymentsResponseData::TransactionResponse { redirection_data, .. } => Some(redirection_data), _ => None, }; assert!(endpoint.is_some()) } // Synchronizes a successful transaction. #[actix_web::test] async fn should_sync_authorized_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "5adebfb1-802e-432b-8b42-5db4b754b2eb".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a unresolved(underpaid) transaction. #[actix_web::test] async fn should_sync_unresolved_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "4cf63e6b-5135-49cb-997f-6e0b30fecebc".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Unresolved); } // Synchronizes a expired transaction. #[actix_web::test] async fn should_sync_expired_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "c36a097a-5091-4317-8749-80343a71c1c4".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Failure); }
crates/router/tests/connectors/opennode.rs
router
full_file
null
null
null
1,364
null
null
null
null
null
null
null
// Implementation: impl webhooks::IncomingWebhook for for Dlocal // File: crates/hyperswitch_connectors/src/connectors/dlocal.rs // Module: hyperswitch_connectors // Methods: 3 total (0 public) impl webhooks::IncomingWebhook for for Dlocal
crates/hyperswitch_connectors/src/connectors/dlocal.rs
hyperswitch_connectors
impl_block
null
null
null
61
null
Dlocal
webhooks::IncomingWebhook for
3
0
null
null
// Function: payment // File: crates/router/src/routes/dummy_connector/core.rs // Module: router pub fn payment( state: SessionState, req: types::DummyConnectorPaymentRequest, ) -> types::DummyConnectorResponse<types::DummyConnectorPaymentResponse>
crates/router/src/routes/dummy_connector/core.rs
router
function_signature
null
null
null
58
payment
null
null
null
null
null
null
// File: crates/hyperswitch_connectors/src/connectors/payeezy.rs // Module: hyperswitch_connectors // Public structs: 1 pub mod transformers; use std::sync::LazyLock; use api_models::webhooks::IncomingWebhookEvent; use base64::Engine; use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::ByteSliceExt, request::{Method, Request, RequestBuilder, RequestContent}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ router_data::{AccessToken, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, types::{ PaymentsAuthorizeType, PaymentsCaptureType, PaymentsVoidType, RefundExecuteType, Response, }, webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; use masking::{ExposeInterface, Mask}; use rand::distributions::DistString; use ring::hmac; use transformers as payeezy; use crate::{constants::headers, types::ResponseRouterData}; #[derive(Debug, Clone)] pub struct Payeezy; impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Payeezy 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 auth = payeezy::PayeezyAuthType::try_from(&req.connector_auth_type)?; let request_payload = self .get_request_body(req, connectors)? .get_inner_value() .expose(); let timestamp = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .ok() .ok_or(errors::ConnectorError::RequestEncodingFailed)? .as_millis() .to_string(); let nonce = rand::distributions::Alphanumeric.sample_string(&mut rand::thread_rng(), 19); let signature_string = auth.api_key.clone().zip(auth.merchant_token.clone()).map( |(api_key, merchant_token)| { format!("{api_key}{nonce}{timestamp}{merchant_token}{request_payload}") }, ); let key = hmac::Key::new(hmac::HMAC_SHA256, auth.api_secret.expose().as_bytes()); let tag = hmac::sign(&key, signature_string.expose().as_bytes()); let hmac_sign = hex::encode(tag); let signature_value = common_utils::consts::BASE64_ENGINE_URL_SAFE.encode(hmac_sign); Ok(vec![ ( headers::CONTENT_TYPE.to_string(), Self.get_content_type().to_string().into(), ), (headers::APIKEY.to_string(), auth.api_key.into_masked()), ( headers::TOKEN.to_string(), auth.merchant_token.into_masked(), ), ( headers::AUTHORIZATION.to_string(), signature_value.into_masked(), ), (headers::NONCE.to_string(), nonce.into_masked()), (headers::TIMESTAMP.to_string(), timestamp.into()), ]) } } impl ConnectorCommon for Payeezy { fn id(&self) -> &'static str { "payeezy" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Base } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.payeezy.base_url.as_ref() } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: payeezy::PayeezyErrorResponse = res .response .parse_struct("payeezy ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); let error_messages: Vec<String> = response .error .messages .iter() .map(|m| m.description.clone()) .collect(); Ok(ErrorResponse { status_code: res.status_code, code: response.transaction_status, message: error_messages.join(", "), reason: None, 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 Payeezy {} impl api::Payment for Payeezy {} impl api::MandateSetup for Payeezy {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Payeezy { fn build_request( &self, _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Payeezy".to_string()) .into(), ) } } impl api::PaymentToken for Payeezy {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Payeezy { // Not Implemented (R) } impl api::PaymentVoid for Payeezy {} impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Payeezy { fn get_headers( &self, req: &PaymentsCancelRouterData, 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: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req.request.connector_transaction_id.clone(); Ok(format!( "{}v1/transactions/{}", self.base_url(connectors), connector_payment_id )) } fn get_request_body( &self, req: &PaymentsCancelRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = payeezy::PayeezyCaptureOrVoidRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsVoidType::get_url(self, req, connectors)?) .headers(PaymentsVoidType::get_headers(self, req, connectors)?) .set_body(PaymentsVoidType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { let response: payeezy::PayeezyPaymentsResponse = res .response .parse_struct("Payeezy PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl api::ConnectorAccessToken for Payeezy {} impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Payeezy {} impl api::PaymentSync for Payeezy {} impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Payeezy { // default implementation of build_request method will be executed } impl api::PaymentCapture for Payeezy {} impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Payeezy { 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> { let connector_payment_id = req.request.connector_transaction_id.clone(); Ok(format!( "{}v1/transactions/{}", self.base_url(connectors), connector_payment_id )) } fn get_request_body( &self, req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let router_obj = payeezy::PayeezyRouterData::try_from(( &self.get_currency_unit(), req.request.currency, req.request.amount_to_capture, req, ))?; let connector_req = payeezy::PayeezyCaptureOrVoidRequest::try_from(&router_obj)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsCaptureType::get_url(self, req, connectors)?) .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: payeezy::PayeezyPaymentsResponse = res .response .parse_struct("Payeezy PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl api::PaymentSession for Payeezy {} impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Payeezy { //TODO: implement sessions flow } impl api::PaymentAuthorize for Payeezy {} impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Payeezy { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}v1/transactions", self.base_url(connectors))) } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let router_obj = payeezy::PayeezyRouterData::try_from(( &self.get_currency_unit(), req.request.currency, req.request.amount, req, ))?; let connector_req = payeezy::PayeezyPaymentsRequest::try_from(&router_obj)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .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: payeezy::PayeezyPaymentsResponse = res .response .parse_struct("payeezy Response") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl api::Refund for Payeezy {} impl api::RefundExecute for Payeezy {} impl api::RefundSync for Payeezy {} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Payeezy { 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> { let connector_payment_id = req.request.connector_transaction_id.clone(); Ok(format!( "{}v1/transactions/{}", self.base_url(connectors), connector_payment_id )) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let router_obj = payeezy::PayeezyRouterData::try_from(( &self.get_currency_unit(), req.request.currency, req.request.refund_amount, req, ))?; let connector_req = payeezy::PayeezyRefundRequest::try_from(&router_obj)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&RefundExecuteType::get_url(self, req, connectors)?) .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> { // Parse the response into a payeezy::RefundResponse let response: payeezy::RefundResponse = res .response .parse_struct("payeezy RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); // Create a new instance of types::RefundsRouterData based on the response, input data, and HTTP code let response_data = ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }; let router_data = RouterData::try_from(response_data) .change_context(errors::ConnectorError::ResponseHandlingFailed)?; Ok(router_data) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Payeezy { // default implementation of build_request method will be executed } #[async_trait::async_trait] impl IncomingWebhook for Payeezy { fn get_webhook_object_reference_id( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { Ok(IncomingWebhookEvent::EventNotSupported) } fn get_webhook_resource_object( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } static PAYEEZY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, enums::CaptureMethod::SequentialAutomatic, ]; let supported_card_networks = vec![ common_enums::CardNetwork::Mastercard, common_enums::CardNetwork::Visa, common_enums::CardNetwork::AmericanExpress, common_enums::CardNetwork::Discover, ]; let mut payeezy_supported_payment_methods = SupportedPaymentMethods::new(); payeezy_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Credit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods, specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::NotSupported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks, } }), ), }, ); payeezy_supported_payment_methods }); static PAYEEZY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Payeezy", description: "Payeezy is a payment gateway platform that facilitates online and mobile payment processing for businesses. It provides a range of features, including support for various payment methods, security features like PCI-DSS compliance and tokenization, and tools for managing transactions and customer interactions.", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Alpha, }; static PAYEEZY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; impl ConnectorSpecifications for Payeezy { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&PAYEEZY_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*PAYEEZY_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&PAYEEZY_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/payeezy.rs
hyperswitch_connectors
full_file
null
null
null
4,880
null
null
null
null
null
null
null
// Struct: GetnetAuthType // File: crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct GetnetAuthType
crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs
hyperswitch_connectors
struct_definition
GetnetAuthType
0
[]
49
null
null
null
null
null
null
null
// Function: find_by_merchant_id_connector_txn_id // File: crates/diesel_models/src/query/payment_attempt.rs // Module: diesel_models pub fn find_by_merchant_id_connector_txn_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, connector_txn_id: &str, ) -> StorageResult<Self>
crates/diesel_models/src/query/payment_attempt.rs
diesel_models
function_signature
null
null
null
80
find_by_merchant_id_connector_txn_id
null
null
null
null
null
null
// Implementation: impl api::subscriptions_v2::SubscriptionsCreateV2 for for Recurly // File: crates/hyperswitch_connectors/src/connectors/recurly.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::subscriptions_v2::SubscriptionsCreateV2 for for Recurly
crates/hyperswitch_connectors/src/connectors/recurly.rs
hyperswitch_connectors
impl_block
null
null
null
74
null
Recurly
api::subscriptions_v2::SubscriptionsCreateV2 for
0
0
null
null
// Implementation: impl ConnectorValidation for for Airwallex // File: crates/hyperswitch_connectors/src/connectors/airwallex.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl ConnectorValidation for for Airwallex
crates/hyperswitch_connectors/src/connectors/airwallex.rs
hyperswitch_connectors
impl_block
null
null
null
57
null
Airwallex
ConnectorValidation for
0
0
null
null
// Struct: ChargebeeWebhookContent // File: crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ChargebeeWebhookContent
crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs
hyperswitch_connectors
struct_definition
ChargebeeWebhookContent
0
[]
52
null
null
null
null
null
null
null
// Implementation: impl api::ConnectorAccessToken for for Santander // File: crates/hyperswitch_connectors/src/connectors/santander.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::ConnectorAccessToken for for Santander
crates/hyperswitch_connectors/src/connectors/santander.rs
hyperswitch_connectors
impl_block
null
null
null
58
null
Santander
api::ConnectorAccessToken for
0
0
null
null
// Struct: CheckbookPaymentsResponse // File: crates/hyperswitch_connectors/src/connectors/checkbook/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct CheckbookPaymentsResponse
crates/hyperswitch_connectors/src/connectors/checkbook/transformers.rs
hyperswitch_connectors
struct_definition
CheckbookPaymentsResponse
0
[]
49
null
null
null
null
null
null
null
// Struct: PaypalMethodData // File: crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PaypalMethodData
crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
hyperswitch_connectors
struct_definition
PaypalMethodData
0
[]
48
null
null
null
null
null
null
null
// Function: evaluate_routing_rule // File: crates/router/src/routes/routing.rs // Module: router pub fn evaluate_routing_rule( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<RoutingEvaluateRequest>, ) -> impl Responder
crates/router/src/routes/routing.rs
router
function_signature
null
null
null
60
evaluate_routing_rule
null
null
null
null
null
null
// Implementation: impl Responder // File: crates/router/src/routes/payments.rs // Module: router // Methods: 0 total (0 public) impl Responder
crates/router/src/routes/payments.rs
router
impl_block
null
null
null
36
null
Responder
null
0
0
null
null
// Struct: StripeBillingDetails // File: crates/router/src/compatibility/stripe/setup_intents/types.rs // Module: router // Implementations: 0 pub struct StripeBillingDetails
crates/router/src/compatibility/stripe/setup_intents/types.rs
router
struct_definition
StripeBillingDetails
0
[]
41
null
null
null
null
null
null
null
// Struct: MonerisCancelRequest // File: crates/hyperswitch_connectors/src/connectors/moneris/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct MonerisCancelRequest
crates/hyperswitch_connectors/src/connectors/moneris/transformers.rs
hyperswitch_connectors
struct_definition
MonerisCancelRequest
0
[]
53
null
null
null
null
null
null
null
// Function: get_recon_token // File: crates/router/src/routes/recon.rs // Module: router pub fn get_recon_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse
crates/router/src/routes/recon.rs
router
function_signature
null
null
null
44
get_recon_token
null
null
null
null
null
null
// Function: server // File: crates/router/src/routes/app.rs // Module: router pub fn server(state: AppState) -> Scope
crates/router/src/routes/app.rs
router
function_signature
null
null
null
29
server
null
null
null
null
null
null
// Struct: HandlerInner // File: crates/drainer/src/handler.rs // Module: drainer // Implementations: 0 pub struct HandlerInner
crates/drainer/src/handler.rs
drainer
struct_definition
HandlerInner
0
[]
34
null
null
null
null
null
null
null
// File: crates/diesel_models/src/query/file.rs // Module: diesel_models // Public functions: 4 use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ errors, file::{FileMetadata, FileMetadataNew, FileMetadataUpdate, FileMetadataUpdateInternal}, schema::file_metadata::dsl, PgPooledConn, StorageResult, }; impl FileMetadataNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<FileMetadata> { generics::generic_insert(conn, self).await } } impl FileMetadata { pub async fn find_by_merchant_id_file_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, file_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::file_id.eq(file_id.to_owned())), ) .await } pub async fn delete_by_merchant_id_file_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, file_id: &str, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::file_id.eq(file_id.to_owned())), ) .await } pub async fn update( self, conn: &PgPooledConn, file_metadata: FileMetadataUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::file_id.eq(self.file_id.to_owned()), FileMetadataUpdateInternal::from(file_metadata), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } }
crates/diesel_models/src/query/file.rs
diesel_models
full_file
null
null
null
495
null
null
null
null
null
null
null
// Struct: IatapayErrorResponse // File: crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct IatapayErrorResponse
crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs
hyperswitch_connectors
struct_definition
IatapayErrorResponse
0
[]
53
null
null
null
null
null
null
null
// Implementation: impl ConnectorValidation for for Stripebilling // File: crates/hyperswitch_connectors/src/connectors/stripebilling.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl ConnectorValidation for for Stripebilling
crates/hyperswitch_connectors/src/connectors/stripebilling.rs
hyperswitch_connectors
impl_block
null
null
null
54
null
Stripebilling
ConnectorValidation for
0
0
null
null
// Struct: WalletPayment // File: crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct WalletPayment
crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs
hyperswitch_connectors
struct_definition
WalletPayment
0
[]
44
null
null
null
null
null
null
null
// Struct: RedirectResponsePayload // File: crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct RedirectResponsePayload
crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs
hyperswitch_connectors
struct_definition
RedirectResponsePayload
0
[]
48
null
null
null
null
null
null
null
// Struct: SignifydWebhookBody // File: crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct SignifydWebhookBody
crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs
hyperswitch_connectors
struct_definition
SignifydWebhookBody
0
[]
55
null
null
null
null
null
null
null
// Trait: GetLockingInput // File: crates/router/src/core/api_locking.rs // Module: router pub trait GetLockingInput
crates/router/src/core/api_locking.rs
router
trait_definition
null
null
null
31
null
null
GetLockingInput
null
null
null
null
// Struct: DefaultPaymentMethod // File: crates/api_models/src/payment_methods.rs // Module: api_models // Implementations: 0 pub struct DefaultPaymentMethod
crates/api_models/src/payment_methods.rs
api_models
struct_definition
DefaultPaymentMethod
0
[]
36
null
null
null
null
null
null
null
// Implementation: impl ConnectorSpecifications for for Square // File: crates/hyperswitch_connectors/src/connectors/square.rs // Module: hyperswitch_connectors // Methods: 3 total (0 public) impl ConnectorSpecifications for for Square
crates/hyperswitch_connectors/src/connectors/square.rs
hyperswitch_connectors
impl_block
null
null
null
51
null
Square
ConnectorSpecifications for
3
0
null
null