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
⌀ |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
// Function: set_payment_method_response
// File: crates/router/src/core/payment_methods/tokenize/card_executor.rs
// Module: router
pub fn set_payment_method_response(
self,
payment_method: &'a domain::PaymentMethod,
) -> NetworkTokenizationBuilder<'a, PaymentMethodCreated>
|
crates/router/src/core/payment_methods/tokenize/card_executor.rs
|
router
|
function_signature
| null | null | null | 63
|
set_payment_method_response
| null | null | null | null | null | null |
// Implementation: impl StrongEq for for Vec
// File: crates/masking/src/strong_secret.rs
// Module: masking
// Methods: 1 total (0 public)
impl StrongEq for for Vec
|
crates/masking/src/strong_secret.rs
|
masking
|
impl_block
| null | null | null | 43
| null |
Vec
|
StrongEq for
| 1
| 0
| null | null |
// Function: validate
// File: crates/api_models/src/admin.rs
// Module: api_models
pub fn validate(&self) -> Result<(), &str>
|
crates/api_models/src/admin.rs
|
api_models
|
function_signature
| null | null | null | 33
|
validate
| null | null | null | null | null | null |
// Function: with_source
// File: crates/hyperswitch_domain_models/src/payments.rs
// Module: hyperswitch_domain_models
pub fn with_source(payment_confirm_source: common_enums::PaymentSource) -> Self
|
crates/hyperswitch_domain_models/src/payments.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 46
|
with_source
| null | null | null | null | null | null |
// Struct: PayoutAmount
// File: crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PayoutAmount
|
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PayoutAmount
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Implementation: impl SubmitEvidence for for Adyen
// File: crates/hyperswitch_connectors/src/connectors/adyen.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl SubmitEvidence for for Adyen
|
crates/hyperswitch_connectors/src/connectors/adyen.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 54
| null |
Adyen
|
SubmitEvidence for
| 0
| 0
| null | null |
// Function: refund_update_core
// File: crates/router/src/core/refunds.rs
// Module: router
pub fn refund_update_core(
state: SessionState,
merchant_context: domain::MerchantContext,
req: refunds::RefundUpdateRequest,
) -> RouterResponse<refunds::RefundResponse>
|
crates/router/src/core/refunds.rs
|
router
|
function_signature
| null | null | null | 66
|
refund_update_core
| null | null | null | null | null | null |
// Struct: PaysafeCaptureRequest
// File: crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaysafeCaptureRequest
|
crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaysafeCaptureRequest
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Function: verify_external_token
// File: crates/router/src/core/external_service_auth.rs
// Module: router
pub fn verify_external_token(
state: SessionState,
json_payload: external_service_auth_api::ExternalVerifyTokenRequest,
external_service_type: ExternalServiceType,
) -> RouterResponse<external_service_auth_api::ExternalVerifyTokenResponse>
|
crates/router/src/core/external_service_auth.rs
|
router
|
function_signature
| null | null | null | 75
|
verify_external_token
| null | null | null | null | null | null |
// Struct: ApplePayAccountDetails
// File: crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ApplePayAccountDetails
|
crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ApplePayAccountDetails
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Struct: NetworkTokenDetailsPaymentMethod
// File: crates/hyperswitch_domain_models/src/payment_method_data.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct NetworkTokenDetailsPaymentMethod
|
crates/hyperswitch_domain_models/src/payment_method_data.rs
|
hyperswitch_domain_models
|
struct_definition
|
NetworkTokenDetailsPaymentMethod
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Implementation: impl PaymentAuthorize for for Signifyd
// File: crates/hyperswitch_connectors/src/connectors/signifyd.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl PaymentAuthorize for for Signifyd
|
crates/hyperswitch_connectors/src/connectors/signifyd.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 56
| null |
Signifyd
|
PaymentAuthorize for
| 0
| 0
| null | null |
// Function: is_true
// File: crates/common_utils/src/types/primitive_wrappers.rs
// Module: common_utils
// Documentation: returns the inner bool value
pub fn is_true(&self) -> bool
|
crates/common_utils/src/types/primitive_wrappers.rs
|
common_utils
|
function_signature
| null | null | null | 44
|
is_true
| null | null | null | null | null | null |
// Struct: TrustpaymentsFilter
// File: crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct TrustpaymentsFilter
|
crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
TrustpaymentsFilter
| 0
|
[] | 48
| null | null | null | null | null | null | null |
// Struct: InterpreterBackend
// File: crates/euclid/src/backend/interpreter.rs
// Module: euclid
// Implementations: 1
pub struct InterpreterBackend<O>
|
crates/euclid/src/backend/interpreter.rs
|
euclid
|
struct_definition
|
InterpreterBackend
| 1
|
[] | 38
| null | null | null | null | null | null | null |
// Implementation: impl api::MandateSetup for for Multisafepay
// File: crates/hyperswitch_connectors/src/connectors/multisafepay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::MandateSetup for for Multisafepay
|
crates/hyperswitch_connectors/src/connectors/multisafepay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 71
| null |
Multisafepay
|
api::MandateSetup for
| 0
| 0
| null | null |
// Function: add_external_account_addition_task
// File: crates/router/src/core/payouts.rs
// Module: router
pub fn add_external_account_addition_task(
db: &dyn StorageInterface,
payout_data: &PayoutData,
schedule_time: time::PrimitiveDateTime,
) -> CustomResult<(), errors::StorageError>
|
crates/router/src/core/payouts.rs
|
router
|
function_signature
| null | null | null | 72
|
add_external_account_addition_task
| null | null | null | null | null | null |
// Implementation: impl api::PaymentSync for for Peachpayments
// File: crates/hyperswitch_connectors/src/connectors/peachpayments.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSync for for Peachpayments
|
crates/hyperswitch_connectors/src/connectors/peachpayments.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Peachpayments
|
api::PaymentSync for
| 0
| 0
| null | null |
// File: crates/router/src/types/storage/dispute.rs
// Module: router
use async_bb8_diesel::AsyncRunQueryDsl;
use common_utils::errors::CustomResult;
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, QueryDsl};
pub use diesel_models::dispute::{Dispute, DisputeNew, DisputeUpdate};
use diesel_models::{errors, query::generics::db_metrics, schema::dispute::dsl};
use error_stack::ResultExt;
use hyperswitch_domain_models::disputes;
use crate::{connection::PgPooledConn, logger};
#[async_trait::async_trait]
pub trait DisputeDbExt: Sized {
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
dispute_list_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
async fn get_dispute_status_with_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::enums::DisputeStatus, i64)>, errors::DatabaseError>;
}
#[async_trait::async_trait]
impl DisputeDbExt for Dispute {
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
dispute_list_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.order(dsl::modified_at.desc())
.into_boxed();
let mut search_by_payment_or_dispute_id = false;
if let (Some(payment_id), Some(dispute_id)) = (
&dispute_list_constraints.payment_id,
&dispute_list_constraints.dispute_id,
) {
search_by_payment_or_dispute_id = true;
filter = filter.filter(
dsl::payment_id
.eq(payment_id.to_owned())
.or(dsl::dispute_id.eq(dispute_id.to_owned())),
);
};
if !search_by_payment_or_dispute_id {
if let Some(payment_id) = &dispute_list_constraints.payment_id {
filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned()));
};
}
if !search_by_payment_or_dispute_id {
if let Some(dispute_id) = &dispute_list_constraints.dispute_id {
filter = filter.filter(dsl::dispute_id.eq(dispute_id.clone()));
};
}
if let Some(time_range) = dispute_list_constraints.time_range {
filter = filter.filter(dsl::created_at.ge(time_range.start_time));
if let Some(end_time) = time_range.end_time {
filter = filter.filter(dsl::created_at.le(end_time));
}
}
if let Some(profile_id) = &dispute_list_constraints.profile_id {
filter = filter.filter(dsl::profile_id.eq_any(profile_id.clone()));
}
if let Some(connector_list) = &dispute_list_constraints.connector {
filter = filter.filter(dsl::connector.eq_any(connector_list.clone()));
}
if let Some(reason) = &dispute_list_constraints.reason {
filter = filter.filter(dsl::connector_reason.eq(reason.clone()));
}
if let Some(dispute_stage) = &dispute_list_constraints.dispute_stage {
filter = filter.filter(dsl::dispute_stage.eq_any(dispute_stage.clone()));
}
if let Some(dispute_status) = &dispute_list_constraints.dispute_status {
filter = filter.filter(dsl::dispute_status.eq_any(dispute_status.clone()));
}
if let Some(currency_list) = &dispute_list_constraints.currency {
filter = filter.filter(dsl::dispute_currency.eq_any(currency_list.clone()));
}
if let Some(merchant_connector_id) = &dispute_list_constraints.merchant_connector_id {
filter = filter.filter(dsl::merchant_connector_id.eq(merchant_connector_id.clone()))
}
if let Some(limit) = dispute_list_constraints.limit {
filter = filter.limit(limit.into());
}
if let Some(offset) = dispute_list_constraints.offset {
filter = filter.offset(offset.into());
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
filter.get_results_async(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering records by predicate")
}
async fn get_dispute_status_with_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::DatabaseError> {
let mut query = <Self as HasTable>::table()
.group_by(dsl::dispute_status)
.select((dsl::dispute_status, diesel::dsl::count_star()))
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.into_boxed();
if let Some(profile_id) = profile_id_list {
query = query.filter(dsl::profile_id.eq_any(profile_id));
}
query = query.filter(dsl::created_at.ge(time_range.start_time));
query = match time_range.end_time {
Some(ending_at) => query.filter(dsl::created_at.le(ending_at)),
None => query,
};
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
query.get_results_async::<(common_enums::DisputeStatus, i64)>(conn),
db_metrics::DatabaseOperation::Count,
)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering records by predicate")
}
}
|
crates/router/src/types/storage/dispute.rs
|
router
|
full_file
| null | null | null | 1,402
| null | null | null | null | null | null | null |
// Function: find_by_algorithm_id_profile_id
// File: crates/diesel_models/src/query/routing_algorithm.rs
// Module: diesel_models
pub fn find_by_algorithm_id_profile_id(
conn: &PgPooledConn,
algorithm_id: &common_utils::id_type::RoutingId,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<Self>
|
crates/diesel_models/src/query/routing_algorithm.rs
|
diesel_models
|
function_signature
| null | null | null | 83
|
find_by_algorithm_id_profile_id
| null | null | null | null | null | null |
// Function: discover_smithy_models
// File: crates/smithy-generator/build.rs
// Module: smithy-generator
pub fn discover_smithy_models() -> Vec<SmithyModel>
|
crates/smithy-generator/build.rs
|
smithy-generator
|
function_signature
| null | null | null | 42
|
discover_smithy_models
| null | null | null | null | null | null |
// File: crates/external_services/src/grpc_client/health_check_client.rs
// Module: external_services
// Public functions: 2
// Public structs: 1
use std::{collections::HashMap, fmt::Debug};
use api_models::health_check::{HealthCheckMap, HealthCheckServices};
use common_utils::{errors::CustomResult, ext_traits::AsyncExt};
use error_stack::ResultExt;
pub use health_check::{
health_check_response::ServingStatus, health_client::HealthClient, HealthCheckRequest,
HealthCheckResponse,
};
use router_env::logger;
#[allow(
missing_docs,
unused_qualifications,
clippy::unwrap_used,
clippy::as_conversions,
clippy::use_self
)]
pub mod health_check {
tonic::include_proto!("grpc.health.v1");
}
use super::{Client, DynamicRoutingClientConfig, GrpcClientSettings};
/// Result type for Dynamic Routing
pub type HealthCheckResult<T> = CustomResult<T, HealthCheckError>;
/// Dynamic Routing Errors
#[derive(Debug, Clone, thiserror::Error)]
pub enum HealthCheckError {
/// The required input is missing
#[error("Missing fields: {0} for building the Health check connection")]
MissingFields(String),
/// Error from gRPC Server
#[error("Error from gRPC Server : {0}")]
ConnectionError(String),
/// status is invalid
#[error("Invalid Status from server")]
InvalidStatus,
}
/// Health Check Client type
#[derive(Debug, Clone)]
pub struct HealthCheckClient {
/// Health clients for all gRPC based services
pub clients: HashMap<HealthCheckServices, HealthClient<Client>>,
}
impl HealthCheckClient {
/// Build connections to all gRPC services
pub async fn build_connections(
config: &GrpcClientSettings,
client: Client,
) -> Result<Self, Box<dyn std::error::Error>> {
let dynamic_routing_config = &config.dynamic_routing_client;
let connection = match dynamic_routing_config {
Some(DynamicRoutingClientConfig::Enabled {
host,
port,
service,
}) => Some((host.clone(), *port, service.clone())),
_ => None,
};
let mut client_map = HashMap::new();
if let Some(conn) = connection {
let uri = format!("http://{}:{}", conn.0, conn.1).parse::<tonic::transport::Uri>()?;
let health_client = HealthClient::with_origin(client, uri);
client_map.insert(HealthCheckServices::DynamicRoutingService, health_client);
}
Ok(Self {
clients: client_map,
})
}
/// Perform health check for all services involved
pub async fn perform_health_check(
&self,
config: &GrpcClientSettings,
) -> HealthCheckResult<HealthCheckMap> {
let dynamic_routing_config = &config.dynamic_routing_client;
let connection = match dynamic_routing_config {
Some(DynamicRoutingClientConfig::Enabled {
host,
port,
service,
}) => Some((host.clone(), *port, service.clone())),
_ => None,
};
let health_client = self
.clients
.get(&HealthCheckServices::DynamicRoutingService);
// SAFETY : This is a safe cast as there exists a valid
// integer value for this variant
#[allow(clippy::as_conversions)]
let expected_status = ServingStatus::Serving as i32;
let mut service_map = HealthCheckMap::new();
let health_check_succeed = connection
.as_ref()
.async_map(|conn| self.get_response_from_grpc_service(conn.2.clone(), health_client))
.await
.transpose()
.change_context(HealthCheckError::ConnectionError(
"error calling dynamic routing service".to_string(),
))
.map_err(|err| logger::error!(error=?err))
.ok()
.flatten()
.is_some_and(|resp| resp.status == expected_status);
connection.and_then(|_conn| {
service_map.insert(
HealthCheckServices::DynamicRoutingService,
health_check_succeed,
)
});
Ok(service_map)
}
async fn get_response_from_grpc_service(
&self,
service: String,
client: Option<&HealthClient<Client>>,
) -> HealthCheckResult<HealthCheckResponse> {
let request = tonic::Request::new(HealthCheckRequest { service });
let mut client = client
.ok_or(HealthCheckError::MissingFields(
"[health_client]".to_string(),
))?
.clone();
let response = client
.check(request)
.await
.change_context(HealthCheckError::ConnectionError(
"Failed to call dynamic routing service".to_string(),
))?
.into_inner();
Ok(response)
}
}
|
crates/external_services/src/grpc_client/health_check_client.rs
|
external_services
|
full_file
| null | null | null | 1,037
| null | null | null | null | null | null | null |
// Struct: Relay
// File: crates/router/src/routes/app.rs
// Module: router
// Implementations: 1
pub struct Relay
|
crates/router/src/routes/app.rs
|
router
|
struct_definition
|
Relay
| 1
|
[] | 30
| null | null | null | null | null | null | null |
// Struct: ErrorInformation
// File: crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ErrorInformation
|
crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ErrorInformation
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Function: validate
// File: crates/router/src/configs/validations.rs
// Module: router
pub fn validate(&self) -> Result<(), ApplicationError>
|
crates/router/src/configs/validations.rs
|
router
|
function_signature
| null | null | null | 35
|
validate
| null | null | null | null | null | null |
// Struct: PayoutListFilterConstraints
// File: crates/api_models/src/payouts.rs
// Module: api_models
// Implementations: 0
pub struct PayoutListFilterConstraints
|
crates/api_models/src/payouts.rs
|
api_models
|
struct_definition
|
PayoutListFilterConstraints
| 0
|
[] | 41
| null | null | null | null | null | null | null |
// Struct: VecLinearErrorStack
// File: crates/router/src/core/errors.rs
// Module: router
// Implementations: 0
pub struct VecLinearErrorStack<'a>
|
crates/router/src/core/errors.rs
|
router
|
struct_definition
|
VecLinearErrorStack
| 0
|
[] | 39
| null | null | null | null | null | null | null |
// Function: is_alternate_network_possible
// File: crates/common_types/src/domain.rs
// Module: common_types
// Documentation: Checks if retry with alternate network is possible.
pub fn is_alternate_network_possible(&self) -> bool
|
crates/common_types/src/domain.rs
|
common_types
|
function_signature
| null | null | null | 49
|
is_alternate_network_possible
| null | null | null | null | null | null |
// Function: deep_health_check_func
// File: crates/router/src/bin/scheduler.rs
// Module: router
pub fn deep_health_check_func(
state: routes::SessionState,
service: &str,
) -> errors::RouterResult<SchedulerHealthCheckResponse>
|
crates/router/src/bin/scheduler.rs
|
router
|
function_signature
| null | null | null | 57
|
deep_health_check_func
| null | null | null | null | null | null |
// Struct: HateoasLink
// File: crates/router/src/types/api/connector_onboarding/paypal.rs
// Module: router
// Implementations: 0
pub struct HateoasLink
|
crates/router/src/types/api/connector_onboarding/paypal.rs
|
router
|
struct_definition
|
HateoasLink
| 0
|
[] | 42
| null | null | null | null | null | null | null |
// Struct: MollieErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct MollieErrorResponse
|
crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
MollieErrorResponse
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Function: get_id
// File: crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
// Module: hyperswitch_domain_models
pub fn get_id(&self) -> &id_type::GlobalAttemptId
|
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 46
|
get_id
| null | null | null | null | null | null |
// Struct: ConsumerSettings
// File: crates/scheduler/src/configs/settings.rs
// Module: scheduler
// Implementations: 0
pub struct ConsumerSettings
|
crates/scheduler/src/configs/settings.rs
|
scheduler
|
struct_definition
|
ConsumerSettings
| 0
|
[] | 34
| null | null | null | null | null | null | null |
// Function: map_dispute_notification_to_event
// File: crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
// Module: hyperswitch_connectors
pub fn map_dispute_notification_to_event(
dispute_code: DisputeUnifiedStatusCode,
) -> Result<api_models::webhooks::IncomingWebhookEvent, error_stack::Report<errors::ConnectorError>>
|
crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 83
|
map_dispute_notification_to_event
| null | null | null | null | null | null |
// Function: refund_create
// File: crates/router/src/compatibility/stripe/refunds.rs
// Module: router
pub fn refund_create(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
) -> HttpResponse
|
crates/router/src/compatibility/stripe/refunds.rs
|
router
|
function_signature
| null | null | null | 71
|
refund_create
| null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
// Module: hyperswitch_connectors
// Public structs: 21
use cards::CardNumber;
use common_enums::enums;
use common_utils::{pii::Email, request::Method, types::StringMajorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankDebitData, BankRedirectData, PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, PaymentMethodToken, RouterData},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
unimplemented_payment_method,
utils::{
AddressDetailsData, BrowserInformationData, CardData as CardDataUtil,
PaymentMethodTokenizationRequestData, PaymentsAuthorizeRequestData, RouterData as _,
},
};
type Error = error_stack::Report<errors::ConnectorError>;
#[derive(Debug, Serialize)]
pub struct MollieRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for MollieRouterData<T> {
fn from((amount, router_data): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MolliePaymentsRequest {
amount: Amount,
description: String,
redirect_url: String,
cancel_url: Option<String>,
webhook_url: String,
locale: Option<String>,
#[serde(flatten)]
payment_method_data: MolliePaymentMethodData,
metadata: Option<MollieMetadata>,
sequence_type: SequenceType,
mandate_id: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct Amount {
currency: enums::Currency,
value: StringMajorUnit,
}
#[derive(Debug, Serialize)]
#[serde(tag = "method")]
#[serde(rename_all = "lowercase")]
pub enum MolliePaymentMethodData {
Applepay(Box<ApplePayMethodData>),
Eps,
Giropay,
Ideal(Box<IdealMethodData>),
Paypal(Box<PaypalMethodData>),
Sofort,
Przelewy24(Box<Przelewy24MethodData>),
Bancontact,
CreditCard(Box<CreditCardMethodData>),
DirectDebit(Box<DirectDebitMethodData>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayMethodData {
apple_pay_payment_token: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IdealMethodData {
issuer: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaypalMethodData {
billing_address: Option<Address>,
shipping_address: Option<Address>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Przelewy24MethodData {
billing_email: Option<Email>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DirectDebitMethodData {
consumer_name: Option<Secret<String>>,
consumer_account: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreditCardMethodData {
billing_address: Option<Address>,
shipping_address: Option<Address>,
card_token: Option<Secret<String>>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SequenceType {
#[default]
Oneoff,
First,
Recurring,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Address {
pub street_and_number: Secret<String>,
pub postal_code: Secret<String>,
pub city: String,
pub region: Option<Secret<String>>,
pub country: api_models::enums::CountryAlpha2,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MollieMetadata {
pub order_id: String,
}
impl TryFrom<&MollieRouterData<&types::PaymentsAuthorizeRouterData>> for MolliePaymentsRequest {
type Error = Error;
fn try_from(
item: &MollieRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let amount = Amount {
currency: item.router_data.request.currency,
value: item.amount.clone(),
};
let description = item.router_data.get_description()?;
let redirect_url = item.router_data.request.get_router_return_url()?;
let payment_method_data = match item.router_data.request.capture_method.unwrap_or_default()
{
enums::CaptureMethod::Automatic | enums::CaptureMethod::SequentialAutomatic => {
match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(_) => {
let pm_token = item.router_data.get_payment_method_token()?;
Ok(MolliePaymentMethodData::CreditCard(Box::new(
CreditCardMethodData {
billing_address: get_billing_details(item.router_data)?,
shipping_address: get_shipping_details(item.router_data)?,
card_token: Some(match pm_token {
PaymentMethodToken::Token(token) => token,
PaymentMethodToken::ApplePayDecrypt(_) => {
Err(unimplemented_payment_method!(
"Apple Pay",
"Simplified",
"Mollie"
))?
}
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Mollie"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Mollie"))?
}
}),
},
)))
}
PaymentMethodData::BankRedirect(ref redirect_data) => {
MolliePaymentMethodData::try_from((item.router_data, redirect_data))
}
PaymentMethodData::Wallet(ref wallet_data) => {
get_payment_method_for_wallet(item.router_data, wallet_data)
}
PaymentMethodData::BankDebit(ref directdebit_data) => {
MolliePaymentMethodData::try_from((directdebit_data, item.router_data))
}
_ => Err(
errors::ConnectorError::NotImplemented("Payment Method".to_string()).into(),
),
}
}
_ => Err(errors::ConnectorError::FlowNotSupported {
flow: format!(
"{} capture",
item.router_data.request.capture_method.unwrap_or_default()
),
connector: "Mollie".to_string(),
}
.into()),
}?;
Ok(Self {
amount,
description,
redirect_url,
cancel_url: None,
/* webhook_url is a mandatory field.
But we can't support webhook in our core hence keeping it as empty string */
webhook_url: "".to_string(),
locale: None,
payment_method_data,
metadata: Some(MollieMetadata {
order_id: item.router_data.connector_request_reference_id.clone(),
}),
sequence_type: SequenceType::Oneoff,
mandate_id: None,
})
}
}
impl TryFrom<(&types::PaymentsAuthorizeRouterData, &BankRedirectData)> for MolliePaymentMethodData {
type Error = Error;
fn try_from(
(item, value): (&types::PaymentsAuthorizeRouterData, &BankRedirectData),
) -> Result<Self, Self::Error> {
match value {
BankRedirectData::Eps { .. } => Ok(Self::Eps),
BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
BankRedirectData::Ideal { .. } => {
Ok(Self::Ideal(Box::new(IdealMethodData {
// To do if possible this should be from the payment request
issuer: None,
})))
}
BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
BankRedirectData::Przelewy24 { .. } => {
Ok(Self::Przelewy24(Box::new(Przelewy24MethodData {
billing_email: item.get_optional_billing_email(),
})))
}
BankRedirectData::BancontactCard { .. } => Ok(Self::Bancontact),
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
impl TryFrom<(&BankDebitData, &types::PaymentsAuthorizeRouterData)> for MolliePaymentMethodData {
type Error = Error;
fn try_from(
(bank_debit_data, item): (&BankDebitData, &types::PaymentsAuthorizeRouterData),
) -> Result<Self, Self::Error> {
match bank_debit_data {
BankDebitData::SepaBankDebit { iban, .. } => {
Ok(Self::DirectDebit(Box::new(DirectDebitMethodData {
consumer_name: item.get_optional_billing_full_name(),
consumer_account: iban.clone(),
})))
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MollieCardTokenRequest {
card_holder: Secret<String>,
card_number: CardNumber,
card_cvv: Secret<String>,
card_expiry_date: Secret<String>,
locale: String,
testmode: bool,
profile_token: Secret<String>,
}
impl TryFrom<&types::TokenizationRouterData> for MollieCardTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => {
let auth = MollieAuthType::try_from(&item.connector_auth_type)?;
let card_holder = item
.get_optional_billing_full_name()
.unwrap_or(Secret::new("".to_string()));
let card_number = ccard.card_number.clone();
let card_expiry_date =
ccard.get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned())?;
let card_cvv = ccard.card_cvc;
let locale = item.request.get_browser_info()?.get_language()?;
let testmode =
item.test_mode
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "test_mode",
})?;
let profile_token = auth
.profile_token
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(Self {
card_holder,
card_number,
card_cvv,
card_expiry_date,
locale,
testmode,
profile_token,
})
}
_ => Err(errors::ConnectorError::NotImplemented(
"Payment Method".to_string(),
))?,
}
}
}
fn get_payment_method_for_wallet(
item: &types::PaymentsAuthorizeRouterData,
wallet_data: &WalletData,
) -> Result<MolliePaymentMethodData, Error> {
match wallet_data {
WalletData::PaypalRedirect { .. } => Ok(MolliePaymentMethodData::Paypal(Box::new(
PaypalMethodData {
billing_address: get_billing_details(item)?,
shipping_address: get_shipping_details(item)?,
},
))),
WalletData::ApplePay(applepay_wallet_data) => {
let apple_pay_encrypted_data = applepay_wallet_data
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
Ok(MolliePaymentMethodData::Applepay(Box::new(
ApplePayMethodData {
apple_pay_payment_token: Secret::new(apple_pay_encrypted_data.to_owned()),
},
)))
}
_ => Err(errors::ConnectorError::NotImplemented("Payment Method".to_string()).into()),
}
}
fn get_shipping_details(
item: &types::PaymentsAuthorizeRouterData,
) -> Result<Option<Address>, Error> {
let shipping_address = item
.get_optional_shipping()
.and_then(|shipping| shipping.address.as_ref());
get_address_details(shipping_address)
}
fn get_billing_details(
item: &types::PaymentsAuthorizeRouterData,
) -> Result<Option<Address>, Error> {
let billing_address = item
.get_optional_billing()
.and_then(|billing| billing.address.as_ref());
get_address_details(billing_address)
}
fn get_address_details(
address: Option<&hyperswitch_domain_models::address::AddressDetails>,
) -> Result<Option<Address>, Error> {
let address_details = match address {
Some(address) => {
let street_and_number = address.get_combined_address_line()?;
let postal_code = address.get_zip()?.to_owned();
let city = address.get_city()?.to_owned();
let region = None;
let country = address.get_country()?.to_owned();
Some(Address {
street_and_number,
postal_code,
city,
region,
country,
})
}
None => None,
};
Ok(address_details)
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MolliePaymentsResponse {
pub resource: String,
pub id: String,
pub amount: Amount,
pub description: Option<String>,
pub metadata: Option<MollieMetadata>,
pub status: MolliePaymentStatus,
pub is_cancelable: Option<bool>,
pub sequence_type: SequenceType,
pub redirect_url: Option<String>,
pub webhook_url: Option<String>,
#[serde(rename = "_links")]
pub links: Links,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum MolliePaymentStatus {
Open,
Canceled,
#[default]
Pending,
Authorized,
Expired,
Failed,
Paid,
}
impl From<MolliePaymentStatus> for enums::AttemptStatus {
fn from(item: MolliePaymentStatus) -> Self {
match item {
MolliePaymentStatus::Paid => Self::Charged,
MolliePaymentStatus::Failed => Self::Failure,
MolliePaymentStatus::Pending => Self::Pending,
MolliePaymentStatus::Open => Self::AuthenticationPending,
MolliePaymentStatus::Canceled => Self::Voided,
MolliePaymentStatus::Authorized => Self::Authorized,
MolliePaymentStatus::Expired => Self::Failure,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Link {
href: Url,
#[serde(rename = "type")]
type_: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Links {
#[serde(rename = "self")]
self_: Option<Link>,
checkout: Option<Link>,
dashboard: Option<Link>,
documentation: Option<Link>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardDetails {
pub card_number: Secret<String>,
pub card_holder: Secret<String>,
pub card_expiry_date: Secret<String>,
pub card_cvv: Secret<String>,
}
pub struct MollieAuthType {
pub(super) api_key: Secret<String>,
pub(super) profile_token: Option<Secret<String>>,
}
impl TryFrom<&ConnectorAuthType> for MollieAuthType {
type Error = Error;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
profile_token: None,
}),
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
profile_token: Some(key1.to_owned()),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MollieCardTokenResponse {
card_token: Secret<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, MollieCardTokenResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, MollieCardTokenResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::Pending,
payment_method_token: Some(PaymentMethodToken::Token(item.response.card_token.clone())),
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.card_token.expose(),
}),
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, MolliePaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, MolliePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let url = item
.response
.links
.checkout
.map(|link| RedirectForm::from((link.href, Method::Get)));
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(url),
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
})
}
}
// REFUND :
#[derive(Default, Debug, Serialize)]
pub struct MollieRefundRequest {
amount: Amount,
description: Option<String>,
metadata: Option<MollieMetadata>,
}
impl<F> TryFrom<&MollieRouterData<&types::RefundsRouterData<F>>> for MollieRefundRequest {
type Error = Error;
fn try_from(
item: &MollieRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let amount = Amount {
currency: item.router_data.request.currency,
value: item.amount.clone(),
};
Ok(Self {
amount,
description: item.router_data.request.reason.to_owned(),
metadata: Some(MollieMetadata {
order_id: item.router_data.request.refund_id.clone(),
}),
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
resource: String,
id: String,
amount: Amount,
settlement_id: Option<String>,
settlement_amount: Option<Amount>,
status: MollieRefundStatus,
description: Option<String>,
metadata: Option<MollieMetadata>,
payment_id: String,
#[serde(rename = "_links")]
links: Links,
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MollieRefundStatus {
Queued,
#[default]
Pending,
Processing,
Refunded,
Failed,
Canceled,
}
impl From<MollieRefundStatus> for enums::RefundStatus {
fn from(item: MollieRefundStatus) -> Self {
match item {
MollieRefundStatus::Queued
| MollieRefundStatus::Pending
| MollieRefundStatus::Processing => Self::Pending,
MollieRefundStatus::Refunded => Self::Success,
MollieRefundStatus::Failed | MollieRefundStatus::Canceled => Self::Failure,
}
}
}
impl<T> TryFrom<RefundsResponseRouterData<T, RefundResponse>> for types::RefundsRouterData<T> {
type Error = Error;
fn try_from(item: RefundsResponseRouterData<T, RefundResponse>) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct MollieErrorResponse {
pub status: u16,
pub title: Option<String>,
pub detail: String,
pub field: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 4,522
| null | null | null | null | null | null | null |
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_)
| WalletData::Paze(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
))?,
},
PaymentMethodData::BankRedirect(ref bank_redirection_data) => {
let bank_redirect_intent = if item.router_data.request.is_auto_capture()? {
PaypalPaymentIntent::Capture
} else {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Manual capture method for Bank Redirect".to_string(),
connector: "Paypal".to_string(),
})?
};
let payment_source =
Some(get_payment_source(item.router_data, bank_redirection_data)?);
Ok(Self {
intent: bank_redirect_intent,
purchase_units,
payment_source,
})
}
PaymentMethodData::CardRedirect(ref card_redirect_data) => {
Self::try_from(card_redirect_data)
}
PaymentMethodData::PayLater(ref paylater_data) => Self::try_from(paylater_data),
PaymentMethodData::BankDebit(ref bank_debit_data) => Self::try_from(bank_debit_data),
PaymentMethodData::BankTransfer(ref bank_transfer_data) => {
Self::try_from(bank_transfer_data.as_ref())
}
PaymentMethodData::Voucher(ref voucher_data) => Self::try_from(voucher_data),
PaymentMethodData::GiftCard(ref giftcard_data) => {
Self::try_from(giftcard_data.as_ref())
}
PaymentMethodData::MandatePayment => {
let payment_method_type = item
.router_data
.get_recurring_mandate_payment_data()?
.payment_method_type
.ok_or_else(missing_field_err("payment_method_type"))?;
let connector_mandate_id = item.router_data.request.connector_mandate_id().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_id",
},
)?;
let payment_source = match payment_method_type {
#[cfg(feature = "v1")]
enums::PaymentMethodType::Credit | enums::PaymentMethodType::Debit => Ok(Some(
PaymentSourceItem::Card(CardRequest::CardVaultStruct(VaultStruct {
vault_id: connector_mandate_id.into(),
})),
)),
#[cfg(feature = "v2")]
enums::PaymentMethodType::Credit
| enums::PaymentMethodType::Debit
| enums::PaymentMethodType::Card => Ok(Some(PaymentSourceItem::Card(
CardRequest::CardVaultStruct(VaultStruct {
vault_id: connector_mandate_id.into(),
}),
))),
enums::PaymentMethodType::Paypal => Ok(Some(PaymentSourceItem::Paypal(
PaypalRedirectionRequest::PaypalVaultStruct(VaultStruct {
vault_id: connector_mandate_id.into(),
}),
))),
enums::PaymentMethodType::Ach
| enums::PaymentMethodType::Affirm
| enums::PaymentMethodType::AfterpayClearpay
| enums::PaymentMethodType::Alfamart
| enums::PaymentMethodType::AliPay
| enums::PaymentMethodType::AliPayHk
| enums::PaymentMethodType::Alma
| enums::PaymentMethodType::AmazonPay
| enums::PaymentMethodType::Paysera
| enums::PaymentMethodType::Skrill
| enums::PaymentMethodType::ApplePay
| enums::PaymentMethodType::Atome
| enums::PaymentMethodType::Bacs
| enums::PaymentMethodType::BancontactCard
| enums::PaymentMethodType::Becs
| enums::PaymentMethodType::Benefit
| enums::PaymentMethodType::Bizum
| enums::PaymentMethodType::BhnCardNetwork
| enums::PaymentMethodType::Blik
| enums::PaymentMethodType::Boleto
| enums::PaymentMethodType::BcaBankTransfer
| enums::PaymentMethodType::BniVa
| enums::PaymentMethodType::BriVa
| enums::PaymentMethodType::CardRedirect
| enums::PaymentMethodType::CimbVa
| enums::PaymentMethodType::ClassicReward
| enums::PaymentMethodType::CryptoCurrency
| enums::PaymentMethodType::Cashapp
| enums::PaymentMethodType::Dana
| enums::PaymentMethodType::DanamonVa
| enums::PaymentMethodType::DirectCarrierBilling
| enums::PaymentMethodType::DuitNow
| enums::PaymentMethodType::Efecty
| enums::PaymentMethodType::Eft
| enums::PaymentMethodType::Eps
| enums::PaymentMethodType::Bluecode
| enums::PaymentMethodType::Fps
| enums::PaymentMethodType::Evoucher
| enums::PaymentMethodType::Giropay
| enums::PaymentMethodType::Givex
| enums::PaymentMethodType::GooglePay
| enums::PaymentMethodType::GoPay
| enums::PaymentMethodType::Gcash
| enums::PaymentMethodType::Ideal
| enums::PaymentMethodType::Interac
| enums::PaymentMethodType::Indomaret
| enums::PaymentMethodType::Klarna
| enums::PaymentMethodType::KakaoPay
| enums::PaymentMethodType::LocalBankRedirect
| enums::PaymentMethodType::MandiriVa
| enums::PaymentMethodType::Knet
| enums::PaymentMethodType::MbWay
| enums::PaymentMethodType::MobilePay
| enums::PaymentMethodType::Momo
| enums::PaymentMethodType::MomoAtm
| enums::PaymentMethodType::Multibanco
| enums::PaymentMethodType::OnlineBankingThailand
| enums::PaymentMethodType::OnlineBankingCzechRepublic
| enums::PaymentMethodType::OnlineBankingFinland
| enums::PaymentMethodType::OnlineBankingFpx
| enums::PaymentMethodType::OnlineBankingPoland
| enums::PaymentMethodType::OnlineBankingSlovakia
| enums::PaymentMethodType::OpenBankingPIS
| enums::PaymentMethodType::Oxxo
| enums::PaymentMethodType::PagoEfectivo
| enums::PaymentMethodType::PermataBankTransfer
| enums::PaymentMethodType::OpenBankingUk
| enums::PaymentMethodType::PayBright
| enums::PaymentMethodType::Pix
| enums::PaymentMethodType::PaySafeCard
| enums::PaymentMethodType::Przelewy24
| enums::PaymentMethodType::PromptPay
| enums::PaymentMethodType::Pse
| enums::PaymentMethodType::RedCompra
| enums::PaymentMethodType::RedPagos
| enums::PaymentMethodType::SamsungPay
| enums::PaymentMethodType::Sepa
| enums::PaymentMethodType::SepaBankTransfer
| enums::PaymentMethodType::Sofort
| enums::PaymentMethodType::Swish
| enums::PaymentMethodType::TouchNGo
| enums::PaymentMethodType::Trustly
| enums::PaymentMethodType::Twint
| enums::PaymentMethodType::UpiCollect
| enums::PaymentMethodType::UpiIntent
| enums::PaymentMethodType::Vipps
| enums::PaymentMethodType::VietQr
| enums::PaymentMethodType::Venmo
| enums::PaymentMethodType::Walley
| enums::PaymentMethodType::WeChatPay
| enums::PaymentMethodType::SevenEleven
| enums::PaymentMethodType::Lawson
| enums::PaymentMethodType::MiniStop
| enums::PaymentMethodType::FamilyMart
| enums::PaymentMethodType::Seicomart
| enums::PaymentMethodType::PayEasy
| enums::PaymentMethodType::LocalBankTransfer
| enums::PaymentMethodType::InstantBankTransfer
| enums::PaymentMethodType::InstantBankTransferFinland
| enums::PaymentMethodType::InstantBankTransferPoland
| enums::PaymentMethodType::Mifinity
| enums::PaymentMethodType::Paze
| enums::PaymentMethodType::IndonesianBankTransfer
| enums::PaymentMethodType::Flexiti
| enums::PaymentMethodType::RevolutPay
| enums::PaymentMethodType::Breadpay => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("paypal"),
))
}
};
Ok(Self {
intent,
purchase_units,
payment_source: payment_source?,
})
}
PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
)
.into())
}
}
}
}
impl TryFrom<&CardRedirectData> for PaypalPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &CardRedirectData) -> Result<Self, Self::Error> {
match value {
CardRedirectData::Knet {}
| CardRedirectData::Benefit {}
| CardRedirectData::MomoAtm {}
| CardRedirectData::CardRedirect {} => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
)
.into()),
}
}
}
impl TryFrom<&PayLaterData> for PaypalPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &PayLaterData) -> Result<Self, Self::Error> {
match value {
PayLaterData::KlarnaRedirect { .. }
| PayLaterData::KlarnaSdk { .. }
| PayLaterData::AffirmRedirect {}
| PayLaterData::AfterpayClearpayRedirect { .. }
| PayLaterData::PayBrightRedirect {}
| PayLaterData::WalleyRedirect {}
| PayLaterData::FlexitiRedirect {}
| PayLaterData::AlmaRedirect {}
| PayLaterData::AtomeRedirect {}
| PayLaterData::BreadpayRedirect {} => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
)
.into()),
}
}
}
impl TryFrom<&BankDebitData> for PaypalPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &BankDebitData) -> Result<Self, Self::Error> {
match value {
BankDebitData::AchBankDebit { .. }
| BankDebitData::SepaBankDebit { .. }
| BankDebitData::BecsBankDebit { .. }
| BankDebitData::BacsBankDebit { .. } => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
)
.into()),
}
}
}
impl TryFrom<&BankTransferData> for PaypalPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &BankTransferData) -> Result<Self, Self::Error> {
match value {
BankTransferData::AchBankTransfer { .. }
| BankTransferData::SepaBankTransfer { .. }
| BankTransferData::BacsBankTransfer { .. }
| BankTransferData::MultibancoBankTransfer { .. }
| BankTransferData::PermataBankTransfer { .. }
| BankTransferData::BcaBankTransfer { .. }
| BankTransferData::BniVaBankTransfer { .. }
| BankTransferData::BriVaBankTransfer { .. }
| BankTransferData::CimbVaBankTransfer { .. }
| BankTransferData::DanamonVaBankTransfer { .. }
| BankTransferData::MandiriVaBankTransfer { .. }
| BankTransferData::Pix { .. }
| BankTransferData::Pse {}
| BankTransferData::InstantBankTransfer {}
| BankTransferData::InstantBankTransferFinland {}
| BankTransferData::InstantBankTransferPoland {}
| BankTransferData::IndonesianBankTransfer { .. }
| BankTransferData::LocalBankTransfer { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
)
.into())
}
}
}
}
impl TryFrom<&VoucherData> for PaypalPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &VoucherData) -> Result<Self, Self::Error> {
match value {
VoucherData::Boleto(_)
| VoucherData::Efecty
| VoucherData::PagoEfectivo
| VoucherData::RedCompra
| VoucherData::RedPagos
| VoucherData::Alfamart(_)
| VoucherData::Indomaret(_)
| VoucherData::Oxxo
| VoucherData::SevenEleven(_)
| VoucherData::Lawson(_)
| VoucherData::MiniStop(_)
| VoucherData::FamilyMart(_)
| VoucherData::Seicomart(_)
| VoucherData::PayEasy(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
)
.into()),
}
}
}
impl TryFrom<&GiftCardData> for PaypalPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &GiftCardData) -> Result<Self, Self::Error> {
match value {
GiftCardData::Givex(_)
| GiftCardData::PaySafeCard {}
| GiftCardData::BhnCardNetwork(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
)
.into()),
}
}
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct PaypalAuthUpdateRequest {
grant_type: String,
client_id: Secret<String>,
client_secret: Secret<String>,
}
impl TryFrom<&RefreshTokenRouterData> for PaypalAuthUpdateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefreshTokenRouterData) -> Result<Self, Self::Error> {
Ok(Self {
grant_type: "client_credentials".to_string(),
client_id: item.get_request_id()?,
client_secret: item.request.app_id.clone(),
})
}
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct PaypalAuthUpdateResponse {
pub access_token: Secret<String>,
pub token_type: String,
pub expires_in: i64,
}
impl<F, T> TryFrom<ResponseRouterData<F, PaypalAuthUpdateResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaypalAuthUpdateResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct PaypalIncrementalAuthRequest {
amount: OrderAmount,
}
impl TryFrom<&PaypalRouterData<&PaymentsIncrementalAuthorizationRouterData>>
for PaypalIncrementalAuthRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaypalRouterData<&PaymentsIncrementalAuthorizationRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: OrderAmount {
currency_code: item.router_data.request.currency,
value: item.amount.clone(),
},
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaypalIncrementalAuthResponse {
status: PaypalIncrementalStatus,
status_details: PaypalIncrementalAuthStatusDetails,
id: String,
invoice_id: String,
custom_id: String,
links: Vec<PaypalLinks>,
amount: OrderAmount,
network_transaction_reference: PaypalNetworkTransactionReference,
expiration_time: String,
create_time: String,
update_time: String,
supplementary_data: PaypalSupplementaryData,
payee: Payee,
name: Option<String>,
message: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaypalIncrementalStatus {
CREATED,
CAPTURED,
DENIED,
PARTIALLYCAPTURED,
VOIDED,
PENDING,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaypalNetworkTransactionReference {
id: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaypalIncrementalAuthStatusDetails {
reason: PaypalStatusPendingReason,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaypalStatusPendingReason {
PENDINGREVIEW,
DECLINEDBYRISKFRAUDFILTERS,
}
impl From<PaypalIncrementalStatus> for common_enums::AuthorizationStatus {
fn from(item: PaypalIncrementalStatus) -> Self {
match item {
PaypalIncrementalStatus::CREATED
| PaypalIncrementalStatus::CAPTURED
| PaypalIncrementalStatus::PARTIALLYCAPTURED => Self::Success,
PaypalIncrementalStatus::PENDING => Self::Processing,
PaypalIncrementalStatus::DENIED | PaypalIncrementalStatus::VOIDED => Self::Failure,
}
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
PaypalIncrementalAuthResponse,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsIncrementalAuthorizationData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
PaypalIncrementalAuthResponse,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status = common_enums::AuthorizationStatus::from(item.response.status);
Ok(Self {
response: Ok(PaymentsResponseData::IncrementalAuthorizationResponse {
status,
error_code: None,
error_message: None,
connector_authorization_id: Some(item.response.id),
}),
..item.data
})
}
}
#[derive(Debug)]
pub enum PaypalAuthType {
TemporaryAuth,
AuthWithDetails(PaypalConnectorCredentials),
}
#[derive(Debug)]
pub enum PaypalConnectorCredentials {
StandardIntegration(StandardFlowCredentials),
PartnerIntegration(PartnerFlowCredentials),
}
impl PaypalConnectorCredentials {
pub fn get_client_id(&self) -> Secret<String> {
match self {
Self::StandardIntegration(item) => item.client_id.clone(),
Self::PartnerIntegration(item) => item.client_id.clone(),
}
}
pub fn get_client_secret(&self) -> Secret<String> {
match self {
Self::StandardIntegration(item) => item.client_secret.clone(),
Self::PartnerIntegration(item) => item.client_secret.clone(),
}
}
pub fn get_payer_id(&self) -> Option<Secret<String>> {
match self {
Self::StandardIntegration(_) => None,
Self::PartnerIntegration(item) => Some(item.payer_id.clone()),
}
}
pub fn generate_authorization_value(&self) -> String {
let auth_id = format!(
"{}:{}",
self.get_client_id().expose(),
self.get_client_secret().expose(),
);
format!("Basic {}", consts::BASE64_ENGINE.encode(auth_id))
}
}
#[derive(Debug)]
pub struct StandardFlowCredentials {
pub(super) client_id: Secret<String>,
pub(super) client_secret: Secret<String>,
}
#[derive(Debug)]
pub struct PartnerFlowCredentials {
pub(super) client_id: Secret<String>,
pub(super) client_secret: Secret<String>,
pub(super) payer_id: Secret<String>,
}
impl PaypalAuthType {
pub fn get_credentials(
&self,
) -> CustomResult<&PaypalConnectorCredentials, errors::ConnectorError> {
match self {
Self::TemporaryAuth => Err(errors::ConnectorError::InvalidConnectorConfig {
config: "TemporaryAuth found in connector_account_details",
}
.into()),
Self::AuthWithDetails(credentials) => Ok(credentials),
}
}
}
impl TryFrom<&ConnectorAuthType> for PaypalAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self::AuthWithDetails(
PaypalConnectorCredentials::StandardIntegration(StandardFlowCredentials {
client_id: key1.to_owned(),
client_secret: api_key.to_owned(),
}),
)),
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self::AuthWithDetails(
PaypalConnectorCredentials::PartnerIntegration(PartnerFlowCredentials {
client_id: key1.to_owned(),
client_secret: api_key.to_owned(),
payer_id: api_secret.to_owned(),
}),
)),
ConnectorAuthType::TemporaryAuth => Ok(Self::TemporaryAuth),
_ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaypalOrderStatus {
Pending,
Completed,
Voided,
Created,
Saved,
PayerActionRequired,
Approved,
}
pub(crate) fn get_order_status(
item: PaypalOrderStatus,
intent: PaypalPaymentIntent,
) -> storage_enums::AttemptStatus {
match item {
PaypalOrderStatus::Completed => {
if intent == PaypalPaymentIntent::Authorize {
storage_enums::AttemptStatus::Authorized
} else {
storage_enums::AttemptStatus::Charged
}
}
PaypalOrderStatus::Voided => storage_enums::AttemptStatus::Voided,
PaypalOrderStatus::Created | PaypalOrderStatus::Saved | PaypalOrderStatus::Pending => {
storage_enums::AttemptStatus::Pending
}
PaypalOrderStatus::Approved => storage_enums::AttemptStatus::AuthenticationSuccessful,
PaypalOrderStatus::PayerActionRequired => {
storage_enums::AttemptStatus::AuthenticationPending
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentsCollectionItem {
amount: OrderAmount,
expiration_time: Option<String>,
id: String,
final_capture: Option<bool>,
status: PaypalPaymentStatus,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PaymentsCollection {
authorizations: Option<Vec<PaymentsCollectionItem>>,
captures: Option<Vec<PaymentsCollectionItem>>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PurchaseUnitItem {
pub reference_id: Option<String>,
pub invoice_id: Option<String>,
pub payments: PaymentsCollection,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaypalThreeDsResponse {
id: String,
status: PaypalOrderStatus,
links: Vec<PaypalLinks>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PaypalPreProcessingResponse {
PaypalLiabilityResponse(PaypalLiabilityResponse),
PaypalNonLiabilityResponse(PaypalNonLiabilityResponse),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaypalLiabilityResponse {
pub payment_source: CardParams,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaypalNonLiabilityResponse {
payment_source: CardsData,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CardParams {
pub card: AuthResult,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthResult {
pub authentication_result: PaypalThreeDsParams,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaypalThreeDsParams {
pub liability_shift: LiabilityShift,
pub three_d_secure: ThreeDsCheck,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreeDsCheck {
pub enrollment_status: Option<EnrollmentStatus>,
pub authentication_status: Option<AuthenticationStatus>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum LiabilityShift {
Possible,
No,
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EnrollmentStatus {
Null,
#[serde(rename = "Y")]
Ready,
#[serde(rename = "N")]
NotReady,
#[serde(rename = "U")]
Unavailable,
#[serde(rename = "B")]
Bypassed,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AuthenticationStatus {
Null,
#[serde(rename = "Y")]
Success,
#[serde(rename = "N")]
Failed,
#[serde(rename = "R")]
Rejected,
#[serde(rename = "A")]
Attempted,
#[serde(rename = "U")]
Unable,
#[serde(rename = "C")]
ChallengeRequired,
#[serde(rename = "I")]
InfoOnly,
#[serde(rename = "D")]
Decoupled,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaypalOrdersResponse {
id: String,
intent: PaypalPaymentIntent,
status: PaypalOrderStatus,
purchase_units: Vec<PurchaseUnitItem>,
payment_source: Option<PaymentSourceItemResponse>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaypalLinks {
href: Option<Url>,
rel: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RedirectPurchaseUnitItem {
pub invoice_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaypalRedirectResponse {
id: String,
intent: PaypalPaymentIntent,
status: PaypalOrderStatus,
purchase_units: Vec<RedirectPurchaseUnitItem>,
links: Vec<PaypalLinks>,
payment_source: Option<PaymentSourceItemResponse>,
}
// Note: Don't change order of deserialization of variant, priority is in descending order
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum PaypalAuthResponse {
PaypalOrdersResponse(PaypalOrdersResponse),
PaypalRedirectResponse(PaypalRedirectResponse),
PaypalThreeDsResponse(PaypalThreeDsResponse),
}
// Note: Don't change order of deserialization of variant, priority is in descending order
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum PaypalSyncResponse {
PaypalOrdersSyncResponse(PaypalOrdersResponse),
PaypalThreeDsSyncResponse(PaypalThreeDsSyncResponse),
PaypalRedirectSyncResponse(PaypalRedirectResponse),
PaypalPaymentsSyncResponse(PaypalPaymentsSyncResponse),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaypalPaymentsSyncResponse {
id: String,
status: PaypalPaymentStatus,
amount: OrderAmount,
invoice_id: Option<String>,
supplementary_data: PaypalSupplementaryData,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaypalThreeDsSyncResponse {
id: String,
status: PaypalOrderStatus,
// provided to separated response of card's 3DS from other
payment_source: CardsData,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CardsData {
card: CardDetails,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CardDetails {
last_digits: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaypalMeta {
pub authorize_id: Option<String>,
pub capture_id: Option<String>,
pub incremental_authorization_id: Option<String>,
pub psync_flow: PaypalPaymentIntent,
pub next_action: Option<api_models::payments::NextActionCall>,
pub order_id: Option<String>,
}
fn get_id_based_on_intent(
intent: &PaypalPaymentIntent,
purchase_unit: &PurchaseUnitItem,
) -> CustomResult<String, errors::ConnectorError> {
|| -> _ {
match intent {
PaypalPaymentIntent::Capture => Some(
purchase_unit
.payments
.captures
.clone()?
.into_iter()
.next()?
.id,
),
PaypalPaymentIntent::Authorize => Some(
purchase_unit
.payments
.authorizations
.clone()?
.into_iter()
.next()?
.id,
),
PaypalPaymentIntent::Authenticate => None,
}
}()
.ok_or_else(|| errors::ConnectorError::MissingConnectorTransactionID.into())
}
fn extract_incremental_authorization_id(response: &PaypalOrdersResponse) -> Option<String> {
for unit in &response.purchase_units {
if let Some(authorizations) = &unit.payments.authorizations {
if let Some(first_auth) = authorizations.first() {
return Some(first_auth.id.clone());
}
}
}
None
}
impl<F, Req> TryFrom<ResponseRouterData<F, PaypalOrdersResponse, Req, PaymentsResponseData>>
for RouterData<F, Req, PaymentsResponseData>
where
Req: GetRequestIncrementalAuthorization,
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaypalOrdersResponse, Req, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let purchase_units = item
.response
.purchase_units
.first()
.ok_or(errors::ConnectorError::MissingConnectorTransactionID)?;
let id = get_id_based_on_intent(&item.response.intent, purchase_units)?;
let (connector_meta, order_id) = match item.response.intent.clone() {
PaypalPaymentIntent::Capture => (
serde_json::json!(PaypalMeta {
authorize_id: None,
capture_id: Some(id),
incremental_authorization_id: None,
psync_flow: item.response.intent.clone(),
next_action: None,
order_id: None,
}),
ResponseId::ConnectorTransactionId(item.response.id.clone()),
),
PaypalPaymentIntent::Authorize => (
serde_json::json!(PaypalMeta {
authorize_id: Some(id),
capture_id: None,
incremental_authorization_id: extract_incremental_authorization_id(
&item.response
),
psync_flow: item.response.intent.clone(),
next_action: None,
order_id: None,
}),
ResponseId::ConnectorTransactionId(item.response.id.clone()),
),
PaypalPaymentIntent::Authenticate => {
Err(errors::ConnectorError::ResponseDeserializationFailed)?
}
};
//payment collection will always have only one element as we only make one transaction per order.
let payment_collection = &item
.response
.purchase_units
.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?
.payments;
//payment collection item will either have "authorizations" field or "capture" field, not both at a time.
let payment_collection_item = match (
&payment_collection.authorizations,
&payment_collection.captures,
) {
(Some(authorizations), None) => authorizations.first(),
(None, Some(captures)) => captures.first(),
(Some(_), Some(captures)) => captures.first(),
_ => None,
}
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
let status = payment_collection_item.status.clone();
let status = storage_enums::AttemptStatus::from(status);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: order_id,
redirection_data: Box::new(None),
mandate_reference: Box::new(Some(MandateReference {
connector_mandate_id: match item.response.payment_source.clone() {
Some(paypal_source) => match paypal_source {
PaymentSourceItemResponse::Paypal(paypal_source) => {
paypal_source.attributes.map(|attr| attr.vault.id)
}
PaymentSourceItemResponse::Card(card) => {
card.attributes.map(|attr| attr.vault.id)
}
PaymentSourceItemResponse::Eps(_)
| PaymentSourceItemResponse::Ideal(_) => None,
},
None => None,
},
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})),
connector_metadata: Some(connector_meta),
network_txn_id: None,
connector_response_reference_id: purchase_units
.invoice_id
.clone()
.or(Some(item.response.id)),
incremental_authorization_allowed: item
.data
.request
.get_request_incremental_authorization(),
charges: None,
}),
..item.data
})
}
}
fn get_redirect_url(
link_vec: Vec<PaypalLinks>,
) -> CustomResult<Option<Url>, errors::ConnectorError> {
let mut link: Option<Url> = None;
for item2 in link_vec.iter() {
if item2.rel == "payer-action" {
link.clone_from(&item2.href)
}
}
Ok(link)
}
impl<F>
ForeignTryFrom<(
ResponseRouterData<F, PaypalSyncResponse, PaymentsSyncData, PaymentsResponseData>,
Option<common_enums::PaymentExperience>,
)> for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, payment_experience): (
ResponseRouterData<F, PaypalSyncResponse, PaymentsSyncData, PaymentsResponseData>,
Option<common_enums::PaymentExperience>,
),
) -> Result<Self, Self::Error> {
match item.response {
PaypalSyncResponse::PaypalOrdersSyncResponse(response) => {
Self::try_from(ResponseRouterData {
response,
data: item.data,
http_code: item.http_code,
})
}
PaypalSyncResponse::PaypalRedirectSyncResponse(response) => Self::foreign_try_from((
ResponseRouterData {
response,
data: item.data,
http_code: item.http_code,
},
payment_experience,
)),
PaypalSyncResponse::PaypalPaymentsSyncResponse(response) => {
Self::try_from(ResponseRouterData {
response,
data: item.data,
http_code: item.http_code,
})
}
PaypalSyncResponse::PaypalThreeDsSyncResponse(response) => {
Self::try_from(ResponseRouterData {
response,
data: item.data,
http_code: item.http_code,
})
}
}
}
}
impl<F, T>
ForeignTryFrom<(
ResponseRouterData<F, PaypalRedirectResponse, T, PaymentsResponseData>,
Option<common_enums::PaymentExperience>,
)> for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, payment_experience): (
ResponseRouterData<F, PaypalRedirectResponse, T, PaymentsResponseData>,
Option<common_enums::PaymentExperience>,
),
) -> Result<Self, Self::Error> {
let status = get_order_status(item.response.clone().status, item.response.intent.clone());
let link = get_redirect_url(item.response.links.clone())?;
// For Paypal SDK flow, we need to trigger SDK client and then complete authorize
let next_action =
if let Some(common_enums::PaymentExperience::InvokeSdkClient) = payment_experience {
Some(api_models::payments::NextActionCall::CompleteAuthorize)
} else {
None
};
let connector_meta = serde_json::json!(PaypalMeta {
authorize_id: None,
capture_id: None,
incremental_authorization_id: None,
psync_flow: item.response.intent,
next_action,
order_id: None,
});
let purchase_units = item.response.purchase_units.first();
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(Some(RedirectForm::from((
link.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?,
Method::Get,
)))),
mandate_reference: Box::new(None),
connector_metadata: Some(connector_meta),
network_txn_id: None,
connector_response_reference_id: Some(
|
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs#chunk1
|
hyperswitch_connectors
|
chunk
| null | null | null | 8,191
| null | null | null | null | null | null | null |
// Struct: NmiAuthType
// File: crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct NmiAuthType
|
crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
NmiAuthType
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Function: delete_by_merchant_id_fingerprint_id
// File: crates/diesel_models/src/query/blocklist.rs
// Module: diesel_models
pub fn delete_by_merchant_id_fingerprint_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> StorageResult<Self>
|
crates/diesel_models/src/query/blocklist.rs
|
diesel_models
|
function_signature
| null | null | null | 79
|
delete_by_merchant_id_fingerprint_id
| null | null | null | null | null | null |
// Implementation: impl webhooks::IncomingWebhook for for Tokenex
// File: crates/hyperswitch_connectors/src/connectors/tokenex.rs
// Module: hyperswitch_connectors
// Methods: 3 total (0 public)
impl webhooks::IncomingWebhook for for Tokenex
|
crates/hyperswitch_connectors/src/connectors/tokenex.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Tokenex
|
webhooks::IncomingWebhook for
| 3
| 0
| null | null |
// Implementation: impl ConnectorCommon for for Payone
// File: crates/hyperswitch_connectors/src/connectors/payone.rs
// Module: hyperswitch_connectors
// Methods: 6 total (0 public)
impl ConnectorCommon for for Payone
|
crates/hyperswitch_connectors/src/connectors/payone.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 53
| null |
Payone
|
ConnectorCommon for
| 6
| 0
| null | null |
// Module Structure
// File: crates/hyperswitch_connectors/src/connectors/sift.rs
// Module: hyperswitch_connectors
// Public submodules:
pub mod transformers;
|
crates/hyperswitch_connectors/src/connectors/sift.rs
|
hyperswitch_connectors
|
module_structure
| null | null | null | 38
| null | null | null | null | null | 1
| 0
|
// Struct: NmiErrorResponseData
// File: crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct NmiErrorResponseData
|
crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
NmiErrorResponseData
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Function: from_storage
// File: crates/router/src/services/kafka/dispute_event.rs
// Module: router
pub fn from_storage(dispute: &'a Dispute) -> Self
|
crates/router/src/services/kafka/dispute_event.rs
|
router
|
function_signature
| null | null | null | 39
|
from_storage
| null | null | null | null | null | null |
// File: crates/router/src/services/kafka/payment_attempt.rs
// Module: router
// Public functions: 2
// Public structs: 2
#[cfg(feature = "v2")]
use common_types::payments;
#[cfg(feature = "v2")]
use common_utils::types;
use common_utils::{id_type, types::MinorUnit};
use diesel_models::enums as storage_enums;
#[cfg(feature = "v2")]
use diesel_models::payment_attempt;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::{
address, payments::payment_attempt::PaymentAttemptFeatureMetadata,
router_response_types::RedirectForm,
};
use hyperswitch_domain_models::{
mandates::MandateDetails, payments::payment_attempt::PaymentAttempt,
};
use time::OffsetDateTime;
#[cfg(feature = "v1")]
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentAttempt<'a> {
pub payment_id: &'a id_type::PaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub attempt_id: &'a String,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
pub save_to_locker: Option<bool>,
pub connector: Option<&'a String>,
pub error_message: Option<&'a String>,
pub offer_amount: Option<MinorUnit>,
pub surcharge_amount: Option<MinorUnit>,
pub tax_amount: Option<MinorUnit>,
pub payment_method_id: Option<&'a String>,
pub payment_method: Option<storage_enums::PaymentMethod>,
pub connector_transaction_id: Option<&'a String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
#[serde(default, with = "time::serde::timestamp::option")]
pub capture_on: Option<OffsetDateTime>,
pub confirm: bool,
pub authentication_type: Option<storage_enums::AuthenticationType>,
#[serde(with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp")]
pub modified_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::option")]
pub last_synced: Option<OffsetDateTime>,
pub cancellation_reason: Option<&'a String>,
pub amount_to_capture: Option<MinorUnit>,
pub mandate_id: Option<&'a String>,
pub browser_info: Option<String>,
pub error_code: Option<&'a String>,
pub connector_metadata: Option<String>,
// TODO: These types should implement copy ideally
pub payment_experience: Option<&'a storage_enums::PaymentExperience>,
pub payment_method_type: Option<&'a storage_enums::PaymentMethodType>,
pub payment_method_data: Option<String>,
pub error_reason: Option<&'a String>,
pub multiple_capture_count: Option<i16>,
pub amount_capturable: MinorUnit,
pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub net_amount: MinorUnit,
pub unified_code: Option<&'a String>,
pub unified_message: Option<&'a String>,
pub mandate_data: Option<&'a MandateDetails>,
pub client_source: Option<&'a String>,
pub client_version: Option<&'a String>,
pub profile_id: &'a id_type::ProfileId,
pub organization_id: &'a id_type::OrganizationId,
pub card_network: Option<String>,
pub card_discovery: Option<String>,
pub routing_approach: Option<storage_enums::RoutingApproach>,
pub debit_routing_savings: Option<MinorUnit>,
pub signature_network: Option<common_enums::CardNetwork>,
pub is_issuer_regulated: Option<bool>,
}
#[cfg(feature = "v1")]
impl<'a> KafkaPaymentAttempt<'a> {
pub fn from_storage(attempt: &'a PaymentAttempt) -> Self {
let card_payment_method_data = attempt
.get_payment_method_data()
.and_then(|data| data.get_additional_card_info());
Self {
payment_id: &attempt.payment_id,
merchant_id: &attempt.merchant_id,
attempt_id: &attempt.attempt_id,
status: attempt.status,
amount: attempt.net_amount.get_order_amount(),
currency: attempt.currency,
save_to_locker: attempt.save_to_locker,
connector: attempt.connector.as_ref(),
error_message: attempt.error_message.as_ref(),
offer_amount: attempt.offer_amount,
surcharge_amount: attempt.net_amount.get_surcharge_amount(),
tax_amount: attempt.net_amount.get_tax_on_surcharge(),
payment_method_id: attempt.payment_method_id.as_ref(),
payment_method: attempt.payment_method,
connector_transaction_id: attempt.connector_transaction_id.as_ref(),
capture_method: attempt.capture_method,
capture_on: attempt.capture_on.map(|i| i.assume_utc()),
confirm: attempt.confirm,
authentication_type: attempt.authentication_type,
created_at: attempt.created_at.assume_utc(),
modified_at: attempt.modified_at.assume_utc(),
last_synced: attempt.last_synced.map(|i| i.assume_utc()),
cancellation_reason: attempt.cancellation_reason.as_ref(),
amount_to_capture: attempt.amount_to_capture,
mandate_id: attempt.mandate_id.as_ref(),
browser_info: attempt.browser_info.as_ref().map(|v| v.to_string()),
error_code: attempt.error_code.as_ref(),
connector_metadata: attempt.connector_metadata.as_ref().map(|v| v.to_string()),
payment_experience: attempt.payment_experience.as_ref(),
payment_method_type: attempt.payment_method_type.as_ref(),
payment_method_data: attempt.payment_method_data.as_ref().map(|v| v.to_string()),
error_reason: attempt.error_reason.as_ref(),
multiple_capture_count: attempt.multiple_capture_count,
amount_capturable: attempt.amount_capturable,
merchant_connector_id: attempt.merchant_connector_id.as_ref(),
net_amount: attempt.net_amount.get_total_amount(),
unified_code: attempt.unified_code.as_ref(),
unified_message: attempt.unified_message.as_ref(),
mandate_data: attempt.mandate_data.as_ref(),
client_source: attempt.client_source.as_ref(),
client_version: attempt.client_version.as_ref(),
profile_id: &attempt.profile_id,
organization_id: &attempt.organization_id,
card_network: attempt
.payment_method_data
.as_ref()
.and_then(|data| data.as_object())
.and_then(|pm| pm.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string()),
card_discovery: attempt
.card_discovery
.map(|discovery| discovery.to_string()),
routing_approach: attempt.routing_approach.clone(),
debit_routing_savings: attempt.debit_routing_savings,
signature_network: card_payment_method_data
.as_ref()
.and_then(|data| data.signature_network.clone()),
is_issuer_regulated: card_payment_method_data.and_then(|data| data.is_regulated),
}
}
}
#[cfg(feature = "v2")]
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentAttempt<'a> {
pub payment_id: &'a id_type::GlobalPaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub attempt_id: &'a id_type::GlobalAttemptId,
pub attempts_group_id: Option<&'a String>,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
pub connector: Option<&'a String>,
pub error_message: Option<&'a String>,
pub surcharge_amount: Option<MinorUnit>,
pub tax_amount: Option<MinorUnit>,
pub payment_method_id: Option<&'a id_type::GlobalPaymentMethodId>,
pub payment_method: storage_enums::PaymentMethod,
pub connector_transaction_id: Option<&'a String>,
pub authentication_type: storage_enums::AuthenticationType,
#[serde(with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp")]
pub modified_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::option")]
pub last_synced: Option<OffsetDateTime>,
pub cancellation_reason: Option<&'a String>,
pub amount_to_capture: Option<MinorUnit>,
pub browser_info: Option<&'a types::BrowserInformation>,
pub error_code: Option<&'a String>,
pub connector_metadata: Option<String>,
// TODO: These types should implement copy ideally
pub payment_experience: Option<&'a storage_enums::PaymentExperience>,
pub payment_method_type: &'a storage_enums::PaymentMethodType,
pub payment_method_data: Option<String>,
pub error_reason: Option<&'a String>,
pub multiple_capture_count: Option<i16>,
pub amount_capturable: MinorUnit,
pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub net_amount: MinorUnit,
pub unified_code: Option<&'a String>,
pub unified_message: Option<&'a String>,
pub client_source: Option<&'a String>,
pub client_version: Option<&'a String>,
pub profile_id: &'a id_type::ProfileId,
pub organization_id: &'a id_type::OrganizationId,
pub card_network: Option<String>,
pub card_discovery: Option<String>,
pub connector_payment_id: Option<types::ConnectorTransactionId>,
pub payment_token: Option<String>,
pub preprocessing_step_id: Option<String>,
pub connector_response_reference_id: Option<String>,
pub updated_by: &'a String,
pub encoded_data: Option<&'a masking::Secret<String>>,
pub external_three_ds_authentication_attempted: Option<bool>,
pub authentication_connector: Option<String>,
pub authentication_id: Option<String>,
pub fingerprint_id: Option<String>,
pub customer_acceptance: Option<&'a masking::Secret<payments::CustomerAcceptance>>,
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
pub charges: Option<payments::ConnectorChargeResponseData>,
pub processor_merchant_id: &'a id_type::MerchantId,
pub created_by: Option<&'a types::CreatedBy>,
pub payment_method_type_v2: storage_enums::PaymentMethod,
pub payment_method_subtype: storage_enums::PaymentMethodType,
pub routing_result: Option<serde_json::Value>,
pub authentication_applied: Option<common_enums::AuthenticationType>,
pub external_reference_id: Option<String>,
pub tax_on_surcharge: Option<MinorUnit>,
pub payment_method_billing_address: Option<masking::Secret<&'a address::Address>>, // adjusted from Encryption
pub redirection_data: Option<&'a RedirectForm>,
pub connector_payment_data: Option<String>,
pub connector_token_details: Option<&'a payment_attempt::ConnectorTokenDetails>,
pub feature_metadata: Option<&'a PaymentAttemptFeatureMetadata>,
pub network_advice_code: Option<String>,
pub network_decline_code: Option<String>,
pub network_error_message: Option<String>,
pub connector_request_reference_id: Option<String>,
}
#[cfg(feature = "v2")]
impl<'a> KafkaPaymentAttempt<'a> {
pub fn from_storage(attempt: &'a PaymentAttempt) -> Self {
use masking::PeekInterface;
let PaymentAttempt {
payment_id,
merchant_id,
attempts_group_id,
amount_details,
status,
connector,
error,
authentication_type,
created_at,
modified_at,
last_synced,
cancellation_reason,
browser_info,
payment_token,
connector_metadata,
payment_experience,
payment_method_data,
routing_result,
preprocessing_step_id,
multiple_capture_count,
connector_response_reference_id,
updated_by,
redirection_data,
encoded_data,
merchant_connector_id,
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
fingerprint_id,
client_source,
client_version,
customer_acceptance,
profile_id,
organization_id,
payment_method_type,
payment_method_id,
connector_payment_id,
payment_method_subtype,
authentication_applied,
external_reference_id,
payment_method_billing_address,
id,
connector_token_details,
card_discovery,
charges,
feature_metadata,
processor_merchant_id,
created_by,
connector_request_reference_id,
network_transaction_id: _,
} = attempt;
let (connector_payment_id, connector_payment_data) = connector_payment_id
.clone()
.map(types::ConnectorTransactionId::form_id_and_data)
.map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
.unwrap_or((None, None));
Self {
payment_id,
merchant_id,
attempt_id: id,
attempts_group_id: attempts_group_id.as_ref(),
status: *status,
amount: amount_details.get_net_amount(),
connector: connector.as_ref(),
error_message: error.as_ref().map(|error_details| &error_details.message),
surcharge_amount: amount_details.get_surcharge_amount(),
tax_amount: amount_details.get_tax_on_surcharge(),
payment_method_id: payment_method_id.as_ref(),
payment_method: *payment_method_type,
connector_transaction_id: connector_response_reference_id.as_ref(),
authentication_type: *authentication_type,
created_at: created_at.assume_utc(),
modified_at: modified_at.assume_utc(),
last_synced: last_synced.map(|i| i.assume_utc()),
cancellation_reason: cancellation_reason.as_ref(),
amount_to_capture: amount_details.get_amount_to_capture(),
browser_info: browser_info.as_ref(),
error_code: error.as_ref().map(|error_details| &error_details.code),
connector_metadata: connector_metadata.as_ref().map(|v| v.peek().to_string()),
payment_experience: payment_experience.as_ref(),
payment_method_type: payment_method_subtype,
payment_method_data: payment_method_data.as_ref().map(|v| v.peek().to_string()),
error_reason: error
.as_ref()
.and_then(|error_details| error_details.reason.as_ref()),
multiple_capture_count: *multiple_capture_count,
amount_capturable: amount_details.get_amount_capturable(),
merchant_connector_id: merchant_connector_id.as_ref(),
net_amount: amount_details.get_net_amount(),
unified_code: error
.as_ref()
.and_then(|error_details| error_details.unified_code.as_ref()),
unified_message: error
.as_ref()
.and_then(|error_details| error_details.unified_message.as_ref()),
client_source: client_source.as_ref(),
client_version: client_version.as_ref(),
profile_id,
organization_id,
card_network: payment_method_data
.as_ref()
.map(|data| data.peek())
.and_then(|data| data.as_object())
.and_then(|pm| pm.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string()),
card_discovery: card_discovery.map(|discovery| discovery.to_string()),
payment_token: payment_token.clone(),
preprocessing_step_id: preprocessing_step_id.clone(),
connector_response_reference_id: connector_response_reference_id.clone(),
updated_by,
encoded_data: encoded_data.as_ref(),
external_three_ds_authentication_attempted: *external_three_ds_authentication_attempted,
authentication_connector: authentication_connector.clone(),
authentication_id: authentication_id
.as_ref()
.map(|id| id.get_string_repr().to_string().clone()),
fingerprint_id: fingerprint_id.clone(),
customer_acceptance: customer_acceptance.as_ref(),
shipping_cost: amount_details.get_shipping_cost(),
order_tax_amount: amount_details.get_order_tax_amount(),
charges: charges.clone(),
processor_merchant_id,
created_by: created_by.as_ref(),
payment_method_type_v2: *payment_method_type,
connector_payment_id: connector_payment_id.as_ref().cloned(),
payment_method_subtype: *payment_method_subtype,
routing_result: routing_result.clone(),
authentication_applied: *authentication_applied,
external_reference_id: external_reference_id.clone(),
tax_on_surcharge: amount_details.get_tax_on_surcharge(),
payment_method_billing_address: payment_method_billing_address
.as_ref()
.map(|v| masking::Secret::new(v.get_inner())),
redirection_data: redirection_data.as_ref(),
connector_payment_data,
connector_token_details: connector_token_details.as_ref(),
feature_metadata: feature_metadata.as_ref(),
network_advice_code: error
.as_ref()
.and_then(|details| details.network_advice_code.clone()),
network_decline_code: error
.as_ref()
.and_then(|details| details.network_decline_code.clone()),
network_error_message: error
.as_ref()
.and_then(|details| details.network_error_message.clone()),
connector_request_reference_id: connector_request_reference_id.clone(),
}
}
}
impl super::KafkaMessage for KafkaPaymentAttempt<'_> {
#[cfg(feature = "v1")]
fn key(&self) -> String {
format!(
"{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id
)
}
#[cfg(feature = "v2")]
fn key(&self) -> String {
format!(
"{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id.get_string_repr()
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::PaymentAttempt
}
}
|
crates/router/src/services/kafka/payment_attempt.rs
|
router
|
full_file
| null | null | null | 3,842
| null | null | null | null | null | null | null |
// Implementation: impl api::RefundExecute for for Paybox
// File: crates/hyperswitch_connectors/src/connectors/paybox.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundExecute for for Paybox
|
crates/hyperswitch_connectors/src/connectors/paybox.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Paybox
|
api::RefundExecute for
| 0
| 0
| null | null |
// Struct: ToggleKVRequest
// File: crates/api_models/src/admin.rs
// Module: api_models
// Implementations: 0
pub struct ToggleKVRequest
|
crates/api_models/src/admin.rs
|
api_models
|
struct_definition
|
ToggleKVRequest
| 0
|
[] | 35
| null | null | null | null | null | null | null |
// Function: generic_update_with_results
// File: crates/diesel_models/src/query/generics.rs
// Module: diesel_models
pub fn generic_update_with_results<T, V, P, R>(
conn: &PgPooledConn,
predicate: P,
values: V,
) -> StorageResult<Vec<R>>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
V: AsChangeset<Target = <Filter<T, P> as HasTable>::Table> + Debug + 'static,
Filter<T, P>: IntoUpdateTarget + 'static,
UpdateStatement<
<Filter<T, P> as HasTable>::Table,
<Filter<T, P> as IntoUpdateTarget>::WhereClause,
<V as AsChangeset>::Changeset,
>: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + Clone,
R: Send + 'static,
// For cloning query (UpdateStatement)
<Filter<T, P> as HasTable>::Table: Clone,
<Filter<T, P> as IntoUpdateTarget>::WhereClause: Clone,
<V as AsChangeset>::Changeset: Clone,
<<Filter<T, P> as HasTable>::Table as QuerySource>::FromClause: Clone,
|
crates/diesel_models/src/query/generics.rs
|
diesel_models
|
function_signature
| null | null | null | 285
|
generic_update_with_results
| null | null | null | null | null | null |
// File: crates/api_models/src/user_role/role.rs
// Module: api_models
// Public structs: 15
use common_enums::{
EntityType, ParentGroup, PermissionGroup, PermissionScope, Resource, RoleScope,
};
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct CreateRoleRequest {
pub role_name: String,
pub groups: Vec<PermissionGroup>,
pub role_scope: RoleScope,
pub entity_type: Option<EntityType>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct CreateRoleV2Request {
pub role_name: String,
pub role_scope: RoleScope,
pub entity_type: Option<EntityType>,
pub parent_groups: Vec<ParentGroupInfoRequest>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UpdateRoleRequest {
pub groups: Option<Vec<PermissionGroup>>,
pub role_name: Option<String>,
}
#[derive(Debug, serde::Serialize)]
pub struct RoleInfoWithGroupsResponse {
pub role_id: String,
pub groups: Vec<PermissionGroup>,
pub role_name: String,
pub role_scope: RoleScope,
pub entity_type: EntityType,
}
#[derive(Debug, serde::Serialize)]
pub struct RoleInfoWithParents {
pub role_id: String,
pub parent_groups: Vec<ParentGroupInfo>,
pub role_name: String,
pub role_scope: RoleScope,
}
#[derive(Debug, serde::Serialize)]
pub struct ParentGroupInfo {
pub name: ParentGroup,
pub description: String,
pub scopes: Vec<PermissionScope>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ParentGroupInfoRequest {
pub name: ParentGroup,
pub scopes: Vec<PermissionScope>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ListRolesQueryParams {
pub entity_type: Option<EntityType>,
pub groups: Option<bool>,
}
#[derive(Debug, serde::Serialize)]
pub struct RoleInfoResponseNew {
pub role_id: String,
pub role_name: String,
pub entity_type: EntityType,
pub groups: Vec<PermissionGroup>,
pub scope: RoleScope,
}
#[derive(Debug, serde::Serialize)]
pub struct RoleInfoResponseWithParentsGroup {
pub role_id: String,
pub role_name: String,
pub entity_type: EntityType,
pub parent_groups: Vec<ParentGroupInfo>,
pub role_scope: RoleScope,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct GetRoleRequest {
pub role_id: String,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ListRolesAtEntityLevelRequest {
pub entity_type: EntityType,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct GetParentGroupsInfoQueryParams {
pub entity_type: Option<EntityType>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub enum RoleCheckType {
Invite,
Update,
}
#[derive(Debug, serde::Serialize, Clone)]
pub struct MinimalRoleInfo {
pub role_id: String,
pub role_name: String,
}
#[derive(Debug, serde::Serialize)]
pub struct GroupsAndResources {
pub groups: Vec<PermissionGroup>,
pub resources: Vec<Resource>,
}
#[derive(Debug, serde::Serialize)]
#[serde(untagged)]
pub enum ListRolesResponse {
WithGroups(Vec<RoleInfoResponseNew>),
WithParentGroups(Vec<RoleInfoResponseWithParentsGroup>),
}
|
crates/api_models/src/user_role/role.rs
|
api_models
|
full_file
| null | null | null | 737
| null | null | null | null | null | null | null |
// Struct: PaymentElement
// File: crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaymentElement
|
crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaymentElement
| 0
|
[] | 46
| null | null | null | null | null | null | null |
// Function: get_error_data
// File: crates/hyperswitch_connectors/src/connectors/nordea/transformers.rs
// Module: hyperswitch_connectors
pub fn get_error_data(error_response: Option<&NordeaErrorBody>) -> Option<&NordeaFailures>
|
crates/hyperswitch_connectors/src/connectors/nordea/transformers.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 59
|
get_error_data
| null | null | null | null | null | null |
// Function: get_year
// File: crates/cards/src/lib.rs
// Module: cards
pub fn get_year(&self) -> &CardExpirationYear
|
crates/cards/src/lib.rs
|
cards
|
function_signature
| null | null | null | 32
|
get_year
| null | null | null | null | null | null |
// Implementation: impl Default for for TtlForExtendedCardInfo
// File: crates/api_models/src/admin.rs
// Module: api_models
// Methods: 1 total (0 public)
impl Default for for TtlForExtendedCardInfo
|
crates/api_models/src/admin.rs
|
api_models
|
impl_block
| null | null | null | 50
| null |
TtlForExtendedCardInfo
|
Default for
| 1
| 0
| null | null |
// Function: perform_surcharge_decision_management_for_saved_cards
// File: crates/router/src/core/payment_methods/surcharge_decision_configs.rs
// Module: router
pub fn perform_surcharge_decision_management_for_saved_cards(
// state: &SessionState,
// algorithm_ref: routing::RoutingAlgorithmRef,
// payment_attempt: &storage::PaymentAttempt,
// payment_intent: &storage::PaymentIntent,
// customer_payment_method_list: &mut [api_models::payment_methods::CustomerPaymentMethod],
// ) -> ConditionalConfigResult<types::SurchargeMetadata>
|
crates/router/src/core/payment_methods/surcharge_decision_configs.rs
|
router
|
function_signature
| null | null | null | 118
|
perform_surcharge_decision_management_for_saved_cards
| null | null | null | null | null | null |
// Function: get_click_to_pay_connector_account_id
// File: crates/common_types/src/payments.rs
// Module: common_types
// Documentation: fn to get click to pay connector_account_id
pub fn get_click_to_pay_connector_account_id(
&self,
) -> Result<common_utils::id_type::MerchantConnectorAccountId, errors::ValidationError>
|
crates/common_types/src/payments.rs
|
common_types
|
function_signature
| null | null | null | 74
|
get_click_to_pay_connector_account_id
| null | null | null | null | null | null |
// Implementation: impl PaymentMethods
// File: crates/router/src/routes/app.rs
// Module: router
// Methods: 1 total (1 public)
impl PaymentMethods
|
crates/router/src/routes/app.rs
|
router
|
impl_block
| null | null | null | 35
| null |
PaymentMethods
| null | 1
| 1
| null | null |
// Implementation: impl ConnectorSpecifications for for Phonepe
// File: crates/hyperswitch_connectors/src/connectors/phonepe.rs
// Module: hyperswitch_connectors
// Methods: 3 total (0 public)
impl ConnectorSpecifications for for Phonepe
|
crates/hyperswitch_connectors/src/connectors/phonepe.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 54
| null |
Phonepe
|
ConnectorSpecifications for
| 3
| 0
| null | null |
// Struct: EliminationInformationEventResponse
// File: crates/router/src/core/payments/routing/utils.rs
// Module: router
// Implementations: 0
pub struct EliminationInformationEventResponse
|
crates/router/src/core/payments/routing/utils.rs
|
router
|
struct_definition
|
EliminationInformationEventResponse
| 0
|
[] | 42
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentSync for for Nexixpay
// File: crates/hyperswitch_connectors/src/connectors/nexixpay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSync for for Nexixpay
|
crates/hyperswitch_connectors/src/connectors/nexixpay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Nexixpay
|
api::PaymentSync for
| 0
| 0
| null | null |
// Struct: DecisionEngineSuccessRateData
// File: crates/api_models/src/open_router.rs
// Module: api_models
// Implementations: 1
pub struct DecisionEngineSuccessRateData
|
crates/api_models/src/open_router.rs
|
api_models
|
struct_definition
|
DecisionEngineSuccessRateData
| 1
|
[] | 40
| null | null | null | null | null | null | null |
// Implementation: impl PaymentSession for for Netcetera
// File: crates/hyperswitch_connectors/src/connectors/netcetera.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl PaymentSession for for Netcetera
|
crates/hyperswitch_connectors/src/connectors/netcetera.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Netcetera
|
PaymentSession for
| 0
| 0
| null | null |
// Implementation: impl api::PaymentSession for for Datatrans
// File: crates/hyperswitch_connectors/src/connectors/datatrans.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSession for for Datatrans
|
crates/hyperswitch_connectors/src/connectors/datatrans.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Datatrans
|
api::PaymentSession for
| 0
| 0
| null | null |
// File: crates/hyperswitch_connectors/src/connectors/wellsfargopayout/transformers.rs
// Module: hyperswitch_connectors
// Public structs: 8
use common_enums::{AttemptStatus, RefundStatus};
use common_utils::types::StringMinorUnit;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::PaymentsAuthorizeRequestData as _,
};
//TODO: Fill the struct with respective fields
pub struct WellsfargopayoutRouterData<T> {
pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(StringMinorUnit, T)> for WellsfargopayoutRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
//Todo : use utils to convert the amount to the type of amount that a connector accepts
Self {
amount,
router_data: item,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct WellsfargopayoutPaymentsRequest {
amount: StringMinorUnit,
card: WellsfargopayoutCard,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct WellsfargopayoutCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&WellsfargopayoutRouterData<&PaymentsAuthorizeRouterData>>
for WellsfargopayoutPaymentsRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &WellsfargopayoutRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card = WellsfargopayoutCard {
number: req_card.card_number,
expiry_month: req_card.card_exp_month,
expiry_year: req_card.card_exp_year,
cvc: req_card.card_cvc,
complete: item.router_data.request.is_auto_capture()?,
};
Ok(Self {
amount: item.amount.clone(),
card,
})
}
_ => Err(ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
}
}
//TODO: Fill the struct with respective fields
// Auth Struct
pub struct WellsfargopayoutAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for WellsfargopayoutAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
//TODO: Append the remaining status flags
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum WellsfargopayoutPaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<WellsfargopayoutPaymentStatus> for AttemptStatus {
fn from(item: WellsfargopayoutPaymentStatus) -> Self {
match item {
WellsfargopayoutPaymentStatus::Succeeded => Self::Charged,
WellsfargopayoutPaymentStatus::Failed => Self::Failure,
WellsfargopayoutPaymentStatus::Processing => Self::Authorizing,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct WellsfargopayoutPaymentsResponse {
status: WellsfargopayoutPaymentStatus,
id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, WellsfargopayoutPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<F, WellsfargopayoutPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct WellsfargopayoutRefundRequest {
pub amount: StringMinorUnit,
}
impl<F> TryFrom<&WellsfargopayoutRouterData<&RefundsRouterData<F>>>
for WellsfargopayoutRefundRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &WellsfargopayoutRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum WellsfargopayoutRefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<WellsfargopayoutRefundStatus> for RefundStatus {
fn from(item: WellsfargopayoutRefundStatus) -> Self {
match item {
WellsfargopayoutRefundStatus::Succeeded => Self::Success,
WellsfargopayoutRefundStatus::Failed => Self::Failure,
WellsfargopayoutRefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: WellsfargopayoutRefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct WellsfargopayoutErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
pub reason: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/wellsfargopayout/transformers.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 1,807
| null | null | null | null | null | null | null |
// Struct: AuthenticationCount
// File: crates/api_models/src/analytics/auth_events.rs
// Module: api_models
// Implementations: 0
pub struct AuthenticationCount
|
crates/api_models/src/analytics/auth_events.rs
|
api_models
|
struct_definition
|
AuthenticationCount
| 0
|
[] | 36
| null | null | null | null | null | null | null |
// Implementation: impl api::ConnectorAccessToken for for Rapyd
// File: crates/hyperswitch_connectors/src/connectors/rapyd.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::ConnectorAccessToken for for Rapyd
|
crates/hyperswitch_connectors/src/connectors/rapyd.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Rapyd
|
api::ConnectorAccessToken for
| 0
| 0
| null | null |
// Implementation: impl NuveiPaymentsGenericResponse for for CompleteAuthorize
// File: crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl NuveiPaymentsGenericResponse for for CompleteAuthorize
|
crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 66
| null |
CompleteAuthorize
|
NuveiPaymentsGenericResponse for
| 0
| 0
| null | null |
// Struct: DetailsType
// File: crates/hyperswitch_connectors/src/connectors/nomupay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct DetailsType
|
crates/hyperswitch_connectors/src/connectors/nomupay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
DetailsType
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Function: routing_retrieve_default_config
// File: crates/openapi/src/routes/profile.rs
// Module: openapi
pub fn routing_retrieve_default_config()
|
crates/openapi/src/routes/profile.rs
|
openapi
|
function_signature
| null | null | null | 34
|
routing_retrieve_default_config
| null | null | null | null | null | null |
// Implementation: impl api::RefundExecute for for Fiserv
// File: crates/hyperswitch_connectors/src/connectors/fiserv.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundExecute for for Fiserv
|
crates/hyperswitch_connectors/src/connectors/fiserv.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 62
| null |
Fiserv
|
api::RefundExecute for
| 0
| 0
| null | null |
// Struct: DeleteTokenDataResponse
// File: crates/api_models/src/tokenization.rs
// Module: api_models
// Implementations: 0
pub struct DeleteTokenDataResponse
|
crates/api_models/src/tokenization.rs
|
api_models
|
struct_definition
|
DeleteTokenDataResponse
| 0
|
[] | 38
| null | null | null | null | null | null | null |
// Struct: BluesnapCompletePaymentsRequest
// File: crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct BluesnapCompletePaymentsRequest
|
crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
BluesnapCompletePaymentsRequest
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Function: delete_totp_attempts_from_redis
// File: crates/router/src/utils/user/two_factor_auth.rs
// Module: router
pub fn delete_totp_attempts_from_redis(
state: &SessionState,
user_id: &str,
) -> UserResult<()>
|
crates/router/src/utils/user/two_factor_auth.rs
|
router
|
function_signature
| null | null | null | 57
|
delete_totp_attempts_from_redis
| null | null | null | null | null | null |
// Struct: Mandate
// File: crates/diesel_models/src/mandate.rs
// Module: diesel_models
// Implementations: 1
pub struct Mandate
|
crates/diesel_models/src/mandate.rs
|
diesel_models
|
struct_definition
|
Mandate
| 1
|
[] | 36
| null | null | null | null | null | null | null |
// Struct: CtpMastercard
// File: crates/hyperswitch_connectors/src/connectors/ctp_mastercard.rs
// Module: hyperswitch_connectors
// Implementations: 16
// Traits: api::Payment, api::PaymentSession, api::ConnectorAccessToken, api::MandateSetup, api::PaymentAuthorize, api::PaymentSync, api::PaymentCapture, api::PaymentVoid, api::Refund, api::RefundExecute, api::RefundSync, api::PaymentToken, ConnectorCommon, ConnectorValidation, webhooks::IncomingWebhook, ConnectorSpecifications
pub struct CtpMastercard
|
crates/hyperswitch_connectors/src/connectors/ctp_mastercard.rs
|
hyperswitch_connectors
|
struct_definition
|
CtpMastercard
| 16
|
[
"api::Payment",
"api::PaymentSession",
"api::ConnectorAccessToken",
"api::MandateSetup",
"api::PaymentAuthorize",
"api::PaymentSync",
"api::PaymentCapture",
"api::PaymentVoid",
"api::Refund",
"api::RefundExecute",
"api::RefundSync",
"api::PaymentToken",
"ConnectorCommon",
"ConnectorValidation",
"webhooks::IncomingWebhook",
"ConnectorSpecifications"
] | 131
| null | null | null | null | null | null | null |
// Implementation: impl api::MandateSetup for for Volt
// File: crates/hyperswitch_connectors/src/connectors/volt.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::MandateSetup for for Volt
|
crates/hyperswitch_connectors/src/connectors/volt.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Volt
|
api::MandateSetup for
| 0
| 0
| null | null |
// File: crates/router/src/core/webhooks/outgoing_v2.rs
// Module: router
use std::collections::HashMap;
use api_models::{webhook_events, webhooks};
use common_utils::{ext_traits, request, type_name, types::keymanager};
use diesel_models::process_tracker::business_status;
use error_stack::{report, Report, ResultExt};
use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation};
use hyperswitch_interfaces::consts;
use masking;
use router_env::{
instrument,
tracing::{self, Instrument},
};
use super::{
types,
utils::{self, increment_webhook_outgoing_received_count},
MERCHANT_ID,
};
use crate::{
core::{
errors::{self, CustomResult},
metrics,
},
events::outgoing_webhook_logs,
logger,
routes::{app::SessionStateInfo, SessionState},
services,
types::{
api, domain,
storage::{self, enums},
transformers::ForeignFrom,
},
};
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub(crate) async fn create_event_and_trigger_outgoing_webhook(
state: SessionState,
business_profile: domain::Profile,
merchant_key_store: &domain::MerchantKeyStore,
event_type: enums::EventType,
event_class: enums::EventClass,
primary_object_id: String,
primary_object_type: enums::EventObjectType,
content: api::OutgoingWebhookContent,
primary_object_created_at: time::PrimitiveDateTime,
) -> CustomResult<(), errors::ApiErrorResponse> {
let delivery_attempt = enums::WebhookDeliveryAttempt::InitialAttempt;
let idempotent_event_id =
utils::get_idempotent_event_id(&primary_object_id, event_type, delivery_attempt)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to generate idempotent event ID")?;
let webhook_url_result = business_profile
.get_webhook_url_from_profile()
.change_context(errors::WebhooksFlowError::MerchantWebhookUrlNotConfigured);
if utils::is_outgoing_webhook_disabled(
&state,
&webhook_url_result,
&business_profile,
&idempotent_event_id,
) {
return Ok(());
}
let event_id = utils::generate_event_id();
let merchant_id = business_profile.merchant_id.clone();
let now = common_utils::date_time::now();
let outgoing_webhook = api::OutgoingWebhook {
merchant_id: merchant_id.clone(),
event_id: event_id.clone(),
event_type,
content: content.clone(),
timestamp: now,
};
let request_content = get_outgoing_webhook_request(outgoing_webhook, &business_profile)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to construct outgoing webhook request content")?;
let event_metadata = storage::EventMetadata::foreign_from(&content);
let key_manager_state = &(&state).into();
let new_event = domain::Event {
event_id: event_id.clone(),
event_type,
event_class,
is_webhook_notified: false,
primary_object_id,
primary_object_type,
created_at: now,
merchant_id: Some(business_profile.merchant_id.clone()),
business_profile_id: Some(business_profile.get_id().to_owned()),
primary_object_created_at: Some(primary_object_created_at),
idempotent_event_id: Some(idempotent_event_id.clone()),
initial_attempt_id: Some(event_id.clone()),
request: Some(
crypto_operation(
key_manager_state,
type_name!(domain::Event),
CryptoOperation::Encrypt(
ext_traits::Encode::encode_to_string_of_json(&request_content)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to encode outgoing webhook request content")
.map(masking::Secret::new)?,
),
keymanager::Identifier::Merchant(merchant_key_store.merchant_id.clone()),
masking::PeekInterface::peek(merchant_key_store.key.get_inner()),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to encrypt outgoing webhook request content")?,
),
response: None,
delivery_attempt: Some(delivery_attempt),
metadata: Some(event_metadata),
is_overall_delivery_successful: Some(false),
};
let event_insert_result = state
.store
.insert_event(key_manager_state, new_event, merchant_key_store)
.await;
let event = match event_insert_result {
Ok(event) => Ok(event),
Err(error) => {
if error.current_context().is_db_unique_violation() {
// If the event_id already exists in the database, it indicates that the event for the resource has already been sent, so we skip the flow
logger::debug!("Event with idempotent ID `{idempotent_event_id}` already exists in the database");
return Ok(());
} else {
logger::error!(event_insertion_failure=?error);
Err(error
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to insert event in events table"))
}
}
}?;
let cloned_key_store = merchant_key_store.clone();
// Using a tokio spawn here and not arbiter because not all caller of this function
// may have an actix arbiter
tokio::spawn(
async move {
Box::pin(trigger_webhook_and_raise_event(
state,
business_profile,
&cloned_key_store,
event,
request_content,
delivery_attempt,
Some(content),
))
.await;
}
.in_current_span(),
);
Ok(())
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub(crate) async fn trigger_webhook_and_raise_event(
state: SessionState,
business_profile: domain::Profile,
merchant_key_store: &domain::MerchantKeyStore,
event: domain::Event,
request_content: webhook_events::OutgoingWebhookRequestContent,
delivery_attempt: enums::WebhookDeliveryAttempt,
content: Option<api::OutgoingWebhookContent>,
) {
logger::debug!(
event_id=%event.event_id,
idempotent_event_id=?event.idempotent_event_id,
initial_attempt_id=?event.initial_attempt_id,
"Attempting to send webhook"
);
let merchant_id = business_profile.merchant_id.clone();
let trigger_webhook_result = trigger_webhook_to_merchant(
state.clone(),
business_profile,
merchant_key_store,
event.clone(),
request_content,
delivery_attempt,
)
.await;
let _ =
raise_webhooks_analytics_event(state, trigger_webhook_result, content, merchant_id, event)
.await;
}
async fn trigger_webhook_to_merchant(
state: SessionState,
business_profile: domain::Profile,
merchant_key_store: &domain::MerchantKeyStore,
event: domain::Event,
request_content: webhook_events::OutgoingWebhookRequestContent,
delivery_attempt: enums::WebhookDeliveryAttempt,
) -> CustomResult<
(domain::Event, Option<Report<errors::WebhooksFlowError>>),
errors::WebhooksFlowError,
> {
let webhook_url = business_profile
.get_webhook_url_from_profile()
.change_context(errors::WebhooksFlowError::MerchantWebhookUrlNotConfigured)?;
let response = build_and_send_request(&state, request_content, webhook_url).await;
metrics::WEBHOOK_OUTGOING_COUNT.add(
1,
router_env::metric_attributes!((MERCHANT_ID, business_profile.merchant_id.clone())),
);
logger::debug!(outgoing_webhook_response=?response);
match response {
Ok(response) => {
delivery_attempt
.handle_success_response(
state,
merchant_key_store.clone(),
&business_profile.merchant_id,
&event.event_id,
None,
response,
)
.await
}
Err(client_error) => {
delivery_attempt
.handle_error_response(
state,
merchant_key_store.clone(),
&business_profile.merchant_id,
&event.event_id,
client_error,
)
.await
}
}
}
async fn raise_webhooks_analytics_event(
state: SessionState,
trigger_webhook_result: CustomResult<
(domain::Event, Option<Report<errors::WebhooksFlowError>>),
errors::WebhooksFlowError,
>,
content: Option<api::OutgoingWebhookContent>,
merchant_id: common_utils::id_type::MerchantId,
fallback_event: domain::Event,
) {
let (updated_event, optional_error) = match trigger_webhook_result {
Ok((updated_event, error)) => (updated_event, error),
Err(error) => (fallback_event, Some(error)),
};
let error = optional_error.and_then(|error| {
logger::error!(?error, "Failed to send webhook to merchant");
serde_json::to_value(error.current_context())
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.inspect_err(|error| {
logger::error!(?error, "Failed to serialize outgoing webhook error as JSON");
})
.ok()
});
let outgoing_webhook_event_content = content
.as_ref()
.and_then(
outgoing_webhook_logs::OutgoingWebhookEventMetric::get_outgoing_webhook_event_content,
)
.or_else(|| {
updated_event
.metadata
.map(outgoing_webhook_logs::OutgoingWebhookEventContent::foreign_from)
});
// Get status_code from webhook response
let status_code = {
let webhook_response: Option<webhook_events::OutgoingWebhookResponseContent> =
updated_event.response.and_then(|res| {
ext_traits::StringExt::parse_struct(
masking::PeekInterface::peek(res.get_inner()),
"OutgoingWebhookResponseContent",
)
.map_err(|error| {
logger::error!(?error, "Error deserializing webhook response");
error
})
.ok()
});
webhook_response.and_then(|res| res.status_code)
};
let webhook_event = outgoing_webhook_logs::OutgoingWebhookEvent::new(
state.tenant.tenant_id.clone(),
merchant_id,
updated_event.event_id,
updated_event.event_type,
outgoing_webhook_event_content,
error,
updated_event.initial_attempt_id,
status_code,
updated_event.delivery_attempt,
);
state.event_handler().log_event(&webhook_event);
}
pub(crate) fn get_outgoing_webhook_request(
outgoing_webhook: api::OutgoingWebhook,
business_profile: &domain::Profile,
) -> CustomResult<webhook_events::OutgoingWebhookRequestContent, errors::WebhooksFlowError> {
#[inline]
fn get_outgoing_webhook_request_inner<WebhookType: types::OutgoingWebhookType>(
outgoing_webhook: api::OutgoingWebhook,
business_profile: &domain::Profile,
) -> CustomResult<webhook_events::OutgoingWebhookRequestContent, errors::WebhooksFlowError>
{
let mut headers = vec![
(
reqwest::header::CONTENT_TYPE.to_string(),
mime::APPLICATION_JSON.essence_str().into(),
),
(
reqwest::header::USER_AGENT.to_string(),
consts::USER_AGENT.to_string().into(),
),
];
let transformed_outgoing_webhook = WebhookType::from(outgoing_webhook);
let payment_response_hash_key = business_profile.payment_response_hash_key.clone();
let custom_headers = business_profile
.outgoing_webhook_custom_http_headers
.clone()
.map(|headers| {
ext_traits::ValueExt::parse_value::<HashMap<String, String>>(
masking::ExposeInterface::expose(headers.into_inner()),
"HashMap<String,String>",
)
.change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed)
.attach_printable("Failed to deserialize outgoing webhook custom HTTP headers")
})
.transpose()?;
if let Some(ref map) = custom_headers {
headers.extend(
map.iter()
.map(|(key, value)| (key.clone(), masking::Mask::into_masked(value.clone()))),
);
};
let outgoing_webhooks_signature = transformed_outgoing_webhook
.get_outgoing_webhooks_signature(payment_response_hash_key)?;
if let Some(signature) = outgoing_webhooks_signature.signature {
WebhookType::add_webhook_header(&mut headers, signature)
}
Ok(webhook_events::OutgoingWebhookRequestContent {
body: outgoing_webhooks_signature.payload,
headers: headers
.into_iter()
.map(|(name, value)| (name, masking::Secret::new(value.into_inner())))
.collect(),
})
}
get_outgoing_webhook_request_inner::<webhooks::OutgoingWebhook>(
outgoing_webhook,
business_profile,
)
}
async fn build_and_send_request(
state: &SessionState,
request_content: webhook_events::OutgoingWebhookRequestContent,
webhook_url: String,
) -> Result<reqwest::Response, Report<common_enums::ApiClientError>> {
let headers = request_content
.headers
.into_iter()
.map(|(name, value)| (name, masking::Mask::into_masked(value)))
.collect();
let request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(&webhook_url)
.attach_default_headers()
.headers(headers)
.set_body(request::RequestContent::RawBytes(
masking::ExposeInterface::expose(request_content.body).into_bytes(),
))
.build();
state
.api_client
.send_request(state, request, None, false)
.await
}
async fn api_client_error_handler(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
client_error: Report<errors::ApiClientError>,
delivery_attempt: enums::WebhookDeliveryAttempt,
_schedule_webhook_retry: types::ScheduleWebhookRetry,
) -> CustomResult<
(domain::Event, Option<Report<errors::WebhooksFlowError>>),
errors::WebhooksFlowError,
> {
// Not including detailed error message in response information since it contains too
// much of diagnostic information to be exposed to the merchant.
let is_webhook_notified = false;
let response_to_store = webhook_events::OutgoingWebhookResponseContent {
body: None,
headers: None,
status_code: None,
error_message: Some("Unable to send request to merchant server".to_string()),
};
let updated_event = update_event_in_storage(
state,
is_webhook_notified,
response_to_store,
merchant_key_store,
merchant_id,
event_id,
)
.await?;
let error = client_error.change_context(errors::WebhooksFlowError::CallToMerchantFailed);
logger::error!(
?error,
?delivery_attempt,
"An error occurred when sending webhook to merchant"
);
//TODO: add outgoing webhook retries support
// if let ScheduleWebhookRetry::WithProcessTracker(process_tracker) = schedule_webhook_retry {
// // Schedule a retry attempt for webhook delivery
// outgoing_webhook_retry::retry_webhook_delivery_task(
// &*state.store,
// merchant_id,
// *process_tracker,
// )
// .await
// .change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)?;
// }
Ok((updated_event, Some(error)))
}
async fn update_event_in_storage(
state: SessionState,
is_webhook_notified: bool,
outgoing_webhook_response: webhook_events::OutgoingWebhookResponseContent,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
) -> CustomResult<domain::Event, errors::WebhooksFlowError> {
let key_manager_state = &(&state).into();
let event_update = domain::EventUpdate::UpdateResponse {
is_webhook_notified,
response: Some(
crypto_operation(
key_manager_state,
type_name!(domain::Event),
CryptoOperation::Encrypt(
ext_traits::Encode::encode_to_string_of_json(&outgoing_webhook_response)
.change_context(
errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed,
)
.map(masking::Secret::new)?,
),
keymanager::Identifier::Merchant(merchant_key_store.merchant_id.clone()),
masking::PeekInterface::peek(merchant_key_store.key.get_inner()),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
.attach_printable("Failed to encrypt outgoing webhook response content")?,
),
};
state
.store
.update_event_by_merchant_id_event_id(
key_manager_state,
merchant_id,
event_id,
event_update,
&merchant_key_store,
)
.await
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
}
async fn update_overall_delivery_status_in_storage(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
updated_event: &domain::Event,
) -> CustomResult<(), errors::WebhooksFlowError> {
let key_manager_state = &(&state).into();
let update_overall_delivery_status = domain::EventUpdate::OverallDeliveryStatusUpdate {
is_overall_delivery_successful: true,
};
let initial_attempt_id = updated_event.initial_attempt_id.as_ref();
let delivery_attempt = updated_event.delivery_attempt;
if let Some((
initial_attempt_id,
enums::WebhookDeliveryAttempt::InitialAttempt
| enums::WebhookDeliveryAttempt::AutomaticRetry,
)) = initial_attempt_id.zip(delivery_attempt)
{
state
.store
.update_event_by_merchant_id_event_id(
key_manager_state,
merchant_id,
initial_attempt_id.as_str(),
update_overall_delivery_status,
&merchant_key_store,
)
.await
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
.attach_printable("Failed to update initial delivery attempt")?;
}
Ok(())
}
async fn handle_successful_delivery(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
updated_event: &domain::Event,
merchant_id: &common_utils::id_type::MerchantId,
process_tracker: Option<storage::ProcessTracker>,
business_status: &'static str,
) -> CustomResult<(), errors::WebhooksFlowError> {
update_overall_delivery_status_in_storage(
state.clone(),
merchant_key_store.clone(),
merchant_id,
updated_event,
)
.await?;
increment_webhook_outgoing_received_count(merchant_id);
match process_tracker {
Some(process_tracker) => state
.store
.as_scheduler()
.finish_process_with_business_status(process_tracker, business_status)
.await
.change_context(
errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed,
),
None => Ok(()),
}
}
async fn handle_failed_delivery(
_state: SessionState,
merchant_id: &common_utils::id_type::MerchantId,
delivery_attempt: enums::WebhookDeliveryAttempt,
status_code: u16,
log_message: &'static str,
_schedule_webhook_retry: types::ScheduleWebhookRetry,
) -> CustomResult<(), errors::WebhooksFlowError> {
utils::increment_webhook_outgoing_not_received_count(merchant_id);
let error = report!(errors::WebhooksFlowError::NotReceivedByMerchant);
logger::warn!(?error, ?delivery_attempt, status_code, %log_message);
//TODO: add outgoing webhook retries support
// if let ScheduleWebhookRetry::WithProcessTracker(process_tracker) = schedule_webhook_retry {
// // Schedule a retry attempt for webhook delivery
// outgoing_webhook_retry::retry_webhook_delivery_task(
// &*state.store,
// merchant_id,
// *process_tracker,
// )
// .await
// .change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)?;
// }
Err(error)
}
impl ForeignFrom<&api::OutgoingWebhookContent> for storage::EventMetadata {
fn foreign_from(content: &api::OutgoingWebhookContent) -> Self {
match content {
webhooks::OutgoingWebhookContent::PaymentDetails(payments_response) => Self::Payment {
payment_id: payments_response.id.clone(),
},
webhooks::OutgoingWebhookContent::RefundDetails(refund_response) => Self::Refund {
payment_id: refund_response.payment_id.clone(),
refund_id: refund_response.id.clone(),
},
webhooks::OutgoingWebhookContent::DisputeDetails(dispute_response) => {
//TODO: add support for dispute outgoing webhook
todo!()
}
webhooks::OutgoingWebhookContent::MandateDetails(mandate_response) => Self::Mandate {
payment_method_id: mandate_response.payment_method_id.clone(),
mandate_id: mandate_response.mandate_id.clone(),
},
#[cfg(feature = "payouts")]
webhooks::OutgoingWebhookContent::PayoutDetails(payout_response) => Self::Payout {
payout_id: payout_response.payout_id.clone(),
},
}
}
}
impl ForeignFrom<storage::EventMetadata> for outgoing_webhook_logs::OutgoingWebhookEventContent {
fn foreign_from(event_metadata: storage::EventMetadata) -> Self {
match event_metadata {
diesel_models::EventMetadata::Payment { payment_id } => Self::Payment {
payment_id,
content: serde_json::Value::Null,
},
diesel_models::EventMetadata::Payout { payout_id } => Self::Payout {
payout_id,
content: serde_json::Value::Null,
},
diesel_models::EventMetadata::Refund {
payment_id,
refund_id,
} => Self::Refund {
payment_id,
refund_id,
content: serde_json::Value::Null,
},
diesel_models::EventMetadata::Dispute {
payment_id,
attempt_id,
dispute_id,
} => Self::Dispute {
payment_id,
attempt_id,
dispute_id,
content: serde_json::Value::Null,
},
diesel_models::EventMetadata::Mandate {
payment_method_id,
mandate_id,
} => Self::Mandate {
payment_method_id,
mandate_id,
content: serde_json::Value::Null,
},
}
}
}
trait OutgoingWebhookResponseHandler {
async fn handle_error_response(
&self,
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
client_error: Report<errors::ApiClientError>,
) -> CustomResult<
(domain::Event, Option<Report<errors::WebhooksFlowError>>),
errors::WebhooksFlowError,
>;
async fn handle_success_response(
&self,
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
process_tracker: Option<storage::ProcessTracker>,
response: reqwest::Response,
) -> CustomResult<
(domain::Event, Option<Report<errors::WebhooksFlowError>>),
errors::WebhooksFlowError,
>;
}
impl OutgoingWebhookResponseHandler for enums::WebhookDeliveryAttempt {
async fn handle_error_response(
&self,
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
client_error: Report<errors::ApiClientError>,
) -> CustomResult<
(domain::Event, Option<Report<errors::WebhooksFlowError>>),
errors::WebhooksFlowError,
> {
let schedule_webhook_retry = match self {
Self::InitialAttempt | Self::ManualRetry => types::ScheduleWebhookRetry::NoSchedule,
Self::AutomaticRetry => {
// ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker))
todo!()
}
};
api_client_error_handler(
state,
merchant_key_store,
merchant_id,
event_id,
client_error,
*self,
schedule_webhook_retry,
)
.await
}
async fn handle_success_response(
&self,
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
process_tracker: Option<storage::ProcessTracker>,
response: reqwest::Response,
) -> CustomResult<
(domain::Event, Option<Report<errors::WebhooksFlowError>>),
errors::WebhooksFlowError,
> {
let status_code = response.status();
let is_webhook_notified = status_code.is_success();
let response_struct = types::WebhookResponse { response };
let outgoing_webhook_response = response_struct
.get_outgoing_webhook_response_content()
.await;
let updated_event = update_event_in_storage(
state.clone(),
is_webhook_notified,
outgoing_webhook_response,
merchant_key_store.clone(),
merchant_id,
event_id,
)
.await?;
let webhook_action_handler = get_action_handler(*self);
let result = if is_webhook_notified {
webhook_action_handler
.notified_action(
state,
merchant_key_store,
&updated_event,
merchant_id,
process_tracker,
)
.await
} else {
webhook_action_handler
.not_notified_action(state, merchant_id, status_code.as_u16())
.await
};
Ok((updated_event, result))
}
}
#[async_trait::async_trait]
trait WebhookNotificationHandler: Send + Sync {
async fn notified_action(
&self,
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
updated_event: &domain::Event,
merchant_id: &common_utils::id_type::MerchantId,
process_tracker: Option<storage::ProcessTracker>,
) -> Option<Report<errors::WebhooksFlowError>>;
async fn not_notified_action(
&self,
state: SessionState,
merchant_id: &common_utils::id_type::MerchantId,
status_code: u16,
) -> Option<Report<errors::WebhooksFlowError>>;
}
struct InitialAttempt;
struct AutomaticRetry;
struct ManualRetry;
#[async_trait::async_trait]
impl WebhookNotificationHandler for InitialAttempt {
async fn notified_action(
&self,
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
updated_event: &domain::Event,
merchant_id: &common_utils::id_type::MerchantId,
process_tracker: Option<storage::ProcessTracker>,
) -> Option<Report<errors::WebhooksFlowError>> {
handle_successful_delivery(
state,
merchant_key_store,
updated_event,
merchant_id,
process_tracker,
business_status::INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL,
)
.await
.err()
.map(|error: Report<errors::WebhooksFlowError>| report!(error))
}
async fn not_notified_action(
&self,
state: SessionState,
merchant_id: &common_utils::id_type::MerchantId,
status_code: u16,
) -> Option<Report<errors::WebhooksFlowError>> {
handle_failed_delivery(
state.clone(),
merchant_id,
enums::WebhookDeliveryAttempt::InitialAttempt,
status_code,
"Ignoring error when sending webhook to merchant",
types::ScheduleWebhookRetry::NoSchedule,
)
.await
.err()
.map(|error| report!(error))
}
}
#[async_trait::async_trait]
impl WebhookNotificationHandler for AutomaticRetry {
async fn notified_action(
&self,
_state: SessionState,
_merchant_key_store: domain::MerchantKeyStore,
_updated_event: &domain::Event,
_merchant_id: &common_utils::id_type::MerchantId,
_process_tracker: Option<storage::ProcessTracker>,
) -> Option<Report<errors::WebhooksFlowError>> {
todo!()
}
async fn not_notified_action(
&self,
_state: SessionState,
_merchant_id: &common_utils::id_type::MerchantId,
_status_code: u16,
) -> Option<Report<errors::WebhooksFlowError>> {
todo!()
}
}
#[async_trait::async_trait]
impl WebhookNotificationHandler for ManualRetry {
async fn notified_action(
&self,
_state: SessionState,
_merchant_key_store: domain::MerchantKeyStore,
_updated_event: &domain::Event,
merchant_id: &common_utils::id_type::MerchantId,
_process_tracker: Option<storage::ProcessTracker>,
) -> Option<Report<errors::WebhooksFlowError>> {
increment_webhook_outgoing_received_count(merchant_id);
None
}
async fn not_notified_action(
&self,
state: SessionState,
merchant_id: &common_utils::id_type::MerchantId,
status_code: u16,
) -> Option<Report<errors::WebhooksFlowError>> {
handle_failed_delivery(
state.clone(),
merchant_id,
enums::WebhookDeliveryAttempt::ManualRetry,
status_code,
"Ignoring error when sending webhook to merchant",
types::ScheduleWebhookRetry::NoSchedule,
)
.await
.err()
.map(|error| report!(error))
}
}
fn get_action_handler(
attempt: enums::WebhookDeliveryAttempt,
) -> Box<dyn WebhookNotificationHandler> {
match attempt {
enums::WebhookDeliveryAttempt::InitialAttempt => Box::new(InitialAttempt),
enums::WebhookDeliveryAttempt::AutomaticRetry => Box::new(AutomaticRetry),
enums::WebhookDeliveryAttempt::ManualRetry => Box::new(ManualRetry),
}
}
|
crates/router/src/core/webhooks/outgoing_v2.rs
|
router
|
full_file
| null | null | null | 6,707
| null | null | null | null | null | null | null |
// Function: is_permanent_card
// File: crates/router/src/types/storage/payment_method.rs
// Module: router
pub fn is_permanent_card(&self) -> bool
|
crates/router/src/types/storage/payment_method.rs
|
router
|
function_signature
| null | null | null | 38
|
is_permanent_card
| null | null | null | null | null | null |
// Struct: StaxCaptureRequest
// File: crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct StaxCaptureRequest
|
crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
StaxCaptureRequest
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Struct: TrustpaymentsTokenizationRequestData
// File: crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct TrustpaymentsTokenizationRequestData
|
crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
TrustpaymentsTokenizationRequestData
| 0
|
[] | 54
| null | null | null | null | null | null | null |
// Struct: Shipping
// File: crates/router/src/compatibility/stripe/setup_intents/types.rs
// Module: router
// Implementations: 0
pub struct Shipping
|
crates/router/src/compatibility/stripe/setup_intents/types.rs
|
router
|
struct_definition
|
Shipping
| 0
|
[] | 37
| null | null | null | null | null | null | null |
// Function: create_recipient
// File: crates/router/src/core/payouts.rs
// Module: router
pub fn create_recipient(
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
|
create_recipient
| null | null | null | null | null | null |
// Struct: PaymentsTokenReference
// File: crates/diesel_models/src/payment_method.rs
// Module: diesel_models
// Implementations: 2
// Traits: std::ops::Deref, std::ops::DerefMut
pub struct PaymentsTokenReference
|
crates/diesel_models/src/payment_method.rs
|
diesel_models
|
struct_definition
|
PaymentsTokenReference
| 2
|
[
"std::ops::Deref",
"std::ops::DerefMut"
] | 55
| null | null | null | null | null | null | null |
// Struct: AuthorizedResponse
// File: crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct AuthorizedResponse
|
crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
|
hyperswitch_connectors
|
struct_definition
|
AuthorizedResponse
| 0
|
[] | 43
| null | null | null | null | null | null | null |
// Trait: DatabaseStore
// File: crates/storage_impl/src/database/store.rs
// Module: storage_impl
pub trait DatabaseStore: Clone + Send + Sync
|
crates/storage_impl/src/database/store.rs
|
storage_impl
|
trait_definition
| null | null | null | 33
| null | null |
DatabaseStore
| null | null | null | null |
// Function: from_role_id_org_id_tenant_id
// File: crates/router/src/services/authorization/roles.rs
// Module: router
pub fn from_role_id_org_id_tenant_id(
state: &SessionState,
role_id: &str,
org_id: &id_type::OrganizationId,
tenant_id: &id_type::TenantId,
) -> CustomResult<Self, errors::StorageError>
|
crates/router/src/services/authorization/roles.rs
|
router
|
function_signature
| null | null | null | 89
|
from_role_id_org_id_tenant_id
| null | null | null | null | null | null |
// Function: connector_retrieve
// File: crates/router/src/routes/admin.rs
// Module: router
pub fn connector_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantConnectorAccountId>,
) -> HttpResponse
|
crates/router/src/routes/admin.rs
|
router
|
function_signature
| null | null | null | 62
|
connector_retrieve
| null | null | null | null | null | null |
// Struct: IatapayRefundRequest
// File: crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct IatapayRefundRequest
|
crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
IatapayRefundRequest
| 0
|
[] | 57
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/signifyd/transformers/auth.rs
// Module: hyperswitch_connectors
// Public structs: 1
use error_stack;
use hyperswitch_domain_models::router_data::ConnectorAuthType;
use hyperswitch_interfaces::errors::ConnectorError;
use masking::Secret;
pub struct SignifydAuthType {
pub api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for SignifydAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
|
crates/hyperswitch_connectors/src/connectors/signifyd/transformers/auth.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 186
| null | null | null | null | null | null | null |
// Function: create_pm_collect_db_entry
// File: crates/router/src/core/payment_methods.rs
// Module: router
pub fn create_pm_collect_db_entry(
state: &SessionState,
merchant_context: &domain::MerchantContext,
pm_collect_link_data: &PaymentMethodCollectLinkData,
return_url: Option<String>,
) -> RouterResult<PaymentMethodCollectLink>
|
crates/router/src/core/payment_methods.rs
|
router
|
function_signature
| null | null | null | 80
|
create_pm_collect_db_entry
| null | null | null | null | null | null |
// Function: get_sdk_event_filters
// File: crates/router/src/analytics.rs
// Module: router
pub fn get_sdk_event_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<GetSdkEventFiltersRequest>,
) -> impl Responder
|
crates/router/src/analytics.rs
|
router
|
function_signature
| null | null | null | 68
|
get_sdk_event_filters
| null | null | null | null | null | null |
// Struct: PartnerReferralThirdPartyDetails
// File: crates/router/src/types/api/connector_onboarding/paypal.rs
// Module: router
// Implementations: 0
pub struct PartnerReferralThirdPartyDetails
|
crates/router/src/types/api/connector_onboarding/paypal.rs
|
router
|
struct_definition
|
PartnerReferralThirdPartyDetails
| 0
|
[] | 46
| null | null | null | null | null | null | null |
// Struct: CardMandateRequest
// File: crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CardMandateRequest
|
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CardMandateRequest
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Struct: VaultFingerprintResponse
// File: crates/router/src/types/payment_methods.rs
// Module: router
// Implementations: 0
pub struct VaultFingerprintResponse
|
crates/router/src/types/payment_methods.rs
|
router
|
struct_definition
|
VaultFingerprintResponse
| 0
|
[] | 37
| null | null | null | null | null | null | null |
// Function: get_updated_feature_metadata
// File: crates/hyperswitch_domain_models/src/payments.rs
// Module: hyperswitch_domain_models
pub fn get_updated_feature_metadata(
&self,
) -> CustomResult<Option<FeatureMetadata>, errors::api_error_response::ApiErrorResponse>
|
crates/hyperswitch_domain_models/src/payments.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 61
|
get_updated_feature_metadata
| null | null | null | null | null | null |
// Function: dummy_connector_refund
// File: crates/router/src/routes/dummy_connector.rs
// Module: router
pub fn dummy_connector_refund(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<types::DummyConnectorRefundRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl actix_web::Responder
|
crates/router/src/routes/dummy_connector.rs
|
router
|
function_signature
| null | null | null | 92
|
dummy_connector_refund
| null | null | null | null | null | null |
// Implementation: impl webhooks::IncomingWebhook for for Mollie
// File: crates/hyperswitch_connectors/src/connectors/mollie.rs
// Module: hyperswitch_connectors
// Methods: 3 total (0 public)
impl webhooks::IncomingWebhook for for Mollie
|
crates/hyperswitch_connectors/src/connectors/mollie.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 64
| null |
Mollie
|
webhooks::IncomingWebhook for
| 3
| 0
| null | null |
// Struct: AuthenticationEligibilityRequest
// File: crates/api_models/src/authentication.rs
// Module: api_models
// Implementations: 2
// Traits: ApiEventMetric
pub struct AuthenticationEligibilityRequest
|
crates/api_models/src/authentication.rs
|
api_models
|
struct_definition
|
AuthenticationEligibilityRequest
| 2
|
[
"ApiEventMetric"
] | 46
| null | null | null | null | null | null | null |
// Struct: MaskedHeaders
// File: crates/api_models/src/admin.rs
// Module: api_models
// Implementations: 1
pub struct MaskedHeaders
|
crates/api_models/src/admin.rs
|
api_models
|
struct_definition
|
MaskedHeaders
| 1
|
[] | 35
| null | null | null | null | null | null | null |
// Function: migrate_payment_method
// File: crates/payment_methods/src/core/migration/payment_methods.rs
// Module: payment_methods
pub fn migrate_payment_method(
state: &state::PaymentMethodsState,
req: pm_api::PaymentMethodMigrate,
merchant_id: &id_type::MerchantId,
merchant_context: &merchant_context::MerchantContext,
controller: &dyn PaymentMethodsController,
) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodMigrateResponse>, errors::ApiErrorResponse>
|
crates/payment_methods/src/core/migration/payment_methods.rs
|
payment_methods
|
function_signature
| null | null | null | 106
|
migrate_payment_method
| null | null | null | null | null | null |
// Struct: RefundResponse
// File: crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct RefundResponse
|
crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
RefundResponse
| 0
|
[] | 48
| 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.