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
⌀ |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
// File: crates/analytics/src/disputes/metrics/sessionized_metrics/dispute_status_metric.rs
// Module: analytics
use std::collections::HashSet;
use api_models::analytics::{
disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::DisputeMetricRow;
use crate::{
enums::AuthInfo,
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(crate) struct DisputeStatusMetric {}
#[async_trait::async_trait]
impl<T> super::DisputeMetric<T> for DisputeStatusMetric
where
T: AnalyticsDataSource + super::DisputeMetricAnalytics,
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: &[DisputeDimensions],
auth: &AuthInfo,
filters: &DisputeFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>
where
T: AnalyticsDataSource + super::DisputeMetricAnalytics,
{
let mut query_builder = QueryBuilder::new(AnalyticsCollection::DisputeSessionized);
for dim in dimensions {
query_builder.add_select_column(dim).switch()?;
}
query_builder.add_select_column("dispute_status").switch()?;
query_builder
.add_select_column(Aggregate::Count {
field: None,
alias: Some("count"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
auth.set_filter_clause(&mut query_builder).switch()?;
time_range.set_filter_clause(&mut query_builder).switch()?;
for dim in dimensions {
query_builder.add_group_by_clause(dim).switch()?;
}
query_builder
.add_group_by_clause("dispute_status")
.switch()?;
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.switch()?;
}
query_builder
.execute_query::<DisputeMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
DisputeMetricsBucketIdentifier::new(
i.dispute_stage.as_ref().map(|i| i.0),
i.connector.clone(),
i.currency.as_ref().map(|i| i.0),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
},
),
i,
))
})
.collect::<error_stack::Result<
HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>,
crate::query::PostProcessingError,
>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
|
crates/analytics/src/disputes/metrics/sessionized_metrics/dispute_status_metric.rs
|
analytics
|
full_file
| null | null | null | 855
| null | null | null | null | null | null | null |
// Function: with_additional_payment_method_data
// File: crates/hyperswitch_domain_models/src/router_data.rs
// Module: hyperswitch_domain_models
pub fn with_additional_payment_method_data(
additional_payment_method_data: AdditionalPaymentMethodConnectorResponse,
) -> Self
|
crates/hyperswitch_domain_models/src/router_data.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 56
|
with_additional_payment_method_data
| null | null | null | null | null | null |
// Function: log_event
// File: crates/router/src/services/kafka.rs
// Module: router
pub fn log_event<T: KafkaMessage>(&self, event: &T) -> MQResult<()>
|
crates/router/src/services/kafka.rs
|
router
|
function_signature
| null | null | null | 42
|
log_event
| null | null | null | null | null | null |
// Struct: SubscriptionPlans
// File: crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct SubscriptionPlans
|
crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs
|
hyperswitch_domain_models
|
struct_definition
|
SubscriptionPlans
| 0
|
[] | 43
| null | null | null | null | null | null | null |
// Struct: NexinetsAuthType
// File: crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct NexinetsAuthType
|
crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
NexinetsAuthType
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// Struct: ReconToken
// File: crates/router/src/services/authentication.rs
// Module: router
// Implementations: 1
pub struct ReconToken
|
crates/router/src/services/authentication.rs
|
router
|
struct_definition
|
ReconToken
| 1
|
[] | 32
| null | null | null | null | null | null | null |
// Struct: ZenBrowserDetails
// File: crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ZenBrowserDetails
|
crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ZenBrowserDetails
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Struct: RazorpayMetaData
// File: crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct RazorpayMetaData
|
crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
RazorpayMetaData
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Struct: EntityInfo
// File: crates/router/src/types/domain/user.rs
// Module: router
// Implementations: 0
pub struct EntityInfo
|
crates/router/src/types/domain/user.rs
|
router
|
struct_definition
|
EntityInfo
| 0
|
[] | 33
| null | null | null | null | null | null | null |
impl webhooks::IncomingWebhook for Nexixpay {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
lazy_static! {
static ref NEXIXPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Nexixpay",
description: "Nexixpay is an Italian bank that specialises in payment systems such as Nexi Payments (formerly known as CartaSi).",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static ref NEXIXPAY_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::JCB,
];
let mut nexixpay_supported_payment_methods = SupportedPaymentMethods::new();
nexixpay_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::Supported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
)
}
);
nexixpay_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::Supported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network,
}
}),
)
}
);
nexixpay_supported_payment_methods
};
static ref NEXIXPAY_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new();
}
impl ConnectorSpecifications for Nexixpay {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*NEXIXPAY_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*NEXIXPAY_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&*NEXIXPAY_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates/hyperswitch_connectors/src/connectors/nexixpay.rs#chunk1
|
hyperswitch_connectors
|
chunk
| null | null | null | 873
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_interfaces/src/api/payouts.rs
// Module: hyperswitch_interfaces
//! Payouts interface
use hyperswitch_domain_models::{
router_flow_types::payouts::{
PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount,
PoSync,
},
router_request_types::PayoutsData,
router_response_types::PayoutsResponseData,
};
use super::ConnectorCommon;
use crate::api::ConnectorIntegration;
/// trait PayoutCancel
pub trait PayoutCancel: ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData> {}
/// trait PayoutCreate
pub trait PayoutCreate: ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData> {}
/// trait PayoutEligibility
pub trait PayoutEligibility:
ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData>
{
}
/// trait PayoutFulfill
pub trait PayoutFulfill: ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> {}
/// trait PayoutQuote
pub trait PayoutQuote: ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData> {}
/// trait PayoutRecipient
pub trait PayoutRecipient:
ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData>
{
}
/// trait PayoutRecipientAccount
pub trait PayoutRecipientAccount:
ConnectorIntegration<PoRecipientAccount, PayoutsData, PayoutsResponseData>
{
}
/// trait PayoutSync
pub trait PayoutSync: ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData> {}
#[cfg(feature = "payouts")]
/// trait Payouts
pub trait Payouts:
ConnectorCommon
+ PayoutCancel
+ PayoutCreate
+ PayoutEligibility
+ PayoutFulfill
+ PayoutQuote
+ PayoutRecipient
+ PayoutRecipientAccount
+ PayoutSync
{
}
/// Empty trait for when payouts feature is disabled
#[cfg(not(feature = "payouts"))]
pub trait Payouts {}
|
crates/hyperswitch_interfaces/src/api/payouts.rs
|
hyperswitch_interfaces
|
full_file
| null | null | null | 476
| null | null | null | null | null | null | null |
// Implementation: impl ClickhouseClient
// File: crates/analytics/src/clickhouse.rs
// Module: analytics
// Methods: 1 total (0 public)
impl ClickhouseClient
|
crates/analytics/src/clickhouse.rs
|
analytics
|
impl_block
| null | null | null | 39
| null |
ClickhouseClient
| null | 1
| 0
| null | null |
// Struct: BankAccountCredentialsOptions
// File: crates/pm_auth/src/connector/plaid/transformers.rs
// Module: pm_auth
// Implementations: 0
pub struct BankAccountCredentialsOptions
|
crates/pm_auth/src/connector/plaid/transformers.rs
|
pm_auth
|
struct_definition
|
BankAccountCredentialsOptions
| 0
|
[] | 43
| null | null | null | null | null | null | null |
// Function: decide_gateway_open_router
// File: crates/router/src/core/routing.rs
// Module: router
pub fn decide_gateway_open_router(
state: SessionState,
req_body: OpenRouterDecideGatewayRequest,
) -> RouterResponse<DecideGatewayResponse>
|
crates/router/src/core/routing.rs
|
router
|
function_signature
| null | null | null | 58
|
decide_gateway_open_router
| null | null | null | null | null | null |
// Function: cancel_payout
// File: crates/router/src/core/payouts.rs
// Module: router
pub fn cancel_payout(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()>
|
crates/router/src/core/payouts.rs
|
router
|
function_signature
| null | null | null | 72
|
cancel_payout
| null | null | null | null | null | null |
// Struct: SkrillDetails
// File: crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct SkrillDetails
|
crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
SkrillDetails
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Function: get_valid_connectors_for_rule
// File: crates/euclid_wasm/src/lib.rs
// Module: euclid_wasm
pub fn get_valid_connectors_for_rule(rule: JsValue) -> JsResult
|
crates/euclid_wasm/src/lib.rs
|
euclid_wasm
|
function_signature
| null | null | null | 47
|
get_valid_connectors_for_rule
| null | null | null | null | null | null |
// Struct: SetupIntents
// File: crates/router/src/compatibility/stripe/app.rs
// Module: router
// Implementations: 1
pub struct SetupIntents
|
crates/router/src/compatibility/stripe/app.rs
|
router
|
struct_definition
|
SetupIntents
| 1
|
[] | 38
| null | null | null | null | null | null | null |
// Function: connector_transaction_id
// File: crates/hyperswitch_connectors/src/connectors/helcim.rs
// Module: hyperswitch_connectors
pub fn connector_transaction_id(
&self,
connector_meta: Option<&serde_json::Value>,
) -> CustomResult<Option<String>, errors::ConnectorError>
|
crates/hyperswitch_connectors/src/connectors/helcim.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 68
|
connector_transaction_id
| null | null | null | null | null | null |
// Struct: RecipientCreateAddress
// File: crates/pm_auth/src/types.rs
// Module: pm_auth
// Implementations: 0
pub struct RecipientCreateAddress
|
crates/pm_auth/src/types.rs
|
pm_auth
|
struct_definition
|
RecipientCreateAddress
| 0
|
[] | 37
| null | null | null | null | null | null | null |
// Struct: PlacetopayErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/placetopay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PlacetopayErrorResponse
|
crates/hyperswitch_connectors/src/connectors/placetopay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PlacetopayErrorResponse
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// Implementation: impl api::Refund for for Forte
// File: crates/hyperswitch_connectors/src/connectors/forte.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::Refund for for Forte
|
crates/hyperswitch_connectors/src/connectors/forte.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Forte
|
api::Refund for
| 0
| 0
| null | null |
// File: crates/analytics/src/disputes/types.rs
// Module: analytics
use api_models::analytics::disputes::{DisputeDimensions, DisputeFilters};
use error_stack::ResultExt;
use crate::{
query::{QueryBuilder, QueryFilter, QueryResult, ToSql},
types::{AnalyticsCollection, AnalyticsDataSource},
};
impl<T> QueryFilter<T> for DisputeFilters
where
T: AnalyticsDataSource,
AnalyticsCollection: ToSql<T>,
{
fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()> {
if !self.connector.is_empty() {
builder
.add_filter_in_range_clause(DisputeDimensions::Connector, &self.connector)
.attach_printable("Error adding connector filter")?;
}
if !self.dispute_stage.is_empty() {
builder
.add_filter_in_range_clause(DisputeDimensions::DisputeStage, &self.dispute_stage)
.attach_printable("Error adding dispute stage filter")?;
}
if !self.currency.is_empty() {
builder
.add_filter_in_range_clause(DisputeDimensions::Currency, &self.currency)
.attach_printable("Error adding currency filter")?;
}
Ok(())
}
}
|
crates/analytics/src/disputes/types.rs
|
analytics
|
full_file
| null | null | null | 265
| null | null | null | null | null | null | null |
// Struct: ErrorResult
// File: crates/api_models/src/analytics/payments.rs
// Module: api_models
// Implementations: 0
pub struct ErrorResult
|
crates/api_models/src/analytics/payments.rs
|
api_models
|
struct_definition
|
ErrorResult
| 0
|
[] | 36
| null | null | null | null | null | null | null |
// Function: payouts_list_by_filter_profile
// File: crates/openapi/src/routes/payouts.rs
// Module: openapi
pub fn payouts_list_by_filter_profile()
|
crates/openapi/src/routes/payouts.rs
|
openapi
|
function_signature
| null | null | null | 36
|
payouts_list_by_filter_profile
| null | null | null | null | null | null |
// Struct: GetAuthEventFilterRequest
// File: crates/api_models/src/analytics.rs
// Module: api_models
// Implementations: 0
pub struct GetAuthEventFilterRequest
|
crates/api_models/src/analytics.rs
|
api_models
|
struct_definition
|
GetAuthEventFilterRequest
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Module Structure
// File: crates/router/src/routes/user.rs
// Module: router
// Public submodules:
pub mod theme;
|
crates/router/src/routes/user.rs
|
router
|
module_structure
| null | null | null | 28
| null | null | null | null | null | 1
| 0
|
// Implementation: impl User
// File: crates/router/src/routes/app.rs
// Module: router
// Methods: 1 total (1 public)
impl User
|
crates/router/src/routes/app.rs
|
router
|
impl_block
| null | null | null | 33
| null |
User
| null | 1
| 1
| null | null |
// Struct: RiskifiedFailedTransactionResponse
// File: crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct RiskifiedFailedTransactionResponse
|
crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs
|
hyperswitch_connectors
|
struct_definition
|
RiskifiedFailedTransactionResponse
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// Function: deserialize_db_op
// File: crates/drainer/src/utils.rs
// Module: drainer
pub fn deserialize_db_op<'de, D>(deserializer: D) -> Result<kv::DBOperation, D::Error>
where
D: serde::Deserializer<'de>,
|
crates/drainer/src/utils.rs
|
drainer
|
function_signature
| null | null | null | 61
|
deserialize_db_op
| null | null | null | null | null | null |
// Implementation: impl api::PaymentAuthorize for for Wellsfargo
// File: crates/hyperswitch_connectors/src/connectors/wellsfargo.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentAuthorize for for Wellsfargo
|
crates/hyperswitch_connectors/src/connectors/wellsfargo.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Wellsfargo
|
api::PaymentAuthorize for
| 0
| 0
| null | null |
// Function: trigger_refund_to_gateway
// File: crates/router/src/core/refunds.rs
// Module: router
pub fn trigger_refund_to_gateway(
state: &SessionState,
refund: &diesel_refund::Refund,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
creds_identifier: Option<String>,
split_refunds: Option<SplitRefundsRequest>,
) -> RouterResult<diesel_refund::Refund>
|
crates/router/src/core/refunds.rs
|
router
|
function_signature
| null | null | null | 113
|
trigger_refund_to_gateway
| null | null | null | null | null | null |
// Struct: PaymentIntentsAnalyticsMetadata
// File: crates/api_models/src/analytics.rs
// Module: api_models
// Implementations: 0
pub struct PaymentIntentsAnalyticsMetadata
|
crates/api_models/src/analytics.rs
|
api_models
|
struct_definition
|
PaymentIntentsAnalyticsMetadata
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Implementation: impl FraudCheckCheckout for for Riskified
// File: crates/hyperswitch_connectors/src/connectors/riskified.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl FraudCheckCheckout for for Riskified
|
crates/hyperswitch_connectors/src/connectors/riskified.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 56
| null |
Riskified
|
FraudCheckCheckout for
| 0
| 0
| null | null |
// Struct: InfoCodes
// File: crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct InfoCodes
|
crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
InfoCodes
| 0
|
[] | 48
| null | null | null | null | null | null | null |
// Implementation: impl ConnectorValidation for for Hipay
// File: crates/hyperswitch_connectors/src/connectors/hipay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl ConnectorValidation for for Hipay
|
crates/hyperswitch_connectors/src/connectors/hipay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 54
| null |
Hipay
|
ConnectorValidation for
| 0
| 0
| null | null |
// Struct: DisputeMetricsBucketIdentifier
// File: crates/api_models/src/analytics/disputes.rs
// Module: api_models
// Implementations: 3
// Traits: Hash, PartialEq
pub struct DisputeMetricsBucketIdentifier
|
crates/api_models/src/analytics/disputes.rs
|
api_models
|
struct_definition
|
DisputeMetricsBucketIdentifier
| 3
|
[
"Hash",
"PartialEq"
] | 50
| null | null | null | null | null | null | null |
// Function: new_for_create
// File: crates/router/src/core/payments/types.rs
// Module: router
pub fn new_for_create(
mut previous_captures: Vec<storage::Capture>,
new_capture: storage::Capture,
) -> Self
|
crates/router/src/core/payments/types.rs
|
router
|
function_signature
| null | null | null | 55
|
new_for_create
| null | null | null | null | null | null |
// Function: generate_client_secret
// File: crates/common_utils/src/id_type/payment.rs
// Module: common_utils
// Documentation: Generate a client id for the payment id
pub fn generate_client_secret(&self) -> String
|
crates/common_utils/src/id_type/payment.rs
|
common_utils
|
function_signature
| null | null | null | 47
|
generate_client_secret
| null | null | null | null | null | null |
// Implementation: impl DummyConnector
// File: crates/router/src/routes/app.rs
// Module: router
// Methods: 1 total (1 public)
impl DummyConnector
|
crates/router/src/routes/app.rs
|
router
|
impl_block
| null | null | null | 35
| null |
DummyConnector
| null | 1
| 1
| null | null |
// Struct: FraudCheck
// File: crates/diesel_models/src/fraud_check.rs
// Module: diesel_models
// Implementations: 0
pub struct FraudCheck
|
crates/diesel_models/src/fraud_check.rs
|
diesel_models
|
struct_definition
|
FraudCheck
| 0
|
[] | 36
| null | null | null | null | null | null | null |
// Struct: PaymentAttemptRecordData
// File: crates/hyperswitch_domain_models/src/payments.rs
// Module: hyperswitch_domain_models
// Implementations: 1
pub struct PaymentAttemptRecordData<F>
|
crates/hyperswitch_domain_models/src/payments.rs
|
hyperswitch_domain_models
|
struct_definition
|
PaymentAttemptRecordData
| 1
|
[] | 46
| null | null | null | null | null | null | null |
// Function: new
// File: crates/diesel_models/src/subscription.rs
// Module: diesel_models
pub fn new(payment_method_id: Option<String>, status: Option<String>) -> Self
|
crates/diesel_models/src/subscription.rs
|
diesel_models
|
function_signature
| null | null | null | 40
|
new
| null | null | null | null | null | null |
// Function: payouts_update
// File: crates/openapi/src/routes/payouts.rs
// Module: openapi
pub fn payouts_update()
|
crates/openapi/src/routes/payouts.rs
|
openapi
|
function_signature
| null | null | null | 30
|
payouts_update
| null | null | null | null | null | null |
// Implementation: impl api::PaymentToken for for Worldpay
// File: crates/hyperswitch_connectors/src/connectors/worldpay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentToken for for Worldpay
|
crates/hyperswitch_connectors/src/connectors/worldpay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Worldpay
|
api::PaymentToken for
| 0
| 0
| null | null |
// Implementation: impl ConnectorCommon for for Flexiti
// File: crates/hyperswitch_connectors/src/connectors/flexiti.rs
// Module: hyperswitch_connectors
// Methods: 6 total (0 public)
impl ConnectorCommon for for Flexiti
|
crates/hyperswitch_connectors/src/connectors/flexiti.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 54
| null |
Flexiti
|
ConnectorCommon for
| 6
| 0
| null | null |
// Function: get_santander_webhook_event
// File: crates/hyperswitch_connectors/src/connectors/santander/transformers.rs
// Module: hyperswitch_connectors
pub fn get_santander_webhook_event(
event_type: FunctionType,
) -> api_models::webhooks::IncomingWebhookEvent
|
crates/hyperswitch_connectors/src/connectors/santander/transformers.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 69
|
get_santander_webhook_event
| null | null | null | null | null | null |
// Implementation: impl Bankofamerica
// File: crates/hyperswitch_connectors/src/connectors/bankofamerica.rs
// Module: hyperswitch_connectors
// Methods: 2 total (2 public)
impl Bankofamerica
|
crates/hyperswitch_connectors/src/connectors/bankofamerica.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 52
| null |
Bankofamerica
| null | 2
| 2
| null | null |
// Function: values
// File: crates/hyperswitch_constraint_graph/src/dense_map.rs
// Module: hyperswitch_constraint_graph
pub fn values(&self) -> slice::Iter<'_, V>
|
crates/hyperswitch_constraint_graph/src/dense_map.rs
|
hyperswitch_constraint_graph
|
function_signature
| null | null | null | 43
|
values
| null | null | null | null | null | null |
// Function: new_with_config_path
// File: crates/router_env/src/logger/config.rs
// Module: router_env
// Documentation: Constructor expecting config path set explicitly.
pub fn new_with_config_path(
explicit_config_path: Option<PathBuf>,
) -> Result<Self, config::ConfigError>
|
crates/router_env/src/logger/config.rs
|
router_env
|
function_signature
| null | null | null | 62
|
new_with_config_path
| null | null | null | null | null | null |
// File: crates/euclid/src/dssa/state_machine.rs
// Module: euclid
// Public functions: 10
// Public structs: 3
use super::types::EuclidAnalysable;
use crate::{dssa::types, frontend::dir, types::Metadata};
#[derive(Debug, Clone, serde::Serialize, thiserror::Error)]
#[serde(tag = "type", content = "info", rename_all = "snake_case")]
pub enum StateMachineError {
#[error("Index out of bounds: {0}")]
IndexOutOfBounds(&'static str),
}
#[derive(Debug)]
struct ComparisonStateMachine<'a> {
values: &'a [dir::DirValue],
logic: &'a dir::DirComparisonLogic,
metadata: &'a Metadata,
count: usize,
ctx_idx: usize,
}
impl<'a> ComparisonStateMachine<'a> {
#[inline]
fn is_finished(&self) -> bool {
self.count + 1 >= self.values.len()
|| matches!(self.logic, dir::DirComparisonLogic::NegativeConjunction)
}
#[inline]
fn advance(&mut self) {
if let dir::DirComparisonLogic::PositiveDisjunction = self.logic {
self.count = (self.count + 1) % self.values.len();
}
}
#[inline]
fn reset(&mut self) {
self.count = 0;
}
#[inline]
fn put(&self, context: &mut types::ConjunctiveContext<'a>) -> Result<(), StateMachineError> {
if let dir::DirComparisonLogic::PositiveDisjunction = self.logic {
*context
.get_mut(self.ctx_idx)
.ok_or(StateMachineError::IndexOutOfBounds(
"in ComparisonStateMachine while indexing into context",
))? = types::ContextValue::assertion(
self.values
.get(self.count)
.ok_or(StateMachineError::IndexOutOfBounds(
"in ComparisonStateMachine while indexing into values",
))?,
self.metadata,
);
}
Ok(())
}
#[inline]
fn push(&self, context: &mut types::ConjunctiveContext<'a>) -> Result<(), StateMachineError> {
match self.logic {
dir::DirComparisonLogic::PositiveDisjunction => {
context.push(types::ContextValue::assertion(
self.values
.get(self.count)
.ok_or(StateMachineError::IndexOutOfBounds(
"in ComparisonStateMachine while pushing",
))?,
self.metadata,
));
}
dir::DirComparisonLogic::NegativeConjunction => {
context.push(types::ContextValue::negation(self.values, self.metadata));
}
}
Ok(())
}
}
#[derive(Debug)]
struct ConditionStateMachine<'a> {
state_machines: Vec<ComparisonStateMachine<'a>>,
start_ctx_idx: usize,
}
impl<'a> ConditionStateMachine<'a> {
fn new(condition: &'a [dir::DirComparison], start_idx: usize) -> Self {
let mut machines = Vec::<ComparisonStateMachine<'a>>::with_capacity(condition.len());
let mut machine_idx = start_idx;
for cond in condition {
let machine = ComparisonStateMachine {
values: &cond.values,
logic: &cond.logic,
metadata: &cond.metadata,
count: 0,
ctx_idx: machine_idx,
};
machines.push(machine);
machine_idx += 1;
}
Self {
state_machines: machines,
start_ctx_idx: start_idx,
}
}
fn init(&self, context: &mut types::ConjunctiveContext<'a>) -> Result<(), StateMachineError> {
for machine in &self.state_machines {
machine.push(context)?;
}
Ok(())
}
#[inline]
fn destroy(&self, context: &mut types::ConjunctiveContext<'a>) {
context.truncate(self.start_ctx_idx);
}
#[inline]
fn is_finished(&self) -> bool {
!self
.state_machines
.iter()
.any(|machine| !machine.is_finished())
}
#[inline]
fn get_next_ctx_idx(&self) -> usize {
self.start_ctx_idx + self.state_machines.len()
}
fn advance(
&mut self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<(), StateMachineError> {
for machine in self.state_machines.iter_mut().rev() {
if machine.is_finished() {
machine.reset();
machine.put(context)?;
} else {
machine.advance();
machine.put(context)?;
break;
}
}
Ok(())
}
}
#[derive(Debug)]
struct IfStmtStateMachine<'a> {
condition_machine: ConditionStateMachine<'a>,
nested: Vec<&'a dir::DirIfStatement>,
nested_idx: usize,
}
impl<'a> IfStmtStateMachine<'a> {
fn new(stmt: &'a dir::DirIfStatement, ctx_start_idx: usize) -> Self {
let condition_machine = ConditionStateMachine::new(&stmt.condition, ctx_start_idx);
let nested: Vec<&'a dir::DirIfStatement> = match &stmt.nested {
None => Vec::new(),
Some(nested_stmts) => nested_stmts.iter().collect(),
};
Self {
condition_machine,
nested,
nested_idx: 0,
}
}
fn init(
&self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<Option<Self>, StateMachineError> {
self.condition_machine.init(context)?;
Ok(self
.nested
.first()
.map(|nested| Self::new(nested, self.condition_machine.get_next_ctx_idx())))
}
#[inline]
fn is_finished(&self) -> bool {
self.nested_idx + 1 >= self.nested.len()
}
#[inline]
fn is_condition_machine_finished(&self) -> bool {
self.condition_machine.is_finished()
}
#[inline]
fn destroy(&self, context: &mut types::ConjunctiveContext<'a>) {
self.condition_machine.destroy(context);
}
#[inline]
fn advance_condition_machine(
&mut self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<(), StateMachineError> {
self.condition_machine.advance(context)?;
Ok(())
}
fn advance(&mut self) -> Result<Option<Self>, StateMachineError> {
if self.nested.is_empty() {
Ok(None)
} else {
self.nested_idx = (self.nested_idx + 1) % self.nested.len();
Ok(Some(Self::new(
self.nested
.get(self.nested_idx)
.ok_or(StateMachineError::IndexOutOfBounds(
"in IfStmtStateMachine while advancing",
))?,
self.condition_machine.get_next_ctx_idx(),
)))
}
}
}
#[derive(Debug)]
struct RuleStateMachine<'a> {
connector_selection_data: &'a [(dir::DirValue, Metadata)],
connectors_added: bool,
if_stmt_machines: Vec<IfStmtStateMachine<'a>>,
running_stack: Vec<IfStmtStateMachine<'a>>,
}
impl<'a> RuleStateMachine<'a> {
fn new<O>(
rule: &'a dir::DirRule<O>,
connector_selection_data: &'a [(dir::DirValue, Metadata)],
) -> Self {
let mut if_stmt_machines: Vec<IfStmtStateMachine<'a>> =
Vec::with_capacity(rule.statements.len());
for stmt in rule.statements.iter().rev() {
if_stmt_machines.push(IfStmtStateMachine::new(
stmt,
connector_selection_data.len(),
));
}
Self {
connector_selection_data,
connectors_added: false,
if_stmt_machines,
running_stack: Vec::new(),
}
}
fn is_finished(&self) -> bool {
self.if_stmt_machines.is_empty() && self.running_stack.is_empty()
}
fn init_next(
&mut self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<(), StateMachineError> {
if self.if_stmt_machines.is_empty() || !self.running_stack.is_empty() {
return Ok(());
}
if !self.connectors_added {
for (dir_val, metadata) in self.connector_selection_data {
context.push(types::ContextValue::assertion(dir_val, metadata));
}
self.connectors_added = true;
}
context.truncate(self.connector_selection_data.len());
if let Some(mut next_running) = self.if_stmt_machines.pop() {
while let Some(nested_running) = next_running.init(context)? {
self.running_stack.push(next_running);
next_running = nested_running;
}
self.running_stack.push(next_running);
}
Ok(())
}
fn advance(
&mut self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<(), StateMachineError> {
let mut condition_machines_finished = true;
for stmt_machine in self.running_stack.iter_mut().rev() {
if !stmt_machine.is_condition_machine_finished() {
condition_machines_finished = false;
stmt_machine.advance_condition_machine(context)?;
break;
} else {
stmt_machine.advance_condition_machine(context)?;
}
}
if !condition_machines_finished {
return Ok(());
}
let mut maybe_next_running: Option<IfStmtStateMachine<'a>> = None;
while let Some(last) = self.running_stack.last_mut() {
if !last.is_finished() {
maybe_next_running = last.advance()?;
break;
} else {
last.destroy(context);
self.running_stack.pop();
}
}
if let Some(mut next_running) = maybe_next_running {
while let Some(nested_running) = next_running.init(context)? {
self.running_stack.push(next_running);
next_running = nested_running;
}
self.running_stack.push(next_running);
} else {
self.init_next(context)?;
}
Ok(())
}
}
#[derive(Debug)]
pub struct RuleContextManager<'a> {
context: types::ConjunctiveContext<'a>,
machine: RuleStateMachine<'a>,
init: bool,
}
impl<'a> RuleContextManager<'a> {
pub fn new<O>(
rule: &'a dir::DirRule<O>,
connector_selection_data: &'a [(dir::DirValue, Metadata)],
) -> Self {
Self {
context: Vec::new(),
machine: RuleStateMachine::new(rule, connector_selection_data),
init: false,
}
}
pub fn advance(&mut self) -> Result<Option<&types::ConjunctiveContext<'a>>, StateMachineError> {
if !self.init {
self.init = true;
self.machine.init_next(&mut self.context)?;
Ok(Some(&self.context))
} else if self.machine.is_finished() {
Ok(None)
} else {
self.machine.advance(&mut self.context)?;
if self.machine.is_finished() {
Ok(None)
} else {
Ok(Some(&self.context))
}
}
}
pub fn advance_mut(
&mut self,
) -> Result<Option<&mut types::ConjunctiveContext<'a>>, StateMachineError> {
if !self.init {
self.init = true;
self.machine.init_next(&mut self.context)?;
Ok(Some(&mut self.context))
} else if self.machine.is_finished() {
Ok(None)
} else {
self.machine.advance(&mut self.context)?;
if self.machine.is_finished() {
Ok(None)
} else {
Ok(Some(&mut self.context))
}
}
}
}
#[derive(Debug)]
pub struct ProgramStateMachine<'a> {
rule_machines: Vec<RuleStateMachine<'a>>,
current_rule_machine: Option<RuleStateMachine<'a>>,
is_init: bool,
}
impl<'a> ProgramStateMachine<'a> {
pub fn new<O>(
program: &'a dir::DirProgram<O>,
connector_selection_data: &'a [Vec<(dir::DirValue, Metadata)>],
) -> Self {
let mut rule_machines: Vec<RuleStateMachine<'a>> = program
.rules
.iter()
.zip(connector_selection_data.iter())
.rev()
.map(|(rule, connector_selection_data)| {
RuleStateMachine::new(rule, connector_selection_data)
})
.collect();
Self {
current_rule_machine: rule_machines.pop(),
rule_machines,
is_init: false,
}
}
pub fn is_finished(&self) -> bool {
self.current_rule_machine
.as_ref()
.is_none_or(|rsm| rsm.is_finished())
&& self.rule_machines.is_empty()
}
pub fn init(
&mut self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<(), StateMachineError> {
if !self.is_init {
if let Some(rsm) = self.current_rule_machine.as_mut() {
rsm.init_next(context)?;
}
self.is_init = true;
}
Ok(())
}
pub fn advance(
&mut self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<(), StateMachineError> {
if self
.current_rule_machine
.as_ref()
.is_none_or(|rsm| rsm.is_finished())
{
self.current_rule_machine = self.rule_machines.pop();
context.clear();
if let Some(rsm) = self.current_rule_machine.as_mut() {
rsm.init_next(context)?;
}
} else if let Some(rsm) = self.current_rule_machine.as_mut() {
rsm.advance(context)?;
}
Ok(())
}
}
pub struct AnalysisContextManager<'a> {
context: types::ConjunctiveContext<'a>,
machine: ProgramStateMachine<'a>,
init: bool,
}
impl<'a> AnalysisContextManager<'a> {
pub fn new<O>(
program: &'a dir::DirProgram<O>,
connector_selection_data: &'a [Vec<(dir::DirValue, Metadata)>],
) -> Self {
let machine = ProgramStateMachine::new(program, connector_selection_data);
let context: types::ConjunctiveContext<'a> = Vec::new();
Self {
context,
machine,
init: false,
}
}
pub fn advance(&mut self) -> Result<Option<&types::ConjunctiveContext<'a>>, StateMachineError> {
if !self.init {
self.init = true;
self.machine.init(&mut self.context)?;
Ok(Some(&self.context))
} else if self.machine.is_finished() {
Ok(None)
} else {
self.machine.advance(&mut self.context)?;
if self.machine.is_finished() {
Ok(None)
} else {
Ok(Some(&self.context))
}
}
}
}
pub fn make_connector_selection_data<O: EuclidAnalysable>(
program: &dir::DirProgram<O>,
) -> Vec<Vec<(dir::DirValue, Metadata)>> {
program
.rules
.iter()
.map(|rule| {
rule.connector_selection
.get_dir_value_for_analysis(rule.name.clone())
})
.collect()
}
#[cfg(all(test, feature = "ast_parser"))]
mod tests {
#![allow(clippy::expect_used)]
use super::*;
use crate::{dirval, frontend::ast, types::DummyOutput};
#[test]
fn test_correct_contexts() {
let program_str = r#"
default: ["stripe", "adyen"]
stripe_first: ["stripe", "adyen"]
{
payment_method = wallet {
payment_method = (card, bank_redirect) {
currency = USD
currency = GBP
}
payment_method = pay_later {
capture_method = automatic
capture_method = manual
}
}
payment_method = card {
payment_method = (card, bank_redirect) & capture_method = (automatic, manual) {
currency = (USD, GBP)
}
}
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let lowered = ast::lowering::lower_program(program).expect("Lowering");
let selection_data = make_connector_selection_data(&lowered);
let mut state_machine = ProgramStateMachine::new(&lowered, &selection_data);
let mut ctx: types::ConjunctiveContext<'_> = Vec::new();
state_machine.init(&mut ctx).expect("State machine init");
let expected_contexts: Vec<Vec<dir::DirValue>> = vec![
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = Card),
dirval!(PaymentCurrency = USD),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = BankRedirect),
dirval!(PaymentCurrency = USD),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = Card),
dirval!(PaymentCurrency = GBP),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = BankRedirect),
dirval!(PaymentCurrency = GBP),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = PayLater),
dirval!(CaptureMethod = Automatic),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = PayLater),
dirval!(CaptureMethod = Manual),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Card),
dirval!(CaptureMethod = Automatic),
dirval!(PaymentCurrency = USD),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Card),
dirval!(CaptureMethod = Automatic),
dirval!(PaymentCurrency = GBP),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Card),
dirval!(CaptureMethod = Manual),
dirval!(PaymentCurrency = USD),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Card),
dirval!(CaptureMethod = Manual),
dirval!(PaymentCurrency = GBP),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = BankRedirect),
dirval!(CaptureMethod = Automatic),
dirval!(PaymentCurrency = USD),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = BankRedirect),
dirval!(CaptureMethod = Automatic),
dirval!(PaymentCurrency = GBP),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = BankRedirect),
dirval!(CaptureMethod = Manual),
dirval!(PaymentCurrency = USD),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = BankRedirect),
dirval!(CaptureMethod = Manual),
dirval!(PaymentCurrency = GBP),
],
];
let mut expected_idx = 0usize;
while !state_machine.is_finished() {
let values = ctx
.iter()
.flat_map(|c| match c.value {
types::CtxValueKind::Assertion(val) => vec![val],
types::CtxValueKind::Negation(vals) => vals.iter().collect(),
})
.collect::<Vec<&dir::DirValue>>();
assert_eq!(
values,
expected_contexts
.get(expected_idx)
.expect("Error deriving contexts")
.iter()
.collect::<Vec<&dir::DirValue>>()
);
expected_idx += 1;
state_machine
.advance(&mut ctx)
.expect("State Machine advance");
}
assert_eq!(expected_idx, 14);
let mut ctx_manager = AnalysisContextManager::new(&lowered, &selection_data);
expected_idx = 0;
while let Some(ctx) = ctx_manager.advance().expect("Context Manager Context") {
let values = ctx
.iter()
.flat_map(|c| match c.value {
types::CtxValueKind::Assertion(val) => vec![val],
types::CtxValueKind::Negation(vals) => vals.iter().collect(),
})
.collect::<Vec<&dir::DirValue>>();
assert_eq!(
values,
expected_contexts
.get(expected_idx)
.expect("Error deriving contexts")
.iter()
.collect::<Vec<&dir::DirValue>>()
);
expected_idx += 1;
}
assert_eq!(expected_idx, 14);
}
}
|
crates/euclid/src/dssa/state_machine.rs
|
euclid
|
full_file
| null | null | null | 4,797
| null | null | null | null | null | null | null |
// Implementation: impl ConnectorValidation for for Netcetera
// File: crates/hyperswitch_connectors/src/connectors/netcetera.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl ConnectorValidation for for Netcetera
|
crates/hyperswitch_connectors/src/connectors/netcetera.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Netcetera
|
ConnectorValidation for
| 0
| 0
| null | null |
// Implementation: impl api::ConnectorAccessToken for for Checkout
// File: crates/hyperswitch_connectors/src/connectors/checkout.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::ConnectorAccessToken for for Checkout
|
crates/hyperswitch_connectors/src/connectors/checkout.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 55
| null |
Checkout
|
api::ConnectorAccessToken for
| 0
| 0
| null | null |
// Struct: TrustpaymentsPaymentsRequest
// File: crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct TrustpaymentsPaymentsRequest
|
crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
TrustpaymentsPaymentsRequest
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// File: crates/test_utils/tests/connectors/checkout_ui.rs
// Module: test_utils
use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct CheckoutSeleniumTest;
impl SeleniumTest for CheckoutSeleniumTest {
fn get_connector_name(&self) -> String {
"checkout".to_string()
}
}
async fn should_make_frictionless_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
let mycon = CheckoutSeleniumTest {};
mycon
.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/18"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Google Search")),
Event::Trigger(Trigger::Sleep(5)), //url gets updated only after some time, so need this timeout to solve the issue
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
let mycon = CheckoutSeleniumTest {};
mycon
.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/20"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(5)), //url gets updated only after some time, so need this timeout to solve the issue
Event::Trigger(Trigger::SwitchFrame(By::Name("cko-3ds2-iframe"))),
Event::Trigger(Trigger::SendKeys(By::Id("password"), "Checkout1!")),
Event::Trigger(Trigger::Click(By::Id("txtButton"))),
Event::Trigger(Trigger::Sleep(2)),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let mycon = CheckoutSeleniumTest {};
mycon
.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/73"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(10)), //url gets updated only after some time, so need this timeout to solve the issue
Event::Trigger(Trigger::SwitchFrame(By::Name("cko-3ds2-iframe"))),
Event::Trigger(Trigger::SendKeys(By::Id("password"), "Checkout1!")),
Event::Trigger(Trigger::Click(By::Id("txtButton"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_frictionless_3ds_payment_test() {
tester!(should_make_frictionless_3ds_payment);
}
#[test]
#[serial]
fn should_make_3ds_payment_test() {
tester!(should_make_3ds_payment);
}
#[test]
#[serial]
#[ignore]
fn should_make_gpay_payment_test() {
tester!(should_make_gpay_payment);
}
|
crates/test_utils/tests/connectors/checkout_ui.rs
|
test_utils
|
full_file
| null | null | null | 816
| null | null | null | null | null | null | null |
// Implementation: impl api::Refund for for Stax
// File: crates/hyperswitch_connectors/src/connectors/stax.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::Refund for for Stax
|
crates/hyperswitch_connectors/src/connectors/stax.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Stax
|
api::Refund for
| 0
| 0
| null | null |
};
// Algorithm was in disabled state
let Some(algo_type_algorithm_id) = algo_type
.clone()
.get_algorithm_id_with_timestamp()
.algorithm_id
else {
return default_specific_dynamic_routing_setup(
state,
key_store,
business_profile,
feature_to_enable,
dynamic_routing_algo_ref,
dynamic_routing_type,
)
.await;
};
let db = state.store.as_ref();
let profile_id = business_profile.get_id().clone();
let algo_type_enabled_features = algo_type.get_enabled_features();
if *algo_type_enabled_features == feature_to_enable {
// algorithm already has the required feature
let routing_algorithm = db
.find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algo_type_algorithm_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let updated_routing_record = routing_algorithm.foreign_into();
return Ok(ApplicationResponse::Json(updated_routing_record));
};
*algo_type_enabled_features = feature_to_enable;
dynamic_routing_algo_ref.update_enabled_features(dynamic_routing_type, feature_to_enable);
update_business_profile_active_dynamic_algorithm_ref(
db,
&state.into(),
&key_store,
business_profile,
dynamic_routing_algo_ref.clone(),
)
.await?;
let routing_algorithm = db
.find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algo_type_algorithm_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let updated_routing_record = routing_algorithm.foreign_into();
core_metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(
1,
router_env::metric_attributes!(("profile_id", profile_id.clone())),
);
Ok(ApplicationResponse::Json(updated_routing_record))
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[instrument(skip_all)]
pub async fn default_specific_dynamic_routing_setup(
state: &SessionState,
key_store: domain::MerchantKeyStore,
business_profile: domain::Profile,
feature_to_enable: routing_types::DynamicRoutingFeatures,
mut dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
dynamic_routing_type: routing_types::DynamicRoutingType,
) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> {
let db = state.store.as_ref();
let key_manager_state = &state.into();
let profile_id = business_profile.get_id().clone();
let merchant_id = business_profile.merchant_id.clone();
let algorithm_id = common_utils::generate_routing_id_of_default_length();
let timestamp = common_utils::date_time::now();
let algo = match dynamic_routing_type {
routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
let default_success_based_routing_config =
if state.conf.open_router.dynamic_routing_enabled {
routing_types::SuccessBasedRoutingConfig::open_router_config_default()
} else {
routing_types::SuccessBasedRoutingConfig::default()
};
routing_algorithm::RoutingAlgorithm {
algorithm_id: algorithm_id.clone(),
profile_id: profile_id.clone(),
merchant_id,
name: SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),
description: None,
kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,
algorithm_data: serde_json::json!(default_success_based_routing_config),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: common_enums::TransactionType::Payment,
decision_engine_routing_id: None,
}
}
routing_types::DynamicRoutingType::EliminationRouting => {
let default_elimination_routing_config =
if state.conf.open_router.dynamic_routing_enabled {
routing_types::EliminationRoutingConfig::open_router_config_default()
} else {
routing_types::EliminationRoutingConfig::default()
};
routing_algorithm::RoutingAlgorithm {
algorithm_id: algorithm_id.clone(),
profile_id: profile_id.clone(),
merchant_id,
name: ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),
description: None,
kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,
algorithm_data: serde_json::json!(default_elimination_routing_config),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: common_enums::TransactionType::Payment,
decision_engine_routing_id: None,
}
}
routing_types::DynamicRoutingType::ContractBasedRouting => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Contract routing cannot be set as default".to_string(),
})
.into())
}
};
// Call to DE here
// Need to map out the cases if this call should always be made or not
if state.conf.open_router.dynamic_routing_enabled {
enable_decision_engine_dynamic_routing_setup(
state,
business_profile.get_id(),
dynamic_routing_type,
&mut dynamic_routing_algo_ref,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to setup decision engine dynamic routing")?;
}
let record = db
.insert_routing_algorithm(algo)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to insert record in routing algorithm table")?;
dynamic_routing_algo_ref.update_algorithm_id(
algorithm_id,
feature_to_enable,
dynamic_routing_type,
);
update_business_profile_active_dynamic_algorithm_ref(
db,
key_manager_state,
&key_store,
business_profile,
dynamic_routing_algo_ref,
)
.await?;
let new_record = record.foreign_into();
core_metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(
1,
router_env::metric_attributes!(("profile_id", profile_id.clone())),
);
Ok(ApplicationResponse::Json(new_record))
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[instrument(skip_all)]
pub async fn create_specific_dynamic_routing_setup(
state: &SessionState,
key_store: domain::MerchantKeyStore,
business_profile: domain::Profile,
feature_to_enable: routing_types::DynamicRoutingFeatures,
mut dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
dynamic_routing_type: routing_types::DynamicRoutingType,
payload: routing_types::DynamicRoutingPayload,
) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> {
let db = state.store.as_ref();
let key_manager_state = &state.into();
let profile_id = business_profile.get_id().clone();
let merchant_id = business_profile.merchant_id.clone();
let algorithm_id = common_utils::generate_routing_id_of_default_length();
let timestamp = common_utils::date_time::now();
let algo = match dynamic_routing_type {
routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
let success_config = match &payload {
routing_types::DynamicRoutingPayload::SuccessBasedRoutingPayload(config) => config,
_ => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid payload type for Success Rate Based Routing".to_string(),
})
.into())
}
};
routing_algorithm::RoutingAlgorithm {
algorithm_id: algorithm_id.clone(),
profile_id: profile_id.clone(),
merchant_id,
name: SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),
description: None,
kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,
algorithm_data: serde_json::json!(success_config),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: common_enums::TransactionType::Payment,
decision_engine_routing_id: None,
}
}
routing_types::DynamicRoutingType::EliminationRouting => {
let elimination_config = match &payload {
routing_types::DynamicRoutingPayload::EliminationRoutingPayload(config) => config,
_ => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid payload type for Elimination Routing".to_string(),
})
.into())
}
};
routing_algorithm::RoutingAlgorithm {
algorithm_id: algorithm_id.clone(),
profile_id: profile_id.clone(),
merchant_id,
name: ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),
description: None,
kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,
algorithm_data: serde_json::json!(elimination_config),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: common_enums::TransactionType::Payment,
decision_engine_routing_id: None,
}
}
routing_types::DynamicRoutingType::ContractBasedRouting => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Contract routing cannot be set as default".to_string(),
})
.into())
}
};
let record = db
.insert_routing_algorithm(algo)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to insert record in routing algorithm table")?;
dynamic_routing_algo_ref.update_feature(feature_to_enable, dynamic_routing_type);
update_business_profile_active_dynamic_algorithm_ref(
db,
key_manager_state,
&key_store,
business_profile,
dynamic_routing_algo_ref,
)
.await?;
let new_record = record.foreign_into();
core_metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(
1,
router_env::metric_attributes!(("profile_id", profile_id.clone())),
);
Ok(ApplicationResponse::Json(new_record))
}
#[derive(Debug, Clone)]
pub struct DynamicRoutingConfigParamsInterpolator {
pub payment_method: Option<common_enums::PaymentMethod>,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub authentication_type: Option<common_enums::AuthenticationType>,
pub currency: Option<common_enums::Currency>,
pub country: Option<common_enums::CountryAlpha2>,
pub card_network: Option<String>,
pub card_bin: Option<String>,
}
impl DynamicRoutingConfigParamsInterpolator {
pub fn new(
payment_method: Option<common_enums::PaymentMethod>,
payment_method_type: Option<common_enums::PaymentMethodType>,
authentication_type: Option<common_enums::AuthenticationType>,
currency: Option<common_enums::Currency>,
country: Option<common_enums::CountryAlpha2>,
card_network: Option<String>,
card_bin: Option<String>,
) -> Self {
Self {
payment_method,
payment_method_type,
authentication_type,
currency,
country,
card_network,
card_bin,
}
}
pub fn get_string_val(
&self,
params: &Vec<routing_types::DynamicRoutingConfigParams>,
) -> String {
let mut parts: Vec<String> = Vec::new();
for param in params {
let val = match param {
routing_types::DynamicRoutingConfigParams::PaymentMethod => self
.payment_method
.as_ref()
.map_or(String::new(), |pm| pm.to_string()),
routing_types::DynamicRoutingConfigParams::PaymentMethodType => self
.payment_method_type
.as_ref()
.map_or(String::new(), |pmt| pmt.to_string()),
routing_types::DynamicRoutingConfigParams::AuthenticationType => self
.authentication_type
.as_ref()
.map_or(String::new(), |at| at.to_string()),
routing_types::DynamicRoutingConfigParams::Currency => self
.currency
.as_ref()
.map_or(String::new(), |cur| cur.to_string()),
routing_types::DynamicRoutingConfigParams::Country => self
.country
.as_ref()
.map_or(String::new(), |cn| cn.to_string()),
routing_types::DynamicRoutingConfigParams::CardNetwork => {
self.card_network.clone().unwrap_or_default()
}
routing_types::DynamicRoutingConfigParams::CardBin => {
self.card_bin.clone().unwrap_or_default()
}
};
if !val.is_empty() {
parts.push(val);
}
}
parts.join(":")
}
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[instrument(skip_all)]
pub async fn enable_decision_engine_dynamic_routing_setup(
state: &SessionState,
profile_id: &id_type::ProfileId,
dynamic_routing_type: routing_types::DynamicRoutingType,
dynamic_routing_algo_ref: &mut routing_types::DynamicRoutingAlgorithmRef,
payload: Option<routing_types::DynamicRoutingPayload>,
) -> RouterResult<()> {
logger::debug!(
"performing call with open_router for profile {}",
profile_id.get_string_repr()
);
let decision_engine_config_request = match dynamic_routing_type {
routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
let success_based_routing_config = payload
.and_then(|p| match p {
routing_types::DynamicRoutingPayload::SuccessBasedRoutingPayload(config) => {
Some(config)
}
_ => None,
})
.unwrap_or_else(
routing_types::SuccessBasedRoutingConfig::open_router_config_default,
);
open_router::DecisionEngineConfigSetupRequest {
merchant_id: profile_id.get_string_repr().to_string(),
config: open_router::DecisionEngineConfigVariant::SuccessRate(
success_based_routing_config
.get_decision_engine_configs()
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Decision engine config not found".to_string(),
})
.attach_printable("Decision engine config not found")?,
),
}
}
routing_types::DynamicRoutingType::EliminationRouting => {
let elimination_based_routing_config = payload
.and_then(|p| match p {
routing_types::DynamicRoutingPayload::EliminationRoutingPayload(config) => {
Some(config)
}
_ => None,
})
.unwrap_or_else(
routing_types::EliminationRoutingConfig::open_router_config_default,
);
open_router::DecisionEngineConfigSetupRequest {
merchant_id: profile_id.get_string_repr().to_string(),
config: open_router::DecisionEngineConfigVariant::Elimination(
elimination_based_routing_config
.get_decision_engine_configs()
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Decision engine config not found".to_string(),
})
.attach_printable("Decision engine config not found")?,
),
}
}
routing_types::DynamicRoutingType::ContractBasedRouting => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Contract routing cannot be set as default".to_string(),
})
.into())
}
};
// Create merchant in Decision Engine if it is not already created
create_merchant_in_decision_engine_if_not_exists(state, profile_id, dynamic_routing_algo_ref)
.await;
routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>(
state,
services::Method::Post,
DECISION_ENGINE_RULE_CREATE_ENDPOINT,
Some(decision_engine_config_request),
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to setup decision engine dynamic routing")?;
Ok(())
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[instrument(skip_all)]
pub async fn update_decision_engine_dynamic_routing_setup(
state: &SessionState,
profile_id: &id_type::ProfileId,
request: serde_json::Value,
dynamic_routing_type: routing_types::DynamicRoutingType,
dynamic_routing_algo_ref: &mut routing_types::DynamicRoutingAlgorithmRef,
) -> RouterResult<()> {
logger::debug!(
"performing call with open_router for profile {}",
profile_id.get_string_repr()
);
let decision_engine_request = match dynamic_routing_type {
routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
let success_rate_config: routing_types::SuccessBasedRoutingConfig = request
.parse_value("SuccessBasedRoutingConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize SuccessBasedRoutingConfig")?;
open_router::DecisionEngineConfigSetupRequest {
merchant_id: profile_id.get_string_repr().to_string(),
config: open_router::DecisionEngineConfigVariant::SuccessRate(
success_rate_config
.get_decision_engine_configs()
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Decision engine config not found".to_string(),
})
.attach_printable("Decision engine config not found")?,
),
}
}
routing_types::DynamicRoutingType::EliminationRouting => {
let elimination_config: routing_types::EliminationRoutingConfig = request
.parse_value("EliminationRoutingConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize EliminationRoutingConfig")?;
open_router::DecisionEngineConfigSetupRequest {
merchant_id: profile_id.get_string_repr().to_string(),
config: open_router::DecisionEngineConfigVariant::Elimination(
elimination_config
.get_decision_engine_configs()
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Decision engine config not found".to_string(),
})
.attach_printable("Decision engine config not found")?,
),
}
}
routing_types::DynamicRoutingType::ContractBasedRouting => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Contract routing cannot be set as default".to_string(),
})
.into())
}
};
// Create merchant in Decision Engine if it is not already created
create_merchant_in_decision_engine_if_not_exists(state, profile_id, dynamic_routing_algo_ref)
.await;
routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>(
state,
services::Method::Post,
DECISION_ENGINE_RULE_UPDATE_ENDPOINT,
Some(decision_engine_request),
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update decision engine dynamic routing")?;
Ok(())
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn get_decision_engine_active_dynamic_routing_algorithm(
state: &SessionState,
profile_id: &id_type::ProfileId,
dynamic_routing_type: open_router::DecisionEngineDynamicAlgorithmType,
) -> RouterResult<Option<open_router::DecisionEngineConfigSetupRequest>> {
logger::debug!(
"decision_engine_euclid: GET api call for decision active {:?} routing algorithm",
dynamic_routing_type
);
let request = open_router::GetDecisionEngineConfigRequest {
merchant_id: profile_id.get_string_repr().to_owned(),
algorithm: dynamic_routing_type,
};
let response: Option<open_router::DecisionEngineConfigSetupRequest> =
routing_utils::ConfigApiClient::send_decision_engine_request(
state,
services::Method::Post,
DECISION_ENGINE_RULE_GET_ENDPOINT,
Some(request),
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get active dynamic algorithm from decision engine")?
.response;
Ok(response)
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[instrument(skip_all)]
pub async fn disable_decision_engine_dynamic_routing_setup(
state: &SessionState,
profile_id: &id_type::ProfileId,
dynamic_routing_type: routing_types::DynamicRoutingType,
dynamic_routing_algo_ref: &mut routing_types::DynamicRoutingAlgorithmRef,
) -> RouterResult<()> {
logger::debug!(
"performing call with open_router for profile {}",
profile_id.get_string_repr()
);
let decision_engine_request = open_router::FetchRoutingConfig {
merchant_id: profile_id.get_string_repr().to_string(),
algorithm: match dynamic_routing_type {
routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
open_router::AlgorithmType::SuccessRate
}
routing_types::DynamicRoutingType::EliminationRouting => {
open_router::AlgorithmType::Elimination
}
routing_types::DynamicRoutingType::ContractBasedRouting => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Contract routing is not enabled for decision engine".to_string(),
})
.into())
}
},
};
// Create merchant in Decision Engine if it is not already created
create_merchant_in_decision_engine_if_not_exists(state, profile_id, dynamic_routing_algo_ref)
.await;
routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>(
state,
services::Method::Post,
DECISION_ENGINE_RULE_DELETE_ENDPOINT,
Some(decision_engine_request),
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to disable decision engine dynamic routing")?;
Ok(())
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn create_merchant_in_decision_engine_if_not_exists(
state: &SessionState,
profile_id: &id_type::ProfileId,
dynamic_routing_algo_ref: &mut routing_types::DynamicRoutingAlgorithmRef,
) {
if !dynamic_routing_algo_ref.is_merchant_created_in_decision_engine {
logger::debug!(
"Creating merchant_account in decision engine for profile {}",
profile_id.get_string_repr()
);
create_decision_engine_merchant(state, profile_id)
.await
.map_err(|err| {
logger::warn!("Merchant creation error in decision_engine: {err:?}");
})
.ok();
// TODO: Update the status based on the status code or error message from the API call
dynamic_routing_algo_ref.update_merchant_creation_status_in_decision_engine(true);
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn create_decision_engine_merchant(
state: &SessionState,
profile_id: &id_type::ProfileId,
) -> RouterResult<()> {
let merchant_account_req = open_router::MerchantAccount {
merchant_id: profile_id.get_string_repr().to_string(),
gateway_success_rate_based_decider_input: None,
};
routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>(
state,
services::Method::Post,
DECISION_ENGINE_MERCHANT_CREATE_ENDPOINT,
Some(merchant_account_req),
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to create merchant account on decision engine")?;
Ok(())
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[instrument(skip_all)]
pub async fn delete_decision_engine_merchant(
state: &SessionState,
profile_id: &id_type::ProfileId,
) -> RouterResult<()> {
let path = format!(
"{}/{}",
DECISION_ENGINE_MERCHANT_BASE_ENDPOINT,
profile_id.get_string_repr()
);
routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>(
state,
services::Method::Delete,
&path,
None::<id_type::ProfileId>,
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to delete merchant account on decision engine")?;
Ok(())
}
|
crates/router/src/core/routing/helpers.rs#chunk2
|
router
|
chunk
| null | null | null | 5,050
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/gocardless.rs
// Module: hyperswitch_connectors
// Public functions: 1
// Public structs: 1
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use common_enums::enums;
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::{ByteSliceExt, BytesExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
CreateConnectorCustomer, PreProcessing,
},
router_request_types::{
AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData,
PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData, TokenizationRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, PaymentsSyncType, Response},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use masking::{Mask, PeekInterface};
use transformers as gocardless;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self, is_mandate_supported, PaymentMethodDataType},
};
#[derive(Clone)]
pub struct Gocardless {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Gocardless {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Gocardless {}
impl api::PaymentSession for Gocardless {}
impl api::ConnectorAccessToken for Gocardless {}
impl api::MandateSetup for Gocardless {}
impl api::PaymentAuthorize for Gocardless {}
impl api::PaymentSync for Gocardless {}
impl api::PaymentCapture for Gocardless {}
impl api::PaymentVoid for Gocardless {}
impl api::Refund for Gocardless {}
impl api::RefundExecute for Gocardless {}
impl api::RefundSync for Gocardless {}
impl api::PaymentToken for Gocardless {}
impl api::ConnectorCustomer for Gocardless {}
impl api::PaymentsPreProcessing for Gocardless {}
const GOCARDLESS_VERSION: &str = "2015-07-06";
const GOCARDLESS_VERSION_HEADER: &str = "GoCardless-Version";
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Gocardless
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
(
GOCARDLESS_VERSION_HEADER.to_string(),
GOCARDLESS_VERSION.to_string().into(),
),
];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Gocardless {
fn id(&self) -> &'static str {
"gocardless"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.gocardless.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = gocardless::GocardlessAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", auth.access_token.peek()).into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: gocardless::GocardlessErrorResponse = res
.response
.parse_struct("GocardlessErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_iter = response.error.errors.iter();
let mut error_reason: Vec<String> = Vec::new();
for error in error_iter {
let reason = error.field.clone().map_or(error.message.clone(), |field| {
format!("{} {}", field, error.message)
});
error_reason.push(reason)
}
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error.code.to_string(),
message: response.error.error_type,
reason: Some(error_reason.join("; ")),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>
for Gocardless
{
fn get_headers(
&self,
req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
_req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/customers", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &ConnectorCustomerRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = gocardless::GocardlessCustomerRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::ConnectorCustomerType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::ConnectorCustomerType::get_headers(
self, req, connectors,
)?)
.set_body(types::ConnectorCustomerType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &ConnectorCustomerRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>,
errors::ConnectorError,
>
where
CreateConnectorCustomer: Clone,
ConnectorCustomerData: Clone,
PaymentsResponseData: Clone,
{
let response: gocardless::GocardlessCustomerResponse = res
.response
.parse_struct("GocardlessCustomerResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Gocardless
{
fn get_headers(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
_req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/customer_bank_accounts",
self.base_url(connectors),
))
}
fn get_request_body(
&self,
req: &TokenizationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = gocardless::GocardlessBankAccountRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::TokenizationType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::TokenizationType::get_headers(self, req, connectors)?)
.set_body(types::TokenizationType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &TokenizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<TokenizationRouterData, errors::ConnectorError>
where
PaymentMethodToken: Clone,
PaymentMethodTokenizationData: Clone,
PaymentsResponseData: Clone,
{
let response: gocardless::GocardlessBankAccountResponse = res
.response
.parse_struct("GocardlessBankAccountResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
for Gocardless
{
}
impl ConnectorValidation for Gocardless {
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::SepaBankDebit,
PaymentMethodDataType::AchBankDebit,
PaymentMethodDataType::BecsBankDebit,
PaymentMethodDataType::BacsBankDebit,
]);
is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Gocardless {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Gocardless {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Gocardless
{
fn get_headers(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
_req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/mandates", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = gocardless::GocardlessMandateRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
// Preprocessing flow is to create mandate, which should to be called only in case of First mandate
if req.request.setup_mandate_details.is_some() {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::SetupMandateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::SetupMandateType::get_headers(self, req, connectors)?)
.set_body(types::SetupMandateType::get_request_body(
self, req, connectors,
)?)
.build(),
))
} else {
Ok(None)
}
}
fn handle_response(
&self,
data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
let response: gocardless::GocardlessMandateResponse = res
.response
.parse_struct("GocardlessMandateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Gocardless {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/payments", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = gocardless::GocardlessRouterData::from((amount, req));
let connector_req =
gocardless::GocardlessPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: gocardless::GocardlessPaymentsResponse = res
.response
.parse_struct("GocardlessPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Gocardless {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/payments/{}",
self.base_url(connectors),
req.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: gocardless::GocardlessPaymentsResponse = res
.response
.parse_struct("GocardlessPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Gocardless {}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Gocardless {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Gocardless {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/refunds", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = gocardless::GocardlessRouterData::from((refund_amount, req));
let connector_req = gocardless::GocardlessRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: gocardless::RefundResponse = res
.response
.parse_struct("gocardless RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Gocardless {
fn build_request(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(None)
}
}
#[async_trait::async_trait]
impl IncomingWebhook for Gocardless {
fn get_webhook_source_verification_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let signature = request
.headers
.get("Webhook-Signature")
.map(|header_value| {
header_value
.to_str()
.map(String::from)
.map_err(|_| errors::ConnectorError::WebhookSignatureNotFound)
})
.ok_or(errors::ConnectorError::WebhookSignatureNotFound)??;
hex::decode(signature).change_context(errors::ConnectorError::WebhookSignatureNotFound)
}
fn get_webhook_source_verification_message(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(format!("{}", String::from_utf8_lossy(request.body))
.as_bytes()
.to_vec())
}
fn get_webhook_object_reference_id(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
let details: gocardless::GocardlessWebhookEvent = request
.body
.parse_struct("GocardlessWebhookEvent")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let first_event = details
.events
.first()
.ok_or_else(|| errors::ConnectorError::WebhookReferenceIdNotFound)?;
let reference_id = match &first_event.links {
transformers::WebhooksLink::PaymentWebhooksLink(link) => {
let payment_id = api_models::payments::PaymentIdType::ConnectorTransactionId(
link.payment.to_owned(),
);
ObjectReferenceId::PaymentId(payment_id)
}
transformers::WebhooksLink::RefundWebhookLink(link) => {
let refund_id =
api_models::webhooks::RefundIdType::ConnectorRefundId(link.refund.to_owned());
ObjectReferenceId::RefundId(refund_id)
}
transformers::WebhooksLink::MandateWebhookLink(link) => {
let mandate_id = api_models::webhooks::MandateIdType::ConnectorMandateId(
link.mandate.to_owned(),
);
ObjectReferenceId::MandateId(mandate_id)
}
};
Ok(reference_id)
}
fn get_webhook_event_type(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let details: gocardless::GocardlessWebhookEvent = request
.body
.parse_struct("GocardlessWebhookEvent")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let first_event = details
.events
.first()
.ok_or_else(|| errors::ConnectorError::WebhookReferenceIdNotFound)?;
let event_type = match &first_event.action {
transformers::WebhookAction::PaymentsAction(action) => match action {
transformers::PaymentsAction::Created
| transformers::PaymentsAction::Submitted
| transformers::PaymentsAction::CustomerApprovalGranted => {
IncomingWebhookEvent::PaymentIntentProcessing
}
transformers::PaymentsAction::CustomerApprovalDenied
| transformers::PaymentsAction::Failed
| transformers::PaymentsAction::Cancelled
| transformers::PaymentsAction::LateFailureSettled => {
IncomingWebhookEvent::PaymentIntentFailure
}
transformers::PaymentsAction::Confirmed | transformers::PaymentsAction::PaidOut => {
IncomingWebhookEvent::PaymentIntentSuccess
}
transformers::PaymentsAction::SurchargeFeeDebited
| transformers::PaymentsAction::ResubmissionRequired => {
IncomingWebhookEvent::EventNotSupported
}
},
transformers::WebhookAction::RefundsAction(action) => match action {
transformers::RefundsAction::Failed => IncomingWebhookEvent::RefundFailure,
transformers::RefundsAction::Paid => IncomingWebhookEvent::RefundSuccess,
transformers::RefundsAction::RefundSettled
| transformers::RefundsAction::FundsReturned
| transformers::RefundsAction::Created => IncomingWebhookEvent::EventNotSupported,
},
transformers::WebhookAction::MandatesAction(action) => match action {
transformers::MandatesAction::Active | transformers::MandatesAction::Reinstated => {
IncomingWebhookEvent::MandateActive
}
transformers::MandatesAction::Expired
| transformers::MandatesAction::Cancelled
| transformers::MandatesAction::Failed
| transformers::MandatesAction::Consumed => IncomingWebhookEvent::MandateRevoked,
transformers::MandatesAction::Created
| transformers::MandatesAction::CustomerApprovalGranted
| transformers::MandatesAction::CustomerApprovalSkipped
| transformers::MandatesAction::Transferred
| transformers::MandatesAction::Submitted
| transformers::MandatesAction::ResubmissionRequested
| transformers::MandatesAction::Replaced
| transformers::MandatesAction::Blocked => IncomingWebhookEvent::EventNotSupported,
},
};
Ok(event_type)
}
fn get_webhook_resource_object(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let details: gocardless::GocardlessWebhookEvent = request
.body
.parse_struct("GocardlessWebhookEvent")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let first_event = details
.events
.first()
.ok_or_else(|| errors::ConnectorError::WebhookReferenceIdNotFound)?
.clone();
match first_event.resource_type {
transformers::WebhookResourceType::Payments => Ok(Box::new(
gocardless::GocardlessPaymentsResponse::try_from(&first_event)?,
)),
transformers::WebhookResourceType::Refunds
| transformers::WebhookResourceType::Mandates => Ok(Box::new(first_event)),
}
}
}
static GOCARDLESS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::SequentialAutomatic,
];
let mut gocardless_supported_payment_methods = SupportedPaymentMethods::new();
gocardless_supported_payment_methods.add(
enums::PaymentMethod::BankDebit,
enums::PaymentMethodType::Ach,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::Supported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
gocardless_supported_payment_methods.add(
enums::PaymentMethod::BankDebit,
enums::PaymentMethodType::Becs,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::Supported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
gocardless_supported_payment_methods.add(
enums::PaymentMethod::BankDebit,
enums::PaymentMethodType::Sepa,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::Supported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
gocardless_supported_payment_methods
});
static GOCARDLESS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "GoCardless",
description: "GoCardless is a fintech company that specialises in bank payments including recurring payments.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static GOCARDLESS_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 3] = [
enums::EventClass::Payments,
enums::EventClass::Refunds,
enums::EventClass::Mandates,
];
impl ConnectorSpecifications for Gocardless {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&GOCARDLESS_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*GOCARDLESS_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&GOCARDLESS_SUPPORTED_WEBHOOK_FLOWS)
}
fn should_call_connector_customer(
&self,
_payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> bool {
true
}
}
|
crates/hyperswitch_connectors/src/connectors/gocardless.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 7,371
| null | null | null | null | null | null | null |
// Function: add_entry_to_blocklist
// File: crates/router/src/core/blocklist.rs
// Module: router
pub fn add_entry_to_blocklist(
state: SessionState,
merchant_context: domain::MerchantContext,
body: api_blocklist::AddToBlocklistRequest,
) -> RouterResponse<api_blocklist::AddToBlocklistResponse>
|
crates/router/src/core/blocklist.rs
|
router
|
function_signature
| null | null | null | 76
|
add_entry_to_blocklist
| null | null | null | null | null | null |
// Function: add_order_by_clause
// File: crates/analytics/src/query.rs
// Module: analytics
pub fn add_order_by_clause(
&mut self,
column: impl ToSql<T>,
order: impl ToSql<T>,
) -> QueryResult<()>
|
crates/analytics/src/query.rs
|
analytics
|
function_signature
| null | null | null | 57
|
add_order_by_clause
| null | null | null | null | null | null |
// Implementation: impl api::Payment for for Novalnet
// File: crates/hyperswitch_connectors/src/connectors/novalnet.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::Payment for for Novalnet
|
crates/hyperswitch_connectors/src/connectors/novalnet.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Novalnet
|
api::Payment for
| 0
| 0
| null | null |
// Function: get_capture_body
// File: crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs
// Module: hyperswitch_connectors
pub fn get_capture_body(
req: &BamboraapacRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Vec<u8>, Error>
|
crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 72
|
get_capture_body
| null | null | null | null | null | null |
// Struct: ToggleDynamicRoutingPath
// File: crates/api_models/src/routing.rs
// Module: api_models
// Implementations: 0
pub struct ToggleDynamicRoutingPath
|
crates/api_models/src/routing.rs
|
api_models
|
struct_definition
|
ToggleDynamicRoutingPath
| 0
|
[] | 38
| null | null | null | null | null | null | null |
// Implementation: impl ConnectorCommon for for Zsl
// File: crates/hyperswitch_connectors/src/connectors/zsl.rs
// Module: hyperswitch_connectors
// Methods: 5 total (0 public)
impl ConnectorCommon for for Zsl
|
crates/hyperswitch_connectors/src/connectors/zsl.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 53
| null |
Zsl
|
ConnectorCommon for
| 5
| 0
| null | null |
// Implementation: impl api::PaymentToken for for Stax
// File: crates/hyperswitch_connectors/src/connectors/stax.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentToken for for Stax
|
crates/hyperswitch_connectors/src/connectors/stax.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Stax
|
api::PaymentToken for
| 0
| 0
| null | null |
// Function: insert
// File: crates/diesel_models/src/query/reverse_lookup.rs
// Module: diesel_models
pub fn insert(self, conn: &PgPooledConn) -> StorageResult<ReverseLookup>
|
crates/diesel_models/src/query/reverse_lookup.rs
|
diesel_models
|
function_signature
| null | null | null | 45
|
insert
| null | null | null | null | null | null |
// Function: get_role_with_groups
// File: crates/router/src/core/user_role/role.rs
// Module: router
pub fn get_role_with_groups(
state: SessionState,
user_from_token: UserFromToken,
role: role_api::GetRoleRequest,
) -> UserResponse<role_api::RoleInfoWithGroupsResponse>
|
crates/router/src/core/user_role/role.rs
|
router
|
function_signature
| null | null | null | 72
|
get_role_with_groups
| null | null | null | null | null | null |
// Struct: CardInfoResponse
// File: crates/api_models/src/cards_info.rs
// Module: api_models
// Implementations: 0
pub struct CardInfoResponse
|
crates/api_models/src/cards_info.rs
|
api_models
|
struct_definition
|
CardInfoResponse
| 0
|
[] | 36
| null | null | null | null | null | null | null |
// Implementation: impl SignatureCalculationData for for PaymentsRequest
// File: crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
// Module: hyperswitch_connectors
// Methods: 2 total (0 public)
impl SignatureCalculationData for for PaymentsRequest
|
crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
PaymentsRequest
|
SignatureCalculationData for
| 2
| 0
| null | null |
// Struct: Invoice
// File: crates/api_models/src/subscription.rs
// Module: api_models
// Implementations: 0
pub struct Invoice
|
crates/api_models/src/subscription.rs
|
api_models
|
struct_definition
|
Invoice
| 0
|
[] | 32
| null | null | null | null | null | null | null |
// Struct: AuthenticatePaymentFlowResponse
// File: crates/router/src/types.rs
// Module: router
// Implementations: 0
pub struct AuthenticatePaymentFlowResponse
|
crates/router/src/types.rs
|
router
|
struct_definition
|
AuthenticatePaymentFlowResponse
| 0
|
[] | 35
| null | null | null | null | null | null | null |
// File: crates/router/src/utils/user_role.rs
// Module: router
// Public functions: 15
use std::{
cmp,
collections::{HashMap, HashSet},
};
use api_models::user_role::role as role_api;
use common_enums::{EntityType, ParentGroup, PermissionGroup};
use common_utils::id_type;
use diesel_models::{
enums::{UserRoleVersion, UserStatus},
role::ListRolesByEntityPayload,
user_role::{UserRole, UserRoleUpdate},
};
use error_stack::{report, Report, ResultExt};
use router_env::logger;
use storage_impl::errors::StorageError;
use strum::IntoEnumIterator;
use crate::{
consts,
core::errors::{UserErrors, UserResult},
db::{
errors::StorageErrorExt,
user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload},
},
routes::SessionState,
services::authorization::{
self as authz,
permission_groups::{ParentGroupExt, PermissionGroupExt},
roles,
},
types::domain,
};
pub fn validate_role_groups(groups: &[PermissionGroup]) -> UserResult<()> {
if groups.is_empty() {
return Err(report!(UserErrors::InvalidRoleOperation))
.attach_printable("Role groups cannot be empty");
}
let unique_groups: HashSet<_> = groups.iter().copied().collect();
if unique_groups.contains(&PermissionGroup::OrganizationManage)
|| unique_groups.contains(&PermissionGroup::InternalManage)
{
return Err(report!(UserErrors::InvalidRoleOperation))
.attach_printable("Invalid groups present in the custom role");
}
if unique_groups.len() != groups.len() {
return Err(report!(UserErrors::InvalidRoleOperation))
.attach_printable("Duplicate permission group found");
}
Ok(())
}
pub async fn validate_role_name(
state: &SessionState,
role_name: &domain::RoleName,
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
tenant_id: &id_type::TenantId,
profile_id: &id_type::ProfileId,
entity_type: &EntityType,
) -> UserResult<()> {
let role_name_str = role_name.clone().get_role_name();
let is_present_in_predefined_roles = roles::predefined_roles::PREDEFINED_ROLES
.iter()
.any(|(_, role_info)| role_info.get_role_name() == role_name_str);
let entity_type_for_role = match entity_type {
EntityType::Tenant | EntityType::Organization => ListRolesByEntityPayload::Organization,
EntityType::Merchant => ListRolesByEntityPayload::Merchant(merchant_id.to_owned()),
EntityType::Profile => {
ListRolesByEntityPayload::Profile(merchant_id.to_owned(), profile_id.to_owned())
}
};
let is_present_in_custom_role = match state
.global_store
.generic_list_roles_by_entity_type(
entity_type_for_role,
false,
tenant_id.to_owned(),
org_id.to_owned(),
)
.await
{
Ok(roles_list) => roles_list
.iter()
.any(|role| role.role_name == role_name_str),
Err(e) => {
if e.current_context().is_db_not_found() {
false
} else {
return Err(UserErrors::InternalServerError.into());
}
}
};
if is_present_in_predefined_roles || is_present_in_custom_role {
return Err(UserErrors::RoleNameAlreadyExists.into());
}
Ok(())
}
pub async fn set_role_info_in_cache_by_user_role(
state: &SessionState,
user_role: &UserRole,
) -> bool {
let Some(ref org_id) = user_role.org_id else {
return false;
};
set_role_info_in_cache_if_required(
state,
user_role.role_id.as_str(),
org_id,
&user_role.tenant_id,
)
.await
.map_err(|e| logger::error!("Error setting permissions in cache {:?}", e))
.is_ok()
}
pub async fn set_role_info_in_cache_by_role_id_org_id(
state: &SessionState,
role_id: &str,
org_id: &id_type::OrganizationId,
tenant_id: &id_type::TenantId,
) -> bool {
set_role_info_in_cache_if_required(state, role_id, org_id, tenant_id)
.await
.map_err(|e| logger::error!("Error setting permissions in cache {:?}", e))
.is_ok()
}
pub async fn set_role_info_in_cache_if_required(
state: &SessionState,
role_id: &str,
org_id: &id_type::OrganizationId,
tenant_id: &id_type::TenantId,
) -> UserResult<()> {
if roles::predefined_roles::PREDEFINED_ROLES.contains_key(role_id) {
return Ok(());
}
let role_info =
roles::RoleInfo::from_role_id_org_id_tenant_id(state, role_id, org_id, tenant_id)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Error getting role_info from role_id")?;
authz::set_role_info_in_cache(
state,
role_id,
&role_info,
i64::try_from(consts::JWT_TOKEN_TIME_IN_SECS)
.change_context(UserErrors::InternalServerError)?,
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Error setting permissions in redis")
}
pub async fn update_v1_and_v2_user_roles_in_db(
state: &SessionState,
user_id: &str,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: Option<&id_type::MerchantId>,
profile_id: Option<&id_type::ProfileId>,
update: UserRoleUpdate,
) -> (
Result<UserRole, Report<StorageError>>,
Result<UserRole, Report<StorageError>>,
) {
let updated_v1_role = state
.global_store
.update_user_role_by_user_id_and_lineage(
user_id,
tenant_id,
org_id,
merchant_id,
profile_id,
update.clone(),
UserRoleVersion::V1,
)
.await
.map_err(|e| {
logger::error!("Error updating user_role {e:?}");
e
});
let updated_v2_role = state
.global_store
.update_user_role_by_user_id_and_lineage(
user_id,
tenant_id,
org_id,
merchant_id,
profile_id,
update,
UserRoleVersion::V2,
)
.await
.map_err(|e| {
logger::error!("Error updating user_role {e:?}");
e
});
(updated_v1_role, updated_v2_role)
}
pub async fn get_single_org_id(
state: &SessionState,
user_role: &UserRole,
) -> UserResult<id_type::OrganizationId> {
let (_, entity_type) = user_role
.get_entity_id_and_type()
.ok_or(UserErrors::InternalServerError)?;
match entity_type {
EntityType::Tenant => Ok(state
.store
.list_merchant_and_org_ids(&state.into(), 1, None)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to get merchants list for org")?
.pop()
.ok_or(UserErrors::InternalServerError)
.attach_printable("No merchants to get merchant or org id")?
.1),
EntityType::Organization | EntityType::Merchant | EntityType::Profile => user_role
.org_id
.clone()
.ok_or(UserErrors::InternalServerError)
.attach_printable("Org_id not found"),
}
}
pub async fn get_single_merchant_id(
state: &SessionState,
user_role: &UserRole,
org_id: &id_type::OrganizationId,
) -> UserResult<id_type::MerchantId> {
let (_, entity_type) = user_role
.get_entity_id_and_type()
.ok_or(UserErrors::InternalServerError)?;
match entity_type {
EntityType::Tenant | EntityType::Organization => Ok(state
.store
.list_merchant_accounts_by_organization_id(&state.into(), org_id)
.await
.to_not_found_response(UserErrors::InvalidRoleOperationWithMessage(
"Invalid Org Id".to_string(),
))?
.first()
.ok_or(UserErrors::InternalServerError)
.attach_printable("No merchants found for org_id")?
.get_id()
.clone()),
EntityType::Merchant | EntityType::Profile => user_role
.merchant_id
.clone()
.ok_or(UserErrors::InternalServerError)
.attach_printable("merchant_id not found"),
}
}
pub async fn get_single_profile_id(
state: &SessionState,
user_role: &UserRole,
merchant_id: &id_type::MerchantId,
) -> UserResult<id_type::ProfileId> {
let (_, entity_type) = user_role
.get_entity_id_and_type()
.ok_or(UserErrors::InternalServerError)?;
match entity_type {
EntityType::Tenant | EntityType::Organization | EntityType::Merchant => {
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
&state.into(),
merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(UserErrors::InternalServerError)?;
Ok(state
.store
.list_profile_by_merchant_id(&state.into(), &key_store, merchant_id)
.await
.change_context(UserErrors::InternalServerError)?
.pop()
.ok_or(UserErrors::InternalServerError)?
.get_id()
.to_owned())
}
EntityType::Profile => user_role
.profile_id
.clone()
.ok_or(UserErrors::InternalServerError)
.attach_printable("profile_id not found"),
}
}
pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite(
state: &SessionState,
user_id: &str,
tenant_id: &id_type::TenantId,
entity_id: String,
entity_type: EntityType,
) -> UserResult<
Option<(
id_type::OrganizationId,
Option<id_type::MerchantId>,
Option<id_type::ProfileId>,
)>,
> {
match entity_type {
EntityType::Tenant => Err(UserErrors::InvalidRoleOperationWithMessage(
"Tenant roles are not allowed for this operation".to_string(),
)
.into()),
EntityType::Organization => {
let Ok(org_id) =
id_type::OrganizationId::try_from(std::borrow::Cow::from(entity_id.clone()))
else {
return Ok(None);
};
let user_roles = state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id,
tenant_id,
org_id: Some(&org_id),
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: Some(UserStatus::InvitationSent),
limit: None,
})
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.collect::<HashSet<_>>();
if user_roles.len() > 1 {
return Ok(None);
}
if let Some(user_role) = user_roles.into_iter().next() {
let (_entity_id, entity_type) = user_role
.get_entity_id_and_type()
.ok_or(UserErrors::InternalServerError)?;
if entity_type != EntityType::Organization {
return Ok(None);
}
return Ok(Some((
user_role.org_id.ok_or(UserErrors::InternalServerError)?,
None,
None,
)));
}
Ok(None)
}
EntityType::Merchant => {
let Ok(merchant_id) = id_type::MerchantId::wrap(entity_id) else {
return Ok(None);
};
let user_roles = state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id,
tenant_id,
org_id: None,
merchant_id: Some(&merchant_id),
profile_id: None,
entity_id: None,
version: None,
status: Some(UserStatus::InvitationSent),
limit: None,
})
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.collect::<HashSet<_>>();
if user_roles.len() > 1 {
return Ok(None);
}
if let Some(user_role) = user_roles.into_iter().next() {
let (_entity_id, entity_type) = user_role
.get_entity_id_and_type()
.ok_or(UserErrors::InternalServerError)?;
if entity_type != EntityType::Merchant {
return Ok(None);
}
return Ok(Some((
user_role.org_id.ok_or(UserErrors::InternalServerError)?,
Some(merchant_id),
None,
)));
}
Ok(None)
}
EntityType::Profile => {
let Ok(profile_id) = id_type::ProfileId::try_from(std::borrow::Cow::from(entity_id))
else {
return Ok(None);
};
let user_roles = state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id,
tenant_id: &state.tenant.tenant_id,
org_id: None,
merchant_id: None,
profile_id: Some(&profile_id),
entity_id: None,
version: None,
status: Some(UserStatus::InvitationSent),
limit: None,
})
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.collect::<HashSet<_>>();
if user_roles.len() > 1 {
return Ok(None);
}
if let Some(user_role) = user_roles.into_iter().next() {
let (_entity_id, entity_type) = user_role
.get_entity_id_and_type()
.ok_or(UserErrors::InternalServerError)?;
if entity_type != EntityType::Profile {
return Ok(None);
}
return Ok(Some((
user_role.org_id.ok_or(UserErrors::InternalServerError)?,
Some(
user_role
.merchant_id
.ok_or(UserErrors::InternalServerError)?,
),
Some(profile_id),
)));
}
Ok(None)
}
}
}
pub async fn get_single_merchant_id_and_profile_id(
state: &SessionState,
user_role: &UserRole,
) -> UserResult<(id_type::MerchantId, id_type::ProfileId)> {
let org_id = get_single_org_id(state, user_role).await?;
let merchant_id = get_single_merchant_id(state, user_role, &org_id).await?;
let profile_id = get_single_profile_id(state, user_role, &merchant_id).await?;
Ok((merchant_id, profile_id))
}
pub async fn fetch_user_roles_by_payload(
state: &SessionState,
payload: ListUserRolesByOrgIdPayload<'_>,
request_entity_type: Option<EntityType>,
) -> UserResult<HashSet<UserRole>> {
Ok(state
.global_store
.list_user_roles_by_org_id(payload)
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.filter_map(|user_role| {
let (_entity_id, entity_type) = user_role.get_entity_id_and_type()?;
request_entity_type
.is_none_or(|req_entity_type| entity_type == req_entity_type)
.then_some(user_role)
})
.collect::<HashSet<_>>())
}
pub fn get_min_entity(
user_entity: EntityType,
filter_entity: Option<EntityType>,
) -> UserResult<EntityType> {
let Some(filter_entity) = filter_entity else {
return Ok(user_entity);
};
if user_entity < filter_entity {
return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
"{user_entity} level user requesting data for {filter_entity:?} level",
));
}
Ok(cmp::min(user_entity, filter_entity))
}
pub fn parent_group_info_request_to_permission_groups(
parent_groups: &[role_api::ParentGroupInfoRequest],
) -> Result<Vec<PermissionGroup>, UserErrors> {
parent_groups
.iter()
.try_fold(Vec::new(), |mut permission_groups, parent_group| {
let scopes = &parent_group.scopes;
if scopes.is_empty() {
return Err(UserErrors::InvalidRoleOperation);
}
let available_scopes = parent_group.name.get_available_scopes();
if !scopes.iter().all(|scope| available_scopes.contains(scope)) {
return Err(UserErrors::InvalidRoleOperation);
}
let groups = PermissionGroup::iter()
.filter(|group| {
group.parent() == parent_group.name && scopes.contains(&group.scope())
})
.collect::<Vec<_>>();
permission_groups.extend(groups);
Ok(permission_groups)
})
}
pub fn permission_groups_to_parent_group_info(
permission_groups: &[PermissionGroup],
entity_type: EntityType,
) -> Vec<role_api::ParentGroupInfo> {
let parent_groups_map: HashMap<ParentGroup, Vec<common_enums::PermissionScope>> =
permission_groups
.iter()
.fold(HashMap::new(), |mut acc, group| {
let parent = group.parent();
let scope = group.scope();
acc.entry(parent).or_default().push(scope);
acc
});
parent_groups_map
.into_iter()
.filter_map(|(name, scopes)| {
let unique_scopes = scopes
.into_iter()
.collect::<HashSet<_>>()
.into_iter()
.collect();
let description =
ParentGroup::get_descriptions_for_groups(entity_type, permission_groups.to_vec())
.and_then(|descriptions| descriptions.get(&name).cloned())?;
Some(role_api::ParentGroupInfo {
name,
description,
scopes: unique_scopes,
})
})
.collect()
}
|
crates/router/src/utils/user_role.rs
|
router
|
full_file
| null | null | null | 3,897
| null | null | null | null | null | null | null |
// Function: retrieve_disputes_list
// File: crates/router/src/routes/disputes.rs
// Module: router
pub fn retrieve_disputes_list(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<dispute_models::DisputeListGetConstraints>,
) -> HttpResponse
|
crates/router/src/routes/disputes.rs
|
router
|
function_signature
| null | null | null | 68
|
retrieve_disputes_list
| null | null | null | null | null | null |
// Struct: SilverflowRefundRequest
// File: crates/hyperswitch_connectors/src/connectors/silverflow/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct SilverflowRefundRequest
|
crates/hyperswitch_connectors/src/connectors/silverflow/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
SilverflowRefundRequest
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Function: payment_method_update_api
// File: crates/openapi/src/routes/payment_method.rs
// Module: openapi
pub fn payment_method_update_api()
|
crates/openapi/src/routes/payment_method.rs
|
openapi
|
function_signature
| null | null | null | 33
|
payment_method_update_api
| null | null | null | null | null | null |
// Module Structure
// File: crates/hyperswitch_connectors/src/connectors/cashtocode.rs
// Module: hyperswitch_connectors
// Public submodules:
pub mod transformers;
|
crates/hyperswitch_connectors/src/connectors/cashtocode.rs
|
hyperswitch_connectors
|
module_structure
| null | null | null | 40
| null | null | null | null | null | 1
| 0
|
// Implementation: impl webhooks::IncomingWebhook for for Amazonpay
// File: crates/hyperswitch_connectors/src/connectors/amazonpay.rs
// Module: hyperswitch_connectors
// Methods: 3 total (0 public)
impl webhooks::IncomingWebhook for for Amazonpay
|
crates/hyperswitch_connectors/src/connectors/amazonpay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 62
| null |
Amazonpay
|
webhooks::IncomingWebhook for
| 3
| 0
| null | null |
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
let customer_details = payout_data.customer_details.to_owned();
let connector_name = connector_data.connector_name.to_string();
// Create the connector label using {profile_id}_{connector_name}
let connector_label = format!(
"{}_{}",
payout_data.profile_id.get_string_repr(),
connector_name
);
let (should_call_connector, _connector_customer_id) =
helpers::should_call_payout_connector_create_customer(
state,
connector_data,
&customer_details,
&connector_label,
);
if should_call_connector {
// 1. Form router data
let router_data = core_utils::construct_payout_router_data(
state,
connector_data,
merchant_context,
payout_data,
)
.await?;
// 2. Fetch connector integration details
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoRecipient,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
// 3. Call connector service
let router_resp = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payout_failed_response()?;
match router_resp.response {
Ok(recipient_create_data) => {
let db = &*state.store;
if let Some(customer) = customer_details {
if let Some(updated_customer) =
customers::update_connector_customer_in_customers(
&connector_label,
Some(&customer),
recipient_create_data.connector_payout_id.clone(),
)
.await
{
#[cfg(feature = "v1")]
{
let customer_id = customer.customer_id.to_owned();
payout_data.customer_details = Some(
db.update_customer_by_customer_id_merchant_id(
&state.into(),
customer_id,
merchant_context.get_merchant_account().get_id().to_owned(),
customer,
updated_customer,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating customers in db")?,
);
}
#[cfg(feature = "v2")]
{
let customer_id = customer.get_id().clone();
payout_data.customer_details = Some(
db.update_customer_by_global_id(
&state.into(),
&customer_id,
customer,
updated_customer,
key_store,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating customers in db")?,
);
}
}
}
// Add next step to ProcessTracker
if recipient_create_data.should_add_next_step_to_process_tracker {
add_external_account_addition_task(
&*state.store,
payout_data,
common_utils::date_time::now().saturating_add(Duration::seconds(consts::STRIPE_ACCOUNT_ONBOARDING_DELAY_IN_SECONDS)),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while adding attach_payout_account_workflow workflow to process tracker")?;
// Update payout status in DB
let status = recipient_create_data
.status
.unwrap_or(api_enums::PayoutStatus::RequiresVendorAccountCreation);
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data
.payout_attempt
.connector_payout_id
.to_owned(),
status,
error_code: None,
error_message: None,
is_eligible: recipient_create_data.payout_eligible,
unified_code: None,
unified_message: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
// Helps callee functions skip the execution
payout_data.should_terminate = true;
} else if let Some(status) = recipient_create_data.status {
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data
.payout_attempt
.connector_payout_id
.to_owned(),
status,
error_code: None,
error_message: None,
is_eligible: recipient_create_data.payout_eligible,
unified_code: None,
unified_message: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
}
}
Err(err) => {
let status = storage_enums::PayoutStatus::Failed;
let (error_code, error_message) = (Some(err.code), Some(err.message));
let (unified_code, unified_message) = helpers::get_gsm_record(
state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
consts::PAYOUT_FLOW_STR,
)
.await
.map_or(
(
Some(crate::consts::DEFAULT_UNIFIED_ERROR_CODE.to_string()),
Some(crate::consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_string()),
),
|gsm| (gsm.unified_code, gsm.unified_message),
);
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(),
status,
error_code,
error_message,
is_eligible: None,
unified_code: unified_code
.map(UnifiedCode::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_code",
})?,
unified_message: unified_message
.map(UnifiedMessage::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_message",
})?,
};
let db = &*state.store;
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
}
}
}
Ok(())
}
#[cfg(feature = "v2")]
pub async fn create_recipient(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
todo!()
}
pub async fn complete_payout_eligibility(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
let payout_attempt = &payout_data.payout_attempt.to_owned();
if !payout_data.should_terminate
&& payout_attempt.is_eligible.is_none()
&& connector_data
.connector_name
.supports_payout_eligibility(payout_data.payouts.payout_type)
{
Box::pin(check_payout_eligibility(
state,
merchant_context,
connector_data,
payout_data,
))
.await
.attach_printable("Eligibility failed for given Payout request")?;
}
utils::when(
!payout_attempt
.is_eligible
.unwrap_or(state.conf.payouts.payout_eligibility),
|| {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Payout method data is invalid".to_string(),
})
.attach_printable("Payout data provided is invalid"))
},
)?;
Ok(())
}
pub async fn check_payout_eligibility(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
// 1. Form Router data
let router_data = core_utils::construct_payout_router_data(
state,
connector_data,
merchant_context,
payout_data,
)
.await?;
// 2. Fetch connector integration details
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoEligibility,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
// 3. Call connector service
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payout_failed_response()?;
// 4. Process data returned by the connector
let db = &*state.store;
match router_data_resp.response {
Ok(payout_response_data) => {
let payout_attempt = &payout_data.payout_attempt;
let status = payout_response_data
.status
.unwrap_or(payout_attempt.status.to_owned());
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id,
status,
error_code: payout_response_data.error_code,
error_message: payout_response_data.error_message,
is_eligible: payout_response_data.payout_eligible,
unified_code: None,
unified_message: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
}
Err(err) => {
let status = storage_enums::PayoutStatus::Failed;
let (error_code, error_message) = (Some(err.code), Some(err.message));
let (unified_code, unified_message) = helpers::get_gsm_record(
state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
consts::PAYOUT_FLOW_STR,
)
.await
.map_or(
(
Some(crate::consts::DEFAULT_UNIFIED_ERROR_CODE.to_string()),
Some(crate::consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_string()),
),
|gsm| (gsm.unified_code, gsm.unified_message),
);
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(),
status,
error_code,
error_message,
is_eligible: Some(false),
unified_code: unified_code
.map(UnifiedCode::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_code",
})?,
unified_message: unified_message
.map(UnifiedMessage::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_message",
})?,
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
}
};
Ok(())
}
pub async fn complete_create_payout(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
if !payout_data.should_terminate
&& matches!(
payout_data.payout_attempt.status,
storage_enums::PayoutStatus::RequiresCreation
| storage_enums::PayoutStatus::RequiresConfirmation
| storage_enums::PayoutStatus::RequiresPayoutMethodData
)
{
if connector_data
.connector_name
.supports_instant_payout(payout_data.payouts.payout_type)
{
// create payout_object only in router
let db = &*state.store;
let payout_attempt = &payout_data.payout_attempt;
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.clone(),
status: storage::enums::PayoutStatus::RequiresFulfillment,
error_code: None,
error_message: None,
is_eligible: None,
unified_code: None,
unified_message: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate {
status: storage::enums::PayoutStatus::RequiresFulfillment,
},
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
} else {
// create payout_object in connector as well as router
Box::pin(create_payout(
state,
merchant_context,
connector_data,
payout_data,
))
.await
.attach_printable("Payout creation failed for given Payout request")?;
}
}
Ok(())
}
pub async fn create_payout(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
// 1. Form Router data
let mut router_data = core_utils::construct_payout_router_data(
state,
connector_data,
merchant_context,
payout_data,
)
.await?;
// 2. Get/Create access token
access_token::create_access_token(
state,
connector_data,
merchant_context,
&mut router_data,
payout_data.payouts.payout_type.to_owned(),
)
.await?;
// 3. Fetch connector integration details
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoCreate,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
// 4. Execute pretasks
complete_payout_quote_steps_if_required(state, connector_data, &mut router_data).await?;
// 5. Call connector service
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payout_failed_response()?;
// 6. Process data returned by the connector
let db = &*state.store;
match router_data_resp.response {
Ok(payout_response_data) => {
let payout_attempt = &payout_data.payout_attempt;
let status = payout_response_data
.status
.unwrap_or(payout_attempt.status.to_owned());
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id,
status,
error_code: payout_response_data.error_code,
error_message: payout_response_data.error_message,
is_eligible: payout_response_data.payout_eligible,
unified_code: None,
unified_message: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
}
Err(err) => {
let status = storage_enums::PayoutStatus::Failed;
let (error_code, error_message) = (Some(err.code), Some(err.message));
let (unified_code, unified_message) = helpers::get_gsm_record(
state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
consts::PAYOUT_FLOW_STR,
)
.await
.map_or(
(
Some(crate::consts::DEFAULT_UNIFIED_ERROR_CODE.to_string()),
Some(crate::consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_string()),
),
|gsm| (gsm.unified_code, gsm.unified_message),
);
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(),
status,
error_code,
error_message,
is_eligible: None,
unified_code: unified_code
.map(UnifiedCode::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_code",
})?,
unified_message: unified_message
.map(UnifiedMessage::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_message",
})?,
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
}
};
Ok(())
}
async fn complete_payout_quote_steps_if_required<F>(
state: &SessionState,
connector_data: &api::ConnectorData,
router_data: &mut types::RouterData<F, types::PayoutsData, types::PayoutsResponseData>,
) -> RouterResult<()> {
if connector_data
.connector_name
.is_payout_quote_call_required()
{
let quote_router_data =
types::PayoutsRouterData::foreign_from((router_data, router_data.request.clone()));
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoQuote,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
"e_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payout_failed_response()?;
match router_data_resp.response.to_owned() {
Ok(resp) => {
router_data.quote_id = resp.connector_payout_id;
}
Err(_err) => {
router_data.response = router_data_resp.response;
}
};
}
Ok(())
}
#[cfg(feature = "v1")]
pub async fn complete_payout_retrieve(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_call_type: api::ConnectorCallType,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
match connector_call_type {
api::ConnectorCallType::PreDetermined(routing_data) => {
create_payout_retrieve(
state,
merchant_context,
&routing_data.connector_data,
payout_data,
)
.await
.attach_printable("Payout retrieval failed for given Payout request")?;
}
api::ConnectorCallType::Retryable(_) | api::ConnectorCallType::SessionMultiple(_) => {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Payout retrieval not supported for given ConnectorCallType")?
}
}
Ok(())
}
#[cfg(feature = "v2")]
pub async fn complete_payout_retrieve(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_call_type: api::ConnectorCallType,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
todo!()
}
pub async fn create_payout_retrieve(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
// 1. Form Router data
let mut router_data = core_utils::construct_payout_router_data(
state,
connector_data,
merchant_context,
payout_data,
)
.await?;
// 2. Get/Create access token
access_token::create_access_token(
state,
connector_data,
merchant_context,
&mut router_data,
payout_data.payouts.payout_type.to_owned(),
)
.await?;
// 3. Fetch connector integration details
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoSync,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
// 4. Call connector service
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payout_failed_response()?;
// 5. Process data returned by the connector
update_retrieve_payout_tracker(state, merchant_context, payout_data, &router_data_resp).await?;
Ok(())
}
pub async fn update_retrieve_payout_tracker<F, T>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payout_data: &mut PayoutData,
payout_router_data: &types::RouterData<F, T, types::PayoutsResponseData>,
) -> RouterResult<()> {
let db = &*state.store;
match payout_router_data.response.as_ref() {
Ok(payout_response_data) => {
let payout_attempt = &payout_data.payout_attempt;
let status = payout_response_data
.status
.unwrap_or(payout_attempt.status.to_owned());
let updated_payout_attempt = if helpers::is_payout_err_state(status) {
let (error_code, error_message) = (
payout_response_data.error_code.clone(),
payout_response_data.error_message.clone(),
);
let (unified_code, unified_message) = helpers::get_gsm_record(
state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
consts::PAYOUT_FLOW_STR,
)
.await
.map_or(
(
Some(crate::consts::DEFAULT_UNIFIED_ERROR_CODE.to_string()),
Some(crate::consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_string()),
),
|gsm| (gsm.unified_code, gsm.unified_message),
);
storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id.clone(),
status,
error_code,
error_message,
is_eligible: payout_response_data.payout_eligible,
unified_code: unified_code
.map(UnifiedCode::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_code",
})?,
unified_message: unified_message
.map(UnifiedMessage::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_message",
})?,
}
} else {
storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id.clone(),
status,
error_code: None,
error_message: None,
is_eligible: payout_response_data.payout_eligible,
unified_code: None,
unified_message: None,
}
};
payout_data.payout_attempt = db
.update_payout_attempt(
payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
}
Err(err) => {
// log in case of error in retrieval
logger::error!("Error in payout retrieval");
// show error in the response of sync
payout_data.payout_attempt.error_code = Some(err.code.to_owned());
payout_data.payout_attempt.error_message = Some(err.message.to_owned());
}
};
Ok(())
}
pub async fn complete_create_recipient_disburse_account(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
if !payout_data.should_terminate
&& matches!(
payout_data.payout_attempt.status,
storage_enums::PayoutStatus::RequiresVendorAccountCreation
| storage_enums::PayoutStatus::RequiresCreation
)
&& connector_data
.connector_name
.supports_vendor_disburse_account_create_for_payout()
&& helpers::should_create_connector_transfer_method(payout_data, connector_data)?.is_none()
{
Box::pin(create_recipient_disburse_account(
state,
merchant_context,
connector_data,
payout_data,
))
.await
.attach_printable("Creation of customer failed")?;
}
Ok(())
}
pub async fn create_recipient_disburse_account(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
// 1. Form Router data
let router_data = core_utils::construct_payout_router_data(
state,
connector_data,
merchant_context,
payout_data,
)
.await?;
// 2. Fetch connector integration details
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoRecipientAccount,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
// 3. Call connector service
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payout_failed_response()?;
// 4. Process data returned by the connector
let db = &*state.store;
match router_data_resp.response {
Ok(payout_response_data) => {
let payout_attempt = &payout_data.payout_attempt;
let status = payout_response_data
.status
.unwrap_or(payout_attempt.status.to_owned());
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id.clone(),
status,
error_code: payout_response_data.error_code,
error_message: payout_response_data.error_message,
is_eligible: payout_response_data.payout_eligible,
unified_code: None,
unified_message: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
if let (
true,
Some(ref payout_method_data),
Some(connector_payout_id),
Some(customer_details),
Some(merchant_connector_id),
) = (
payout_data.payouts.recurring,
payout_data.payout_method_data.clone(),
payout_response_data.connector_payout_id.clone(),
payout_data.customer_details.clone(),
connector_data.merchant_connector_id.clone(),
) {
let connector_mandate_details = HashMap::from([(
merchant_connector_id.clone(),
PayoutsMandateReferenceRecord {
transfer_method_id: Some(connector_payout_id),
},
)]);
let common_connector_mandate = CommonMandateReference {
payments: None,
payouts: Some(PayoutsMandateReference(connector_mandate_details)),
};
let connector_mandate_details_value = common_connector_mandate
.get_mandate_details_value()
.map_err(|err| {
router_env::logger::error!(
"Failed to get get_mandate_details_value : {:?}",
err
);
errors::ApiErrorResponse::MandateUpdateFailed
})?;
if let Some(pm_method) = payout_data.payment_method.clone() {
let pm_update =
diesel_models::PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
#[cfg(feature = "v1")]
connector_mandate_details: Some(connector_mandate_details_value),
#[cfg(feature = "v2")]
connector_mandate_details: Some(common_connector_mandate),
};
payout_data.payment_method = Some(
db.update_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
pm_method,
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Unable to find payment method")?,
);
} else {
#[cfg(feature = "v1")]
let customer_id = Some(customer_details.customer_id);
#[cfg(feature = "v2")]
let customer_id = customer_details.merchant_reference_id;
if let Some(customer_id) = customer_id {
helpers::save_payout_data_to_locker(
state,
payout_data,
&customer_id,
payout_method_data,
Some(connector_mandate_details_value),
merchant_context,
)
.await
.attach_printable("Failed to save payout data to locker")?;
}
};
}
}
Err(err) => {
let (error_code, error_message) = (Some(err.code), Some(err.message));
let (unified_code, unified_message) = helpers::get_gsm_record(
state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
consts::PAYOUT_FLOW_STR,
)
.await
.map_or(
(
Some(crate::consts::DEFAULT_UNIFIED_ERROR_CODE.to_string()),
Some(crate::consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_string()),
),
|gsm| (gsm.unified_code, gsm.unified_message),
);
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(),
status: storage_enums::PayoutStatus::Failed,
error_code,
error_message,
is_eligible: None,
unified_code: unified_code
.map(UnifiedCode::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_code",
})?,
unified_message: unified_message
.map(UnifiedMessage::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_message",
})?,
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
}
};
Ok(())
}
pub async fn cancel_payout(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
// 1. Form Router data
let router_data = core_utils::construct_payout_router_data(
state,
connector_data,
merchant_context,
payout_data,
)
.await?;
// 2. Fetch connector integration details
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoCancel,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
// 3. Call connector service
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payout_failed_response()?;
// 4. Process data returned by the connector
let db = &*state.store;
|
crates/router/src/core/payouts.rs#chunk1
|
router
|
chunk
| null | null | null | 8,188
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/paypal.rs
// Module: hyperswitch_connectors
// Public functions: 2
// Public structs: 1
pub mod transformers;
use std::{fmt::Write, sync::LazyLock};
use base64::Engine;
use common_enums::{enums, CallConnectorAction, PaymentAction};
use common_utils::{
consts,
errors::CustomResult,
ext_traits::ByteSliceExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{
AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector, StringMinorUnit,
StringMinorUnitForConnector,
},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{
Authorize, Capture, IncrementalAuthorization, PSync, PaymentMethodToken,
PostSessionTokens, PreProcessing, SdkSessionUpdate, Session, SetupMandate, Void,
},
refunds::{Execute, RSync},
CompleteAuthorize, VerifyWebhookSource,
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
PaymentsIncrementalAuthorizationData, PaymentsPostSessionTokensData,
PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, ResponseId,
SdkPaymentsSessionUpdateData, SetupMandateRequestData, VerifyWebhookSourceRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt, VerifyWebhookSourceResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsIncrementalAuthorizationRouterData,
PaymentsPostSessionTokensRouterData, PaymentsPreProcessingRouterData,
PaymentsSyncRouterData, RefreshTokenRouterData, RefundSyncRouterData, RefundsRouterData,
SdkSessionUpdateRouterData, SetupMandateRouterData, VerifyWebhookSourceRouterData,
},
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::payouts::{PoCreate, PoFulfill, PoSync},
router_response_types::PayoutsResponseData,
types::{PayoutsData, PayoutsRouterData},
};
#[cfg(feature = "payouts")]
use hyperswitch_interfaces::types::{PayoutFulfillType, PayoutSyncType};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation, PaymentIncrementalAuthorization,
},
configs::Connectors,
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
disputes, errors,
events::connector_api_logs::ConnectorEvent,
types::{
IncrementalAuthorizationType, PaymentsAuthorizeType, PaymentsCaptureType,
PaymentsCompleteAuthorizeType, PaymentsPostSessionTokensType, PaymentsPreProcessingType,
PaymentsSyncType, PaymentsVoidType, RefreshTokenType, RefundExecuteType, RefundSyncType,
Response, SdkSessionUpdateType, SetupMandateType, VerifyWebhookSourceType,
},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use masking::{ExposeInterface, Mask, Maskable, PeekInterface, Secret};
#[cfg(feature = "payouts")]
use router_env::{instrument, tracing};
use transformers::{
self as paypal, auth_headers, PaypalAuthResponse, PaypalIncrementalAuthResponse, PaypalMeta,
PaypalWebhookEventType,
};
use crate::{
constants::{self, headers},
types::ResponseRouterData,
utils::{
self as connector_utils, to_connector_meta, ConnectorErrorType, ConnectorErrorTypeMapping,
ForeignTryFrom, PaymentMethodDataType, PaymentsAuthorizeRequestData,
PaymentsCompleteAuthorizeRequestData, RefundsRequestData,
},
};
#[derive(Clone)]
pub struct Paypal {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
amount_converter_webhooks: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Paypal {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
amount_converter_webhooks: &StringMinorUnitForConnector,
}
}
}
impl api::Payment for Paypal {}
impl api::PaymentSession for Paypal {}
impl api::PaymentToken for Paypal {}
impl api::ConnectorAccessToken for Paypal {}
impl api::MandateSetup for Paypal {}
impl api::PaymentAuthorize for Paypal {}
impl api::PaymentsCompleteAuthorize for Paypal {}
impl api::PaymentSync for Paypal {}
impl api::PaymentCapture for Paypal {}
impl api::PaymentVoid for Paypal {}
impl api::Refund for Paypal {}
impl api::RefundExecute for Paypal {}
impl api::RefundSync for Paypal {}
impl api::ConnectorVerifyWebhookSource for Paypal {}
impl api::PaymentPostSessionTokens for Paypal {}
impl api::PaymentSessionUpdate for Paypal {}
impl api::Payouts for Paypal {}
#[cfg(feature = "payouts")]
impl api::PayoutCreate for Paypal {}
#[cfg(feature = "payouts")]
impl api::PayoutFulfill for Paypal {}
#[cfg(feature = "payouts")]
impl api::PayoutSync for Paypal {}
impl Paypal {
pub fn get_order_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
//Handled error response separately for Orders as the end point is different for Orders - (Authorize) and Payments - (Capture, void, refund, rsync).
//Error response have different fields for Orders and Payments.
let response: paypal::PaypalOrderErrorResponse = res
.response
.parse_struct("Paypal ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_reason = response.details.clone().map(|order_errors| {
order_errors
.iter()
.map(|error| {
let mut reason = format!("description - {}", error.description);
if let Some(value) = &error.value {
reason.push_str(&format!(", value - {value}"));
}
if let Some(field) = error
.field
.as_ref()
.and_then(|field| field.split('/').next_back())
{
reason.push_str(&format!(", field - {field}"));
}
reason.push(';');
reason
})
.collect::<String>()
});
let errors_list = response.details.unwrap_or_default();
let option_error_code_message =
connector_utils::get_error_code_error_message_based_on_priority(
self.clone(),
errors_list
.into_iter()
.map(|errors| errors.into())
.collect(),
);
Ok(ErrorResponse {
status_code: res.status_code,
code: option_error_code_message
.clone()
.map(|error_code_message| error_code_message.error_code)
.unwrap_or(NO_ERROR_CODE.to_string()),
message: option_error_code_message
.map(|error_code_message| error_code_message.error_message)
.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason: error_reason.or(Some(response.message)),
attempt_status: None,
connector_transaction_id: response.debug_id,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Paypal
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let access_token = req
.access_token
.clone()
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
let key = &req.connector_request_reference_id;
let auth = paypal::PaypalAuthType::try_from(&req.connector_auth_type)?;
let mut headers = vec![
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", access_token.token.peek()).into_masked(),
),
(
auth_headers::PREFER.to_string(),
"return=representation".to_string().into(),
),
(
auth_headers::PAYPAL_REQUEST_ID.to_string(),
key.to_string().into_masked(),
),
];
if let Ok(paypal::PaypalConnectorCredentials::PartnerIntegration(credentials)) =
auth.get_credentials()
{
let auth_assertion_header =
construct_auth_assertion_header(&credentials.payer_id, &credentials.client_id);
headers.extend(vec![
(
auth_headers::PAYPAL_AUTH_ASSERTION.to_string(),
auth_assertion_header.to_string().into_masked(),
),
(
auth_headers::PAYPAL_PARTNER_ATTRIBUTION_ID.to_string(),
"HyperSwitchPPCP_SP".to_string().into(),
),
])
} else {
headers.extend(vec![(
auth_headers::PAYPAL_PARTNER_ATTRIBUTION_ID.to_string(),
"HyperSwitchlegacy_Ecom".to_string().into(),
)])
}
Ok(headers)
}
}
fn construct_auth_assertion_header(
payer_id: &Secret<String>,
client_id: &Secret<String>,
) -> String {
let algorithm = consts::BASE64_ENGINE
.encode("{\"alg\":\"none\"}")
.to_string();
let merchant_credentials = format!(
"{{\"iss\":\"{}\",\"payer_id\":\"{}\"}}",
client_id.clone().expose(),
payer_id.clone().expose()
);
let encoded_credentials = consts::BASE64_ENGINE
.encode(merchant_credentials)
.to_string();
format!("{algorithm}.{encoded_credentials}.")
}
impl ConnectorCommon for Paypal {
fn id(&self) -> &'static str {
"paypal"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.paypal.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let auth = paypal::PaypalAuthType::try_from(auth_type)?;
let credentials = auth.get_credentials()?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
credentials.get_client_secret().into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: paypal::PaypalPaymentErrorResponse = res
.response
.parse_struct("Paypal ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_reason = response
.details
.clone()
.map(|error_details| {
error_details
.iter()
.try_fold(String::new(), |mut acc, error| {
if let Some(description) = &error.description {
write!(acc, "description - {description} ;")
.change_context(
errors::ConnectorError::ResponseDeserializationFailed,
)
.attach_printable("Failed to concatenate error details")
.map(|_| acc)
} else {
Ok(acc)
}
})
})
.transpose()?;
let reason = match error_reason {
Some(err_reason) => err_reason
.is_empty()
.then(|| response.message.to_owned())
.or(Some(err_reason)),
None => Some(response.message.to_owned()),
};
let errors_list = response.details.unwrap_or_default();
let option_error_code_message =
connector_utils::get_error_code_error_message_based_on_priority(
self.clone(),
errors_list
.into_iter()
.map(|errors| errors.into())
.collect(),
);
Ok(ErrorResponse {
status_code: res.status_code,
code: option_error_code_message
.clone()
.map(|error_code_message| error_code_message.error_code)
.unwrap_or(NO_ERROR_CODE.to_string()),
message: option_error_code_message
.map(|error_code_message| error_code_message.error_message)
.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason,
attempt_status: None,
connector_transaction_id: response.debug_id,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Paypal {
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::Card,
PaymentMethodDataType::PaypalRedirect,
PaymentMethodDataType::PaypalSdk,
]);
connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Paypal
{
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Paypal {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Paypal {
fn get_url(
&self,
_req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v1/oauth2/token", self.base_url(connectors)))
}
fn get_content_type(&self) -> &'static str {
"application/x-www-form-urlencoded"
}
fn get_headers(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let auth = paypal::PaypalAuthType::try_from(&req.connector_auth_type)?;
let credentials = auth.get_credentials()?;
let auth_val = credentials.generate_authorization_value();
Ok(vec![
(
headers::CONTENT_TYPE.to_string(),
RefreshTokenType::get_content_type(self).to_string().into(),
),
(headers::AUTHORIZATION.to_string(), auth_val.into_masked()),
])
}
fn get_request_body(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = paypal::PaypalAuthUpdateRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let req = Some(
RequestBuilder::new()
.method(Method::Post)
.headers(RefreshTokenType::get_headers(self, req, connectors)?)
.url(&RefreshTokenType::get_url(self, req, connectors)?)
.set_body(RefreshTokenType::get_request_body(self, req, connectors)?)
.build(),
);
Ok(req)
}
fn handle_response(
&self,
data: &RefreshTokenRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> {
let response: paypal::PaypalAuthUpdateResponse = res
.response
.parse_struct("Paypal PaypalAuthUpdateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: paypal::PaypalAccessTokenErrorResponse = res
.response
.parse_struct("Paypal AccessTokenErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error.clone(),
message: response.error.clone(),
reason: Some(response.error_description),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Paypal {
fn get_url(
&self,
_req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v1/payments/payouts", self.base_url(connectors)))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoFulfill>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = connector_utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.destination_currency,
)?;
let connector_router_data =
paypal::PaypalRouterData::try_from((amount, None, None, None, req))?;
let connector_req = paypal::PaypalFulfillRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PayoutFulfillType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutFulfillType::get_headers(self, req, connectors)?)
.set_body(PayoutFulfillType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &PayoutsRouterData<PoFulfill>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoFulfill>, errors::ConnectorError> {
let response: paypal::PaypalFulfillResponse = res
.response
.parse_struct("PaypalFulfillResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData> for Paypal {
fn get_url(
&self,
req: &PayoutsRouterData<PoSync>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let batch_id = req.request.connector_payout_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_payout_id",
},
)?;
Ok(format!(
"{}v1/payments/payouts/{}",
self.base_url(connectors),
batch_id
))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoSync>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn build_request(
&self,
req: &PayoutsRouterData<PoSync>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Get)
.url(&PayoutSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutSyncType::get_headers(self, req, connectors)?)
.build();
Ok(Some(request))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &PayoutsRouterData<PoSync>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoSync>, errors::ConnectorError> {
let response: paypal::PaypalPayoutSyncResponse = res
.response
.parse_struct("PaypalPayoutSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData> for Paypal {
fn build_request(
&self,
_req: &PayoutsRouterData<PoCreate>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
// Eligibility check for wallet is not implemented
Err(
errors::ConnectorError::NotImplemented("Payout Eligibility for Paypal".to_string())
.into(),
)
}
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Paypal {
fn get_headers(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}v3/vault/payment-tokens/",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = paypal::PaypalZeroMandateRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&SetupMandateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(SetupMandateType::get_headers(self, req, connectors)?)
.set_body(SetupMandateType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
let response: paypal::PaypalSetupMandatesResponse = res
.response
.parse_struct("PaypalSetupMandatesResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>
for Paypal
{
fn get_headers(
&self,
req: &PaymentsPostSessionTokensRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsPostSessionTokensRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v2/checkout/orders", self.base_url(connectors)))
}
fn build_request(
&self,
req: &PaymentsPostSessionTokensRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsPostSessionTokensType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(PaymentsPostSessionTokensType::get_headers(
self, req, connectors,
)?)
.set_body(PaymentsPostSessionTokensType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn get_request_body(
&self,
req: &PaymentsPostSessionTokensRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = connector_utils::convert_amount(
self.amount_converter,
req.request.amount,
req.request.currency,
)?;
let shipping_cost = connector_utils::convert_amount(
self.amount_converter,
req.request.shipping_cost.unwrap_or(MinorUnit::zero()),
req.request.currency,
)?;
let order_amount = connector_utils::convert_amount(
self.amount_converter,
req.request.order_amount,
req.request.currency,
)?;
let connector_router_data = paypal::PaypalRouterData::try_from((
amount,
Some(shipping_cost),
None,
Some(order_amount),
req,
))?;
let connector_req = paypal::PaypalPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn handle_response(
&self,
data: &PaymentsPostSessionTokensRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsPostSessionTokensRouterData, errors::ConnectorError> {
let response: paypal::PaypalRedirectResponse = res
.response
.parse_struct("PaypalRedirectResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.get_order_error_response(res, event_builder)
}
}
impl ConnectorIntegration<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>
for Paypal
{
fn get_headers(
&self,
req: &SdkSessionUpdateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &SdkSessionUpdateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let session_id =
req.request
.session_id
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "session_id",
})?;
Ok(format!(
"{}v2/checkout/orders/{}",
self.base_url(connectors),
session_id
))
}
fn build_request(
&self,
req: &SdkSessionUpdateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Patch)
.url(&SdkSessionUpdateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(SdkSessionUpdateType::get_headers(self, req, connectors)?)
.set_body(SdkSessionUpdateType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn get_request_body(
&self,
req: &SdkSessionUpdateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let order_amount = connector_utils::convert_amount(
self.amount_converter,
req.request.order_amount,
req.request.currency,
)?;
let amount = connector_utils::convert_amount(
self.amount_converter,
req.request.amount,
req.request.currency,
)?;
let order_tax_amount = connector_utils::convert_amount(
self.amount_converter,
req.request.order_tax_amount,
req.request.currency,
)?;
let shipping_cost = connector_utils::convert_amount(
self.amount_converter,
req.request.shipping_cost.unwrap_or(MinorUnit::zero()),
req.request.currency,
)?;
let connector_router_data = paypal::PaypalRouterData::try_from((
amount,
Some(shipping_cost),
Some(order_tax_amount),
Some(order_amount),
req,
))?;
let connector_req = paypal::PaypalUpdateOrderRequest::try_from(&connector_router_data)?;
// encode only for for urlencoded things.
Ok(RequestContent::Json(Box::new(
connector_req.get_inner_value(),
)))
}
fn handle_response(
&self,
data: &SdkSessionUpdateRouterData,
_event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<SdkSessionUpdateRouterData, errors::ConnectorError> {
router_env::logger::debug!("Expected zero bytes response, skipped parsing of the response");
// https://developer.paypal.com/docs/api/orders/v2/#orders_patch
// If 204 status code, then the session was updated successfully.
let status = if res.status_code == 204 {
enums::PaymentResourceUpdateStatus::Success
} else {
enums::PaymentResourceUpdateStatus::Failure
};
Ok(SdkSessionUpdateRouterData {
response: Ok(PaymentsResponseData::PaymentResourceUpdateResponse { status }),
..data.clone()
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Paypal {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
match &req.request.payment_method_data {
PaymentMethodData::Wallet(WalletData::PaypalSdk(paypal_wallet_data)) => {
let authorize_url = if req.request.is_auto_capture()? {
"capture".to_string()
} else {
"authorize".to_string()
};
Ok(format!(
"{}v2/checkout/orders/{}/{authorize_url}",
self.base_url(connectors),
paypal_wallet_data.token
))
}
_ => Ok(format!("{}v2/checkout/orders", self.base_url(connectors))),
}
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = connector_utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let shipping_cost = connector_utils::convert_amount(
self.amount_converter,
req.request.shipping_cost.unwrap_or(MinorUnit::zero()),
req.request.currency,
)?;
let connector_router_data =
paypal::PaypalRouterData::try_from((amount, Some(shipping_cost), None, None, req))?;
let connector_req = paypal::PaypalPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let payment_method_data = req.request.payment_method_data.clone();
let req = match payment_method_data {
PaymentMethodData::Wallet(WalletData::PaypalSdk(_)) => RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.build(),
_ => RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
};
Ok(Some(req))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: PaypalAuthResponse =
res.response
.parse_struct("paypal PaypalAuthResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
match response {
PaypalAuthResponse::PaypalOrdersResponse(response) => {
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
PaypalAuthResponse::PaypalRedirectResponse(response) => {
|
crates/hyperswitch_connectors/src/connectors/paypal.rs#chunk0
|
hyperswitch_connectors
|
chunk
| null | null | null | 8,179
| null | null | null | null | null | null | null |
// Function: get_irrelevant_merchant_id
// File: crates/common_utils/src/id_type/merchant.rs
// Module: common_utils
// Documentation: Get a merchant id with a value of `irrelevant_merchant_id`
pub fn get_irrelevant_merchant_id() -> Self
|
crates/common_utils/src/id_type/merchant.rs
|
common_utils
|
function_signature
| null | null | null | 58
|
get_irrelevant_merchant_id
| null | null | null | null | null | null |
// Function: create_payment_method_intent_api
// File: crates/openapi/src/routes/payment_method.rs
// Module: openapi
pub fn create_payment_method_intent_api()
|
crates/openapi/src/routes/payment_method.rs
|
openapi
|
function_signature
| null | null | null | 35
|
create_payment_method_intent_api
| null | null | null | null | null | null |
// Struct: PayeezyCard
// File: crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PayeezyCard
|
crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PayeezyCard
| 0
|
[] | 50
| null | null | null | null | null | null | null |
response_url_data
.data
.three_ds_method_data
.map(|three_ds_method_data| three_ds_method_data.expose())
.unwrap_or_default(),
),
(
"token".to_string(),
response_url_data
.data
.token
.map(|token: Secret<String>| token.expose())
.unwrap_or_default(),
),
(
"provider".to_string(),
response_url_data.data.provider.unwrap_or_default(),
),
(
"version".to_string(),
response_url_data.data.version.unwrap_or_default(),
),
]),
})
}
impl<F, T>
ForeignTryFrom<ResponseRouterData<F, AirwallexAuthorizeResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
item: ResponseRouterData<F, AirwallexAuthorizeResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let ResponseRouterData {
response,
data,
http_code,
} = item;
match response {
AirwallexAuthorizeResponse::AirwallexPaymentsResponse(res) => {
Self::try_from(ResponseRouterData::<
F,
AirwallexPaymentsResponse,
T,
PaymentsResponseData,
> {
response: res,
data,
http_code,
})
}
AirwallexAuthorizeResponse::AirwallexRedirectResponse(res) => {
Self::try_from(ResponseRouterData::<
F,
AirwallexRedirectResponse,
T,
PaymentsResponseData,
> {
response: res,
data,
http_code,
})
}
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, AirwallexPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AirwallexPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (status, redirection_data) = item.response.next_action.clone().map_or(
// If no next action is there, map the status and set redirection form as None
(
get_payment_status(
&item.response.status,
&item
.response
.next_action
.clone()
.map(AirwallexNextAction::Payments)
.clone(),
),
None,
),
|response_url_data| {
// If the connector sends a customer action response that is already under
// process from our end it can cause an infinite loop to break this this check
// is added and fail the payment
if matches!(
(
response_url_data.stage.clone(),
item.data.status,
item.response.status.clone(),
),
// If the connector sends waiting for DDC and our status is already DDC Pending
// that means we initiated the call to collect the data and now we expect a different response
(
AirwallexNextActionStage::WaitingDeviceDataCollection,
enums::AttemptStatus::DeviceDataCollectionPending,
_
)
// If the connector sends waiting for Customer Action and our status is already Authenticaition Pending
// that means we initiated the call to authenticate and now we do not expect a requires_customer action
// it will start a loop
| (
_,
enums::AttemptStatus::AuthenticationPending,
AirwallexPaymentStatus::RequiresCustomerAction,
)
) {
// Fail the payment for above conditions
(enums::AttemptStatus::AuthenticationFailed, None)
} else {
(
//Build the redirect form and update the payment status
get_payment_status(
&item.response.status,
&item
.response
.next_action
.map(AirwallexNextAction::Payments)
.clone(),
),
get_redirection_form(response_url_data),
)
}
},
);
Ok(Self {
status,
reference_id: Some(item.response.id.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, AirwallexRedirectResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AirwallexRedirectResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (status, redirection_data) = item.response.next_action.clone().map_or(
(
get_payment_status(
&item.response.status,
&item
.response
.next_action
.clone()
.map(AirwallexNextAction::Redirect)
.clone(),
),
None,
),
|response_url_data| {
let redirection_data =
Some(RedirectForm::from((response_url_data.url, Method::Get)));
(
get_payment_status(
&item.response.status,
&item
.response
.next_action
.map(AirwallexNextAction::Redirect)
.clone(),
),
redirection_data,
)
},
);
Ok(Self {
status,
reference_id: Some(item.response.id.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl
TryFrom<
ResponseRouterData<
PSync,
AirwallexPaymentsSyncResponse,
PaymentsSyncData,
PaymentsResponseData,
>,
> for types::PaymentsSyncRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
PSync,
AirwallexPaymentsSyncResponse,
PaymentsSyncData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status = get_payment_status(
&item.response.status,
&item
.response
.next_action
.clone()
.map(AirwallexNextAction::Payments)
.clone(),
);
let redirection_data = if let Some(redirect_url_data) = item.response.next_action {
get_redirection_form(redirect_url_data)
} else {
None
};
Ok(Self {
status,
reference_id: Some(item.response.id.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct AirwallexRefundRequest {
// Unique ID to be sent for each transaction/operation request to the connector
request_id: String,
amount: Option<StringMajorUnit>,
reason: Option<String>,
//Identifier for the PaymentIntent for which Refund is requested
payment_intent_id: String,
}
impl<F> TryFrom<&AirwallexRouterData<&types::RefundsRouterData<F>>> for AirwallexRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AirwallexRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
request_id: Uuid::new_v4().to_string(),
amount: Some(item.amount.to_owned()),
reason: item.router_data.request.reason.clone(),
payment_intent_id: item.router_data.request.connector_transaction_id.clone(),
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Received,
Accepted,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Received | RefundStatus::Accepted => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
//A unique number that tags a credit or debit card transaction when it goes from the merchant's bank through to the cardholder's bank.
acquirer_reference_number: Option<String>,
amount: f32,
//Unique identifier for the Refund
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<ParsingError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<ParsingError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
}),
..item.data
})
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AirwallexWebhookData {
pub source_id: Option<String>,
pub name: AirwallexWebhookEventType,
pub data: AirwallexObjectData,
}
#[derive(Debug, Deserialize, strum::Display, PartialEq)]
pub enum AirwallexWebhookEventType {
#[serde(rename = "payment_intent.created")]
PaymentIntentCreated,
#[serde(rename = "payment_intent.requires_payment_method")]
PaymentIntentRequiresPaymentMethod,
#[serde(rename = "payment_intent.cancelled")]
PaymentIntentCancelled,
#[serde(rename = "payment_intent.succeeded")]
PaymentIntentSucceeded,
#[serde(rename = "payment_intent.requires_capture")]
PaymentIntentRequiresCapture,
#[serde(rename = "payment_intent.requires_customer_action")]
PaymentIntentRequiresCustomerAction,
#[serde(rename = "payment_attempt.authorized")]
PaymentAttemptAuthorized,
#[serde(rename = "payment_attempt.authorization_failed")]
PaymentAttemptAuthorizationFailed,
#[serde(rename = "payment_attempt.capture_requested")]
PaymentAttemptCaptureRequested,
#[serde(rename = "payment_attempt.capture_failed")]
PaymentAttemptCaptureFailed,
#[serde(rename = "payment_attempt.authentication_redirected")]
PaymentAttemptAuthenticationRedirected,
#[serde(rename = "payment_attempt.authentication_failed")]
PaymentAttemptAuthenticationFailed,
#[serde(rename = "payment_attempt.failed_to_process")]
PaymentAttemptFailedToProcess,
#[serde(rename = "payment_attempt.cancelled")]
PaymentAttemptCancelled,
#[serde(rename = "payment_attempt.expired")]
PaymentAttemptExpired,
#[serde(rename = "payment_attempt.risk_declined")]
PaymentAttemptRiskDeclined,
#[serde(rename = "payment_attempt.settled")]
PaymentAttemptSettled,
#[serde(rename = "payment_attempt.paid")]
PaymentAttemptPaid,
#[serde(rename = "refund.received")]
RefundReceived,
#[serde(rename = "refund.accepted")]
RefundAccepted,
#[serde(rename = "refund.succeeded")]
RefundSucceeded,
#[serde(rename = "refund.failed")]
RefundFailed,
#[serde(rename = "dispute.rfi_responded_by_merchant")]
DisputeRfiRespondedByMerchant,
#[serde(rename = "dispute.dispute.pre_chargeback_accepted")]
DisputePreChargebackAccepted,
#[serde(rename = "dispute.accepted")]
DisputeAccepted,
#[serde(rename = "dispute.dispute_received_by_merchant")]
DisputeReceivedByMerchant,
#[serde(rename = "dispute.dispute_responded_by_merchant")]
DisputeRespondedByMerchant,
#[serde(rename = "dispute.won")]
DisputeWon,
#[serde(rename = "dispute.lost")]
DisputeLost,
#[serde(rename = "dispute.dispute_reversed")]
DisputeReversed,
#[serde(other)]
Unknown,
}
pub fn is_transaction_event(event_code: &AirwallexWebhookEventType) -> bool {
matches!(
event_code,
AirwallexWebhookEventType::PaymentAttemptFailedToProcess
| AirwallexWebhookEventType::PaymentAttemptAuthorized
)
}
pub fn is_refund_event(event_code: &AirwallexWebhookEventType) -> bool {
matches!(
event_code,
AirwallexWebhookEventType::RefundSucceeded | AirwallexWebhookEventType::RefundFailed
)
}
pub fn is_dispute_event(event_code: &AirwallexWebhookEventType) -> bool {
matches!(
event_code,
AirwallexWebhookEventType::DisputeAccepted
| AirwallexWebhookEventType::DisputePreChargebackAccepted
| AirwallexWebhookEventType::DisputeRespondedByMerchant
| AirwallexWebhookEventType::DisputeWon
| AirwallexWebhookEventType::DisputeLost
)
}
#[derive(Debug, Deserialize)]
pub struct AirwallexObjectData {
pub object: serde_json::Value,
}
#[derive(Debug, Deserialize)]
pub struct AirwallexDisputeObject {
pub payment_intent_id: String,
pub dispute_amount: MinorUnit,
pub dispute_currency: enums::Currency,
pub stage: AirwallexDisputeStage,
pub dispute_id: String,
pub dispute_reason_type: Option<String>,
pub dispute_original_reason_code: Option<String>,
pub status: String,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub created_at: Option<PrimitiveDateTime>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub updated_at: Option<PrimitiveDateTime>,
}
#[derive(Debug, Deserialize, strum::Display, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum AirwallexDisputeStage {
Rfi,
Dispute,
Arbitration,
}
#[derive(Debug, Deserialize)]
pub struct AirwallexWebhookDataResource {
// Should this be a secret by default since it represents webhook payload
pub object: Secret<serde_json::Value>,
}
#[derive(Debug, Deserialize)]
pub struct AirwallexWebhookObjectResource {
pub data: AirwallexWebhookDataResource,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct AirwallexErrorResponse {
pub code: String,
pub message: String,
pub source: Option<String>,
}
impl TryFrom<AirwallexWebhookEventType> for api_models::webhooks::IncomingWebhookEvent {
type Error = errors::ConnectorError;
fn try_from(value: AirwallexWebhookEventType) -> Result<Self, Self::Error> {
Ok(match value {
AirwallexWebhookEventType::PaymentAttemptFailedToProcess => Self::PaymentIntentFailure,
AirwallexWebhookEventType::PaymentAttemptAuthorized => Self::PaymentIntentSuccess,
AirwallexWebhookEventType::RefundSucceeded => Self::RefundSuccess,
AirwallexWebhookEventType::RefundFailed => Self::RefundFailure,
AirwallexWebhookEventType::DisputeAccepted
| AirwallexWebhookEventType::DisputePreChargebackAccepted => Self::DisputeAccepted,
AirwallexWebhookEventType::DisputeRespondedByMerchant => Self::DisputeChallenged,
AirwallexWebhookEventType::DisputeWon | AirwallexWebhookEventType::DisputeReversed => {
Self::DisputeWon
}
AirwallexWebhookEventType::DisputeLost => Self::DisputeLost,
AirwallexWebhookEventType::Unknown
| AirwallexWebhookEventType::PaymentAttemptAuthenticationRedirected
| AirwallexWebhookEventType::PaymentIntentCreated
| AirwallexWebhookEventType::PaymentIntentRequiresPaymentMethod
| AirwallexWebhookEventType::PaymentIntentCancelled
| AirwallexWebhookEventType::PaymentIntentSucceeded
| AirwallexWebhookEventType::PaymentIntentRequiresCapture
| AirwallexWebhookEventType::PaymentIntentRequiresCustomerAction
| AirwallexWebhookEventType::PaymentAttemptAuthorizationFailed
| AirwallexWebhookEventType::PaymentAttemptCaptureRequested
| AirwallexWebhookEventType::PaymentAttemptCaptureFailed
| AirwallexWebhookEventType::PaymentAttemptAuthenticationFailed
| AirwallexWebhookEventType::PaymentAttemptCancelled
| AirwallexWebhookEventType::PaymentAttemptExpired
| AirwallexWebhookEventType::PaymentAttemptRiskDeclined
| AirwallexWebhookEventType::PaymentAttemptSettled
| AirwallexWebhookEventType::PaymentAttemptPaid
| AirwallexWebhookEventType::RefundReceived
| AirwallexWebhookEventType::RefundAccepted
| AirwallexWebhookEventType::DisputeRfiRespondedByMerchant
| AirwallexWebhookEventType::DisputeReceivedByMerchant => Self::EventNotSupported,
})
}
}
impl From<AirwallexDisputeStage> for api_models::enums::DisputeStage {
fn from(code: AirwallexDisputeStage) -> Self {
match code {
AirwallexDisputeStage::Rfi => Self::PreDispute,
AirwallexDisputeStage::Dispute => Self::Dispute,
AirwallexDisputeStage::Arbitration => Self::PreArbitration,
}
}
}
|
crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs#chunk1
|
hyperswitch_connectors
|
chunk
| null | null | null | 4,176
| null | null | null | null | null | null | null |
// Function: delete_file_using_file_id
// File: crates/router/src/core/files/helpers.rs
// Module: router
pub fn delete_file_using_file_id(
state: &SessionState,
file_key: String,
merchant_context: &domain::MerchantContext,
) -> CustomResult<(), errors::ApiErrorResponse>
|
crates/router/src/core/files/helpers.rs
|
router
|
function_signature
| null | null | null | 66
|
delete_file_using_file_id
| null | null | null | null | null | null |
// Struct: WorldpayvantivCardData
// File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct WorldpayvantivCardData
|
crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
WorldpayvantivCardData
| 0
|
[] | 55
| null | null | null | null | null | null | null |
// Struct: CompleteAuthorizeRedirectResponse
// File: crates/hyperswitch_domain_models/src/router_response_types.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct CompleteAuthorizeRedirectResponse
|
crates/hyperswitch_domain_models/src/router_response_types.rs
|
hyperswitch_domain_models
|
struct_definition
|
CompleteAuthorizeRedirectResponse
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// Function: http_response_json
// File: crates/drainer/src/services.rs
// Module: drainer
pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpResponse
|
crates/drainer/src/services.rs
|
drainer
|
function_signature
| null | null | null | 44
|
http_response_json
| null | null | null | null | null | null |
// Trait: PaymentAttemptInterface
// File: crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
// Module: hyperswitch_domain_models
pub trait PaymentAttemptInterface
|
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
|
hyperswitch_domain_models
|
trait_definition
| null | null | null | 37
| null | null |
PaymentAttemptInterface
| null | null | null | null |
// Struct: ConnectorRoutingData
// File: crates/router/src/types/api/fraud_check.rs
// Module: router
// Implementations: 0
pub struct ConnectorRoutingData
|
crates/router/src/types/api/fraud_check.rs
|
router
|
struct_definition
|
ConnectorRoutingData
| 0
|
[] | 37
| null | null | null | null | null | null | null |
// File: crates/router/src/types/domain.rs
// Module: router
pub mod behaviour {
pub use hyperswitch_domain_models::behaviour::{Conversion, ReverseConversion};
}
mod payment_attempt {
pub use hyperswitch_domain_models::payments::payment_attempt::*;
}
mod merchant_account {
pub use hyperswitch_domain_models::merchant_account::*;
}
#[cfg(feature = "v2")]
mod business_profile {
pub use hyperswitch_domain_models::business_profile::{
Profile, ProfileGeneralUpdate, ProfileSetter, ProfileUpdate,
};
}
#[cfg(feature = "v1")]
mod business_profile {
pub use hyperswitch_domain_models::business_profile::{
ExternalVaultDetails, Profile, ProfileGeneralUpdate, ProfileSetter, ProfileUpdate,
};
}
pub mod merchant_context {
pub use hyperswitch_domain_models::merchant_context::{Context, MerchantContext};
}
mod customers {
pub use hyperswitch_domain_models::customer::*;
}
pub mod callback_mapper {
pub use hyperswitch_domain_models::callback_mapper::CallbackMapper;
}
mod network_tokenization {
pub use hyperswitch_domain_models::network_tokenization::*;
}
pub use customers::*;
pub use merchant_account::*;
mod address;
mod event;
mod merchant_connector_account;
mod merchant_key_store {
pub use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;
}
pub use hyperswitch_domain_models::bulk_tokenization::*;
pub mod payment_methods {
pub use hyperswitch_domain_models::payment_methods::*;
}
pub mod consts {
pub use hyperswitch_domain_models::consts::*;
}
pub mod payment_method_data {
pub use hyperswitch_domain_models::payment_method_data::*;
}
pub mod authentication {
pub use hyperswitch_domain_models::router_request_types::authentication::*;
}
#[cfg(feature = "v2")]
pub mod vault {
pub use hyperswitch_domain_models::vault::*;
}
#[cfg(feature = "v2")]
pub mod tokenization {
pub use hyperswitch_domain_models::tokenization::*;
}
mod routing {
pub use hyperswitch_domain_models::routing::*;
}
pub mod payments;
pub mod types;
#[cfg(feature = "olap")]
pub mod user;
pub mod user_key_store;
pub use address::*;
pub use business_profile::*;
pub use callback_mapper::*;
pub use consts::*;
pub use event::*;
pub use merchant_connector_account::*;
pub use merchant_context::*;
pub use merchant_key_store::*;
pub use network_tokenization::*;
pub use payment_attempt::*;
pub use payment_method_data::*;
pub use payment_methods::*;
pub use routing::*;
#[cfg(feature = "v2")]
pub use tokenization::*;
#[cfg(feature = "olap")]
pub use user::*;
pub use user_key_store::*;
#[cfg(feature = "v2")]
pub use vault::*;
|
crates/router/src/types/domain.rs
|
router
|
full_file
| null | null | null | 545
| null | null | null | null | null | null | null |
// Struct: TokenizedCardValue1
// File: crates/hyperswitch_domain_models/src/payment_method_data.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct TokenizedCardValue1
|
crates/hyperswitch_domain_models/src/payment_method_data.rs
|
hyperswitch_domain_models
|
struct_definition
|
TokenizedCardValue1
| 0
|
[] | 47
| null | null | null | null | null | null | null |
Some(RedirectForm::CybersourceConsumerAuth {
access_token: token.expose(),
step_up_url,
})
}
_ => None,
};
let three_ds_data = serde_json::to_value(
info_response
.consumer_authentication_information
.validate_response,
)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!({
"three_ds_data": three_ds_data
})),
network_txn_id: None,
connector_response_reference_id,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
CybersourceAuthenticateResponse::ErrorInformation(error_response) => {
let detailed_error_info =
error_response
.error_information
.details
.to_owned()
.map(|details| {
details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message,
detailed_error_info,
None,
);
let error_message = error_response.error_information.reason.to_owned();
let response = Err(ErrorResponse {
code: error_message
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
Ok(Self {
response,
status: enums::AttemptStatus::AuthenticationFailed,
..item.data
})
}
}
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
CybersourceAuthenticateResponse,
PaymentsPostAuthenticateData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsPostAuthenticateData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
CybersourceAuthenticateResponse,
PaymentsPostAuthenticateData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
CybersourceAuthenticateResponse::ClientAuthCheckInfo(info_response) => {
let status = enums::AttemptStatus::from(info_response.status);
let risk_info: Option<ClientRiskInformation> = None;
if utils::is_payment_failure(status) {
let response = Err(get_error_response(
&info_response.error_information,
&None,
&risk_info,
Some(status),
item.http_code,
info_response.id.clone(),
));
Ok(Self {
status,
response,
..item.data
})
} else {
let connector_response_reference_id = Some(
info_response
.client_reference_information
.code
.unwrap_or(info_response.id.clone()),
);
let redirection_data = match (
info_response
.consumer_authentication_information
.access_token,
info_response
.consumer_authentication_information
.step_up_url,
) {
(Some(token), Some(step_up_url)) => {
Some(RedirectForm::CybersourceConsumerAuth {
access_token: token.expose(),
step_up_url,
})
}
_ => None,
};
let three_ds_data = serde_json::to_value(
info_response
.consumer_authentication_information
.validate_response,
)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!({
"three_ds_data": three_ds_data
})),
network_txn_id: None,
connector_response_reference_id,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
CybersourceAuthenticateResponse::ErrorInformation(error_response) => {
let detailed_error_info =
error_response
.error_information
.details
.to_owned()
.map(|details| {
details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message,
detailed_error_info,
None,
);
let error_message = error_response.error_information.reason.to_owned();
let response = Err(ErrorResponse {
code: error_message
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
Ok(Self {
response,
status: enums::AttemptStatus::AuthenticationFailed,
..item.data
})
}
}
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
CybersourceTransactionResponse,
PaymentsSyncData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
CybersourceTransactionResponse,
PaymentsSyncData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response.application_information.status {
Some(status) => {
let status =
map_cybersource_attempt_status(status, item.data.request.is_auto_capture()?);
let incremental_authorization_allowed =
Some(status == enums::AttemptStatus::Authorized);
let risk_info: Option<ClientRiskInformation> = None;
if utils::is_payment_failure(status) {
Ok(Self {
response: Err(get_error_response(
&item.response.error_information,
&item.response.processor_information,
&risk_info,
Some(status),
item.http_code,
item.response.id.clone(),
)),
status: enums::AttemptStatus::Failure,
..item.data
})
} else {
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
.response
.client_reference_information
.map(|cref| cref.code)
.unwrap_or(Some(item.response.id)),
incremental_authorization_allowed,
charges: None,
}),
..item.data
})
}
}
None => Ok(Self {
status: item.data.status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceRefundRequest {
order_information: OrderInformation,
client_reference_information: ClientReferenceInformation,
}
impl<F> TryFrom<&CybersourceRouterData<&RefundsRouterData<F>>> for CybersourceRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &CybersourceRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
order_information: OrderInformation {
amount_details: Amount {
total_amount: item.amount.clone(),
currency: item.router_data.request.currency,
},
},
client_reference_information: ClientReferenceInformation {
code: Some(item.router_data.request.refund_id.clone()),
},
})
}
}
impl From<CybersourceRefundStatus> for enums::RefundStatus {
fn from(item: CybersourceRefundStatus) -> Self {
match item {
CybersourceRefundStatus::Succeeded | CybersourceRefundStatus::Transmitted => {
Self::Success
}
CybersourceRefundStatus::Cancelled
| CybersourceRefundStatus::Failed
| CybersourceRefundStatus::Voided => Self::Failure,
CybersourceRefundStatus::Pending => Self::Pending,
}
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CybersourceRefundStatus {
Succeeded,
Transmitted,
Failed,
Pending,
Voided,
Cancelled,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceRefundResponse {
id: String,
status: CybersourceRefundStatus,
error_information: Option<CybersourceErrorInformation>,
}
impl TryFrom<RefundsResponseRouterData<Execute, CybersourceRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, CybersourceRefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status.clone());
let response = if utils::is_refund_failure(refund_status) {
Err(get_error_response(
&item.response.error_information,
&None,
&None,
None,
item.http_code,
item.response.id.clone(),
))
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status: enums::RefundStatus::from(item.response.status),
})
};
Ok(Self {
response,
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RsyncApplicationInformation {
status: Option<CybersourceRefundStatus>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceRsyncResponse {
id: String,
application_information: Option<RsyncApplicationInformation>,
error_information: Option<CybersourceErrorInformation>,
}
impl TryFrom<RefundsResponseRouterData<RSync, CybersourceRsyncResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, CybersourceRsyncResponse>,
) -> Result<Self, Self::Error> {
let response = match item
.response
.application_information
.and_then(|application_information| application_information.status)
{
Some(status) => {
let refund_status = enums::RefundStatus::from(status.clone());
if utils::is_refund_failure(refund_status) {
if status == CybersourceRefundStatus::Voided {
Err(get_error_response(
&Some(CybersourceErrorInformation {
message: Some(constants::REFUND_VOIDED.to_string()),
reason: Some(constants::REFUND_VOIDED.to_string()),
details: None,
}),
&None,
&None,
None,
item.http_code,
item.response.id.clone(),
))
} else {
Err(get_error_response(
&item.response.error_information,
&None,
&None,
None,
item.http_code,
item.response.id.clone(),
))
}
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
})
}
}
None => Ok(RefundsResponseData {
connector_refund_id: item.response.id.clone(),
refund_status: match item.data.response {
Ok(response) => response.refund_status,
Err(_) => common_enums::RefundStatus::Pending,
},
}),
};
Ok(Self {
response,
..item.data
})
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourcePayoutFulfillRequest {
client_reference_information: ClientReferenceInformation,
order_information: OrderInformation,
recipient_information: CybersourceRecipientInfo,
sender_information: CybersourceSenderInfo,
processing_information: CybersourceProcessingInfo,
payment_information: PaymentInformation,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceRecipientInfo {
first_name: Secret<String>,
last_name: Secret<String>,
address1: Secret<String>,
locality: String,
administrative_area: Secret<String>,
postal_code: Secret<String>,
country: enums::CountryAlpha2,
phone_number: Option<Secret<String>>,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceSenderInfo {
reference_number: String,
account: CybersourceAccountInfo,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceAccountInfo {
funds_source: CybersourcePayoutFundSourceType,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
pub enum CybersourcePayoutFundSourceType {
#[serde(rename = "05")]
Disbursement,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceProcessingInfo {
business_application_id: CybersourcePayoutBusinessType,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
pub enum CybersourcePayoutBusinessType {
#[serde(rename = "PP")]
PersonToPerson,
#[serde(rename = "AA")]
AccountToAccount,
}
#[cfg(feature = "payouts")]
impl TryFrom<&CybersourceRouterData<&PayoutsRouterData<PoFulfill>>>
for CybersourcePayoutFulfillRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CybersourceRouterData<&PayoutsRouterData<PoFulfill>>,
) -> Result<Self, Self::Error> {
let payout_type = item.router_data.request.get_payout_type()?;
match payout_type {
enums::PayoutType::Card => {
let client_reference_information = ClientReferenceInformation {
code: Some(item.router_data.connector_request_reference_id.clone()),
};
let order_information = OrderInformation {
amount_details: Amount {
total_amount: item.amount.to_owned(),
currency: item.router_data.request.destination_currency,
},
};
let billing_address = item.router_data.get_billing_address()?;
let phone_address = item.router_data.get_billing_phone()?;
let recipient_information =
CybersourceRecipientInfo::try_from((billing_address, phone_address))?;
let sender_information = CybersourceSenderInfo {
reference_number: item.router_data.connector_request_reference_id.clone(),
account: CybersourceAccountInfo {
funds_source: CybersourcePayoutFundSourceType::Disbursement,
},
};
let processing_information = CybersourceProcessingInfo {
business_application_id: CybersourcePayoutBusinessType::PersonToPerson, // this means sender and receiver are different
};
let payout_method_data = item.router_data.get_payout_method_data()?;
let payment_information = PaymentInformation::try_from(payout_method_data)?;
Ok(Self {
client_reference_information,
order_information,
recipient_information,
sender_information,
processing_information,
payment_information,
})
}
enums::PayoutType::Bank | enums::PayoutType::Wallet => {
Err(errors::ConnectorError::NotSupported {
message: "PayoutType is not supported".to_string(),
connector: "Cybersource",
})?
}
}
}
}
#[cfg(feature = "payouts")]
impl TryFrom<(&AddressDetails, &PhoneDetails)> for CybersourceRecipientInfo {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: (&AddressDetails, &PhoneDetails)) -> Result<Self, Self::Error> {
let (billing_address, phone_address) = item;
Ok(Self {
first_name: billing_address.get_first_name()?.to_owned(),
last_name: billing_address.get_last_name()?.to_owned(),
address1: billing_address.get_line1()?.to_owned(),
locality: billing_address.get_city()?.to_owned(),
administrative_area: {
billing_address
.to_state_code_as_optional()
.unwrap_or_else(|_| {
billing_address
.state
.remove_new_line()
.as_ref()
.map(|state| truncate_string(state, 20)) //NOTE: Cybersource connector throws error if billing state exceeds 20 characters, so truncation is done to avoid payment failure
})
.ok_or_else(|| errors::ConnectorError::MissingRequiredField {
field_name: "billing_address.state",
})?
},
postal_code: billing_address.get_zip()?.to_owned(),
country: billing_address.get_country()?.to_owned(),
phone_number: phone_address.number.clone(),
})
}
}
#[cfg(feature = "payouts")]
impl TryFrom<PayoutMethodData> for PaymentInformation {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: PayoutMethodData) -> Result<Self, Self::Error> {
match item {
PayoutMethodData::Card(card_details) => {
let card_issuer = card_details.get_card_issuer().ok();
let card_type = card_issuer.map(String::from);
let card = Card {
number: card_details.card_number,
expiration_month: card_details.expiry_month,
expiration_year: card_details.expiry_year,
security_code: None,
card_type,
type_selection_indicator: None,
};
Ok(Self::Cards(Box::new(CardPaymentInformation { card })))
}
PayoutMethodData::Bank(_) | PayoutMethodData::Wallet(_) => {
Err(errors::ConnectorError::NotSupported {
message: "PayoutMethod is not supported".to_string(),
connector: "Cybersource",
})?
}
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceFulfillResponse {
id: String,
status: CybersourcePayoutStatus,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CybersourcePayoutStatus {
Accepted,
Declined,
InvalidRequest,
}
#[cfg(feature = "payouts")]
fn map_payout_status(status: CybersourcePayoutStatus) -> enums::PayoutStatus {
match status {
CybersourcePayoutStatus::Accepted => enums::PayoutStatus::Success,
CybersourcePayoutStatus::Declined | CybersourcePayoutStatus::InvalidRequest => {
enums::PayoutStatus::Failed
}
}
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, CybersourceFulfillResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, CybersourceFulfillResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(map_payout_status(item.response.status)),
connector_payout_id: Some(item.response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceStandardErrorResponse {
pub error_information: Option<ErrorInformation>,
pub status: Option<String>,
pub message: Option<String>,
pub reason: Option<String>,
pub details: Option<Vec<Details>>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceNotAvailableErrorResponse {
pub errors: Vec<CybersourceNotAvailableErrorObject>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceNotAvailableErrorObject {
#[serde(rename = "type")]
pub error_type: Option<String>,
pub message: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceServerErrorResponse {
pub status: Option<String>,
pub message: Option<String>,
pub reason: Option<Reason>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Reason {
SystemError,
ServerTimeout,
ServiceTimeout,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CybersourceAuthenticationErrorResponse {
pub response: AuthenticationErrorInformation,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CybersourceErrorResponse {
AuthenticationError(Box<CybersourceAuthenticationErrorResponse>),
//If the request resource is not available/exists in cybersource
NotAvailableError(Box<CybersourceNotAvailableErrorResponse>),
StandardError(Box<CybersourceStandardErrorResponse>),
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Details {
pub field: String,
pub reason: String,
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct ErrorInformation {
pub message: String,
pub reason: String,
pub details: Option<Vec<Details>>,
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct AuthenticationErrorInformation {
pub rmsg: String,
}
pub fn get_error_response(
error_data: &Option<CybersourceErrorInformation>,
processor_information: &Option<ClientProcessorInformation>,
risk_information: &Option<ClientRiskInformation>,
attempt_status: Option<enums::AttemptStatus>,
status_code: u16,
transaction_id: String,
) -> ErrorResponse {
let avs_message = risk_information
.clone()
.map(|client_risk_information| {
client_risk_information.rules.map(|rules| {
rules
.iter()
.map(|risk_info| {
risk_info.name.clone().map_or("".to_string(), |name| {
format!(" , {}", name.clone().expose())
})
})
.collect::<Vec<String>>()
.join("")
})
})
.unwrap_or(Some("".to_string()));
let detailed_error_info = error_data.as_ref().and_then(|error_data| {
error_data.details.as_ref().map(|details| {
details
.iter()
.map(|detail| format!("{} : {}", detail.field, detail.reason))
.collect::<Vec<_>>()
.join(", ")
})
});
let network_decline_code = processor_information
.as_ref()
.and_then(|info| info.response_code.clone());
let network_advice_code = processor_information.as_ref().and_then(|info| {
info.merchant_advice
.as_ref()
.and_then(|merchant_advice| merchant_advice.code_raw.clone())
});
let reason = get_error_reason(
error_data
.as_ref()
.and_then(|error_info| error_info.message.clone()),
detailed_error_info,
avs_message,
);
let error_message = error_data
.as_ref()
.and_then(|error_info| error_info.reason.clone());
ErrorResponse {
code: error_message
.clone()
.unwrap_or_else(|| hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_message
.unwrap_or_else(|| hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason,
status_code,
attempt_status,
connector_transaction_id: Some(transaction_id),
network_advice_code,
network_decline_code,
network_error_message: None,
connector_metadata: None,
}
}
pub fn get_error_reason(
error_info: Option<String>,
detailed_error_info: Option<String>,
avs_error_info: Option<String>,
) -> Option<String> {
match (error_info, detailed_error_info, avs_error_info) {
(Some(message), Some(details), Some(avs_message)) => Some(format!(
"{message}, detailed_error_information: {details}, avs_message: {avs_message}",
)),
(Some(message), Some(details), None) => {
Some(format!("{message}, detailed_error_information: {details}"))
}
(Some(message), None, Some(avs_message)) => {
Some(format!("{message}, avs_message: {avs_message}"))
}
(None, Some(details), Some(avs_message)) => {
Some(format!("{details}, avs_message: {avs_message}"))
}
(Some(message), None, None) => Some(message),
(None, Some(details), None) => Some(details),
(None, None, Some(avs_message)) => Some(avs_message),
(None, None, None) => None,
}
}
fn get_cybersource_card_type(card_network: common_enums::CardNetwork) -> Option<&'static str> {
match card_network {
common_enums::CardNetwork::Visa => Some("001"),
common_enums::CardNetwork::Mastercard => Some("002"),
common_enums::CardNetwork::AmericanExpress => Some("003"),
common_enums::CardNetwork::JCB => Some("007"),
common_enums::CardNetwork::DinersClub => Some("005"),
common_enums::CardNetwork::Discover => Some("004"),
common_enums::CardNetwork::CartesBancaires => Some("036"),
common_enums::CardNetwork::UnionPay => Some("062"),
//"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024"
common_enums::CardNetwork::Maestro => Some("042"),
common_enums::CardNetwork::Interac
| common_enums::CardNetwork::RuPay
| common_enums::CardNetwork::Star
| common_enums::CardNetwork::Accel
| common_enums::CardNetwork::Pulse
| common_enums::CardNetwork::Nyce => None,
}
}
pub trait RemoveNewLine {
fn remove_new_line(&self) -> Self;
}
impl RemoveNewLine for Option<Secret<String>> {
fn remove_new_line(&self) -> Self {
self.clone().map(|masked_value| {
let new_string = masked_value.expose().replace("\n", " ");
Secret::new(new_string)
})
}
}
impl RemoveNewLine for Option<String> {
fn remove_new_line(&self) -> Self {
self.clone().map(|value| value.replace("\n", " "))
}
}
|
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs#chunk4
|
hyperswitch_connectors
|
chunk
| null | null | null | 6,210
| null | null | null | null | null | null | null |
// Struct: Tokenization
// File: crates/hyperswitch_domain_models/src/tokenization.rs
// Module: hyperswitch_domain_models
// Implementations: 2
// Traits: super::behaviour::Conversion
pub struct Tokenization
|
crates/hyperswitch_domain_models/src/tokenization.rs
|
hyperswitch_domain_models
|
struct_definition
|
Tokenization
| 2
|
[
"super::behaviour::Conversion"
] | 50
| null | null | null | null | null | null | null |
// File: crates/router/src/routes/dummy_connector/errors.rs
// Module: router
#[derive(Clone, Debug, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorType {
ServerNotAvailable,
ObjectNotFound,
InvalidRequestError,
}
#[derive(Debug, Clone, router_derive::ApiError)]
#[error(error_type_enum = ErrorType)]
// TODO: Remove this line if InternalServerError is used anywhere
#[allow(dead_code)]
pub enum DummyConnectorErrors {
#[error(error_type = ErrorType::ServerNotAvailable, code = "DC_00", message = "Something went wrong")]
InternalServerError,
#[error(error_type = ErrorType::ObjectNotFound, code = "DC_01", message = "Payment does not exist in our records")]
PaymentNotFound,
#[error(error_type = ErrorType::InvalidRequestError, code = "DC_02", message = "Missing required param: {field_name}")]
MissingRequiredField { field_name: &'static str },
#[error(error_type = ErrorType::InvalidRequestError, code = "DC_03", message = "The refund amount exceeds the amount captured")]
RefundAmountExceedsPaymentAmount,
#[error(error_type = ErrorType::InvalidRequestError, code = "DC_04", message = "Card not supported. Please use test cards")]
CardNotSupported,
#[error(error_type = ErrorType::ObjectNotFound, code = "DC_05", message = "Refund does not exist in our records")]
RefundNotFound,
#[error(error_type = ErrorType::InvalidRequestError, code = "DC_06", message = "Payment is not successful")]
PaymentNotSuccessful,
#[error(error_type = ErrorType::ServerNotAvailable, code = "DC_07", message = "Error occurred while storing the payment")]
PaymentStoringError,
#[error(error_type = ErrorType::InvalidRequestError, code = "DC_08", message = "Payment declined: {message}")]
PaymentDeclined { message: &'static str },
}
impl core::fmt::Display for DummyConnectorErrors {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
r#"{{"error":{}}}"#,
serde_json::to_string(self)
.unwrap_or_else(|_| "Dummy connector error response".to_string())
)
}
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse>
for DummyConnectorErrors
{
fn switch(&self) -> api_models::errors::types::ApiErrorResponse {
use api_models::errors::types::{ApiError, ApiErrorResponse as AER};
match self {
Self::InternalServerError => {
AER::InternalServerError(ApiError::new("DC", 0, self.error_message(), None))
}
Self::PaymentNotFound => {
AER::NotFound(ApiError::new("DC", 1, self.error_message(), None))
}
Self::MissingRequiredField { field_name: _ } => {
AER::BadRequest(ApiError::new("DC", 2, self.error_message(), None))
}
Self::RefundAmountExceedsPaymentAmount => {
AER::InternalServerError(ApiError::new("DC", 3, self.error_message(), None))
}
Self::CardNotSupported => {
AER::BadRequest(ApiError::new("DC", 4, self.error_message(), None))
}
Self::RefundNotFound => {
AER::NotFound(ApiError::new("DC", 5, self.error_message(), None))
}
Self::PaymentNotSuccessful => {
AER::BadRequest(ApiError::new("DC", 6, self.error_message(), None))
}
Self::PaymentStoringError => {
AER::InternalServerError(ApiError::new("DC", 7, self.error_message(), None))
}
Self::PaymentDeclined { message: _ } => {
AER::BadRequest(ApiError::new("DC", 8, self.error_message(), None))
}
}
}
}
|
crates/router/src/routes/dummy_connector/errors.rs
|
router
|
full_file
| null | null | null | 890
| null | null | null | null | null | null | null |
// File: crates/analytics/src/payments/metrics/sessionized_metrics/success_rate.rs
// Module: analytics
use std::collections::HashSet;
use api_models::analytics::{
payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::PaymentMetricRow;
use crate::{
enums::AuthInfo,
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(crate) struct PaymentSuccessRate;
#[async_trait::async_trait]
impl<T> super::PaymentMetric<T> for PaymentSuccessRate
where
T: AnalyticsDataSource + super::PaymentMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[PaymentDimensions],
auth: &AuthInfo,
filters: &PaymentFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> {
let mut query_builder: QueryBuilder<T> =
QueryBuilder::new(AnalyticsCollection::PaymentSessionized);
let mut dimensions = dimensions.to_vec();
dimensions.push(PaymentDimensions::PaymentStatus);
for dim in dimensions.iter() {
query_builder.add_select_column(dim).switch()?;
}
query_builder
.add_select_column(Aggregate::Count {
field: None,
alias: Some("count"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
auth.set_filter_clause(&mut query_builder).switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
for dim in dimensions.iter() {
query_builder
.add_group_by_clause(dim)
.attach_printable("Error grouping by dimensions")
.switch()?;
}
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.attach_printable("Error adding granularity")
.switch()?;
}
query_builder
.execute_query::<PaymentMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
PaymentMetricsBucketIdentifier::new(
i.currency.as_ref().map(|i| i.0),
None,
i.connector.clone(),
i.authentication_type.as_ref().map(|i| i.0),
i.payment_method.clone(),
i.payment_method_type.clone(),
i.client_source.clone(),
i.client_version.clone(),
i.profile_id.clone(),
i.card_network.clone(),
i.merchant_id.clone(),
i.card_last_4.clone(),
i.card_issuer.clone(),
i.error_reason.clone(),
i.routing_approach.as_ref().map(|i| i.0.clone()),
i.signature_network.clone(),
i.is_issuer_regulated,
i.is_debit_routed,
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
},
),
i,
))
})
.collect::<error_stack::Result<
HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>,
crate::query::PostProcessingError,
>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
|
crates/analytics/src/payments/metrics/sessionized_metrics/success_rate.rs
|
analytics
|
full_file
| null | null | null | 961
| null | null | null | null | null | null | null |
// Struct: ThreedsecureioErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ThreedsecureioErrorResponse
|
crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ThreedsecureioErrorResponse
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// Implementation: impl Responder
// File: crates/router/src/routes/routing.rs
// Module: router
// Methods: 0 total (0 public)
impl Responder
|
crates/router/src/routes/routing.rs
|
router
|
impl_block
| null | null | null | 36
| null |
Responder
| null | 0
| 0
| null | null |
// Struct: OpayoRouterData
// File: crates/hyperswitch_connectors/src/connectors/opayo/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct OpayoRouterData<T>
|
crates/hyperswitch_connectors/src/connectors/opayo/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
OpayoRouterData
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Function: is_recovery_transaction_event
// File: crates/api_models/src/webhooks.rs
// Module: api_models
pub fn is_recovery_transaction_event(&self) -> bool
|
crates/api_models/src/webhooks.rs
|
api_models
|
function_signature
| null | null | null | 36
|
is_recovery_transaction_event
| null | null | null | null | null | null |
// Struct: BusinessCollectLinkConfig
// File: crates/api_models/src/admin.rs
// Module: api_models
// Implementations: 0
pub struct BusinessCollectLinkConfig
|
crates/api_models/src/admin.rs
|
api_models
|
struct_definition
|
BusinessCollectLinkConfig
| 0
|
[] | 37
| null | null | null | null | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.