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::ConnectorRedirectResponse for for Authorizedotnet // File: crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs // Module: hyperswitch_connectors // Methods: 1 total (0 public) impl api::ConnectorRedirectResponse for for Authorizedotnet
crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs
hyperswitch_connectors
impl_block
null
null
null
63
null
Authorizedotnet
api::ConnectorRedirectResponse for
1
0
null
null
// Struct: BluesnapDisputeWebhookBody // File: crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct BluesnapDisputeWebhookBody
crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
hyperswitch_connectors
struct_definition
BluesnapDisputeWebhookBody
0
[]
56
null
null
null
null
null
null
null
// Struct: WellsfargoPaymentsResponse // File: crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct WellsfargoPaymentsResponse
crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
hyperswitch_connectors
struct_definition
WellsfargoPaymentsResponse
0
[]
53
null
null
null
null
null
null
null
// Module Structure // File: crates/common_enums/src/enums.rs // Module: common_enums // Public exports: pub use accounts::{ MerchantAccountRequestType, MerchantAccountType, MerchantProductType, OrganizationType, }; pub use payments::ProductType; pub use ui::*; pub use super::connector_enums::RoutableConnectors; pub use super::{ DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDeleteStatus as DeleteStatus, DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbFraudCheckStatus as FraudCheckStatus, DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentType as PaymentType, DbProcessTrackerStatus as ProcessTrackerStatus, DbRefundStatus as RefundStatus, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbRoutingApproach as RoutingApproach, DbScaExemptionType as ScaExemptionType, DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, DbTokenizationFlag as TokenizationFlag, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, };
crates/common_enums/src/enums.rs
common_enums
module_structure
null
null
null
324
null
null
null
null
null
0
5
// Function: merchant_account_transfer_keys // File: crates/router/src/routes/admin.rs // Module: router pub fn merchant_account_transfer_keys( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<api_models::admin::MerchantKeyTransferRequest>, ) -> HttpResponse
crates/router/src/routes/admin.rs
router
function_signature
null
null
null
64
merchant_account_transfer_keys
null
null
null
null
null
null
// Implementation: impl api::PaymentSync for for Trustpayments // File: crates/hyperswitch_connectors/src/connectors/trustpayments.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentSync for for Trustpayments
crates/hyperswitch_connectors/src/connectors/trustpayments.rs
hyperswitch_connectors
impl_block
null
null
null
58
null
Trustpayments
api::PaymentSync for
0
0
null
null
// Function: organization_retrieve // File: crates/openapi/src/routes/organization.rs // Module: openapi pub fn organization_retrieve()
crates/openapi/src/routes/organization.rs
openapi
function_signature
null
null
null
31
organization_retrieve
null
null
null
null
null
null
// Implementation: impl api::MandateSetup for for Bankofamerica // File: crates/hyperswitch_connectors/src/connectors/bankofamerica.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::MandateSetup for for Bankofamerica
crates/hyperswitch_connectors/src/connectors/bankofamerica.rs
hyperswitch_connectors
impl_block
null
null
null
68
null
Bankofamerica
api::MandateSetup for
0
0
null
null
// Module Structure // File: crates/router/src/types/api/admin.rs // Module: router // Public exports: pub use api_models::admin; pub use api_models::{ admin::{ MaskedHeaders, MerchantAccountCreate, MerchantAccountDeleteResponse, MerchantAccountResponse, MerchantAccountUpdate, MerchantConnectorCreate, MerchantConnectorDeleteResponse, MerchantConnectorDetails, MerchantConnectorDetailsWrap, MerchantConnectorId, MerchantConnectorResponse, MerchantDetails, MerchantId, PaymentMethodsEnabled, ProfileCreate, ProfileResponse, ProfileUpdate, ToggleAllKVRequest, ToggleAllKVResponse, ToggleKVRequest, ToggleKVResponse, WebhookDetails, }, organization::{ OrganizationCreateRequest, OrganizationId, OrganizationResponse, OrganizationUpdateRequest, }, };
crates/router/src/types/api/admin.rs
router
module_structure
null
null
null
156
null
null
null
null
null
0
2
// File: crates/router/src/workflows/api_key_expiry.rs // Module: router // Public structs: 1 use common_utils::{errors::ValidationError, ext_traits::ValueExt, types::user::ThemeLineage}; use diesel_models::{ enums as storage_enums, process_tracker::business_status, ApiKeyExpiryTrackingData, }; use router_env::logger; use scheduler::{workflows::ProcessTrackerWorkflow, SchedulerSessionState}; use crate::{ consts, errors, logger::error, routes::{metrics, SessionState}, services::email::types::ApiKeyExpiryReminder, types::{api, domain::UserEmail, storage}, utils::{ user::{self as user_utils, theme as theme_utils}, OptionExt, }, }; pub struct ApiKeyExpiryWorkflow; #[async_trait::async_trait] impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow { async fn execute_workflow<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { let db = &*state.store; let tracking_data: ApiKeyExpiryTrackingData = process .tracking_data .clone() .parse_value("ApiKeyExpiryTrackingData")?; let key_manager_satte = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_satte, &tracking_data.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await?; let merchant_account = db .find_merchant_account_by_merchant_id( key_manager_satte, &tracking_data.merchant_id, &key_store, ) .await?; let email_id = merchant_account .merchant_details .clone() .parse_value::<api::MerchantDetails>("MerchantDetails")? .primary_email .ok_or(errors::ProcessTrackerError::EValidationError( ValidationError::MissingRequiredField { field_name: "email".to_string(), } .into(), ))?; let task_id = process.id.clone(); let retry_count = process.retry_count; let api_key_name = tracking_data.api_key_name.clone(); let prefix = tracking_data.prefix.clone(); let expires_in = tracking_data .expiry_reminder_days .get( usize::try_from(retry_count) .map_err(|_| errors::ProcessTrackerError::TypeConversionError)?, ) .ok_or(errors::ProcessTrackerError::EApiErrorResponse)?; let theme = theme_utils::get_most_specific_theme_using_lineage( state, ThemeLineage::Merchant { tenant_id: state.tenant.tenant_id.clone(), org_id: merchant_account.get_org_id().clone(), merchant_id: merchant_account.get_id().clone(), }, ) .await .map_err(|err| { logger::error!(?err, "Failed to get theme"); errors::ProcessTrackerError::EApiErrorResponse })?; let email_contents = ApiKeyExpiryReminder { recipient_email: UserEmail::from_pii_email(email_id).map_err(|error| { logger::error!( ?error, "Failed to convert recipient's email to UserEmail from pii::Email" ); errors::ProcessTrackerError::EApiErrorResponse })?, subject: consts::EMAIL_SUBJECT_API_KEY_EXPIRY, expires_in: *expires_in, api_key_name, prefix, theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), theme_config: theme .map(|theme| theme.email_config()) .unwrap_or(state.conf.theme.email_config.clone()), }; state .email_client .clone() .compose_and_send_email( user_utils::get_base_url(state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) .await .map_err(errors::ProcessTrackerError::EEmailError)?; // If all the mails have been sent, then retry_count would be equal to length of the expiry_reminder_days vector if retry_count == i32::try_from(tracking_data.expiry_reminder_days.len() - 1) .map_err(|_| errors::ProcessTrackerError::TypeConversionError)? { state .get_db() .as_scheduler() .finish_process_with_business_status(process, business_status::COMPLETED_BY_PT) .await? } // If tasks are remaining that has to be scheduled else { let expiry_reminder_day = tracking_data .expiry_reminder_days .get( usize::try_from(retry_count + 1) .map_err(|_| errors::ProcessTrackerError::TypeConversionError)?, ) .ok_or(errors::ProcessTrackerError::EApiErrorResponse)?; let updated_schedule_time = tracking_data.api_key_expiry.map(|api_key_expiry| { api_key_expiry.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day))) }); let updated_process_tracker_data = storage::ProcessTrackerUpdate::Update { name: None, retry_count: Some(retry_count + 1), schedule_time: updated_schedule_time, tracking_data: None, business_status: None, status: Some(storage_enums::ProcessTrackerStatus::New), updated_at: Some(common_utils::date_time::now()), }; let task_ids = vec![task_id]; db.process_tracker_update_process_status_by_ids(task_ids, updated_process_tracker_data) .await?; // Remaining tasks are re-scheduled, so will be resetting the added count metrics::TASKS_RESET_COUNT .add(1, router_env::metric_attributes!(("flow", "ApiKeyExpiry"))); } Ok(()) } async fn error_handler<'a>( &'a self, _state: &'a SessionState, process: storage::ProcessTracker, _error: errors::ProcessTrackerError, ) -> errors::CustomResult<(), errors::ProcessTrackerError> { error!(%process.id, "Failed while executing workflow"); Ok(()) } }
crates/router/src/workflows/api_key_expiry.rs
router
full_file
null
null
null
1,346
null
null
null
null
null
null
null
// Struct: AciWebhookAuthenticationDetails // File: crates/hyperswitch_connectors/src/connectors/aci/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct AciWebhookAuthenticationDetails
crates/hyperswitch_connectors/src/connectors/aci/transformers.rs
hyperswitch_connectors
struct_definition
AciWebhookAuthenticationDetails
0
[]
53
null
null
null
null
null
null
null
// Struct: Health // File: crates/router/src/bin/scheduler.rs // Module: router // Implementations: 1 pub struct Health
crates/router/src/bin/scheduler.rs
router
struct_definition
Health
1
[]
31
null
null
null
null
null
null
null
// File: crates/analytics/src/sdk_events/metrics.rs // Module: analytics // Public structs: 1 use std::collections::HashSet; use api_models::analytics::{ sdk_events::{ SdkEventDimensions, SdkEventFilters, SdkEventMetrics, SdkEventMetricsBucketIdentifier, }, Granularity, TimeRange, }; use time::PrimitiveDateTime; use crate::{ query::{Aggregate, GroupByClause, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, MetricsResult}, }; mod average_payment_time; mod load_time; mod payment_attempts; mod payment_data_filled_count; mod payment_method_selected_count; mod payment_methods_call_count; mod sdk_initiated_count; mod sdk_rendered_count; use average_payment_time::AveragePaymentTime; use load_time::LoadTime; use payment_attempts::PaymentAttempts; use payment_data_filled_count::PaymentDataFilledCount; use payment_method_selected_count::PaymentMethodSelectedCount; use payment_methods_call_count::PaymentMethodsCallCount; use sdk_initiated_count::SdkInitiatedCount; use sdk_rendered_count::SdkRenderedCount; #[derive(Debug, PartialEq, Eq, serde::Deserialize, Hash)] pub struct SdkEventMetricRow { pub total: Option<bigdecimal::BigDecimal>, pub count: Option<i64>, pub time_bucket: Option<String>, pub payment_method: Option<String>, pub platform: Option<String>, pub browser_name: Option<String>, pub source: Option<String>, pub component: Option<String>, pub payment_experience: Option<String>, } pub trait SdkEventMetricAnalytics: LoadRow<SdkEventMetricRow> {} #[async_trait::async_trait] pub trait SdkEventMetric<T> where T: AnalyticsDataSource + SdkEventMetricAnalytics, { async fn load_metrics( &self, dimensions: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>>; } #[async_trait::async_trait] impl<T> SdkEventMetric<T> for SdkEventMetrics where T: AnalyticsDataSource + SdkEventMetricAnalytics, 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: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { match self { Self::PaymentAttempts => { PaymentAttempts .load_metrics( dimensions, publishable_key, filters, granularity, time_range, pool, ) .await } Self::PaymentMethodsCallCount => { PaymentMethodsCallCount .load_metrics( dimensions, publishable_key, filters, granularity, time_range, pool, ) .await } Self::SdkRenderedCount => { SdkRenderedCount .load_metrics( dimensions, publishable_key, filters, granularity, time_range, pool, ) .await } Self::SdkInitiatedCount => { SdkInitiatedCount .load_metrics( dimensions, publishable_key, filters, granularity, time_range, pool, ) .await } Self::PaymentMethodSelectedCount => { PaymentMethodSelectedCount .load_metrics( dimensions, publishable_key, filters, granularity, time_range, pool, ) .await } Self::PaymentDataFilledCount => { PaymentDataFilledCount .load_metrics( dimensions, publishable_key, filters, granularity, time_range, pool, ) .await } Self::AveragePaymentTime => { AveragePaymentTime .load_metrics( dimensions, publishable_key, filters, granularity, time_range, pool, ) .await } Self::LoadTime => { LoadTime .load_metrics( dimensions, publishable_key, filters, granularity, time_range, pool, ) .await } } } }
crates/analytics/src/sdk_events/metrics.rs
analytics
full_file
null
null
null
1,010
null
null
null
null
null
null
null
// File: crates/router/tests/connectors/worldpay.rs // Module: router use futures::future::OptionFuture; use router::types::{self, domain, storage::enums}; use serde_json::json; use serial_test::serial; use wiremock::{ matchers::{body_json, method, path}, Mock, ResponseTemplate, }; use crate::{ connector_auth, utils::{self, ConnectorActions, LocalMock, MockConfig}, }; struct Worldpay; impl LocalMock for Worldpay {} impl ConnectorActions for Worldpay {} impl utils::Connector for Worldpay { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Worldpay; utils::construct_connector_data_old( Box::new(Worldpay::new()), types::Connector::Worldpay, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .worldpay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "worldpay".to_string() } } #[actix_web::test] #[serial] async fn should_authorize_card_payment() { let conn = Worldpay {}; let _mock = conn.start_server(get_mock_config()).await; let response = conn.authorize_payment(None, None).await.unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); assert_eq!( utils::get_connector_transaction_id(response.response), Some("123456".to_string()) ); } #[actix_web::test] #[serial] async fn should_authorize_gpay_payment() { let conn = Worldpay {}; let _mock = conn.start_server(get_mock_config()).await; let response = conn .authorize_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Wallet( domain::WalletData::GooglePay(domain::GooglePayWalletData { pm_type: "CARD".to_string(), description: "Visa1234567890".to_string(), info: domain::GooglePayPaymentMethodInfo { card_network: "VISA".to_string(), card_details: "1234".to_string(), assurance_details: None, }, tokenization_data: common_types::payments::GpayTokenizationData::Encrypted( common_types::payments::GpayEcryptedTokenizationData { token_type: "worldpay".to_string(), token: "someToken".to_string(), }, ), }), ), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); assert_eq!( utils::get_connector_transaction_id(response.response), Some("123456".to_string()) ); } #[actix_web::test] #[serial] async fn should_authorize_applepay_payment() { let conn = Worldpay {}; let _mock = conn.start_server(get_mock_config()).await; let response = conn .authorize_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Wallet( domain::WalletData::ApplePay(domain::ApplePayWalletData { payment_data: common_types::payments::ApplePayPaymentData::Encrypted( "someData".to_string(), ), transaction_identifier: "someId".to_string(), payment_method: domain::ApplepayPaymentMethod { display_name: "someName".to_string(), network: "visa".to_string(), pm_type: "card".to_string(), }, }), ), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); assert_eq!( utils::get_connector_transaction_id(response.response), Some("123456".to_string()) ); } #[actix_web::test] #[serial] async fn should_capture_already_authorized_payment() { let connector = Worldpay {}; let _mock = connector.start_server(get_mock_config()).await; let authorize_response = connector.authorize_payment(None, None).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response: OptionFuture<_> = txn_id .map(|transaction_id| async move { connector .capture_payment(transaction_id, None, None) .await .unwrap() .status }) .into(); assert_eq!(response.await, Some(enums::AttemptStatus::Charged)); } #[actix_web::test] #[serial] async fn should_sync_payment() { let connector = Worldpay {}; let _mock = connector.start_server(get_mock_config()).await; let response = connector .sync_payment( Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "112233".to_string(), ), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } #[actix_web::test] #[serial] async fn should_void_already_authorized_payment() { let connector = Worldpay {}; let _mock = connector.start_server(get_mock_config()).await; let authorize_response = connector.authorize_payment(None, None).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response: OptionFuture<_> = txn_id .map(|transaction_id| async move { connector .void_payment(transaction_id, None, None) .await .unwrap() .status }) .into(); assert_eq!(response.await, Some(enums::AttemptStatus::Voided)); } #[actix_web::test] #[serial] async fn should_fail_capture_for_invalid_payment() { let connector = Worldpay {}; let _mock = connector.start_server(get_mock_config()).await; let authorize_response = connector.authorize_payment(None, None).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); let response = connector .capture_payment("12345".to_string(), None, None) .await .unwrap(); let err = response.response.unwrap_err(); assert_eq!( err.message, "You must provide valid transaction id to capture payment".to_string() ); assert_eq!(err.code, "invalid-id".to_string()); } #[actix_web::test] #[serial] async fn should_refund_succeeded_payment() { let connector = Worldpay {}; let _mock = connector.start_server(get_mock_config()).await; //make a successful payment let response = connector.make_payment(None, None).await.unwrap(); //try refund for previous payment let transaction_id = utils::get_connector_transaction_id(response.response).unwrap(); let response = connector .refund_payment(transaction_id, None, None) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } #[actix_web::test] #[serial] async fn should_sync_refund() { let connector = Worldpay {}; let _mock = connector.start_server(get_mock_config()).await; let response = connector .sync_refund("654321".to_string(), None, None) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } fn get_mock_config() -> MockConfig { let authorized = json!({ "outcome": "authorized", "_links": { "payments:cancel": { "href": "/payments/authorizations/cancellations/123456" }, "payments:settle": { "href": "/payments/settlements/123456" }, "payments:partialSettle": { "href": "/payments/settlements/partials/123456" }, "payments:events": { "href": "/payments/events/123456" }, "curies": [ { "name": "payments", "href": "/rels/payments/{rel}", "templated": true } ] } }); let settled = json!({ "_links": { "payments:refund": { "href": "/payments/settlements/refunds/full/654321" }, "payments:partialRefund": { "href": "/payments/settlements/refunds/partials/654321" }, "payments:events": { "href": "/payments/events/654321" }, "curies": [ { "name": "payments", "href": "/rels/payments/{rel}", "templated": true } ] } }); let error_resp = json!({ "errorName": "invalid-id", "message": "You must provide valid transaction id to capture payment" }); let partial_refund = json!({ "_links": { "payments:events": { "href": "https://try.access.worldpay.com/payments/events/eyJrIjoiazNhYjYzMiJ9" }, "curies": [{ "name": "payments", "href": "https://try.access.worldpay.com/rels/payments/{rel}", "templated": true }] } }); let partial_refund_req_body = json!({ "value": { "amount": 100, "currency": "USD" }, "reference": "123456" }); let refunded = json!({ "lastEvent": "refunded", "_links": { "payments:cancel": "/payments/authorizations/cancellations/654321", "payments:settle": "/payments/settlements/full/654321", "payments:partialSettle": "/payments/settlements/partials/654321", "curies": [ { "name": "payments", "href": "/rels/payments/{rel}", "templated": true } ] } }); let sync_payment = json!({ "lastEvent": "authorized", "_links": { "payments:events": "/payments/authorizations/events/654321", "payments:settle": "/payments/settlements/full/654321", "payments:partialSettle": "/payments/settlements/partials/654321", "curies": [ { "name": "payments", "href": "/rels/payments/{rel}", "templated": true } ] } }); MockConfig { address: Some("127.0.0.1:9090".to_string()), mocks: vec![ Mock::given(method("POST")) .and(path("/payments/authorizations".to_string())) .respond_with(ResponseTemplate::new(201).set_body_json(authorized)), Mock::given(method("POST")) .and(path("/payments/settlements/123456".to_string())) .respond_with(ResponseTemplate::new(202).set_body_json(settled)), Mock::given(method("GET")) .and(path("/payments/events/112233".to_string())) .respond_with(ResponseTemplate::new(200).set_body_json(sync_payment)), Mock::given(method("POST")) .and(path("/payments/settlements/12345".to_string())) .respond_with(ResponseTemplate::new(400).set_body_json(error_resp)), Mock::given(method("POST")) .and(path( "/payments/settlements/refunds/partials/123456".to_string(), )) .and(body_json(partial_refund_req_body)) .respond_with(ResponseTemplate::new(202).set_body_json(partial_refund)), Mock::given(method("GET")) .and(path("/payments/events/654321".to_string())) .respond_with(ResponseTemplate::new(200).set_body_json(refunded)), ], } }
crates/router/tests/connectors/worldpay.rs
router
full_file
null
null
null
2,803
null
null
null
null
null
null
null
// Implementation: impl api::RefundSync for for Bambora // File: crates/hyperswitch_connectors/src/connectors/bambora.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::RefundSync for for Bambora
crates/hyperswitch_connectors/src/connectors/bambora.rs
hyperswitch_connectors
impl_block
null
null
null
62
null
Bambora
api::RefundSync for
0
0
null
null
// Struct: BamboraapacAuthType // File: crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct BamboraapacAuthType
crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs
hyperswitch_connectors
struct_definition
BamboraapacAuthType
0
[]
58
null
null
null
null
null
null
null
// Struct: MerchantAccountUpdateInternal // File: crates/diesel_models/src/merchant_account.rs // Module: diesel_models // Implementations: 2 pub struct MerchantAccountUpdateInternal
crates/diesel_models/src/merchant_account.rs
diesel_models
struct_definition
MerchantAccountUpdateInternal
2
[]
40
null
null
null
null
null
null
null
// Struct: CustomerAcceptance // File: crates/common_types/src/payments.rs // Module: common_types // Implementations: 2 // Traits: masking::SerializableSecret pub struct CustomerAcceptance
crates/common_types/src/payments.rs
common_types
struct_definition
CustomerAcceptance
2
[ "masking::SerializableSecret" ]
44
null
null
null
null
null
null
null
// Implementation: impl api::PaymentToken for for Worldpayvantiv // File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentToken for for Worldpayvantiv
crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
hyperswitch_connectors
impl_block
null
null
null
63
null
Worldpayvantiv
api::PaymentToken for
0
0
null
null
// Struct: RouterHealthCheckResponse // File: crates/api_models/src/health_check.rs // Module: api_models // Implementations: 1 // Traits: common_utils::events::ApiEventMetric pub struct RouterHealthCheckResponse
crates/api_models/src/health_check.rs
api_models
struct_definition
RouterHealthCheckResponse
1
[ "common_utils::events::ApiEventMetric" ]
51
null
null
null
null
null
null
null
// Implementation: impl ProphetpayCardContext // File: crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs // Module: hyperswitch_connectors // Methods: 1 total (0 public) impl ProphetpayCardContext
crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs
hyperswitch_connectors
impl_block
null
null
null
53
null
ProphetpayCardContext
null
1
0
null
null
// Function: get_payout_method_data_from_temporary_locker // File: crates/router/src/core/payment_methods/vault.rs // Module: router pub fn get_payout_method_data_from_temporary_locker( state: &routes::SessionState, lookup_key: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> RouterResult<(Option<api::PayoutMethodData>, SupplementaryVaultData)>
crates/router/src/core/payment_methods/vault.rs
router
function_signature
null
null
null
92
get_payout_method_data_from_temporary_locker
null
null
null
null
null
null
// Implementation: impl Flexiti // File: crates/hyperswitch_connectors/src/connectors/flexiti.rs // Module: hyperswitch_connectors // Methods: 1 total (1 public) impl Flexiti
crates/hyperswitch_connectors/src/connectors/flexiti.rs
hyperswitch_connectors
impl_block
null
null
null
46
null
Flexiti
null
1
1
null
null
// Function: get_disputes_aggregate_profile // File: crates/router/src/routes/disputes.rs // Module: router pub fn get_disputes_aggregate_profile( state: web::Data<AppState>, req: HttpRequest, query_param: web::Query<common_utils::types::TimeRange>, ) -> HttpResponse
crates/router/src/routes/disputes.rs
router
function_signature
null
null
null
71
get_disputes_aggregate_profile
null
null
null
null
null
null
// Implementation: impl api::PaymentCapture for for Boku // File: crates/hyperswitch_connectors/src/connectors/boku.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentCapture for for Boku
crates/hyperswitch_connectors/src/connectors/boku.rs
hyperswitch_connectors
impl_block
null
null
null
57
null
Boku
api::PaymentCapture for
0
0
null
null
// Function: get_refund_body // File: crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs // Module: hyperswitch_connectors pub fn get_refund_body( req: &BamboraapacRouterData<&types::RefundExecuteRouterData>, ) -> Result<Vec<u8>, Error>
crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs
hyperswitch_connectors
function_signature
null
null
null
75
get_refund_body
null
null
null
null
null
null
// Struct: TelemetryGuard // File: crates/router_env/src/logger/setup.rs // Module: router_env // Implementations: 0 pub struct TelemetryGuard
crates/router_env/src/logger/setup.rs
router_env
struct_definition
TelemetryGuard
0
[]
36
null
null
null
null
null
null
null
// Implementation: impl ApiEventMetric for for ListBlocklistQuery // File: crates/api_models/src/blocklist.rs // Module: api_models // Methods: 0 total (0 public) impl ApiEventMetric for for ListBlocklistQuery
crates/api_models/src/blocklist.rs
api_models
impl_block
null
null
null
51
null
ListBlocklistQuery
ApiEventMetric for
0
0
null
null
// Struct: PaymentMethodMetaData // File: crates/api_models/src/three_ds_decision_rule.rs // Module: api_models // Implementations: 0 pub struct PaymentMethodMetaData
crates/api_models/src/three_ds_decision_rule.rs
api_models
struct_definition
PaymentMethodMetaData
0
[]
39
null
null
null
null
null
null
null
// File: crates/api_models/src/tokenization.rs // Module: api_models // Public structs: 4 use common_enums; use common_utils::id_type; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::{schema, ToSchema}; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct GenericTokenizationResponse { /// Unique identifier returned by the tokenization service #[schema(value_type = String, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalTokenId, /// Created time of the tokenization id #[schema(value_type = PrimitiveDateTime,example = "2024-02-24T11:04:09.922Z")] pub created_at: PrimitiveDateTime, /// Status of the tokenization id created #[schema(value_type = String,example = "enabled")] pub flag: common_enums::TokenizationFlag, } #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct GenericTokenizationRequest { /// Customer ID for which the tokenization is requested #[schema(value_type = String, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")] pub customer_id: id_type::GlobalCustomerId, /// Request for tokenization which contains the data to be tokenized #[schema(value_type = Object,example = json!({ "city": "NY", "unit": "245" }))] pub token_request: masking::Secret<serde_json::Value>, } #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct DeleteTokenDataRequest { /// Customer ID for which the tokenization is requested #[schema(value_type = String, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")] pub customer_id: id_type::GlobalCustomerId, /// Session ID associated with the tokenization request #[schema(value_type = String, example = "12345_pms_01926c58bc6e77c09e809964e72af8c8")] pub session_id: id_type::GlobalPaymentMethodSessionId, } #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct DeleteTokenDataResponse { /// Unique identifier returned by the tokenization service #[schema(value_type = String, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalTokenId, }
crates/api_models/src/tokenization.rs
api_models
full_file
null
null
null
700
null
null
null
null
null
null
null
// Function: authentication_create // File: crates/router/src/routes/authentication.rs // Module: router pub fn authentication_create( state: web::Data<app::AppState>, req: HttpRequest, json_payload: web::Json<AuthenticationCreateRequest>, ) -> impl Responder
crates/router/src/routes/authentication.rs
router
function_signature
null
null
null
59
authentication_create
null
null
null
null
null
null
// Implementation: impl common_utils::events::ApiEventMetric for for RelayRetrieveRequest // File: crates/api_models/src/relay.rs // Module: api_models // Methods: 0 total (0 public) impl common_utils::events::ApiEventMetric for for RelayRetrieveRequest
crates/api_models/src/relay.rs
api_models
impl_block
null
null
null
59
null
RelayRetrieveRequest
common_utils::events::ApiEventMetric for
0
0
null
null
// Implementation: impl ConnectorValidation for for Zen // File: crates/hyperswitch_connectors/src/connectors/zen.rs // Module: hyperswitch_connectors // Methods: 1 total (0 public) impl ConnectorValidation for for Zen
crates/hyperswitch_connectors/src/connectors/zen.rs
hyperswitch_connectors
impl_block
null
null
null
51
null
Zen
ConnectorValidation for
1
0
null
null
// Function: collect // File: crates/analytics/src/auth_events/accumulator.rs // Module: analytics pub fn collect(self) -> AuthEventMetricsBucketValue
crates/analytics/src/auth_events/accumulator.rs
analytics
function_signature
null
null
null
34
collect
null
null
null
null
null
null
// Function: get_refunds_filters_profile // File: crates/router/src/routes/refunds.rs // Module: router pub fn get_refunds_filters_profile( state: web::Data<AppState>, req: HttpRequest, ) -> HttpResponse
crates/router/src/routes/refunds.rs
router
function_signature
null
null
null
50
get_refunds_filters_profile
null
null
null
null
null
null
// File: crates/hyperswitch_interfaces/src/crm.rs // Module: hyperswitch_interfaces // Public structs: 1 use common_enums::CountryAlpha2; use common_utils::{ errors::CustomResult, request::{Request, RequestContent}, }; use masking::Secret; use super::types::Proxy; use crate::errors::HttpClientError; /// Crm Payload structure #[derive(Clone, Debug, serde::Serialize, Default)] pub struct CrmPayload { /// The legal name of the business. pub legal_business_name: Option<String>, /// A label or tag associated with the business. pub business_label: Option<String>, /// The location of the business, represented as a country code (ISO Alpha-2 format). pub business_location: Option<CountryAlpha2>, /// The display name of the business. pub display_name: Option<String>, /// The email address of the point of contact (POC) for the business. pub poc_email: Option<Secret<String>>, /// The type of business (e.g., LLC, Corporation, etc.). pub business_type: Option<String>, /// A unique identifier for the business. pub business_identifier: Option<String>, /// The website URL of the business. pub business_website: Option<String>, /// The name of the point of contact (POC) for the business. pub poc_name: Option<Secret<String>>, /// The contact number of the point of contact (POC) for the business. pub poc_contact: Option<Secret<String>>, /// Additional comments or notes about the business. pub comments: Option<String>, /// Indicates whether the Crm process for the business is completed. pub is_completed: bool, /// The name of the country where the business is located. pub business_country_name: Option<String>, } /// Trait defining the interface for encryption management #[async_trait::async_trait] pub trait CrmInterface: Send + Sync { /// Make body for the request async fn make_body(&self, details: CrmPayload) -> RequestContent; /// Encrypt the given input data async fn make_request(&self, body: RequestContent, origin_base_url: String) -> Request; /// Decrypt the given input data async fn send_request( &self, proxy: &Proxy, request: Request, ) -> CustomResult<reqwest::Response, HttpClientError>; }
crates/hyperswitch_interfaces/src/crm.rs
hyperswitch_interfaces
full_file
null
null
null
525
null
null
null
null
null
null
null
// Implementation: impl api::Refund for for Opayo // File: crates/hyperswitch_connectors/src/connectors/opayo.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::Refund for for Opayo
crates/hyperswitch_connectors/src/connectors/opayo.rs
hyperswitch_connectors
impl_block
null
null
null
57
null
Opayo
api::Refund for
0
0
null
null
// Function: get_recovery_codes // File: crates/router/src/types/domain/user.rs // Module: router pub fn get_recovery_codes(&self) -> Option<Vec<Secret<String>>>
crates/router/src/types/domain/user.rs
router
function_signature
null
null
null
38
get_recovery_codes
null
null
null
null
null
null
// Struct: FiservCancelRequest // File: crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct FiservCancelRequest
crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
hyperswitch_connectors
struct_definition
FiservCancelRequest
0
[]
52
null
null
null
null
null
null
null
// Function: find_by_user_email // File: crates/diesel_models/src/query/user.rs // Module: diesel_models pub fn find_by_user_email( conn: &PgPooledConn, user_email: &pii::Email, ) -> StorageResult<Self>
crates/diesel_models/src/query/user.rs
diesel_models
function_signature
null
null
null
58
find_by_user_email
null
null
null
null
null
null
// Implementation: impl api::ConnectorMandateRevoke for for Wellsfargo // File: crates/hyperswitch_connectors/src/connectors/wellsfargo.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::ConnectorMandateRevoke for for Wellsfargo
crates/hyperswitch_connectors/src/connectors/wellsfargo.rs
hyperswitch_connectors
impl_block
null
null
null
69
null
Wellsfargo
api::ConnectorMandateRevoke for
0
0
null
null
// Struct: RiskifiedMetadata // File: crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct RiskifiedMetadata
crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs
hyperswitch_connectors
struct_definition
RiskifiedMetadata
0
[]
49
null
null
null
null
null
null
null
// Struct: PoRecipient // File: crates/hyperswitch_domain_models/src/router_flow_types/payouts.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct PoRecipient
crates/hyperswitch_domain_models/src/router_flow_types/payouts.rs
hyperswitch_domain_models
struct_definition
PoRecipient
0
[]
44
null
null
null
null
null
null
null
// Struct: Card // File: crates/hyperswitch_connectors/src/connectors/globalpay/response.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct Card
crates/hyperswitch_connectors/src/connectors/globalpay/response.rs
hyperswitch_connectors
struct_definition
Card
0
[]
41
null
null
null
null
null
null
null
// Implementation: impl StreamData // File: crates/drainer/src/types.rs // Module: drainer // Methods: 1 total (1 public) impl StreamData
crates/drainer/src/types.rs
drainer
impl_block
null
null
null
36
null
StreamData
null
1
1
null
null
// Struct: GetCard // File: crates/router/src/core/payment_methods/transformers.rs // Module: router // Implementations: 0 pub struct GetCard<'a>
crates/router/src/core/payment_methods/transformers.rs
router
struct_definition
GetCard
0
[]
39
null
null
null
null
null
null
null
// Struct: DummyConnectorPaymentConfirmRequest // File: crates/router/src/routes/dummy_connector/types.rs // Module: router // Implementations: 0 pub struct DummyConnectorPaymentConfirmRequest
crates/router/src/routes/dummy_connector/types.rs
router
struct_definition
DummyConnectorPaymentConfirmRequest
0
[]
41
null
null
null
null
null
null
null
// Function: list_initial_webhook_delivery_attempts // File: crates/router/src/routes/webhook_events.rs // Module: router pub fn list_initial_webhook_delivery_attempts( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, json_payload: web::Json<EventListConstraints>, ) -> impl Responder
crates/router/src/routes/webhook_events.rs
router
function_signature
null
null
null
82
list_initial_webhook_delivery_attempts
null
null
null
null
null
null
// Function: get_scope_name // File: crates/router/src/services/authorization/permissions.rs // Module: router pub fn get_scope_name(scope: PermissionScope) -> &'static str
crates/router/src/services/authorization/permissions.rs
router
function_signature
null
null
null
39
get_scope_name
null
null
null
null
null
null
// Struct: TrustpayApplePayResponse // File: crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct TrustpayApplePayResponse
crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
hyperswitch_connectors
struct_definition
TrustpayApplePayResponse
0
[]
52
null
null
null
null
null
null
null
// Implementation: impl api::RefundSync for for Barclaycard // File: crates/hyperswitch_connectors/src/connectors/barclaycard.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::RefundSync for for Barclaycard
crates/hyperswitch_connectors/src/connectors/barclaycard.rs
hyperswitch_connectors
impl_block
null
null
null
63
null
Barclaycard
api::RefundSync for
0
0
null
null
// Struct: ChargebackTransactionDetails // File: crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ChargebackTransactionDetails
crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
hyperswitch_connectors
struct_definition
ChargebackTransactionDetails
0
[]
51
null
null
null
null
null
null
null
// Function: payments_retrieve // File: crates/router/src/routes/payments.rs // Module: router pub fn payments_retrieve( state: web::Data<app::AppState>, req: actix_web::HttpRequest, path: web::Path<common_utils::id_type::PaymentId>, json_payload: web::Query<payment_types::PaymentRetrieveBody>, ) -> impl Responder
crates/router/src/routes/payments.rs
router
function_signature
null
null
null
85
payments_retrieve
null
null
null
null
null
null
// Implementation: impl std::fmt::Debug for for RedisStore // File: crates/storage_impl/src/redis.rs // Module: storage_impl // Methods: 1 total (0 public) impl std::fmt::Debug for for RedisStore
crates/storage_impl/src/redis.rs
storage_impl
impl_block
null
null
null
51
null
RedisStore
std::fmt::Debug for
1
0
null
null
// Function: should_call_connector_create_customer // File: crates/router/src/core/payments/customers.rs // Module: router pub fn should_call_connector_create_customer<'a>( connector: &api::ConnectorData, customer: &'a Option<domain::Customer>, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, connector_label: &str, ) -> (bool, Option<&'a str>)
crates/router/src/core/payments/customers.rs
router
function_signature
null
null
null
94
should_call_connector_create_customer
null
null
null
null
null
null
// File: crates/hyperswitch_interfaces/src/configs.rs // Module: hyperswitch_interfaces pub use hyperswitch_domain_models::connector_endpoints::Connectors;
crates/hyperswitch_interfaces/src/configs.rs
hyperswitch_interfaces
full_file
null
null
null
35
null
null
null
null
null
null
null
// Struct: RefundResponse // File: crates/hyperswitch_connectors/src/connectors/phonepe/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct RefundResponse
crates/hyperswitch_connectors/src/connectors/phonepe/transformers.rs
hyperswitch_connectors
struct_definition
RefundResponse
0
[]
48
null
null
null
null
null
null
null
// Struct: PaymentInfo // File: crates/api_models/src/open_router.rs // Module: api_models // Implementations: 0 pub struct PaymentInfo
crates/api_models/src/open_router.rs
api_models
struct_definition
PaymentInfo
0
[]
34
null
null
null
null
null
null
null
// Function: compare_password // File: crates/router/src/types/domain/user.rs // Module: router pub fn compare_password(&self, candidate: &Secret<String>) -> UserResult<()>
crates/router/src/types/domain/user.rs
router
function_signature
null
null
null
39
compare_password
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
// Implementation: impl ConfirmSubscriptionRequest // File: crates/api_models/src/subscription.rs // Module: api_models // Methods: 2 total (2 public) impl ConfirmSubscriptionRequest
crates/api_models/src/subscription.rs
api_models
impl_block
null
null
null
39
null
ConfirmSubscriptionRequest
null
2
2
null
null
// Struct: ProcessingInformation // File: crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ProcessingInformation
crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
hyperswitch_connectors
struct_definition
ProcessingInformation
0
[]
47
null
null
null
null
null
null
null
// Implementation: impl Eq for for StrongSecret // File: crates/masking/src/strong_secret.rs // Module: masking // Methods: 0 total (0 public) impl Eq for for StrongSecret
crates/masking/src/strong_secret.rs
masking
impl_block
null
null
null
43
null
StrongSecret
Eq for
0
0
null
null
deserializer: D, ) -> Result<Option<enums::Currency>, D::Error> where D: serde::Deserializer<'de>, { let string_data: Option<String> = Option::deserialize(deserializer)?; match string_data { Some(ref value) if !value.is_empty() => value .clone() .parse_enum("Currency") .map(Some) .map_err(|_| serde::de::Error::custom(format!("Invalid currency code: {value}"))), _ => Ok(None), } } #[cfg(feature = "payouts")] pub trait CustomerDetails { fn get_customer_id(&self) -> Result<id_type::CustomerId, errors::ConnectorError>; fn get_customer_name( &self, ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError>; fn get_customer_email(&self) -> Result<Email, errors::ConnectorError>; fn get_customer_phone( &self, ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError>; fn get_customer_phone_country_code(&self) -> Result<String, errors::ConnectorError>; } #[cfg(feature = "payouts")] impl CustomerDetails for hyperswitch_domain_models::router_request_types::CustomerDetails { fn get_customer_id(&self) -> Result<id_type::CustomerId, errors::ConnectorError> { self.customer_id .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "customer_id", }) } fn get_customer_name( &self, ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError> { self.name .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "customer_name", }) } fn get_customer_email(&self) -> Result<Email, errors::ConnectorError> { self.email .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "customer_email", }) } fn get_customer_phone( &self, ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError> { self.phone .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "customer_phone", }) } fn get_customer_phone_country_code(&self) -> Result<String, errors::ConnectorError> { self.phone_country_code .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "customer_phone_country_code", }) } } pub fn get_card_details( payment_method_data: PaymentMethodData, connector_name: &'static str, ) -> Result<Card, errors::ConnectorError> { match payment_method_data { PaymentMethodData::Card(details) => Ok(details), _ => Err(errors::ConnectorError::NotSupported { message: SELECTED_PAYMENT_METHOD.to_string(), connector: connector_name, })?, } } pub fn get_authorise_integrity_object<T>( amount_convertor: &dyn AmountConvertor<Output = T>, amount: T, currency: String, ) -> Result<AuthoriseIntegrityObject, error_stack::Report<errors::ConnectorError>> { let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) .change_context(errors::ConnectorError::ParsingFailed)?; let amount_in_minor_unit = convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)?; Ok(AuthoriseIntegrityObject { amount: amount_in_minor_unit, currency: currency_enum, }) } pub fn get_sync_integrity_object<T>( amount_convertor: &dyn AmountConvertor<Output = T>, amount: T, currency: String, ) -> Result<SyncIntegrityObject, error_stack::Report<errors::ConnectorError>> { let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) .change_context(errors::ConnectorError::ParsingFailed)?; let amount_in_minor_unit = convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)?; Ok(SyncIntegrityObject { amount: Some(amount_in_minor_unit), currency: Some(currency_enum), }) } pub fn get_capture_integrity_object<T>( amount_convertor: &dyn AmountConvertor<Output = T>, capture_amount: Option<T>, currency: String, ) -> Result<CaptureIntegrityObject, error_stack::Report<errors::ConnectorError>> { let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) .change_context(errors::ConnectorError::ParsingFailed)?; let capture_amount_in_minor_unit = capture_amount .map(|amount| convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)) .transpose()?; Ok(CaptureIntegrityObject { capture_amount: capture_amount_in_minor_unit, currency: currency_enum, }) } pub fn get_refund_integrity_object<T>( amount_convertor: &dyn AmountConvertor<Output = T>, refund_amount: T, currency: String, ) -> Result<RefundIntegrityObject, error_stack::Report<errors::ConnectorError>> { let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) .change_context(errors::ConnectorError::ParsingFailed)?; let refund_amount_in_minor_unit = convert_back_amount_to_minor_units(amount_convertor, refund_amount, currency_enum)?; Ok(RefundIntegrityObject { currency: currency_enum, refund_amount: refund_amount_in_minor_unit, }) } #[cfg(feature = "frm")] pub trait FraudCheckSaleRequest { fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>; } #[cfg(feature = "frm")] impl FraudCheckSaleRequest for FraudCheckSaleData { fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> { self.order_details .clone() .ok_or_else(missing_field_err("order_details")) } } #[cfg(feature = "frm")] pub trait FraudCheckRecordReturnRequest { fn get_currency(&self) -> Result<enums::Currency, Error>; } #[cfg(feature = "frm")] impl FraudCheckRecordReturnRequest for FraudCheckRecordReturnData { fn get_currency(&self) -> Result<enums::Currency, Error> { self.currency.ok_or_else(missing_field_err("currency")) } } pub trait SplitPaymentData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest>; } impl SplitPaymentData for PaymentsCaptureData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { None } } impl SplitPaymentData for PaymentsAuthorizeData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { self.split_payments.clone() } } impl SplitPaymentData for PaymentsSyncData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { self.split_payments.clone() } } impl SplitPaymentData for PaymentsCancelData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { None } } impl SplitPaymentData for SetupMandateRequestData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { None } } impl SplitPaymentData for ExternalVaultProxyPaymentsData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { None } } pub struct XmlSerializer; impl XmlSerializer { pub fn serialize_to_xml_bytes<T: Serialize>( item: &T, xml_version: &str, xml_encoding: Option<&str>, xml_standalone: Option<&str>, xml_doc_type: Option<&str>, ) -> Result<Vec<u8>, error_stack::Report<errors::ConnectorError>> { let mut xml_bytes = Vec::new(); let mut writer = Writer::new(std::io::Cursor::new(&mut xml_bytes)); writer .write_event(Event::Decl(BytesDecl::new( xml_version, xml_encoding, xml_standalone, ))) .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("Failed to write XML declaration")?; if let Some(xml_doc_type_data) = xml_doc_type { writer .write_event(Event::DocType(BytesText::from_escaped(xml_doc_type_data))) .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("Failed to write the XML declaration")?; }; let xml_body = quick_xml::se::to_string(&item) .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("Failed to serialize the XML body")?; writer .write_event(Event::Text(BytesText::from_escaped(xml_body))) .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("Failed to serialize the XML body")?; Ok(xml_bytes) } } pub fn deserialize_zero_minor_amount_as_none<'de, D>( deserializer: D, ) -> Result<Option<MinorUnit>, D::Error> where D: serde::de::Deserializer<'de>, { let amount = Option::<MinorUnit>::deserialize(deserializer)?; match amount { Some(value) if value.get_amount_as_i64() == 0 => Ok(None), _ => Ok(amount), } }
crates/hyperswitch_connectors/src/utils.rs#chunk10
hyperswitch_connectors
chunk
null
null
null
2,093
null
null
null
null
null
null
null
// Implementation: impl Responder // File: crates/router/src/routes/webhook_events.rs // Module: router // Methods: 0 total (0 public) impl Responder
crates/router/src/routes/webhook_events.rs
router
impl_block
null
null
null
37
null
Responder
null
0
0
null
null
// Struct: PaymentCaptureRequest // File: crates/hyperswitch_connectors/src/connectors/payme/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PaymentCaptureRequest
crates/hyperswitch_connectors/src/connectors/payme/transformers.rs
hyperswitch_connectors
struct_definition
PaymentCaptureRequest
0
[]
47
null
null
null
null
null
null
null
// File: crates/masking/src/serde.rs // Module: masking // Public functions: 1 //! Serde-related. pub use erased_serde::Serialize as ErasedSerialize; pub use serde::{de, Deserialize, Serialize, Serializer}; use serde_json::{value::Serializer as JsonValueSerializer, Value}; use crate::{Secret, Strategy, StrongSecret, ZeroizableSecret}; /// Marker trait for secret types which can be [`Serialize`]-d by [`serde`]. /// /// When the `serde` feature of this crate is enabled and types are marked with /// this trait, they receive a [`Serialize` impl] for `Secret<T>`. /// (NOTE: all types which impl `DeserializeOwned` receive a [`Deserialize`] /// impl) /// /// This is done deliberately to prevent accidental exfiltration of secrets /// via `serde` serialization. #[cfg_attr(docsrs, cfg(feature = "serde"))] pub trait SerializableSecret: Serialize {} // #[cfg_attr(docsrs, doc(cfg(feature = "serde")))] // pub trait NonSerializableSecret: Serialize {} impl SerializableSecret for Value {} impl SerializableSecret for u8 {} impl SerializableSecret for u16 {} impl SerializableSecret for i8 {} impl SerializableSecret for i32 {} impl SerializableSecret for i64 {} impl SerializableSecret for url::Url {} #[cfg(feature = "time")] impl SerializableSecret for time::Date {} impl<T: SerializableSecret> SerializableSecret for &T {} impl<'de, T, I> Deserialize<'de> for Secret<T, I> where T: Clone + de::DeserializeOwned + Sized, I: Strategy<T>, { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: de::Deserializer<'de>, { T::deserialize(deserializer).map(Self::new) } } impl<T, I> Serialize for Secret<T, I> where T: SerializableSecret + Serialize + Sized, I: Strategy<T>, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { pii_serializer::pii_serialize(self, serializer) } } impl<'de, T, I> Deserialize<'de> for StrongSecret<T, I> where T: Clone + de::DeserializeOwned + Sized + ZeroizableSecret, I: Strategy<T>, { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { T::deserialize(deserializer).map(Self::new) } } impl<T, I> Serialize for StrongSecret<T, I> where T: SerializableSecret + Serialize + ZeroizableSecret + Sized, I: Strategy<T>, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { pii_serializer::pii_serialize(self, serializer) } } /// Masked serialization. /// /// the default behaviour for secrets is to serialize in exposed format since the common use cases /// for storing the secret to database or sending it over the network requires the secret to be exposed /// This method allows to serialize the secret in masked format if needed for logs or other insecure exposures pub fn masked_serialize<T: Serialize>(value: &T) -> Result<Value, serde_json::Error> { value.serialize(PIISerializer { inner: JsonValueSerializer, }) } /// Masked serialization. /// /// Trait object for supporting serialization to Value while accounting for masking /// The usual Serde Serialize trait cannot be used as trait objects /// like &dyn Serialize or boxed trait objects like Box<dyn Serialize> because of Rust's "object safety" rules. /// In particular, the trait contains generic methods which cannot be made into a trait object. /// In this case we remove the generic for assuming the serialization to be of 2 types only raw json or masked json pub trait ErasedMaskSerialize: ErasedSerialize { /// Masked serialization. fn masked_serialize(&self) -> Result<Value, serde_json::Error>; } impl<T: Serialize + ErasedSerialize> ErasedMaskSerialize for T { fn masked_serialize(&self) -> Result<Value, serde_json::Error> { masked_serialize(self) } } impl Serialize for dyn ErasedMaskSerialize + '_ { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { erased_serde::serialize(self, serializer) } } impl Serialize for dyn ErasedMaskSerialize + '_ + Send { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { erased_serde::serialize(self, serializer) } } use pii_serializer::PIISerializer; mod pii_serializer { use std::fmt::Display; pub(super) fn pii_serialize< V: Serialize, T: std::fmt::Debug + PeekInterface<V>, S: Serializer, >( value: &T, serializer: S, ) -> Result<S::Ok, S::Error> { // Mask the value if the serializer is of type PIISerializer // or send empty map if the serializer is of type FlatMapSerializer over PiiSerializer if std::any::type_name::<S>() == std::any::type_name::<PIISerializer>() { format!("{value:?}").serialize(serializer) } else if std::any::type_name::<S>() == std::any::type_name::< serde::__private::ser::FlatMapSerializer<'_, SerializeMap<PIISerializer>>, >() { std::collections::HashMap::<String, String>::from([]).serialize(serializer) } else { value.peek().serialize(serializer) } } use serde::{Serialize, Serializer}; use serde_json::{value::Serializer as JsonValueSerializer, Map, Value}; use crate::PeekInterface; pub(super) struct PIISerializer { pub inner: JsonValueSerializer, } impl Clone for PIISerializer { fn clone(&self) -> Self { Self { inner: JsonValueSerializer, } } } impl Serializer for PIISerializer { type Ok = Value; type Error = serde_json::Error; type SerializeSeq = SerializeVec<Self>; type SerializeTuple = SerializeVec<Self>; type SerializeTupleStruct = SerializeVec<Self>; type SerializeTupleVariant = SerializeTupleVariant<Self>; type SerializeMap = SerializeMap<Self>; type SerializeStruct = SerializeMap<Self>; type SerializeStructVariant = SerializeStructVariant<Self>; #[inline] fn serialize_bool(self, value: bool) -> Result<Self::Ok, Self::Error> { self.inner.serialize_bool(value) } #[inline] fn serialize_i8(self, value: i8) -> Result<Self::Ok, Self::Error> { self.serialize_i64(value.into()) } #[inline] fn serialize_i16(self, value: i16) -> Result<Self::Ok, Self::Error> { self.serialize_i64(value.into()) } #[inline] fn serialize_i32(self, value: i32) -> Result<Self::Ok, Self::Error> { self.serialize_i64(value.into()) } fn serialize_i64(self, value: i64) -> Result<Self::Ok, Self::Error> { self.inner.serialize_i64(value) } fn serialize_i128(self, value: i128) -> Result<Self::Ok, Self::Error> { self.inner.serialize_i128(value) } #[inline] fn serialize_u8(self, value: u8) -> Result<Self::Ok, Self::Error> { self.serialize_u64(value.into()) } #[inline] fn serialize_u16(self, value: u16) -> Result<Self::Ok, Self::Error> { self.serialize_u64(value.into()) } #[inline] fn serialize_u32(self, value: u32) -> Result<Self::Ok, Self::Error> { self.serialize_u64(value.into()) } #[inline] fn serialize_u64(self, value: u64) -> Result<Self::Ok, Self::Error> { Ok(Value::Number(value.into())) } fn serialize_u128(self, value: u128) -> Result<Self::Ok, Self::Error> { self.inner.serialize_u128(value) } #[inline] fn serialize_f32(self, float: f32) -> Result<Self::Ok, Self::Error> { Ok(Value::from(float)) } #[inline] fn serialize_f64(self, float: f64) -> Result<Self::Ok, Self::Error> { Ok(Value::from(float)) } #[inline] fn serialize_char(self, value: char) -> Result<Self::Ok, Self::Error> { let mut s = String::new(); s.push(value); Ok(Value::String(s)) } #[inline] fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error> { Ok(Value::String(value.to_owned())) } fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error> { let vec = value.iter().map(|&b| Value::Number(b.into())).collect(); Ok(Value::Array(vec)) } #[inline] fn serialize_unit(self) -> Result<Self::Ok, Self::Error> { Ok(Value::Null) } #[inline] fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> { self.serialize_unit() } #[inline] fn serialize_unit_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, ) -> Result<Self::Ok, Self::Error> { self.serialize_str(variant) } #[inline] fn serialize_newtype_struct<T>( self, _name: &'static str, value: &T, ) -> Result<Self::Ok, Self::Error> where T: ?Sized + Serialize, { value.serialize(self) } fn serialize_newtype_variant<T>( self, _name: &'static str, _variant_index: u32, variant: &'static str, value: &T, ) -> Result<Self::Ok, Self::Error> where T: ?Sized + Serialize, { let mut values = Map::new(); values.insert(String::from(variant), value.serialize(self)?); Ok(Value::Object(values)) } #[inline] fn serialize_none(self) -> Result<Self::Ok, Self::Error> { self.serialize_unit() } #[inline] fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error> where T: ?Sized + Serialize, { value.serialize(self) } fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> { Ok(SerializeVec { vec: Vec::with_capacity(len.unwrap_or(0)), ser: self, }) } fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> { self.serialize_seq(Some(len)) } fn serialize_tuple_struct( self, _name: &'static str, len: usize, ) -> Result<Self::SerializeTupleStruct, Self::Error> { self.serialize_seq(Some(len)) } fn serialize_tuple_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize, ) -> Result<Self::SerializeTupleVariant, Self::Error> { Ok(SerializeTupleVariant { name: String::from(variant), vec: Vec::with_capacity(len), ser: self, }) } fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> { Ok(SerializeMap { inner: self.clone().inner.serialize_map(len)?, ser: self, }) } fn serialize_struct( self, _name: &'static str, len: usize, ) -> Result<Self::SerializeStruct, Self::Error> { self.serialize_map(Some(len)) } fn serialize_struct_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, _len: usize, ) -> Result<Self::SerializeStructVariant, Self::Error> { Ok(SerializeStructVariant { name: String::from(variant), map: Map::new(), ser: self, }) } fn collect_str<T>(self, value: &T) -> Result<Self::Ok, Self::Error> where T: ?Sized + Display, { self.inner.collect_str(value) } } pub(super) struct SerializeVec<T: Serializer> { vec: Vec<Value>, ser: T, } impl<T: Serializer<Ok = Value> + Clone> serde::ser::SerializeSeq for SerializeVec<T> { type Ok = Value; type Error = T::Error; fn serialize_element<V>(&mut self, value: &V) -> Result<(), Self::Error> where V: ?Sized + Serialize, { self.vec.push(value.serialize(self.ser.clone())?); Ok(()) } fn end(self) -> Result<Self::Ok, Self::Error> { Ok(Value::Array(self.vec)) } } impl<T: Serializer<Ok = Value> + Clone> serde::ser::SerializeTuple for SerializeVec<T> { type Ok = Value; type Error = T::Error; fn serialize_element<V>(&mut self, value: &V) -> Result<(), Self::Error> where V: ?Sized + Serialize, { serde::ser::SerializeSeq::serialize_element(self, value) } fn end(self) -> Result<Self::Ok, Self::Error> { serde::ser::SerializeSeq::end(self) } } impl<T: Serializer<Ok = Value> + Clone> serde::ser::SerializeTupleStruct for SerializeVec<T> { type Ok = Value; type Error = T::Error; fn serialize_field<V>(&mut self, value: &V) -> Result<(), Self::Error> where V: ?Sized + Serialize, { serde::ser::SerializeSeq::serialize_element(self, value) } fn end(self) -> Result<Self::Ok, Self::Error> { serde::ser::SerializeSeq::end(self) } } pub(super) struct SerializeStructVariant<T: Serializer> { name: String, map: Map<String, Value>, ser: T, } impl<T: Serializer<Ok = Value> + Clone> serde::ser::SerializeStructVariant for SerializeStructVariant<T> { type Ok = Value; type Error = T::Error; fn serialize_field<V>(&mut self, key: &'static str, value: &V) -> Result<(), Self::Error> where V: ?Sized + Serialize, { self.map .insert(String::from(key), value.serialize(self.ser.clone())?); Ok(()) } fn end(self) -> Result<Self::Ok, Self::Error> { let mut object = Map::new(); object.insert(self.name, Value::Object(self.map)); Ok(Value::Object(object)) } } pub(super) struct SerializeTupleVariant<T: Serializer> { name: String, vec: Vec<Value>, ser: T, } impl<T: Serializer<Ok = Value> + Clone> serde::ser::SerializeTupleVariant for SerializeTupleVariant<T> { type Ok = Value; type Error = T::Error; fn serialize_field<V>(&mut self, value: &V) -> Result<(), Self::Error> where V: ?Sized + Serialize, { self.vec.push(value.serialize(self.ser.clone())?); Ok(()) } fn end(self) -> Result<Value, Self::Error> { let mut object = Map::new(); object.insert(self.name, Value::Array(self.vec)); Ok(Value::Object(object)) } } pub(super) struct SerializeMap<T: Serializer> { inner: <serde_json::value::Serializer as Serializer>::SerializeMap, ser: T, } impl<T: Serializer<Ok = Value, Error = serde_json::Error> + Clone> serde::ser::SerializeMap for SerializeMap<T> { type Ok = Value; type Error = T::Error; fn serialize_key<V>(&mut self, key: &V) -> Result<(), Self::Error> where V: ?Sized + Serialize, { self.inner.serialize_key(key)?; Ok(()) } fn serialize_value<V>(&mut self, value: &V) -> Result<(), Self::Error> where V: ?Sized + Serialize, { let value = value.serialize(self.ser.clone())?; self.inner.serialize_value(&value)?; Ok(()) } fn end(self) -> Result<Value, Self::Error> { self.inner.end() } } impl<T: Serializer<Ok = Value, Error = serde_json::Error> + Clone> serde::ser::SerializeStruct for SerializeMap<T> { type Ok = Value; type Error = T::Error; fn serialize_field<V>(&mut self, key: &'static str, value: &V) -> Result<(), Self::Error> where V: ?Sized + Serialize, { serde::ser::SerializeMap::serialize_entry(self, key, value) } fn end(self) -> Result<Value, Self::Error> { serde::ser::SerializeMap::end(self) } } }
crates/masking/src/serde.rs
masking
full_file
null
null
null
3,970
null
null
null
null
null
null
null
// File: crates/common_types/src/three_ds_decision_rule_engine.rs // Module: common_types // Public functions: 2 // Public structs: 1 use common_utils::impl_to_sql_from_sql_json; use diesel::{sql_types::Jsonb, AsExpression, FromSqlRow}; use euclid::frontend::dir::{DirKeyKind, EuclidDirFilter}; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; /// Enum representing the possible outcomes of the 3DS Decision Rule Engine. #[derive( Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, Default, )] #[diesel(sql_type = Jsonb)] #[serde(rename_all = "snake_case")] pub enum ThreeDSDecision { /// No 3DS authentication required #[default] NoThreeDs, /// Mandate 3DS Challenge ChallengeRequested, /// Prefer 3DS Challenge ChallengePreferred, /// Request 3DS Exemption, Type: Transaction Risk Analysis (TRA) ThreeDsExemptionRequestedTra, /// Request 3DS Exemption, Type: Low Value Transaction ThreeDsExemptionRequestedLowValue, /// No challenge requested by merchant (e.g., delegated authentication) IssuerThreeDsExemptionRequested, } impl_to_sql_from_sql_json!(ThreeDSDecision); impl ThreeDSDecision { /// Checks if the decision is to mandate a 3DS challenge pub fn should_force_3ds_challenge(self) -> bool { matches!(self, Self::ChallengeRequested) } } /// Struct representing the output configuration for the 3DS Decision Rule Engine. #[derive( Serialize, Default, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct ThreeDSDecisionRule { /// The decided 3DS action based on the rules pub decision: ThreeDSDecision, } impl ThreeDSDecisionRule { /// Returns the decision pub fn get_decision(&self) -> ThreeDSDecision { self.decision } } impl_to_sql_from_sql_json!(ThreeDSDecisionRule); impl EuclidDirFilter for ThreeDSDecisionRule { const ALLOWED: &'static [DirKeyKind] = &[ DirKeyKind::CardNetwork, DirKeyKind::PaymentAmount, DirKeyKind::PaymentCurrency, DirKeyKind::IssuerName, DirKeyKind::IssuerCountry, DirKeyKind::CustomerDevicePlatform, DirKeyKind::CustomerDeviceType, DirKeyKind::CustomerDeviceDisplaySize, DirKeyKind::AcquirerCountry, DirKeyKind::AcquirerFraudRate, ]; }
crates/common_types/src/three_ds_decision_rule_engine.rs
common_types
full_file
null
null
null
592
null
null
null
null
null
null
null
// Function: get_role_info_from_db // File: crates/router/src/utils/user.rs // Module: router pub fn get_role_info_from_db(&self, state: &SessionState) -> UserResult<RoleInfo>
crates/router/src/utils/user.rs
router
function_signature
null
null
null
46
get_role_info_from_db
null
null
null
null
null
null
// Struct: GetPaymentMetricRequest // File: crates/api_models/src/analytics.rs // Module: api_models // Implementations: 0 pub struct GetPaymentMetricRequest
crates/api_models/src/analytics.rs
api_models
struct_definition
GetPaymentMetricRequest
0
[]
38
null
null
null
null
null
null
null
// Implementation: impl WebhookDetails // File: crates/api_models/src/admin.rs // Module: api_models // Methods: 2 total (1 public) impl WebhookDetails
crates/api_models/src/admin.rs
api_models
impl_block
null
null
null
38
null
WebhookDetails
null
2
1
null
null
// Struct: DashboardRequestPayload // File: crates/connector_configs/src/common_config.rs // Module: connector_configs // Implementations: 0 pub struct DashboardRequestPayload
crates/connector_configs/src/common_config.rs
connector_configs
struct_definition
DashboardRequestPayload
0
[]
37
null
null
null
null
null
null
null
// Implementation: impl AcceptDispute for for Worldpayvantiv // File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl AcceptDispute for for Worldpayvantiv
crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
hyperswitch_connectors
impl_block
null
null
null
61
null
Worldpayvantiv
AcceptDispute for
0
0
null
null
// Implementation: impl Responder // File: crates/router/src/analytics.rs // Module: router // Methods: 0 total (0 public) impl Responder
crates/router/src/analytics.rs
router
impl_block
null
null
null
35
null
Responder
null
0
0
null
null
// Struct: AnalysisError // File: crates/euclid/src/dssa/types.rs // Module: euclid // Implementations: 1 // Traits: fmt::Display pub struct AnalysisError
crates/euclid/src/dssa/types.rs
euclid
struct_definition
AnalysisError
1
[ "fmt::Display" ]
43
null
null
null
null
null
null
null
// Function: into_stripe_next_action // File: crates/router/src/compatibility/stripe/payment_intents/types.rs // Module: router pub fn into_stripe_next_action( next_action: Option<payments::NextActionData>, return_url: Option<String>, ) -> Option<StripeNextAction>
crates/router/src/compatibility/stripe/payment_intents/types.rs
router
function_signature
null
null
null
67
into_stripe_next_action
null
null
null
null
null
null
// File: crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs // Module: router // Public structs: 1 use api_models::payments::ExternalVaultProxyPaymentsRequest; use async_trait::async_trait; use common_enums::enums; use common_utils::{ crypto::Encryptable, ext_traits::{AsyncExt, ValueExt}, types::keymanager::ToEncryptable, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, payments::PaymentConfirmData, }; use hyperswitch_interfaces::api::ConnectorSpecifications; use masking::PeekInterface; use router_env::{instrument, tracing}; use super::{Domain, GetTracker, Operation, PostUpdateTracker, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, payment_methods::{self, PaymentMethodExt}, payments::{ self, operations::{self, ValidateStatusForOperation}, OperationSessionGetters, OperationSessionSetters, }, }, routes::{app::ReqState, SessionState}, types::{ self, api::{self, ConnectorCallType}, domain::{self, types as domain_types}, storage::{self, enums as storage_enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy)] pub struct ExternalVaultProxyPaymentIntent; impl ValidateStatusForOperation for ExternalVaultProxyPaymentIntent { /// Validate if the current operation can be performed on the current status of the payment intent fn validate_status_for_operation( &self, intent_status: common_enums::IntentStatus, ) -> Result<(), errors::ApiErrorResponse> { match intent_status { common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Processing => Ok(()), common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::Expired => { Err(errors::ApiErrorResponse::PaymentUnexpectedState { current_flow: format!("{self:?}"), field_name: "status".to_string(), current_value: intent_status.to_string(), states: ["requires_payment_method", "failed", "processing"].join(", "), }) } } } } type BoxedConfirmOperation<'b, F> = super::BoxedOperation<'b, F, ExternalVaultProxyPaymentsRequest, PaymentConfirmData<F>>; impl<F: Send + Clone + Sync> Operation<F, ExternalVaultProxyPaymentsRequest> for &ExternalVaultProxyPaymentIntent { type Data = PaymentConfirmData<F>; fn to_validate_request( &self, ) -> RouterResult< &(dyn ValidateRequest<F, ExternalVaultProxyPaymentsRequest, Self::Data> + Send + Sync), > { Ok(*self) } fn to_get_tracker( &self, ) -> RouterResult< &(dyn GetTracker<F, Self::Data, ExternalVaultProxyPaymentsRequest> + Send + Sync), > { Ok(*self) } fn to_domain( &self, ) -> RouterResult<&(dyn Domain<F, ExternalVaultProxyPaymentsRequest, Self::Data>)> { Ok(*self) } fn to_update_tracker( &self, ) -> RouterResult< &(dyn UpdateTracker<F, Self::Data, ExternalVaultProxyPaymentsRequest> + Send + Sync), > { Ok(*self) } } #[automatically_derived] impl<F: Send + Clone + Sync> Operation<F, ExternalVaultProxyPaymentsRequest> for ExternalVaultProxyPaymentIntent { type Data = PaymentConfirmData<F>; fn to_validate_request( &self, ) -> RouterResult< &(dyn ValidateRequest<F, ExternalVaultProxyPaymentsRequest, Self::Data> + Send + Sync), > { Ok(self) } fn to_get_tracker( &self, ) -> RouterResult< &(dyn GetTracker<F, Self::Data, ExternalVaultProxyPaymentsRequest> + Send + Sync), > { Ok(self) } fn to_domain( &self, ) -> RouterResult<&dyn Domain<F, ExternalVaultProxyPaymentsRequest, Self::Data>> { Ok(self) } fn to_update_tracker( &self, ) -> RouterResult< &(dyn UpdateTracker<F, Self::Data, ExternalVaultProxyPaymentsRequest> + Send + Sync), > { Ok(self) } } impl<F: Send + Clone + Sync> ValidateRequest<F, ExternalVaultProxyPaymentsRequest, PaymentConfirmData<F>> for ExternalVaultProxyPaymentIntent { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, _request: &ExternalVaultProxyPaymentsRequest, merchant_context: &'a domain::MerchantContext, ) -> RouterResult<operations::ValidateResult> { let validate_result = operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: false, }; Ok(validate_result) } } #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, ExternalVaultProxyPaymentsRequest> for ExternalVaultProxyPaymentIntent { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &common_utils::id_type::GlobalPaymentId, request: &ExternalVaultProxyPaymentsRequest, merchant_context: &domain::MerchantContext, _profile: &domain::Profile, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<operations::GetTrackerResponse<PaymentConfirmData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_intent = db .find_payment_intent_by_id( key_manager_state, payment_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; self.validate_status_for_operation(payment_intent.status)?; let cell_id = state.conf.cell_information.id.clone(); let batch_encrypted_data = domain_types::crypto_operation( key_manager_state, common_utils::type_name!(hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt), domain_types::CryptoOperation::BatchEncrypt( hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::to_encryptable( hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt { payment_method_billing_address: None, }, ), ), common_utils::types::keymanager::Identifier::Merchant(merchant_context.get_merchant_account().get_id().to_owned()), merchant_context.get_merchant_key_store().key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting payment intent details".to_string())?; let encrypted_data = hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::from_encryptable(batch_encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting payment intent details")?; let payment_attempt = match payment_intent.active_attempt_id.clone() { Some(ref active_attempt_id) => db .find_payment_attempt_by_id( key_manager_state, merchant_context.get_merchant_key_store(), active_attempt_id, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Could not find payment attempt")?, None => { // TODO: Implement external vault specific payment attempt creation logic let payment_attempt_domain_model: hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt = hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt::external_vault_proxy_create_domain_model( &payment_intent, cell_id, storage_scheme, request, encrypted_data ) .await?; db.insert_payment_attempt( key_manager_state, merchant_context.get_merchant_key_store(), payment_attempt_domain_model, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not insert payment attempt")? } }; // TODO: Extract external vault specific token/credentials from request let processor_payment_token = None; // request.external_vault_details.processor_payment_token.clone(); let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new( payment_intent .shipping_address .clone() .map(|address| address.into_inner()), payment_intent .billing_address .clone() .map(|address| address.into_inner()), payment_attempt .payment_method_billing_address .clone() .map(|address| address.into_inner()), Some(true), ); // TODO: Implement external vault specific mandate data handling let mandate_data_input = api_models::payments::MandateIds { mandate_id: None, mandate_reference_id: processor_payment_token.map(|token| { api_models::payments::MandateReferenceId::ConnectorMandateId( api_models::payments::ConnectorMandateReferenceId::new( Some(token), None, None, None, None, ), ) }), }; let payment_method_data = request.payment_method_data.payment_method_data.clone().map( hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::from, ); let payment_data = PaymentConfirmData { flow: std::marker::PhantomData, payment_intent, payment_attempt, payment_method_data: None, // TODO: Review for external vault payment_address, mandate_data: Some(mandate_data_input), payment_method: None, merchant_connector_details: None, external_vault_pmd: payment_method_data, }; let get_trackers_response = operations::GetTrackerResponse { payment_data }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, ExternalVaultProxyPaymentsRequest, PaymentConfirmData<F>> for ExternalVaultProxyPaymentIntent { async fn get_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentConfirmData<F>, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<(BoxedConfirmOperation<'a, F>, Option<domain::Customer>), errors::StorageError> { match payment_data.payment_intent.customer_id.clone() { Some(id) => { let customer = state .store .find_customer_by_global_id( &state.into(), &id, merchant_key_store, storage_scheme, ) .await?; Ok((Box::new(self), Some(customer))) } None => Ok((Box::new(self), None)), } } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut PaymentConfirmData<F>, _storage_scheme: storage_enums::MerchantStorageScheme, _key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( BoxedConfirmOperation<'a, F>, Option<PaymentMethodData>, Option<String>, )> { // TODO: Implement external vault specific payment method data creation Ok((Box::new(self), None, None)) } async fn create_or_fetch_payment_method<'a>( &'a self, state: &SessionState, merchant_context: &domain::MerchantContext, business_profile: &domain::Profile, payment_data: &mut PaymentConfirmData<F>, ) -> CustomResult<(), errors::ApiErrorResponse> { match ( payment_data.payment_intent.customer_id.clone(), payment_data.external_vault_pmd.clone(), payment_data.payment_attempt.customer_acceptance.clone(), payment_data.payment_attempt.payment_token.clone(), ) { (Some(customer_id), Some(hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::Card(card_details)), Some(_), None) => { let payment_method_data = api::PaymentMethodCreateData::ProxyCard(api::ProxyCardDetails::from(*card_details)); let billing = payment_data .payment_address .get_payment_method_billing() .cloned() .map(From::from); let req = api::PaymentMethodCreate { payment_method_type: payment_data.payment_attempt.payment_method_type, payment_method_subtype: payment_data.payment_attempt.payment_method_subtype, metadata: None, customer_id, payment_method_data, billing, psp_tokenization: None, network_tokenization: None, }; let (_pm_response, payment_method) = Box::pin(payment_methods::create_payment_method_core( state, &state.get_req_state(), req, merchant_context, business_profile, )) .await?; payment_data.payment_method = Some(payment_method); } (_, Some(hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::VaultToken(vault_token)), None, Some(payment_token)) => { payment_data.external_vault_pmd = Some(payment_methods::get_external_vault_token( state, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, payment_token.clone(), vault_token.clone(), &payment_data.payment_attempt.payment_method_type ) .await?); } _ => { router_env::logger::debug!( "No payment method to create or fetch for external vault proxy payment intent" ); } } Ok(()) } #[cfg(feature = "v2")] async fn update_payment_method<'a>( &'a self, state: &SessionState, merchant_context: &domain::MerchantContext, payment_data: &mut PaymentConfirmData<F>, ) { if let (true, Some(payment_method)) = ( payment_data.payment_attempt.customer_acceptance.is_some(), payment_data.payment_method.as_ref(), ) { payment_methods::update_payment_method_status_internal( state, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, common_enums::PaymentMethodStatus::Active, payment_method.get_id(), ) .await .map_err(|err| router_env::logger::error!(err=?err)); }; } #[instrument(skip_all)] async fn populate_payment_data<'a>( &'a self, _state: &SessionState, payment_data: &mut PaymentConfirmData<F>, _merchant_context: &domain::MerchantContext, _business_profile: &domain::Profile, connector_data: &api::ConnectorData, ) -> CustomResult<(), errors::ApiErrorResponse> { let connector_request_reference_id = connector_data .connector .generate_connector_request_reference_id( &payment_data.payment_intent, &payment_data.payment_attempt, ); payment_data.set_connector_request_reference_id(Some(connector_request_reference_id)); Ok(()) } async fn perform_routing<'a>( &'a self, merchant_context: &domain::MerchantContext, business_profile: &domain::Profile, state: &SessionState, payment_data: &mut PaymentConfirmData<F>, ) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse> { payments::connector_selection( state, merchant_context, business_profile, payment_data, None, ) .await } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentConfirmData<F>, ExternalVaultProxyPaymentsRequest> for ExternalVaultProxyPaymentIntent { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, _req_state: ReqState, mut payment_data: PaymentConfirmData<F>, _customer: Option<domain::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<api_models::enums::FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(BoxedConfirmOperation<'b, F>, PaymentConfirmData<F>)> where F: 'b + Send, { let db = &*state.store; let key_manager_state = &state.into(); let intent_status = common_enums::IntentStatus::Processing; let attempt_status = common_enums::AttemptStatus::Pending; let connector = payment_data .payment_attempt .connector .clone() .get_required_value("connector") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Connector is none when constructing response")?; let merchant_connector_id = Some( payment_data .payment_attempt .merchant_connector_id .clone() .get_required_value("merchant_connector_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Merchant connector id is none when constructing response")?, ); let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::ConfirmIntent { status: intent_status, updated_by: storage_scheme.to_string(), active_attempt_id: Some(payment_data.payment_attempt.id.clone()), }; let authentication_type = payment_data .payment_intent .authentication_type .unwrap_or_default(); let connector_request_reference_id = payment_data .payment_attempt .connector_request_reference_id .clone(); let connector_response_reference_id = payment_data .payment_attempt .connector_response_reference_id .clone(); let payment_attempt_update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ConfirmIntent { status: attempt_status, updated_by: storage_scheme.to_string(), connector, merchant_connector_id, authentication_type, connector_request_reference_id, connector_response_reference_id, }; let updated_payment_intent = db .update_payment_intent( key_manager_state, payment_data.payment_intent.clone(), payment_intent_update, key_store, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment intent")?; payment_data.payment_intent = updated_payment_intent; let updated_payment_attempt = db .update_payment_attempt( key_manager_state, key_store, payment_data.payment_attempt.clone(), payment_attempt_update, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment attempt")?; payment_data.payment_attempt = updated_payment_attempt; Ok((Box::new(self), payment_data)) } } #[cfg(feature = "v2")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::PaymentsAuthorizeData> for ExternalVaultProxyPaymentIntent { 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")?; payment_data.payment_intent = updated_payment_intent; payment_data.payment_attempt = updated_payment_attempt; // TODO: Add external vault specific post-update logic Ok(payment_data) } }
crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs
router
full_file
null
null
null
4,790
null
null
null
null
null
null
null
// Function: parse_evidence_type // File: crates/router/src/routes/disputes/utils.rs // Module: router pub fn parse_evidence_type( field: &mut Field, ) -> CustomResult<Option<disputes::EvidenceType>, errors::ApiErrorResponse>
crates/router/src/routes/disputes/utils.rs
router
function_signature
null
null
null
58
parse_evidence_type
null
null
null
null
null
null
// Struct: StripeBillingDetails // File: crates/router/src/compatibility/stripe/payment_intents/types.rs // Module: router // Implementations: 0 pub struct StripeBillingDetails
crates/router/src/compatibility/stripe/payment_intents/types.rs
router
struct_definition
StripeBillingDetails
0
[]
41
null
null
null
null
null
null
null
// Struct: CaptureResponseData // File: crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct CaptureResponseData
crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
hyperswitch_connectors
struct_definition
CaptureResponseData
0
[]
48
null
null
null
null
null
null
null
// Function: retry_webhook_delivery_attempt // File: crates/router/src/routes/webhook_events.rs // Module: router pub fn retry_webhook_delivery_attempt( state: web::Data<AppState>, req: HttpRequest, path: web::Path<(common_utils::id_type::MerchantId, String)
crates/router/src/routes/webhook_events.rs
router
function_signature
null
null
null
66
retry_webhook_delivery_attempt
null
null
null
null
null
null
// Function: authenticate_authentication_client_secret_and_check_expiry // File: crates/router/src/core/unified_authentication_service/utils.rs // Module: router pub fn authenticate_authentication_client_secret_and_check_expiry( req_client_secret: &String, authentication: &diesel_models::authentication::Authentication, ) -> RouterResult<()>
crates/router/src/core/unified_authentication_service/utils.rs
router
function_signature
null
null
null
65
authenticate_authentication_client_secret_and_check_expiry
null
null
null
null
null
null
// Implementation: impl api::PaymentVoid for for Celero // File: crates/hyperswitch_connectors/src/connectors/celero.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentVoid for for Celero
crates/hyperswitch_connectors/src/connectors/celero.rs
hyperswitch_connectors
impl_block
null
null
null
58
null
Celero
api::PaymentVoid for
0
0
null
null
// Struct: AuthMethodDetails // File: crates/api_models/src/user.rs // Module: api_models // Implementations: 0 pub struct AuthMethodDetails
crates/api_models/src/user.rs
api_models
struct_definition
AuthMethodDetails
0
[]
35
null
null
null
null
null
null
null
// Struct: PartnerFlowCredentials // File: crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PartnerFlowCredentials
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
hyperswitch_connectors
struct_definition
PartnerFlowCredentials
0
[]
47
null
null
null
null
null
null
null
// Implementation: impl Worldpayxml // File: crates/hyperswitch_connectors/src/connectors/worldpayxml.rs // Module: hyperswitch_connectors // Methods: 1 total (1 public) impl Worldpayxml
crates/hyperswitch_connectors/src/connectors/worldpayxml.rs
hyperswitch_connectors
impl_block
null
null
null
48
null
Worldpayxml
null
1
1
null
null
// Function: new // File: crates/hyperswitch_connectors/src/connectors/thunes.rs // Module: hyperswitch_connectors pub fn new() -> &'static Self
crates/hyperswitch_connectors/src/connectors/thunes.rs
hyperswitch_connectors
function_signature
null
null
null
38
new
null
null
null
null
null
null
// Function: profile_retrieve // File: crates/openapi/src/routes/profile.rs // Module: openapi pub fn profile_retrieve()
crates/openapi/src/routes/profile.rs
openapi
function_signature
null
null
null
30
profile_retrieve
null
null
null
null
null
null
// Implementation: impl AuthorizationInterface for for KafkaStore // File: crates/router/src/db/kafka_store.rs // Module: router // Methods: 3 total (0 public) impl AuthorizationInterface for for KafkaStore
crates/router/src/db/kafka_store.rs
router
impl_block
null
null
null
45
null
KafkaStore
AuthorizationInterface for
3
0
null
null
// Struct: ApplepayPaymentMethod // File: crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ApplepayPaymentMethod
crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
hyperswitch_connectors
struct_definition
ApplepayPaymentMethod
0
[]
50
null
null
null
null
null
null
null
// Implementation: impl PaymentToken for for Riskified // File: crates/hyperswitch_connectors/src/connectors/riskified.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl PaymentToken for for Riskified
crates/hyperswitch_connectors/src/connectors/riskified.rs
hyperswitch_connectors
impl_block
null
null
null
54
null
Riskified
PaymentToken for
0
0
null
null
// File: crates/router/src/core/webhooks/utils.rs // Module: router // Public functions: 5 use std::marker::PhantomData; use base64::Engine; use common_utils::{ consts, crypto::{self, GenerateDigest}, errors::CustomResult, ext_traits::ValueExt, }; use error_stack::{Report, ResultExt}; use redis_interface as redis; use router_env::tracing; use super::MERCHANT_ID; use crate::{ core::{ errors::{self}, metrics, payments::helpers, }, db::{get_and_deserialize_key, StorageInterface}, errors::RouterResult, routes::app::SessionStateInfo, services::logger, types::{self, api, domain, PaymentAddress}, SessionState, }; const IRRELEVANT_ATTEMPT_ID_IN_SOURCE_VERIFICATION_FLOW: &str = "irrelevant_attempt_id_in_source_verification_flow"; const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_SOURCE_VERIFICATION_FLOW: &str = "irrelevant_connector_request_reference_id_in_source_verification_flow"; /// Check whether the merchant has configured to disable the webhook `event` for the `connector` /// First check for the key "whconf_{merchant_id}_{connector_id}" in redis, /// if not found, fetch from configs table in database pub async fn is_webhook_event_disabled( db: &dyn StorageInterface, connector_id: &str, merchant_id: &common_utils::id_type::MerchantId, event: &api::IncomingWebhookEvent, ) -> bool { let redis_key = merchant_id.get_webhook_config_disabled_events_key(connector_id); let merchant_webhook_disable_config_result: CustomResult< api::MerchantWebhookConfig, redis_interface::errors::RedisError, > = get_and_deserialize_key(db, &redis_key, "MerchantWebhookConfig").await; match merchant_webhook_disable_config_result { Ok(merchant_webhook_config) => merchant_webhook_config.contains(event), Err(..) => { //if failed to fetch from redis. fetch from db and populate redis db.find_config_by_key(&redis_key) .await .map(|config| { match serde_json::from_str::<api::MerchantWebhookConfig>(&config.config) { Ok(set) => set.contains(event), Err(err) => { logger::warn!(?err, "error while parsing merchant webhook config"); false } } }) .unwrap_or_else(|err| { logger::warn!(?err, "error while fetching merchant webhook config"); false }) } } } pub async fn construct_webhook_router_data( state: &SessionState, connector_name: &str, merchant_connector_account: domain::MerchantConnectorAccount, merchant_context: &domain::MerchantContext, connector_wh_secrets: &api_models::webhooks::ConnectorWebhookSecrets, request_details: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<types::VerifyWebhookSourceRouterData, errors::ApiErrorResponse> { let auth_type: types::ConnectorAuthType = helpers::MerchantConnectorAccountType::DbVal(Box::new(merchant_connector_account.clone())) .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError)?; let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_context.get_merchant_account().get_id().clone(), connector: connector_name.to_string(), customer_id: None, tenant_id: state.tenant.tenant_id.clone(), payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("source_verification_flow") .get_string_repr() .to_owned(), attempt_id: IRRELEVANT_ATTEMPT_ID_IN_SOURCE_VERIFICATION_FLOW.to_string(), status: diesel_models::enums::AttemptStatus::default(), payment_method: diesel_models::enums::PaymentMethod::default(), connector_auth_type: auth_type, description: None, address: PaymentAddress::default(), auth_type: diesel_models::enums::AuthenticationType::default(), connector_meta_data: None, connector_wallets_details: None, amount_captured: None, minor_amount_captured: None, request: types::VerifyWebhookSourceRequestData { webhook_headers: request_details.headers.clone(), webhook_body: request_details.body.to_vec().clone(), merchant_secret: connector_wh_secrets.to_owned(), }, response: Err(types::ErrorResponse::default()), access_token: None, session_token: None, reference_id: None, payment_method_token: None, connector_customer: None, recurring_mandate_payment_data: None, preprocessing_id: None, connector_request_reference_id: IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_SOURCE_VERIFICATION_FLOW.to_string(), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode: None, payment_method_balance: None, payment_method_status: None, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, }; Ok(router_data) } #[inline] pub(crate) fn get_idempotent_event_id( primary_object_id: &str, event_type: types::storage::enums::EventType, delivery_attempt: types::storage::enums::WebhookDeliveryAttempt, ) -> Result<String, Report<errors::WebhooksFlowError>> { use crate::types::storage::enums::WebhookDeliveryAttempt; const EVENT_ID_SUFFIX_LENGTH: usize = 8; let common_prefix = format!("{primary_object_id}_{event_type}"); // Hash the common prefix with SHA256 and encode with URL-safe base64 without padding let digest = crypto::Sha256 .generate_digest(common_prefix.as_bytes()) .change_context(errors::WebhooksFlowError::IdGenerationFailed) .attach_printable("Failed to generate idempotent event ID")?; let base_encoded = consts::BASE64_ENGINE_URL_SAFE_NO_PAD.encode(digest); let result = match delivery_attempt { WebhookDeliveryAttempt::InitialAttempt => base_encoded, WebhookDeliveryAttempt::AutomaticRetry | WebhookDeliveryAttempt::ManualRetry => { common_utils::generate_id(EVENT_ID_SUFFIX_LENGTH, &base_encoded) } }; Ok(result) } #[inline] pub(crate) fn generate_event_id() -> String { common_utils::generate_time_ordered_id("evt") } pub fn increment_webhook_outgoing_received_count(merchant_id: &common_utils::id_type::MerchantId) { metrics::WEBHOOK_OUTGOING_RECEIVED_COUNT.add( 1, router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())), ) } pub fn increment_webhook_outgoing_not_received_count( merchant_id: &common_utils::id_type::MerchantId, ) { metrics::WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT.add( 1, router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())), ); } pub fn is_outgoing_webhook_disabled( state: &SessionState, webhook_url_result: &Result<String, Report<errors::WebhooksFlowError>>, business_profile: &domain::Profile, idempotent_event_id: &str, ) -> bool { if !state.conf.webhooks.outgoing_enabled || webhook_url_result.is_err() || webhook_url_result.as_ref().is_ok_and(String::is_empty) { logger::debug!( business_profile_id=?business_profile.get_id(), %idempotent_event_id, "Outgoing webhooks are disabled in application configuration, or merchant webhook URL \ could not be obtained; skipping outgoing webhooks for event" ); return true; } false } const WEBHOOK_LOCK_PREFIX: &str = "WEBHOOK_LOCK"; pub(super) async fn perform_redis_lock<A>( state: &A, unique_locking_key: &str, merchant_id: common_utils::id_type::MerchantId, ) -> RouterResult<Option<String>> where A: SessionStateInfo, { let lock_value: String = uuid::Uuid::new_v4().to_string(); let redis_conn = state .store() .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error connecting to redis")?; let redis_locking_key = format!( "{}_{}_{}", WEBHOOK_LOCK_PREFIX, merchant_id.get_string_repr(), unique_locking_key ); let redis_lock_expiry_seconds = state.conf().webhooks.redis_lock_expiry_seconds; let redis_lock_result = redis_conn .set_key_if_not_exists_with_expiry( &redis_locking_key.as_str().into(), lock_value.clone(), Some(i64::from(redis_lock_expiry_seconds)), ) .await; match redis_lock_result { Ok(redis::SetnxReply::KeySet) => { logger::info!("Lock acquired for for {redis_locking_key}"); Ok(Some(lock_value)) } Ok(redis::SetnxReply::KeyNotSet) => { logger::info!("Lock already held for {redis_locking_key}"); Ok(None) } Err(err) => Err(err .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error acquiring redis lock")), } } pub(super) async fn free_redis_lock<A>( state: &A, unique_locking_key: &str, merchant_id: common_utils::id_type::MerchantId, lock_value: Option<String>, ) -> RouterResult<()> where A: SessionStateInfo, { let redis_conn = state .store() .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error connecting to redis")?; let redis_locking_key = format!( "{}_{}_{}", WEBHOOK_LOCK_PREFIX, merchant_id.get_string_repr(), unique_locking_key ); match redis_conn .get_key::<Option<String>>(&redis_locking_key.as_str().into()) .await { Ok(val) => { if val == lock_value { match redis_conn .delete_key(&redis_locking_key.as_str().into()) .await { Ok(redis::types::DelReply::KeyDeleted) => { logger::info!("Lock freed {redis_locking_key}"); tracing::Span::current().record("redis_lock_released", redis_locking_key); Ok(()) } Ok(redis::types::DelReply::KeyNotDeleted) => Err( errors::ApiErrorResponse::InternalServerError, ) .attach_printable("Status release lock called but key is not found in redis"), Err(error) => Err(error) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while deleting redis key"), } } else { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("The redis value which acquired the lock is not equal to the redis value requesting for releasing the lock") } } Err(error) => Err(error) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while deleting redis key"), } }
crates/router/src/core/webhooks/utils.rs
router
full_file
null
null
null
2,564
null
null
null
null
null
null
null
// File: crates/router/src/utils.rs // Module: router // Public functions: 24 pub mod chat; #[cfg(feature = "olap")] pub mod connector_onboarding; pub mod currency; pub mod db_utils; pub mod ext_traits; #[cfg(feature = "kv_store")] pub mod storage_partitioning; #[cfg(feature = "olap")] pub mod user; #[cfg(feature = "olap")] pub mod user_role; #[cfg(feature = "olap")] pub mod verify_connector; use std::fmt::Debug; use api_models::{ enums, payments::{self}, webhooks, }; use common_utils::types::keymanager::KeyManagerState; pub use common_utils::{ crypto::{self, Encryptable}, ext_traits::{ByteSliceExt, BytesExt, Encode, StringExt, ValueExt}, fp_utils::when, id_type, pii, validation::validate_email, }; #[cfg(feature = "v1")] use common_utils::{ type_name, types::keymanager::{Identifier, ToEncryptable}, }; use error_stack::ResultExt; pub use hyperswitch_connectors::utils::QrImage; use hyperswitch_domain_models::payments::PaymentIntent; #[cfg(feature = "v1")] use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation}; use masking::{ExposeInterface, SwitchStrategy}; use nanoid::nanoid; use serde::de::DeserializeOwned; use serde_json::Value; use tracing_futures::Instrument; pub use self::ext_traits::{OptionExt, ValidateCall}; use crate::{ consts, core::{ authentication::types::ExternalThreeDSConnectorMetadata, errors::{self, CustomResult, RouterResult, StorageErrorExt}, payments as payments_core, }, headers::ACCEPT_LANGUAGE, logger, routes::{metrics, SessionState}, services::{self, authentication::get_header_value_by_key}, types::{self, domain, transformers::ForeignInto}, }; #[cfg(feature = "v1")] use crate::{core::webhooks as webhooks_core, types::storage}; pub mod error_parser { use std::fmt::Display; use actix_web::{ error::{Error, JsonPayloadError}, http::StatusCode, HttpRequest, ResponseError, }; #[derive(Debug)] struct CustomJsonError { err: JsonPayloadError, } // Display is a requirement defined by the actix crate for implementing ResponseError trait impl Display for CustomJsonError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str( serde_json::to_string(&serde_json::json!({ "error": { "error_type": "invalid_request", "message": self.err.to_string(), "code": "IR_06", } })) .as_deref() .unwrap_or("Invalid Json Error"), ) } } impl ResponseError for CustomJsonError { fn status_code(&self) -> StatusCode { StatusCode::BAD_REQUEST } fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> { use actix_web::http::header; actix_web::HttpResponseBuilder::new(self.status_code()) .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)) .body(self.to_string()) } } pub fn custom_json_error_handler(err: JsonPayloadError, _req: &HttpRequest) -> Error { Error::from(CustomJsonError { err }) } } #[inline] pub fn generate_id(length: usize, prefix: &str) -> String { format!("{}_{}", prefix, nanoid!(length, &consts::ALPHABETS)) } pub trait ConnectorResponseExt: Sized { fn get_response(self) -> RouterResult<types::Response>; fn get_error_response(self) -> RouterResult<types::Response>; fn get_response_inner<T: DeserializeOwned>(self, type_name: &'static str) -> RouterResult<T> { self.get_response()? .response .parse_struct(type_name) .change_context(errors::ApiErrorResponse::InternalServerError) } } impl<E> ConnectorResponseExt for Result<Result<types::Response, types::Response>, error_stack::Report<E>> { fn get_error_response(self) -> RouterResult<types::Response> { self.map_err(|error| error.change_context(errors::ApiErrorResponse::InternalServerError)) .attach_printable("Error while receiving response") .and_then(|inner| match inner { Ok(res) => { logger::error!(response=?res); Err(errors::ApiErrorResponse::InternalServerError).attach_printable(format!( "Expecting error response, received response: {res:?}" )) } Err(err_res) => Ok(err_res), }) } fn get_response(self) -> RouterResult<types::Response> { self.map_err(|error| error.change_context(errors::ApiErrorResponse::InternalServerError)) .attach_printable("Error while receiving response") .and_then(|inner| match inner { Err(err_res) => { logger::error!(error_response=?err_res); Err(errors::ApiErrorResponse::InternalServerError).attach_printable(format!( "Expecting response, received error response: {err_res:?}" )) } Ok(res) => Ok(res), }) } } #[inline] pub fn get_payout_attempt_id(payout_id: &str, attempt_count: i16) -> String { format!("{payout_id}_{attempt_count}") } #[cfg(feature = "v1")] pub async fn find_payment_intent_from_payment_id_type( state: &SessionState, payment_id_type: payments::PaymentIdType, merchant_context: &domain::MerchantContext, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { let key_manager_state: KeyManagerState = state.into(); let db = &*state.store; match payment_id_type { payments::PaymentIdType::PaymentIntentId(payment_id) => db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound), payments::PaymentIdType::ConnectorTransactionId(connector_transaction_id) => { let attempt = db .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_context.get_merchant_account().get_id(), &connector_transaction_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &attempt.payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } payments::PaymentIdType::PaymentAttemptId(attempt_id) => { let attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &attempt_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &attempt.payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } payments::PaymentIdType::PreprocessingId(_) => { Err(errors::ApiErrorResponse::PaymentNotFound)? } } } #[cfg(feature = "v1")] pub async fn find_payment_intent_from_refund_id_type( state: &SessionState, refund_id_type: webhooks::RefundIdType, merchant_context: &domain::MerchantContext, connector_name: &str, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { let db = &*state.store; let refund = match refund_id_type { webhooks::RefundIdType::RefundId(id) => db .find_refund_by_merchant_id_refund_id( merchant_context.get_merchant_account().get_id(), &id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?, webhooks::RefundIdType::ConnectorRefundId(id) => db .find_refund_by_merchant_id_connector_refund_id_connector( merchant_context.get_merchant_account().get_id(), &id, connector_name, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?, }; let attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &refund.attempt_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( &state.into(), &attempt.payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } #[cfg(feature = "v1")] pub async fn find_payment_intent_from_mandate_id_type( state: &SessionState, mandate_id_type: webhooks::MandateIdType, merchant_context: &domain::MerchantContext, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { let db = &*state.store; let mandate = match mandate_id_type { webhooks::MandateIdType::MandateId(mandate_id) => db .find_mandate_by_merchant_id_mandate_id( merchant_context.get_merchant_account().get_id(), mandate_id.as_str(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?, webhooks::MandateIdType::ConnectorMandateId(connector_mandate_id) => db .find_mandate_by_merchant_id_connector_mandate_id( merchant_context.get_merchant_account().get_id(), connector_mandate_id.as_str(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?, }; db.find_payment_intent_by_payment_id_merchant_id( &state.into(), &mandate .original_payment_id .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("original_payment_id not present in mandate record")?, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } #[cfg(feature = "v1")] pub async fn find_mca_from_authentication_id_type( state: &SessionState, authentication_id_type: webhooks::AuthenticationIdType, merchant_context: &domain::MerchantContext, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; let authentication = match authentication_id_type { webhooks::AuthenticationIdType::AuthenticationId(authentication_id) => db .find_authentication_by_merchant_id_authentication_id( merchant_context.get_merchant_account().get_id(), &authentication_id, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?, webhooks::AuthenticationIdType::ConnectorAuthenticationId(connector_authentication_id) => { db.find_authentication_by_merchant_id_connector_authentication_id( merchant_context.get_merchant_account().get_id().clone(), connector_authentication_id, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)? } }; #[cfg(feature = "v1")] { // raise error if merchant_connector_id is not present since it should we be present in the current flow let mca_id = authentication .merchant_connector_id .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("merchant_connector_id not present in authentication record")?; db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( &state.into(), merchant_context.get_merchant_account().get_id(), &mca_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: mca_id.get_string_repr().to_string(), }, ) } #[cfg(feature = "v2")] //get mca using id { let _ = key_store; let _ = authentication; todo!() } } #[cfg(feature = "v1")] pub async fn get_mca_from_payment_intent( state: &SessionState, merchant_context: &domain::MerchantContext, payment_intent: PaymentIntent, connector_name: &str, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; let key_manager_state: &KeyManagerState = &state.into(); #[cfg(feature = "v1")] let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &payment_intent.active_attempt.get_id(), merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; #[cfg(feature = "v2")] let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( key_manager_state, key_store, &payment_intent.active_attempt.get_id(), merchant_account.get_id(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; match payment_attempt.merchant_connector_id { Some(merchant_connector_id) => { #[cfg(feature = "v1")] { db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_context.get_merchant_account().get_id(), &merchant_connector_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, ) } #[cfg(feature = "v2")] { //get mca using id let _id = merchant_connector_id; let _ = key_store; let _ = key_manager_state; let _ = connector_name; todo!() } } None => { let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")? .clone(); #[cfg(feature = "v1")] { db.find_merchant_connector_account_by_profile_id_connector_name( key_manager_state, &profile_id, connector_name, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: format!( "profile_id {} and connector_name {connector_name}", profile_id.get_string_repr() ), }, ) } #[cfg(feature = "v2")] { //get mca using id let _ = profile_id; todo!() } } } } #[cfg(feature = "payouts")] pub async fn get_mca_from_payout_attempt( state: &SessionState, merchant_context: &domain::MerchantContext, payout_id_type: webhooks::PayoutIdType, connector_name: &str, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; let payout = match payout_id_type { webhooks::PayoutIdType::PayoutAttemptId(payout_attempt_id) => db .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_context.get_merchant_account().get_id(), &payout_attempt_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?, webhooks::PayoutIdType::ConnectorPayoutId(connector_payout_id) => db .find_payout_attempt_by_merchant_id_connector_payout_id( merchant_context.get_merchant_account().get_id(), &connector_payout_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?, }; let key_manager_state: &KeyManagerState = &state.into(); match payout.merchant_connector_id { Some(merchant_connector_id) => { #[cfg(feature = "v1")] { db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_context.get_merchant_account().get_id(), &merchant_connector_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, ) } #[cfg(feature = "v2")] { //get mca using id let _id = merchant_connector_id; let _ = merchant_context.get_merchant_key_store(); let _ = connector_name; let _ = key_manager_state; todo!() } } None => { #[cfg(feature = "v1")] { db.find_merchant_connector_account_by_profile_id_connector_name( key_manager_state, &payout.profile_id, connector_name, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: format!( "profile_id {} and connector_name {}", payout.profile_id.get_string_repr(), connector_name ), }, ) } #[cfg(feature = "v2")] { todo!() } } } } #[cfg(feature = "v1")] pub async fn get_mca_from_object_reference_id( state: &SessionState, object_reference_id: webhooks::ObjectReferenceId, merchant_context: &domain::MerchantContext, connector_name: &str, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; #[cfg(feature = "v1")] let default_profile_id = merchant_context .get_merchant_account() .default_profile .as_ref(); #[cfg(feature = "v2")] let default_profile_id = Option::<&String>::None; match default_profile_id { Some(profile_id) => { #[cfg(feature = "v1")] { db.find_merchant_connector_account_by_profile_id_connector_name( &state.into(), profile_id, connector_name, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: format!( "profile_id {} and connector_name {connector_name}", profile_id.get_string_repr() ), }, ) } #[cfg(feature = "v2")] { let _db = db; let _profile_id = profile_id; todo!() } } _ => match object_reference_id { webhooks::ObjectReferenceId::PaymentId(payment_id_type) => { get_mca_from_payment_intent( state, merchant_context, find_payment_intent_from_payment_id_type( state, payment_id_type, merchant_context, ) .await?, connector_name, ) .await } webhooks::ObjectReferenceId::RefundId(refund_id_type) => { get_mca_from_payment_intent( state, merchant_context, find_payment_intent_from_refund_id_type( state, refund_id_type, merchant_context, connector_name, ) .await?, connector_name, ) .await } webhooks::ObjectReferenceId::MandateId(mandate_id_type) => { get_mca_from_payment_intent( state, merchant_context, find_payment_intent_from_mandate_id_type( state, mandate_id_type, merchant_context, ) .await?, connector_name, ) .await } webhooks::ObjectReferenceId::ExternalAuthenticationID(authentication_id_type) => { find_mca_from_authentication_id_type( state, authentication_id_type, merchant_context, ) .await } #[cfg(feature = "payouts")] webhooks::ObjectReferenceId::PayoutId(payout_id_type) => { get_mca_from_payout_attempt(state, merchant_context, payout_id_type, connector_name) .await } }, } } // validate json format for the error pub fn handle_json_response_deserialization_failure( res: types::Response, connector: &'static str, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { metrics::RESPONSE_DESERIALIZATION_FAILURE .add(1, router_env::metric_attributes!(("connector", connector))); let response_data = String::from_utf8(res.response.to_vec()) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; // check for whether the response is in json format match serde_json::from_str::<Value>(&response_data) { // in case of unexpected response but in json format Ok(_) => Err(errors::ConnectorError::ResponseDeserializationFailed)?, // in case of unexpected response but in html or string format Err(error_msg) => { logger::error!(deserialization_error=?error_msg); logger::error!("UNEXPECTED RESPONSE FROM CONNECTOR: {}", response_data); Ok(types::ErrorResponse { status_code: res.status_code, code: consts::NO_ERROR_CODE.to_string(), message: consts::UNSUPPORTED_ERROR_MESSAGE.to_string(), reason: Some(response_data), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } } pub fn get_http_status_code_type( status_code: u16, ) -> CustomResult<String, errors::ApiErrorResponse> { let status_code_type = match status_code { 100..=199 => "1xx", 200..=299 => "2xx", 300..=399 => "3xx", 400..=499 => "4xx", 500..=599 => "5xx", _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid http status code")?, }; Ok(status_code_type.to_string()) } pub fn add_connector_http_status_code_metrics(option_status_code: Option<u16>) { if let Some(status_code) = option_status_code { let status_code_type = get_http_status_code_type(status_code).ok(); match status_code_type.as_deref() { Some("1xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_1XX_COUNT.add(1, &[]), Some("2xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_2XX_COUNT.add(1, &[]), Some("3xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_3XX_COUNT.add(1, &[]), Some("4xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_4XX_COUNT.add(1, &[]), Some("5xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_5XX_COUNT.add(1, &[]), _ => logger::info!("Skip metrics as invalid http status code received from connector"), }; } else { logger::info!("Skip metrics as no http status code received from connector") } } #[cfg(feature = "v1")] #[async_trait::async_trait] pub trait CustomerAddress { async fn get_address_update( &self, state: &SessionState, address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, merchant_id: id_type::MerchantId, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError>; async fn get_domain_address( &self, state: &SessionState, address_details: payments::AddressDetails, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError>; } #[cfg(feature = "v1")] #[async_trait::async_trait] impl CustomerAddress for api_models::customers::CustomerRequest { async fn get_address_update( &self, state: &SessionState, address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, merchant_id: id_type::MerchantId, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError> { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address_details.line1.clone(), line2: address_details.line2.clone(), line3: address_details.line3.clone(), state: address_details.state.clone(), first_name: address_details.first_name.clone(), last_name: address_details.last_name.clone(), zip: address_details.zip.clone(), phone_number: self.phone.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), origin_zip: address_details.origin_zip.clone(), }, )), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; Ok(storage::AddressUpdate::Update { city: address_details.city, country: address_details.country, line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, zip: encryptable_address.zip, state: encryptable_address.state, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: self.phone_country_code.clone(), updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), origin_zip: encryptable_address.origin_zip, }) } async fn get_domain_address( &self, state: &SessionState, address_details: payments::AddressDetails, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError> { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address_details.line1.clone(), line2: address_details.line2.clone(), line3: address_details.line3.clone(), state: address_details.state.clone(), first_name: address_details.first_name.clone(), last_name: address_details.last_name.clone(), zip: address_details.zip.clone(), phone_number: self.phone.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), origin_zip: address_details.origin_zip.clone(), }, )), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; let address = domain::Address { city: address_details.city, country: address_details.country, line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, zip: encryptable_address.zip, state: encryptable_address.state, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: self.phone_country_code.clone(), merchant_id: merchant_id.to_owned(), address_id: generate_id(consts::ID_LENGTH, "add"), created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), origin_zip: encryptable_address.origin_zip, }; Ok(domain::CustomerAddress { address, customer_id: customer_id.to_owned(), }) } } #[cfg(feature = "v1")] #[async_trait::async_trait] impl CustomerAddress for api_models::customers::CustomerUpdateRequest { async fn get_address_update( &self, state: &SessionState, address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, merchant_id: id_type::MerchantId, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError> { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address_details.line1.clone(), line2: address_details.line2.clone(), line3: address_details.line3.clone(), state: address_details.state.clone(), first_name: address_details.first_name.clone(), last_name: address_details.last_name.clone(), zip: address_details.zip.clone(), phone_number: self.phone.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), origin_zip: address_details.origin_zip.clone(), }, )), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; Ok(storage::AddressUpdate::Update { city: address_details.city, country: address_details.country, line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, zip: encryptable_address.zip, state: encryptable_address.state, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: self.phone_country_code.clone(), updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), origin_zip: encryptable_address.origin_zip, }) } async fn get_domain_address( &self, state: &SessionState, address_details: payments::AddressDetails, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError> { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address_details.line1.clone(), line2: address_details.line2.clone(), line3: address_details.line3.clone(), state: address_details.state.clone(), first_name: address_details.first_name.clone(), last_name: address_details.last_name.clone(), zip: address_details.zip.clone(), phone_number: self.phone.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), origin_zip: address_details.origin_zip.clone(), }, )), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; let address = domain::Address { city: address_details.city, country: address_details.country, line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, zip: encryptable_address.zip, state: encryptable_address.state, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: self.phone_country_code.clone(), merchant_id: merchant_id.to_owned(), address_id: generate_id(consts::ID_LENGTH, "add"), created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), origin_zip: encryptable_address.origin_zip, }; Ok(domain::CustomerAddress { address, customer_id: customer_id.to_owned(), }) } } pub fn add_apple_pay_flow_metrics( apple_pay_flow: &Option<domain::ApplePayFlow>, connector: Option<String>, merchant_id: id_type::MerchantId, ) { if let Some(flow) = apple_pay_flow { match flow { domain::ApplePayFlow::Simplified(_) => metrics::APPLE_PAY_SIMPLIFIED_FLOW.add( 1, router_env::metric_attributes!( ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_id.clone()), ), ), domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW.add( 1, router_env::metric_attributes!( ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_id.clone()), ), ), } } } pub fn add_apple_pay_payment_status_metrics( payment_attempt_status: enums::AttemptStatus, apple_pay_flow: Option<domain::ApplePayFlow>, connector: Option<String>, merchant_id: id_type::MerchantId, ) { if payment_attempt_status == enums::AttemptStatus::Charged { if let Some(flow) = apple_pay_flow { match flow { domain::ApplePayFlow::Simplified(_) => {
crates/router/src/utils.rs#chunk0
router
chunk
null
null
null
8,181
null
null
null
null
null
null
null
// Struct: MockTokenizeDBValue // File: crates/router/src/core/payment_methods/vault.rs // Module: router // Implementations: 0 pub struct MockTokenizeDBValue
crates/router/src/core/payment_methods/vault.rs
router
struct_definition
MockTokenizeDBValue
0
[]
41
null
null
null
null
null
null
null
// Struct: BoletoVoucherData // File: crates/hyperswitch_domain_models/src/payment_method_data.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct BoletoVoucherData
crates/hyperswitch_domain_models/src/payment_method_data.rs
hyperswitch_domain_models
struct_definition
BoletoVoucherData
0
[]
49
null
null
null
null
null
null
null
// Implementation: impl PaymentSession for for Cybersource // File: crates/hyperswitch_connectors/src/connectors/cybersource.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl PaymentSession for for Cybersource
crates/hyperswitch_connectors/src/connectors/cybersource.rs
hyperswitch_connectors
impl_block
null
null
null
57
null
Cybersource
PaymentSession for
0
0
null
null
pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } /// Indicates if 3DS method data was successfully completed or not #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: Option<enums::AttemptStatus>, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateResponse { /// The identifier for the payment pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: enums::AttemptStatus, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] /// Indicates if 3DS method data was successfully completed or not pub enum ThreeDsCompletionIndicator { /// 3DS method successfully completed #[serde(rename = "Y")] Success, /// 3DS method was not successful #[serde(rename = "N")] Failure, /// 3DS method URL was unavailable #[serde(rename = "U")] NotAvailable, } /// Device Channel indicating whether request is coming from App or Browser #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)] pub enum DeviceChannel { #[serde(rename = "APP")] App, #[serde(rename = "BRW")] Browser, } /// SDK Information if request is from SDK #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkInformation { /// Unique ID created on installations of the 3DS Requestor App on a Consumer Device pub sdk_app_id: String, /// JWE Object containing data encrypted by the SDK for the DS to decrypt pub sdk_enc_data: String, /// Public key component of the ephemeral key pair generated by the 3DS SDK pub sdk_ephem_pub_key: HashMap<String, String>, /// Unique transaction identifier assigned by the 3DS SDK pub sdk_trans_id: String, /// Identifies the vendor and version for the 3DS SDK that is integrated in a 3DS Requestor App pub sdk_reference_number: String, /// Indicates maximum amount of time in minutes pub sdk_max_timeout: u8, /// Indicates the type of 3DS SDK pub sdk_type: Option<SdkType>, } /// Enum representing the type of 3DS SDK. #[derive(Serialize, Deserialize, Debug, Clone, ToSchema)] pub enum SdkType { #[serde(rename = "01")] DefaultSdk, #[serde(rename = "02")] SplitSdk, #[serde(rename = "03")] LimitedSdk, #[serde(rename = "04")] BrowserSdk, #[serde(rename = "05")] ShellSdk, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct ListMethodsForPaymentsRequest { /// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK #[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")] pub client_secret: Option<String>, /// The two-letter ISO currency code #[serde(deserialize_with = "parse_comma_separated", default)] #[schema(value_type = Option<Vec<CountryAlpha2>>, example = json!(["US", "UK", "IN"]))] pub accepted_countries: Option<Vec<api_enums::CountryAlpha2>>, /// Filter by amount #[schema(example = 60)] pub amount: Option<MinorUnit>, /// The three-letter ISO currency code #[serde(deserialize_with = "parse_comma_separated", default)] #[schema(value_type = Option<Vec<Currency>>,example = json!(["USD", "EUR"]))] pub accepted_currencies: Option<Vec<api_enums::Currency>>, /// Indicates whether the payment method supports recurring payments. Optional. #[schema(example = true)] pub recurring_enabled: Option<bool>, /// Indicates whether the payment method is eligible for card networks #[serde(deserialize_with = "parse_comma_separated", default)] #[schema(value_type = Option<Vec<CardNetwork>>, example = json!(["visa", "mastercard"]))] pub card_networks: Option<Vec<api_enums::CardNetwork>>, /// Indicates the limit of last used payment methods #[schema(example = 1)] pub limit: Option<i64>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponseForPayments { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypesForPayments>, /// The list of payment methods that are saved by the given customer /// This field is only returned if the customer_id is provided in the request #[schema(value_type = Option<Vec<CustomerPaymentMethodResponseItem>>)] pub customer_payment_methods: Option<Vec<payment_methods::CustomerPaymentMethodResponseItem>>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypesForPayments { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The payment experience for the payment method #[schema(value_type = Option<Vec<PaymentExperience>>)] pub payment_experience: Option<Vec<common_enums::PaymentExperience>>, /// payment method subtype specific information #[serde(flatten)] #[schema(value_type = Option<PaymentMethodSubtypeSpecificData>)] pub extra_information: Option<payment_methods::PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. #[schema(value_type = RequiredFieldInfo)] pub required_fields: Vec<payment_methods::RequiredFieldInfo>, /// surcharge details for this payment method type if exists #[schema(value_type = Option<SurchargeDetailsResponse>)] pub surcharge_details: Option<payment_methods::SurchargeDetailsResponse>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationResponse { /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = TransactionStatus)] pub transaction_status: common_enums::TransactionStatus, /// Access Server URL to be used for challenge submission pub acs_url: Option<String>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, /// Challenge request key which should be set as form field name for creq pub challenge_request_key: Option<String>, /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_dsserver_trans_id: Option<String>, /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred pub three_ds_requestor_app_url: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsApproveRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRejectRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentsStartRequest { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. This field is auto generated and is returned in the API response. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. pub merchant_id: id_type::MerchantId, /// The identifier for the payment transaction pub attempt_id: String, } /// additional data that might be required by hyperswitch #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, /// revenue recovery data for payment intent pub revenue_recovery: Option<PaymentRevenueRecoveryMetadata>, } #[cfg(feature = "v2")] impl FeatureMetadata { pub fn get_retry_count(&self) -> Option<u16> { self.revenue_recovery .as_ref() .map(|metadata| metadata.total_retry_count) } pub fn set_payment_revenue_recovery_metadata_using_api( self, payment_revenue_recovery_metadata: PaymentRevenueRecoveryMetadata, ) -> Self { Self { redirect_response: self.redirect_response, search_tags: self.search_tags, apple_pay_recurring_details: self.apple_pay_recurring_details, revenue_recovery: Some(payment_revenue_recovery_metadata), } } } /// additional data that might be required by hyperswitch #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringDetails { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingDetails, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_url: common_utils::types::Url, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingDetails { /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The date of the first payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RecurringPaymentIntervalUnit { Year, Month, Day, Hour, Minute, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct FrmMessage { pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: Option<String>, pub frm_status: Option<String>, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, } #[cfg(feature = "v2")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::GlobalPaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } #[allow(dead_code)] pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } #[cfg(feature = "v1")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::PaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } pub mod amount { use serde::de; use super::Amount; struct AmountVisitor; struct OptionalAmountVisitor; use crate::payments::MinorUnit; // This is defined to provide guarded deserialization of amount // which itself handles zero and non-zero values internally impl de::Visitor<'_> for AmountVisitor { type Value = Amount; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } } impl<'de> de::Visitor<'de> for OptionalAmountVisitor { type Value = Option<Amount>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_i64(AmountVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_any(AmountVisitor) } pub(crate) fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<Amount>, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_option(OptionalAmountVisitor) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_mandate_type() { let mandate_type = MandateType::default(); assert_eq!( serde_json::to_string(&mandate_type).unwrap(), r#"{"multi_use":null}"# ) } } #[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)] pub struct RetrievePaymentLinkRequest { /// It's a token used for client side verification. pub client_secret: Option<String>, } #[derive(Clone, Debug, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkResponse { /// URL for rendering the open payment link pub link: String, /// URL for rendering the secure payment link pub secure_link: Option<String>, /// Identifier for the payment link pub payment_link_id: String, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RetrievePaymentLinkResponse { /// Identifier for Payment Link pub payment_link_id: String, /// Identifier for Merchant #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Open payment link (without any security checks and listing SPMs) pub link_to_pay: String, /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Date and time of Payment Link creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Date and time of Expiration for Payment Link #[serde(with = "common_utils::custom_serde::iso8601::option")] pub expiry: Option<PrimitiveDateTime>, /// Description for Payment Link pub description: Option<String>, /// Status Of the Payment Link pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, /// Secure payment link (with security checks and listing saved payment methods) pub secure_link: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum PaymentLinkData { PaymentLinkDetails(Box<PaymentLinkDetails>), PaymentLinkStatusDetails(Box<PaymentLinkStatusDetails>), } #[derive(Debug, serde::Serialize, Clone)] pub struct PaymentLinkDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub pub_key: String, pub client_secret: String, pub payment_id: id_type::PaymentId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub merchant_logo: String, pub return_url: String, pub merchant_name: String, pub order_details: Option<Vec<OrderDetailsWithStringAmount>>, pub max_items_visible_after_collapse: i8, pub theme: String, pub merchant_description: Option<String>, pub sdk_layout: String, pub display_sdk_only: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub background_image: Option<admin::PaymentLinkBackgroundImageConfig>, pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, pub branding_visibility: Option<bool>, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, pub payment_form_header_text: Option<String>, pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>, pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, pub is_setup_mandate_flow: Option<bool>, pub capture_method: Option<common_enums::CaptureMethod>, pub setup_future_usage_applied: Option<common_enums::FutureUsage>, pub color_icon_card_cvc_error: Option<String>, } #[derive(Debug, serde::Serialize, Clone)] pub struct SecurePaymentLinkDetails { pub enabled_saved_payment_method: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, #[serde(flatten)] pub payment_link_details: PaymentLinkDetails, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, pub payment_form_header_text: Option<String>, pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>, pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, pub color_icon_card_cvc_error: Option<String>, } #[derive(Debug, serde::Serialize)] pub struct PaymentLinkStatusDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub payment_id: id_type::PaymentId, pub merchant_logo: String, pub merchant_name: String, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub status: PaymentLinkStatusWrap, pub error_code: Option<String>, pub error_message: Option<String>, pub redirect: bool, pub theme: String, pub return_url: String, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub capture_method: Option<common_enums::CaptureMethod>, pub setup_future_usage_applied: Option<common_enums::FutureUsage>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentLinkListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// The time at which payment link is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentLinkListResponse { /// The number of payment links included in the list pub size: usize, // The list of payment link response objects pub data: Vec<PaymentLinkResponse>, } /// Configure a custom payment link for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] #[schema(value_type = Option<PaymentLinkConfigRequest>)] /// Theme config for the particular payment pub theme_config: admin::PaymentLinkConfigRequest, } #[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithStringAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product pub amount: StringMajorUnit, /// Product Image link pub product_img_link: Option<String>, } /// Status Of the Payment Link #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentLinkStatus { Active, Expired, } #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] #[serde(untagged)] pub enum PaymentLinkStatusWrap { PaymentLinkStatus(PaymentLinkStatus), IntentStatus(api_enums::IntentStatus), } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct ExtendedCardInfoResponse { // Encrypted customer payment method data pub payload: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ClickToPaySessionResponse { pub dpa_id: String, pub dpa_name: String, pub locale: String, #[schema(value_type = Vec<CardNetwork>, example = "[Visa, Mastercard]")] pub card_brands: HashSet<api_enums::CardNetwork>, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub merchant_category_code: String, pub merchant_country_code: String, #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, #[schema(value_type = Currency)] pub transaction_currency_code: common_enums::Currency, #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone_number: Option<Secret<String>>, #[schema(max_length = 255, value_type = Option<String>, example = "[email protected]")] pub email: Option<Email>, pub phone_country_code: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, pub dpa_client_id: Option<String>, } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_api_contract { #![allow(clippy::unwrap_used)] #![allow(clippy::panic)] use std::str::FromStr; use super::*; #[test] fn test_successful_card_deser() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } "#; let expected_card_number_string = "4242424242424242"; let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap(); let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); if let Some(PaymentMethodData::Card(card_data)) = payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data { assert_eq!(card_data.card_number, expected_card_number); } else { panic!("Received unexpected response") } } #[test] fn test_successful_payment_method_reward() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "reward", "payment_method_data": "reward", "payment_method_type": "evoucher" } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert_eq!( payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data, Some(PaymentMethodData::Reward) ); } #[test] fn test_payment_method_data_with_payment_method_billing() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method_data": { "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Bhat" } } } } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert!(payments_request .unwrap() .payment_method_data .unwrap() .billing .is_some()); } } #[cfg(test)] mod payments_response_api_contract { #![allow(clippy::unwrap_used)] use super::*; #[derive(Debug, serde::Serialize)] struct TestPaymentsResponse { #[serde(serialize_with = "serialize_payment_method_data_response")]
crates/api_models/src/payments.rs#chunk10
api_models
chunk
null
null
null
8,181
null
null
null
null
null
null
null
// Struct: ZeroMandates // File: crates/payment_methods/src/configs/settings.rs // Module: payment_methods // Implementations: 0 pub struct ZeroMandates
crates/payment_methods/src/configs/settings.rs
payment_methods
struct_definition
ZeroMandates
0
[]
39
null
null
null
null
null
null
null
// Struct: AuthenticationErrorMessage // File: crates/api_models/src/analytics/auth_events.rs // Module: api_models // Implementations: 0 pub struct AuthenticationErrorMessage
crates/api_models/src/analytics/auth_events.rs
api_models
struct_definition
AuthenticationErrorMessage
0
[]
36
null
null
null
null
null
null
null
// Struct: RefundResponse // File: crates/hyperswitch_connectors/src/connectors/noon/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct RefundResponse
crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
hyperswitch_connectors
struct_definition
RefundResponse
0
[]
47
null
null
null
null
null
null
null