text
stringlengths 65
57.3k
| file_path
stringlengths 22
92
| module
stringclasses 38
values | type
stringclasses 7
values | struct_name
stringlengths 3
60
⌀ | impl_count
int64 0
60
⌀ | traits
listlengths 0
59
⌀ | tokens
int64 16
8.19k
| function_name
stringlengths 3
85
⌀ | type_name
stringlengths 1
67
⌀ | trait_name
stringclasses 573
values | method_count
int64 0
31
⌀ | public_method_count
int64 0
19
⌀ | submodule_count
int64 0
56
⌀ | export_count
int64 0
9
⌀ |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
// Implementation: impl StripebillingWebhookBody
// File: crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs
// Module: hyperswitch_connectors
// Methods: 1 total (1 public)
impl StripebillingWebhookBody
|
crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 55
| null |
StripebillingWebhookBody
| null | 1
| 1
| null | null |
// Struct: CustomerInfo
// File: crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CustomerInfo
|
crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CustomerInfo
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Function: create_cards_info
// File: crates/router/src/routes/cards_info.rs
// Module: router
pub fn create_cards_info(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<cards_info_api_types::CardInfoCreateRequest>,
) -> impl Responder
|
crates/router/src/routes/cards_info.rs
|
router
|
function_signature
| null | null | null | 66
|
create_cards_info
| null | null | null | null | null | null |
// Function: contract_based_routing_update_configs
// File: crates/openapi/src/routes/routing.rs
// Module: openapi
pub fn contract_based_routing_update_configs()
|
crates/openapi/src/routes/routing.rs
|
openapi
|
function_signature
| null | null | null | 35
|
contract_based_routing_update_configs
| null | null | null | null | null | null |
// Implementation: impl OutgoingWebhookEventMetric for for OutgoingWebhookContent
// File: crates/router/src/events/outgoing_webhook_logs.rs
// Module: router
// Methods: 1 total (0 public)
impl OutgoingWebhookEventMetric for for OutgoingWebhookContent
|
crates/router/src/events/outgoing_webhook_logs.rs
|
router
|
impl_block
| null | null | null | 61
| null |
OutgoingWebhookContent
|
OutgoingWebhookEventMetric for
| 1
| 0
| null | null |
// Struct: CancelInputData
// File: crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CancelInputData
|
crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CancelInputData
| 0
|
[] | 48
| null | null | null | null | null | null | null |
// Struct: BankAccountDetail
// File: crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct BankAccountDetail
|
crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs
|
hyperswitch_connectors
|
struct_definition
|
BankAccountDetail
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Function: create_payout
// File: crates/router/src/core/payouts.rs
// Module: router
pub fn create_payout(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()>
|
crates/router/src/core/payouts.rs
|
router
|
function_signature
| null | null | null | 72
|
create_payout
| null | null | null | null | null | null |
// Function: profiles_list
// File: crates/openapi/src/routes/merchant_account.rs
// Module: openapi
pub fn profiles_list()
|
crates/openapi/src/routes/merchant_account.rs
|
openapi
|
function_signature
| null | null | null | 30
|
profiles_list
| null | null | null | null | null | null |
// Function: add_nested_filter_clause
// File: crates/analytics/src/query.rs
// Module: analytics
pub fn add_nested_filter_clause(&mut self, filter: Filter)
|
crates/analytics/src/query.rs
|
analytics
|
function_signature
| null | null | null | 37
|
add_nested_filter_clause
| null | null | null | null | null | null |
// Struct: MolliePaymentsResponse
// File: crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct MolliePaymentsResponse
|
crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
MolliePaymentsResponse
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Trait: NodeViz
// File: crates/hyperswitch_constraint_graph/src/types.rs
// Module: hyperswitch_constraint_graph
pub trait NodeViz
|
crates/hyperswitch_constraint_graph/src/types.rs
|
hyperswitch_constraint_graph
|
trait_definition
| null | null | null | 34
| null | null |
NodeViz
| null | null | null | null |
// Struct: PayuRefundResponseData
// File: crates/hyperswitch_connectors/src/connectors/payu/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PayuRefundResponseData
|
crates/hyperswitch_connectors/src/connectors/payu/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PayuRefundResponseData
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// Struct: CybersourceAccountInfo
// File: crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CybersourceAccountInfo
|
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CybersourceAccountInfo
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// Implementation: impl CustomerResponse
// File: crates/api_models/src/customers.rs
// Module: api_models
// Methods: 1 total (1 public)
impl CustomerResponse
|
crates/api_models/src/customers.rs
|
api_models
|
impl_block
| null | null | null | 37
| null |
CustomerResponse
| null | 1
| 1
| null | null |
// Implementation: impl api::Refund for for Bamboraapac
// File: crates/hyperswitch_connectors/src/connectors/bamboraapac.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::Refund for for Bamboraapac
|
crates/hyperswitch_connectors/src/connectors/bamboraapac.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 66
| null |
Bamboraapac
|
api::Refund for
| 0
| 0
| null | null |
// Implementation: impl SeriesBucket for for Granularity
// File: crates/analytics/src/query.rs
// Module: analytics
// Methods: 4 total (0 public)
impl SeriesBucket for for Granularity
|
crates/analytics/src/query.rs
|
analytics
|
impl_block
| null | null | null | 43
| null |
Granularity
|
SeriesBucket for
| 4
| 0
| null | null |
// Struct: PaymentResponseData
// File: crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaymentResponseData
|
crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaymentResponseData
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Struct: CloneConnectorRequest
// File: crates/api_models/src/user.rs
// Module: api_models
// Implementations: 0
pub struct CloneConnectorRequest
|
crates/api_models/src/user.rs
|
api_models
|
struct_definition
|
CloneConnectorRequest
| 0
|
[] | 35
| null | null | null | null | null | null | null |
// Function: make_value_node
// File: crates/hyperswitch_constraint_graph/src/builder.rs
// Module: hyperswitch_constraint_graph
pub fn make_value_node<M: Metadata>(
&mut self,
value: NodeValue<V>,
info: Option<&'static str>,
metadata: Option<M>,
) -> NodeId
|
crates/hyperswitch_constraint_graph/src/builder.rs
|
hyperswitch_constraint_graph
|
function_signature
| null | null | null | 71
|
make_value_node
| null | null | null | null | null | null |
// Implementation: impl webhooks::IncomingWebhook for for Breadpay
// File: crates/hyperswitch_connectors/src/connectors/breadpay.rs
// Module: hyperswitch_connectors
// Methods: 3 total (0 public)
impl webhooks::IncomingWebhook for for Breadpay
|
crates/hyperswitch_connectors/src/connectors/breadpay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 62
| null |
Breadpay
|
webhooks::IncomingWebhook for
| 3
| 0
| null | null |
// Implementation: impl ApiEventMetric for for GatewayStatusMap
// File: crates/diesel_models/src/gsm.rs
// Module: diesel_models
// Methods: 1 total (0 public)
impl ApiEventMetric for for GatewayStatusMap
|
crates/diesel_models/src/gsm.rs
|
diesel_models
|
impl_block
| null | null | null | 50
| null |
GatewayStatusMap
|
ApiEventMetric for
| 1
| 0
| null | null |
// Function: new
// File: crates/test_utils/src/connector_auth.rs
// Module: test_utils
pub fn new() -> Self
|
crates/test_utils/src/connector_auth.rs
|
test_utils
|
function_signature
| null | null | null | 29
|
new
| null | null | null | null | null | null |
// Implementation: impl DerefMut for for CycleCheck
// File: crates/hyperswitch_constraint_graph/src/types.rs
// Module: hyperswitch_constraint_graph
// Methods: 1 total (0 public)
impl DerefMut for for CycleCheck
|
crates/hyperswitch_constraint_graph/src/types.rs
|
hyperswitch_constraint_graph
|
impl_block
| null | null | null | 52
| null |
CycleCheck
|
DerefMut for
| 1
| 0
| null | null |
// Struct: FiuuSyncStatus
// File: crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct FiuuSyncStatus
|
crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
FiuuSyncStatus
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Struct: ApplePayCryptogramDataInternal
// File: crates/hyperswitch_domain_models/src/router_data.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct ApplePayCryptogramDataInternal
|
crates/hyperswitch_domain_models/src/router_data.rs
|
hyperswitch_domain_models
|
struct_definition
|
ApplePayCryptogramDataInternal
| 0
|
[] | 48
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentSession for for Payme
// File: crates/hyperswitch_connectors/src/connectors/payme.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSession for for Payme
|
crates/hyperswitch_connectors/src/connectors/payme.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Payme
|
api::PaymentSession for
| 0
| 0
| null | null |
// Implementation: impl api::PaymentSync for for Datatrans
// File: crates/hyperswitch_connectors/src/connectors/datatrans.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSync for for Datatrans
|
crates/hyperswitch_connectors/src/connectors/datatrans.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Datatrans
|
api::PaymentSync for
| 0
| 0
| null | null |
// Struct: PaymentAddress
// File: crates/hyperswitch_domain_models/src/payment_address.rs
// Module: hyperswitch_domain_models
// Implementations: 1
pub struct PaymentAddress
|
crates/hyperswitch_domain_models/src/payment_address.rs
|
hyperswitch_domain_models
|
struct_definition
|
PaymentAddress
| 1
|
[] | 40
| null | null | null | null | null | null | null |
// File: crates/router/src/types/storage/refund.rs
// Module: router
use api_models::payments::AmountFilter;
use async_bb8_diesel::AsyncRunQueryDsl;
use common_utils::errors::CustomResult;
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, QueryDsl};
#[cfg(feature = "v1")]
use diesel_models::schema::refund::dsl;
#[cfg(feature = "v2")]
use diesel_models::schema_v2::refund::dsl;
use diesel_models::{
enums::{Currency, RefundStatus},
errors,
query::generics::db_metrics,
refund::Refund,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::refunds;
use crate::{connection::PgPooledConn, logger};
#[async_trait::async_trait]
pub trait RefundDbExt: Sized {
#[cfg(feature = "v1")]
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &refunds::RefundListConstraints,
limit: i64,
offset: i64,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
#[cfg(feature = "v2")]
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: refunds::RefundListConstraints,
limit: i64,
offset: i64,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
#[cfg(feature = "v1")]
async fn filter_by_meta_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &common_utils::types::TimeRange,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError>;
#[cfg(feature = "v1")]
async fn get_refunds_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &refunds::RefundListConstraints,
) -> CustomResult<i64, errors::DatabaseError>;
#[cfg(feature = "v1")]
async fn get_refund_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<(RefundStatus, i64)>, errors::DatabaseError>;
#[cfg(feature = "v2")]
async fn get_refunds_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: refunds::RefundListConstraints,
) -> CustomResult<i64, errors::DatabaseError>;
}
#[async_trait::async_trait]
impl RefundDbExt for Refund {
#[cfg(feature = "v1")]
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &refunds::RefundListConstraints,
limit: i64,
offset: i64,
) -> 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_pay_or_ref_id = false;
if let (Some(pid), Some(ref_id)) = (
&refund_list_details.payment_id,
&refund_list_details.refund_id,
) {
search_by_pay_or_ref_id = true;
filter = filter
.filter(
dsl::payment_id
.eq(pid.to_owned())
.or(dsl::refund_id.eq(ref_id.to_owned())),
)
.limit(limit)
.offset(offset);
};
if !search_by_pay_or_ref_id {
match &refund_list_details.payment_id {
Some(pid) => {
filter = filter.filter(dsl::payment_id.eq(pid.to_owned()));
}
None => {
filter = filter.limit(limit).offset(offset);
}
};
}
if !search_by_pay_or_ref_id {
match &refund_list_details.refund_id {
Some(ref_id) => {
filter = filter.filter(dsl::refund_id.eq(ref_id.to_owned()));
}
None => {
filter = filter.limit(limit).offset(offset);
}
};
}
match &refund_list_details.profile_id {
Some(profile_id) => {
filter = filter
.filter(dsl::profile_id.eq_any(profile_id.to_owned()))
.limit(limit)
.offset(offset);
}
None => {
filter = filter.limit(limit).offset(offset);
}
};
if let Some(time_range) = refund_list_details.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));
}
}
filter = match refund_list_details.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.between(start, end)),
Some(AmountFilter {
start_amount: Some(start),
end_amount: None,
}) => filter.filter(dsl::refund_amount.ge(start)),
Some(AmountFilter {
start_amount: None,
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.le(end)),
_ => filter,
};
if let Some(connector) = refund_list_details.connector.clone() {
filter = filter.filter(dsl::connector.eq_any(connector));
}
if let Some(merchant_connector_id) = refund_list_details.merchant_connector_id.clone() {
filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id));
}
if let Some(filter_currency) = &refund_list_details.currency {
filter = filter.filter(dsl::currency.eq_any(filter_currency.clone()));
}
if let Some(filter_refund_status) = &refund_list_details.refund_status {
filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status.clone()));
}
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")
}
#[cfg(feature = "v2")]
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: refunds::RefundListConstraints,
limit: i64,
offset: i64,
) -> 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();
if let Some(payment_id) = &refund_list_details.payment_id {
filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned()));
}
if let Some(refund_id) = &refund_list_details.refund_id {
filter = filter.filter(dsl::id.eq(refund_id.to_owned()));
}
if let Some(time_range) = &refund_list_details.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));
}
}
filter = match refund_list_details.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.between(start, end)),
Some(AmountFilter {
start_amount: Some(start),
end_amount: None,
}) => filter.filter(dsl::refund_amount.ge(start)),
Some(AmountFilter {
start_amount: None,
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.le(end)),
_ => filter,
};
if let Some(connector) = refund_list_details.connector {
filter = filter.filter(dsl::connector.eq_any(connector));
}
if let Some(connector_id_list) = refund_list_details.connector_id_list {
filter = filter.filter(dsl::connector_id.eq_any(connector_id_list));
}
if let Some(filter_currency) = refund_list_details.currency {
filter = filter.filter(dsl::currency.eq_any(filter_currency));
}
if let Some(filter_refund_status) = refund_list_details.refund_status {
filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status));
}
filter = filter.limit(limit).offset(offset);
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")
// todo!()
}
#[cfg(feature = "v1")]
async fn filter_by_meta_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &common_utils::types::TimeRange,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError> {
let start_time = refund_list_details.start_time;
let end_time = refund_list_details
.end_time
.unwrap_or_else(common_utils::date_time::now);
let filter = <Self as HasTable>::table()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.order(dsl::modified_at.desc())
.filter(dsl::created_at.ge(start_time))
.filter(dsl::created_at.le(end_time));
let filter_connector: Vec<String> = filter
.clone()
.select(dsl::connector)
.distinct()
.order_by(dsl::connector.asc())
.get_results_async(conn)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error filtering records by connector")?;
let filter_currency: Vec<Currency> = filter
.clone()
.select(dsl::currency)
.distinct()
.order_by(dsl::currency.asc())
.get_results_async(conn)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error filtering records by currency")?;
let filter_status: Vec<RefundStatus> = filter
.select(dsl::refund_status)
.distinct()
.order_by(dsl::refund_status.asc())
.get_results_async(conn)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error filtering records by refund status")?;
let meta = api_models::refunds::RefundListMetaData {
connector: filter_connector,
currency: filter_currency,
refund_status: filter_status,
};
Ok(meta)
}
#[cfg(feature = "v1")]
async fn get_refunds_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &refunds::RefundListConstraints,
) -> CustomResult<i64, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
.count()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.into_boxed();
let mut search_by_pay_or_ref_id = false;
if let (Some(pid), Some(ref_id)) = (
&refund_list_details.payment_id,
&refund_list_details.refund_id,
) {
search_by_pay_or_ref_id = true;
filter = filter.filter(
dsl::payment_id
.eq(pid.to_owned())
.or(dsl::refund_id.eq(ref_id.to_owned())),
);
};
if !search_by_pay_or_ref_id {
if let Some(pay_id) = &refund_list_details.payment_id {
filter = filter.filter(dsl::payment_id.eq(pay_id.to_owned()));
}
}
if !search_by_pay_or_ref_id {
if let Some(ref_id) = &refund_list_details.refund_id {
filter = filter.filter(dsl::refund_id.eq(ref_id.to_owned()));
}
}
if let Some(profile_id) = &refund_list_details.profile_id {
filter = filter.filter(dsl::profile_id.eq_any(profile_id.to_owned()));
}
if let Some(time_range) = refund_list_details.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));
}
}
filter = match refund_list_details.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.between(start, end)),
Some(AmountFilter {
start_amount: Some(start),
end_amount: None,
}) => filter.filter(dsl::refund_amount.ge(start)),
Some(AmountFilter {
start_amount: None,
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.le(end)),
_ => filter,
};
if let Some(connector) = refund_list_details.connector.clone() {
filter = filter.filter(dsl::connector.eq_any(connector));
}
if let Some(merchant_connector_id) = refund_list_details.merchant_connector_id.clone() {
filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id))
}
if let Some(filter_currency) = &refund_list_details.currency {
filter = filter.filter(dsl::currency.eq_any(filter_currency.clone()));
}
if let Some(filter_refund_status) = &refund_list_details.refund_status {
filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status.clone()));
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
filter
.get_result_async::<i64>(conn)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering count of refunds")
}
#[cfg(feature = "v2")]
async fn get_refunds_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: refunds::RefundListConstraints,
) -> CustomResult<i64, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
.count()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.into_boxed();
if let Some(payment_id) = &refund_list_details.payment_id {
filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned()));
}
if let Some(refund_id) = &refund_list_details.refund_id {
filter = filter.filter(dsl::id.eq(refund_id.to_owned()));
}
if let Some(time_range) = refund_list_details.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));
}
}
filter = match refund_list_details.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.between(start, end)),
Some(AmountFilter {
start_amount: Some(start),
end_amount: None,
}) => filter.filter(dsl::refund_amount.ge(start)),
Some(AmountFilter {
start_amount: None,
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.le(end)),
_ => filter,
};
if let Some(connector) = refund_list_details.connector {
filter = filter.filter(dsl::connector.eq_any(connector));
}
if let Some(connector_id_list) = refund_list_details.connector_id_list {
filter = filter.filter(dsl::connector_id.eq_any(connector_id_list));
}
if let Some(filter_currency) = refund_list_details.currency {
filter = filter.filter(dsl::currency.eq_any(filter_currency));
}
if let Some(filter_refund_status) = refund_list_details.refund_status {
filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status));
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
filter
.get_result_async::<i64>(conn)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering count of refunds")
}
#[cfg(feature = "v1")]
async fn get_refund_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<(RefundStatus, i64)>, errors::DatabaseError> {
let mut query = <Self as HasTable>::table()
.group_by(dsl::refund_status)
.select((dsl::refund_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!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
query.get_results_async::<(RefundStatus, i64)>(conn),
db_metrics::DatabaseOperation::Count,
)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering status count of refunds")
}
}
|
crates/router/src/types/storage/refund.rs
|
router
|
full_file
| null | null | null | 4,158
| null | null | null | null | null | null | null |
// Implementation: impl GenericLink
// File: crates/diesel_models/src/query/generic_link.rs
// Module: diesel_models
// Methods: 3 total (0 public)
impl GenericLink
|
crates/diesel_models/src/query/generic_link.rs
|
diesel_models
|
impl_block
| null | null | null | 40
| null |
GenericLink
| null | 3
| 0
| null | null |
// Function: get_role_from_token
// File: crates/router/src/routes/user_role.rs
// Module: router
pub fn get_role_from_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse
|
crates/router/src/routes/user_role.rs
|
router
|
function_signature
| null | null | null | 44
|
get_role_from_token
| null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs
// Module: hyperswitch_connectors
// Public functions: 1
// Public structs: 34
use std::str::FromStr;
use common_enums::enums::CaptureMethod;
use common_utils::types::MinorUnit;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{PaymentsCancelData, ResponseId},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefreshTokenRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
get_unimplemented_payment_method_error_message, CardData, RouterData as OtherRouterData,
},
};
pub struct JpmorganRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for JpmorganRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct JpmorganAuthUpdateRequest {
pub grant_type: String,
pub scope: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct JpmorganAuthUpdateResponse {
pub access_token: Secret<String>,
pub scope: String,
pub token_type: String,
pub expires_in: i64,
}
impl TryFrom<&RefreshTokenRouterData> for JpmorganAuthUpdateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(_item: &RefreshTokenRouterData) -> Result<Self, Self::Error> {
Ok(Self {
grant_type: String::from("client_credentials"),
scope: String::from("jpm:payments:sandbox"),
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, JpmorganAuthUpdateResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, JpmorganAuthUpdateResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganPaymentsRequest {
capture_method: CapMethod,
amount: MinorUnit,
currency: common_enums::Currency,
merchant: JpmorganMerchant,
payment_method_type: JpmorganPaymentMethodType,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCard {
account_number: Secret<String>,
expiry: Expiry,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganPaymentMethodType {
card: JpmorganCard,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Expiry {
month: Secret<i32>,
year: Secret<i32>,
}
#[derive(Serialize, Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganMerchantSoftware {
company_name: Secret<String>,
product_name: Secret<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganMerchant {
merchant_software: JpmorganMerchantSoftware,
}
fn map_capture_method(
capture_method: CaptureMethod,
) -> Result<CapMethod, error_stack::Report<errors::ConnectorError>> {
match capture_method {
CaptureMethod::Automatic => Ok(CapMethod::Now),
CaptureMethod::Manual => Ok(CapMethod::Manual),
CaptureMethod::Scheduled
| CaptureMethod::ManualMultiple
| CaptureMethod::SequentialAutomatic => {
Err(errors::ConnectorError::NotImplemented("Capture Method".to_string()).into())
}
}
}
impl TryFrom<&JpmorganRouterData<&PaymentsAuthorizeRouterData>> for JpmorganPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &JpmorganRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
if item.router_data.is_three_ds() {
return Err(errors::ConnectorError::NotSupported {
message: "3DS payments".to_string(),
connector: "Jpmorgan",
}
.into());
}
let capture_method =
map_capture_method(item.router_data.request.capture_method.unwrap_or_default());
let merchant_software = JpmorganMerchantSoftware {
company_name: String::from("JPMC").into(),
product_name: String::from("Hyperswitch").into(),
};
let merchant = JpmorganMerchant { merchant_software };
let expiry: Expiry = Expiry {
month: Secret::new(
req_card
.card_exp_month
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
),
year: req_card.get_expiry_year_as_4_digit_i32()?,
};
let account_number = Secret::new(req_card.card_number.to_string());
let card = JpmorganCard {
account_number,
expiry,
};
let payment_method_type = JpmorganPaymentMethodType { card };
Ok(Self {
capture_method: capture_method?,
currency: item.router_data.request.currency,
amount: item.amount,
merchant,
payment_method_type,
})
}
PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("jpmorgan"),
)
.into()),
}
}
}
//JP Morgan uses access token only due to which we aren't reading the fields in this struct
#[derive(Debug)]
pub struct JpmorganAuthType {
pub(super) _api_key: Secret<String>,
pub(super) _key1: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for JpmorganAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
_api_key: api_key.to_owned(),
_key1: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum JpmorganTransactionStatus {
Success,
Denied,
Error,
}
#[derive(Default, Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum JpmorganTransactionState {
Closed,
Authorized,
Voided,
#[default]
Pending,
Declined,
Error,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganPaymentsResponse {
transaction_id: String,
request_id: String,
transaction_state: JpmorganTransactionState,
response_status: String,
response_code: String,
response_message: String,
payment_method_type: PaymentMethodType,
capture_method: Option<CapMethod>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Merchant {
merchant_id: Option<String>,
merchant_software: JpmorganMerchantSoftware,
merchant_category_code: Option<String>,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentMethodType {
card: Option<Card>,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Card {
expiry: Option<ExpiryResponse>,
card_type: Option<Secret<String>>,
card_type_name: Option<Secret<String>>,
masked_account_number: Option<Secret<String>>,
card_type_indicators: Option<CardTypeIndicators>,
network_response: Option<NetworkResponse>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkResponse {
address_verification_result: Option<Secret<String>>,
address_verification_result_code: Option<Secret<String>>,
card_verification_result_code: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExpiryResponse {
month: Option<Secret<i32>>,
year: Option<Secret<i32>>,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardTypeIndicators {
issuance_country_code: Option<Secret<String>>,
is_durbin_regulated: Option<bool>,
card_product_types: Secret<Vec<String>>,
}
pub fn attempt_status_from_transaction_state(
transaction_state: JpmorganTransactionState,
) -> common_enums::AttemptStatus {
match transaction_state {
JpmorganTransactionState::Authorized => common_enums::AttemptStatus::Authorized,
JpmorganTransactionState::Closed => common_enums::AttemptStatus::Charged,
JpmorganTransactionState::Declined | JpmorganTransactionState::Error => {
common_enums::AttemptStatus::Failure
}
JpmorganTransactionState::Pending => common_enums::AttemptStatus::Pending,
JpmorganTransactionState::Voided => common_enums::AttemptStatus::Voided,
}
}
impl<F, T> TryFrom<ResponseRouterData<F, JpmorganPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, JpmorganPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let transaction_state = match item.response.transaction_state {
JpmorganTransactionState::Closed => match item.response.capture_method {
Some(CapMethod::Now) => JpmorganTransactionState::Closed,
_ => JpmorganTransactionState::Authorized,
},
JpmorganTransactionState::Authorized => JpmorganTransactionState::Authorized,
JpmorganTransactionState::Voided => JpmorganTransactionState::Voided,
JpmorganTransactionState::Pending => JpmorganTransactionState::Pending,
JpmorganTransactionState::Declined => JpmorganTransactionState::Declined,
JpmorganTransactionState::Error => JpmorganTransactionState::Error,
};
let status = attempt_status_from_transaction_state(transaction_state);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCaptureRequest {
capture_method: Option<CapMethod>,
amount: MinorUnit,
currency: Option<common_enums::Currency>,
}
#[derive(Debug, Default, Copy, Serialize, Deserialize, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum CapMethod {
#[default]
Now,
Delayed,
Manual,
}
impl TryFrom<&JpmorganRouterData<&PaymentsCaptureRouterData>> for JpmorganCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &JpmorganRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let capture_method = Some(map_capture_method(
item.router_data.request.capture_method.unwrap_or_default(),
)?);
Ok(Self {
capture_method,
amount: item.amount,
currency: Some(item.router_data.request.currency),
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCaptureResponse {
pub transaction_id: String,
pub request_id: String,
pub transaction_state: JpmorganTransactionState,
pub response_status: JpmorganTransactionStatus,
pub response_code: String,
pub response_message: String,
pub payment_method_type: PaymentMethodTypeCapRes,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentMethodTypeCapRes {
pub card: Option<CardCapRes>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardCapRes {
pub card_type: Option<Secret<String>>,
pub card_type_name: Option<Secret<String>>,
unmasked_account_number: Option<Secret<String>>,
}
impl<F, T> TryFrom<ResponseRouterData<F, JpmorganCaptureResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, JpmorganCaptureResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = attempt_status_from_transaction_state(item.response.transaction_state);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganPSyncResponse {
transaction_id: String,
transaction_state: JpmorganTransactionState,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum JpmorganResponseStatus {
Success,
Denied,
Error,
}
impl<F, PaymentsSyncData>
TryFrom<ResponseRouterData<F, JpmorganPSyncResponse, PaymentsSyncData, PaymentsResponseData>>
for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, JpmorganPSyncResponse, PaymentsSyncData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = attempt_status_from_transaction_state(item.response.transaction_state);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TransactionData {
payment_type: Option<Secret<String>>,
status_code: Secret<i32>,
txn_secret: Option<Secret<String>>,
tid: Option<Secret<i64>>,
test_mode: Option<Secret<i8>>,
status: Option<JpmorganTransactionStatus>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganRefundRequest {
pub merchant: MerchantRefundReq,
pub amount: MinorUnit,
pub currency: common_enums::Currency,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantRefundReq {
pub merchant_software: JpmorganMerchantSoftware,
}
impl<F> TryFrom<&JpmorganRouterData<&RefundsRouterData<F>>> for JpmorganRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &JpmorganRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let merchant_software = JpmorganMerchantSoftware {
company_name: String::from("JPMC").into(),
product_name: String::from("Hyperswitch").into(),
};
let merchant = MerchantRefundReq { merchant_software };
let amount = item.amount;
let currency = item.router_data.request.currency;
Ok(Self {
merchant,
amount,
currency,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganRefundResponse {
pub transaction_id: Option<String>,
pub request_id: String,
pub transaction_state: JpmorganTransactionState,
pub amount: MinorUnit,
pub currency: common_enums::Currency,
pub response_status: JpmorganResponseStatus,
pub response_code: String,
pub response_message: String,
pub transaction_reference_id: Option<String>,
pub remaining_refundable_amount: Option<i64>,
}
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for common_enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
}
}
}
impl From<(JpmorganResponseStatus, JpmorganTransactionState)> for RefundStatus {
fn from(
(response_status, transaction_state): (JpmorganResponseStatus, JpmorganTransactionState),
) -> Self {
match response_status {
JpmorganResponseStatus::Success => match transaction_state {
JpmorganTransactionState::Voided | JpmorganTransactionState::Closed => {
Self::Succeeded
}
JpmorganTransactionState::Declined | JpmorganTransactionState::Error => {
Self::Failed
}
JpmorganTransactionState::Pending | JpmorganTransactionState::Authorized => {
Self::Processing
}
},
JpmorganResponseStatus::Denied | JpmorganResponseStatus::Error => Self::Failed,
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, JpmorganRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, JpmorganRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item
.response
.transaction_id
.clone()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?,
refund_status: RefundStatus::from((
item.response.response_status,
item.response.transaction_state,
))
.into(),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganRefundSyncResponse {
transaction_id: String,
request_id: String,
transaction_state: JpmorganTransactionState,
amount: MinorUnit,
currency: common_enums::Currency,
response_status: JpmorganResponseStatus,
response_code: String,
}
impl TryFrom<RefundsResponseRouterData<RSync, JpmorganRefundSyncResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, JpmorganRefundSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id.clone(),
refund_status: RefundStatus::from((
item.response.response_status,
item.response.transaction_state,
))
.into(),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ReversalReason {
NoResponse,
LateResponse,
UnableToDeliver,
CardDeclined,
MacNotVerified,
MacSyncError,
ZekSyncError,
SystemMalfunction,
SuspectedFraud,
}
impl FromStr for ReversalReason {
type Err = error_stack::Report<errors::ConnectorError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_uppercase().as_str() {
"NO_RESPONSE" => Ok(Self::NoResponse),
"LATE_RESPONSE" => Ok(Self::LateResponse),
"UNABLE_TO_DELIVER" => Ok(Self::UnableToDeliver),
"CARD_DECLINED" => Ok(Self::CardDeclined),
"MAC_NOT_VERIFIED" => Ok(Self::MacNotVerified),
"MAC_SYNC_ERROR" => Ok(Self::MacSyncError),
"ZEK_SYNC_ERROR" => Ok(Self::ZekSyncError),
"SYSTEM_MALFUNCTION" => Ok(Self::SystemMalfunction),
"SUSPECTED_FRAUD" => Ok(Self::SuspectedFraud),
_ => Err(report!(errors::ConnectorError::InvalidDataFormat {
field_name: "cancellation_reason",
})),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCancelRequest {
pub amount: Option<i64>,
pub is_void: Option<bool>,
pub reversal_reason: Option<ReversalReason>,
}
impl TryFrom<JpmorganRouterData<&PaymentsCancelRouterData>> for JpmorganCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: JpmorganRouterData<&PaymentsCancelRouterData>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.router_data.request.amount,
is_void: Some(true),
reversal_reason: item
.router_data
.request
.cancellation_reason
.as_ref()
.map(|reason| ReversalReason::from_str(reason))
.transpose()?,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCancelResponse {
transaction_id: String,
request_id: String,
response_status: JpmorganResponseStatus,
response_code: String,
response_message: String,
payment_method_type: JpmorganPaymentMethodTypeCancelResponse,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganPaymentMethodTypeCancelResponse {
pub card: CardCancelResponse,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardCancelResponse {
pub card_type: Secret<String>,
pub card_type_name: Secret<String>,
}
impl<F>
TryFrom<ResponseRouterData<F, JpmorganCancelResponse, PaymentsCancelData, PaymentsResponseData>>
for RouterData<F, PaymentsCancelData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
JpmorganCancelResponse,
PaymentsCancelData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status = match item.response.response_status {
JpmorganResponseStatus::Success => common_enums::AttemptStatus::Voided,
JpmorganResponseStatus::Denied | JpmorganResponseStatus::Error => {
common_enums::AttemptStatus::Failure
}
};
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganValidationErrors {
pub code: Option<String>,
pub message: Option<String>,
pub entity: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganErrorInformation {
pub code: Option<String>,
pub message: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganErrorResponse {
pub response_status: JpmorganTransactionStatus,
pub response_code: String,
pub response_message: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 5,820
| null | null | null | null | null | null | null |
// Function: get_decrypted_vault_response_payload
// File: crates/router/src/core/payment_methods/transformers.rs
// Module: router
pub fn get_decrypted_vault_response_payload(
jwekey: &settings::Jwekey,
jwe_body: encryption::JweBody,
decryption_scheme: settings::DecryptionScheme,
) -> CustomResult<String, errors::VaultError>
|
crates/router/src/core/payment_methods/transformers.rs
|
router
|
function_signature
| null | null | null | 84
|
get_decrypted_vault_response_payload
| null | null | null | null | null | null |
// Function: is_network_token_payment_method_data
// File: crates/hyperswitch_domain_models/src/payment_method_data.rs
// Module: hyperswitch_domain_models
pub fn is_network_token_payment_method_data(&self) -> bool
|
crates/hyperswitch_domain_models/src/payment_method_data.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 47
|
is_network_token_payment_method_data
| null | null | null | null | null | null |
// Implementation: impl IncomingWebhook for for DummyConnector
// File: crates/hyperswitch_connectors/src/connectors/dummyconnector.rs
// Module: hyperswitch_connectors
// Methods: 3 total (0 public)
impl IncomingWebhook for for DummyConnector
|
crates/hyperswitch_connectors/src/connectors/dummyconnector.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 56
| null |
DummyConnector
|
IncomingWebhook for
| 3
| 0
| null | null |
// Implementation: impl api::ConnectorAccessToken for for HyperswitchVault
// File: crates/hyperswitch_connectors/src/connectors/hyperswitch_vault.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::ConnectorAccessToken for for HyperswitchVault
|
crates/hyperswitch_connectors/src/connectors/hyperswitch_vault.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 65
| null |
HyperswitchVault
|
api::ConnectorAccessToken for
| 0
| 0
| null | null |
// Struct: OpensearchHit
// File: crates/api_models/src/analytics/search.rs
// Module: api_models
// Implementations: 0
pub struct OpensearchHit
|
crates/api_models/src/analytics/search.rs
|
api_models
|
struct_definition
|
OpensearchHit
| 0
|
[] | 39
| null | null | null | null | null | null | null |
// Function: from_storage
// File: crates/router/src/services/kafka/refund.rs
// Module: router
pub fn from_storage(refund: &'a Refund) -> Self
|
crates/router/src/services/kafka/refund.rs
|
router
|
function_signature
| null | null | null | 38
|
from_storage
| null | null | null | null | null | null |
// Struct: AirwallexCardPaymentOptions
// File: crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct AirwallexCardPaymentOptions
|
crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
AirwallexCardPaymentOptions
| 0
|
[] | 55
| null | null | null | null | null | null | null |
// Struct: LoonioRefundRequest
// File: crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct LoonioRefundRequest
|
crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
LoonioRefundRequest
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Struct: RedsysThreeDsInvokeData
// File: crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct RedsysThreeDsInvokeData
|
crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
RedsysThreeDsInvokeData
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// Implementation: impl ApiKeyId
// File: crates/common_utils/src/id_type/api_key.rs
// Module: common_utils
// Methods: 1 total (1 public)
impl ApiKeyId
|
crates/common_utils/src/id_type/api_key.rs
|
common_utils
|
impl_block
| null | null | null | 39
| null |
ApiKeyId
| null | 1
| 1
| null | null |
// Struct: NovalnetMandate
// File: crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct NovalnetMandate
|
crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
NovalnetMandate
| 0
|
[] | 54
| null | null | null | null | null | null | null |
// Implementation: impl MessagingInterface for for EventsHandler
// File: crates/router/src/events.rs
// Module: router
// Methods: 1 total (0 public)
impl MessagingInterface for for EventsHandler
|
crates/router/src/events.rs
|
router
|
impl_block
| null | null | null | 42
| null |
EventsHandler
|
MessagingInterface for
| 1
| 0
| null | null |
// Struct: CheckoutDisputeWebhookBody
// File: crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CheckoutDisputeWebhookBody
|
crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CheckoutDisputeWebhookBody
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// File: crates/router/src/utils/ext_traits.rs
// Module: router
pub use hyperswitch_domain_models::ext_traits::OptionExt;
use crate::core::errors::{self, CustomResult};
pub trait ValidateCall<T, F> {
fn validate_opt(self, func: F) -> CustomResult<(), errors::ValidationError>;
}
impl<T, F> ValidateCall<T, F> for Option<&T>
where
F: Fn(&T) -> CustomResult<(), errors::ValidationError>,
{
fn validate_opt(self, func: F) -> CustomResult<(), errors::ValidationError> {
match self {
Some(val) => func(val),
None => Ok(()),
}
}
}
|
crates/router/src/utils/ext_traits.rs
|
router
|
full_file
| null | null | null | 145
| null | null | null | null | null | null | null |
// File: crates/router/src/types/api/verify_connector.rs
// Module: router
// Public structs: 1
pub mod paypal;
pub mod stripe;
use error_stack::ResultExt;
use crate::{
consts,
core::errors,
services::{
self,
connector_integration_interface::{BoxedConnectorIntegrationInterface, ConnectorEnum},
},
types::{self, api, api::ConnectorCommon, domain, storage::enums as storage_enums},
SessionState,
};
#[derive(Clone)]
pub struct VerifyConnectorData {
pub connector: ConnectorEnum,
pub connector_auth: types::ConnectorAuthType,
pub card_details: domain::Card,
}
impl VerifyConnectorData {
fn get_payment_authorize_data(&self) -> types::PaymentsAuthorizeData {
types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(self.card_details.clone()),
email: None,
customer_name: None,
amount: 1000,
minor_amount: common_utils::types::MinorUnit::new(1000),
confirm: true,
order_tax_amount: None,
currency: storage_enums::Currency::USD,
metadata: None,
mandate_id: None,
webhook_url: None,
customer_id: None,
off_session: None,
browser_info: None,
session_token: None,
order_details: None,
order_category: None,
capture_method: None,
enrolled_for_3ds: false,
router_return_url: None,
surcharge_details: None,
setup_future_usage: None,
payment_experience: None,
payment_method_type: None,
statement_descriptor: None,
setup_mandate_details: None,
complete_authorize_url: None,
related_transaction_id: None,
statement_descriptor_suffix: None,
request_extended_authorization: None,
request_incremental_authorization: false,
authentication_data: None,
customer_acceptance: None,
split_payments: None,
merchant_order_reference_id: None,
integrity_object: None,
additional_payment_method_data: None,
shipping_cost: None,
merchant_account_id: None,
merchant_config_currency: None,
connector_testing_data: None,
order_id: None,
locale: None,
payment_channel: None,
enable_partial_authorization: None,
enable_overcapture: None,
is_stored_credential: None,
}
}
fn get_router_data<F, R1, R2>(
&self,
state: &SessionState,
request_data: R1,
access_token: Option<types::AccessToken>,
) -> types::RouterData<F, R1, R2> {
let attempt_id =
common_utils::generate_id_with_default_len(consts::VERIFY_CONNECTOR_ID_PREFIX);
types::RouterData {
flow: std::marker::PhantomData,
status: storage_enums::AttemptStatus::Started,
request: request_data,
response: Err(errors::ApiErrorResponse::InternalServerError.into()),
connector: self.connector.id().to_string(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
test_mode: None,
attempt_id: attempt_id.clone(),
description: None,
customer_id: None,
tenant_id: state.tenant.tenant_id.clone(),
merchant_id: common_utils::id_type::MerchantId::default(),
reference_id: None,
access_token,
session_token: None,
payment_method: storage_enums::PaymentMethod::Card,
amount_captured: None,
minor_amount_captured: None,
preprocessing_id: None,
connector_customer: None,
connector_auth_type: self.connector_auth.clone(),
connector_meta_data: None,
connector_wallets_details: None,
payment_method_token: None,
connector_api_version: None,
recurring_mandate_payment_data: None,
payment_method_status: None,
connector_request_reference_id: attempt_id,
address: types::PaymentAddress::new(None, None, None, None),
payment_id: common_utils::id_type::PaymentId::default()
.get_string_repr()
.to_owned(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
payment_method_balance: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
}
}
}
#[async_trait::async_trait]
pub trait VerifyConnector {
async fn verify(
state: &SessionState,
connector_data: VerifyConnectorData,
) -> errors::RouterResponse<()> {
let authorize_data = connector_data.get_payment_authorize_data();
let access_token = Self::get_access_token(state, connector_data.clone()).await?;
let router_data = connector_data.get_router_data(state, authorize_data, access_token);
let request = connector_data
.connector
.get_connector_integration()
.build_request(&router_data, &state.conf.connectors)
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Payment request cannot be built".to_string(),
})?
.ok_or(errors::ApiErrorResponse::InternalServerError)?;
let response =
services::call_connector_api(&state.to_owned(), request, "verify_connector_request")
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
match response {
Ok(_) => Ok(services::ApplicationResponse::StatusOk),
Err(error_response) => {
Self::handle_payment_error_response::<
api::Authorize,
types::PaymentFlowData,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>(
connector_data.connector.get_connector_integration(),
error_response,
)
.await
}
}
}
async fn get_access_token(
_state: &SessionState,
_connector_data: VerifyConnectorData,
) -> errors::CustomResult<Option<types::AccessToken>, errors::ApiErrorResponse> {
// AccessToken is None for the connectors without the AccessToken Flow.
// If a connector has that, then it should override this implementation.
Ok(None)
}
async fn handle_payment_error_response<F, ResourceCommonData, Req, Resp>(
// connector: &(dyn api::Connector + Sync),
connector: BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>,
error_response: types::Response,
) -> errors::RouterResponse<()> {
let error = connector
.get_error_response(error_response, None)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Err(errors::ApiErrorResponse::InvalidRequestData {
message: error.reason.unwrap_or(error.message),
}
.into())
}
async fn handle_access_token_error_response<F, ResourceCommonData, Req, Resp>(
connector: BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>,
error_response: types::Response,
) -> errors::RouterResult<Option<types::AccessToken>> {
let error = connector
.get_error_response(error_response, None)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Err(errors::ApiErrorResponse::InvalidRequestData {
message: error.reason.unwrap_or(error.message),
}
.into())
}
}
|
crates/router/src/types/api/verify_connector.rs
|
router
|
full_file
| null | null | null | 1,655
| null | null | null | null | null | null | null |
// Struct: AuthorizedotnetErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct AuthorizedotnetErrorResponse
|
crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
AuthorizedotnetErrorResponse
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Struct: PaymentType
// File: crates/hyperswitch_connectors/src/connectors/silverflow/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaymentType
|
crates/hyperswitch_connectors/src/connectors/silverflow/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaymentType
| 0
|
[] | 46
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentSession for for Trustpay
// File: crates/hyperswitch_connectors/src/connectors/trustpay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSession for for Trustpay
|
crates/hyperswitch_connectors/src/connectors/trustpay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Trustpay
|
api::PaymentSession for
| 0
| 0
| null | null |
// Struct: NoonRefundResponseTransactions
// File: crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct NoonRefundResponseTransactions
|
crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
NoonRefundResponseTransactions
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Function: insert_resource
// File: crates/storage_impl/src/kv_router_store.rs
// Module: storage_impl
pub fn insert_resource<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
create_resource_fut: R,
resource_new: M,
InsertResourceParams {
insertable,
reverse_lookups,
key,
identifier,
resource_type,
}: InsertResourceParams<'_>,
) -> error_stack::Result<D, errors::StorageError>
where
D: Debug + Sync + Conversion,
M: StorageModel<D>,
R: futures::Future<Output = error_stack::Result<M, DatabaseError>> + Send,
|
crates/storage_impl/src/kv_router_store.rs
|
storage_impl
|
function_signature
| null | null | null | 164
|
insert_resource
| null | null | null | null | null | null |
// Implementation: impl User
// File: crates/diesel_models/src/query/user.rs
// Module: diesel_models
// Methods: 6 total (0 public)
impl User
|
crates/diesel_models/src/query/user.rs
|
diesel_models
|
impl_block
| null | null | null | 36
| null |
User
| null | 6
| 0
| null | null |
// Implementation: impl ReverseLookupInterface for for KafkaStore
// File: crates/router/src/db/kafka_store.rs
// Module: router
// Methods: 2 total (0 public)
impl ReverseLookupInterface for for KafkaStore
|
crates/router/src/db/kafka_store.rs
|
router
|
impl_block
| null | null | null | 47
| null |
KafkaStore
|
ReverseLookupInterface for
| 2
| 0
| null | null |
// Struct: UnifiedAuthenticationServicePostAuthenticateResponse
// File: crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct UnifiedAuthenticationServicePostAuthenticateResponse
|
crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
UnifiedAuthenticationServicePostAuthenticateResponse
| 0
|
[] | 55
| null | null | null | null | null | null | null |
// Struct: PaymentInput
// File: crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaymentInput
|
crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaymentInput
| 0
|
[] | 46
| null | null | null | null | null | null | null |
// Struct: InvoiceHandler
// File: crates/router/src/core/subscription.rs
// Module: router
// Implementations: 1
pub struct InvoiceHandler
|
crates/router/src/core/subscription.rs
|
router
|
struct_definition
|
InvoiceHandler
| 1
|
[] | 33
| null | null | null | null | null | null | null |
// Implementation: impl std::hash::Hash for for Maskable
// File: crates/masking/src/maskable.rs
// Module: masking
// Methods: 1 total (0 public)
impl std::hash::Hash for for Maskable
|
crates/masking/src/maskable.rs
|
masking
|
impl_block
| null | null | null | 51
| null |
Maskable
|
std::hash::Hash for
| 1
| 0
| null | null |
// Struct: RecipientCreateResponse
// File: crates/pm_auth/src/types.rs
// Module: pm_auth
// Implementations: 0
pub struct RecipientCreateResponse
|
crates/pm_auth/src/types.rs
|
pm_auth
|
struct_definition
|
RecipientCreateResponse
| 0
|
[] | 37
| null | null | null | null | null | null | null |
// Struct: CloneConnectorDestination
// File: crates/api_models/src/user.rs
// Module: api_models
// Implementations: 0
pub struct CloneConnectorDestination
|
crates/api_models/src/user.rs
|
api_models
|
struct_definition
|
CloneConnectorDestination
| 0
|
[] | 35
| null | null | null | null | null | null | null |
// Struct: Shipping
// File: crates/router/src/compatibility/stripe/payment_intents/types.rs
// Module: router
// Implementations: 0
pub struct Shipping
|
crates/router/src/compatibility/stripe/payment_intents/types.rs
|
router
|
struct_definition
|
Shipping
| 0
|
[] | 37
| null | null | null | null | null | null | null |
domain::types::crypto_operation::<String, masking::WithType>(
&(&state).into(),
type_name!(storage_user::User),
domain::types::CryptoOperation::Encrypt(totp.get_secret_base32().into()),
Identifier::User(key_store.user_id.clone()),
key_store.key.peek(),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(UserErrors::InternalServerError)?
.into(),
),
totp_recovery_codes: None,
},
)
.await
.change_context(UserErrors::InternalServerError)?;
let _ = tfa_utils::delete_totp_secret_from_redis(&state, &user_token.user_id)
.await
.map_err(|error| logger::error!(?error));
// This is not the main task of this API, so we don't throw error if this fails.
// Any following API which requires TOTP will throw error if TOTP is not set in redis
// and FE will ask user to enter TOTP again
let _ = tfa_utils::insert_totp_in_redis(&state, &user_token.user_id)
.await
.map_err(|error| logger::error!(?error));
Ok(ApplicationResponse::StatusOk)
}
pub async fn generate_recovery_codes(
state: SessionState,
user_token: auth::UserIdFromAuth,
) -> UserResponse<user_api::RecoveryCodes> {
if !tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await? {
return Err(UserErrors::TotpRequired.into());
}
let recovery_codes = domain::RecoveryCodes::generate_new();
state
.global_store
.update_user_by_user_id(
&user_token.user_id,
storage_user::UserUpdate::TotpUpdate {
totp_status: None,
totp_secret: None,
totp_recovery_codes: Some(
recovery_codes
.get_hashed()
.change_context(UserErrors::InternalServerError)?,
),
},
)
.await
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::Json(user_api::RecoveryCodes {
recovery_codes: recovery_codes.into_inner(),
}))
}
pub async fn transfer_user_key_store_keymanager(
state: SessionState,
req: user_api::UserKeyTransferRequest,
) -> UserResponse<user_api::UserTransferKeyResponse> {
let db = &state.global_store;
let key_stores = db
.get_all_user_key_store(
&(&state).into(),
&state.store.get_master_key().to_vec().into(),
req.from,
req.limit,
)
.await
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::Json(
user_api::UserTransferKeyResponse {
total_transferred: send_request_to_key_service_for_user(&state, key_stores)
.await
.change_context(UserErrors::InternalServerError)?,
},
))
}
pub async fn verify_recovery_code(
state: SessionState,
user_token: auth::UserIdFromAuth,
req: user_api::VerifyRecoveryCodeRequest,
) -> UserResponse<()> {
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_id(&user_token.user_id)
.await
.change_context(UserErrors::InternalServerError)?
.into();
if user_from_db.get_totp_status() != TotpStatus::Set {
return Err(UserErrors::TwoFactorAuthNotSetup.into());
}
let user_recovery_code_attempts =
tfa_utils::get_recovery_code_attempts_from_redis(&state, &user_token.user_id).await?;
if user_recovery_code_attempts >= consts::user::RECOVERY_CODE_MAX_ATTEMPTS {
return Err(UserErrors::MaxRecoveryCodeAttemptsReached.into());
}
let mut recovery_codes = user_from_db
.get_recovery_codes()
.ok_or(UserErrors::InternalServerError)?;
let Some(matching_index) = utils::user::password::get_index_for_correct_recovery_code(
&req.recovery_code,
&recovery_codes,
)?
else {
let _ = tfa_utils::insert_recovery_code_attempts_in_redis(
&state,
&user_token.user_id,
user_recovery_code_attempts + 1,
)
.await
.inspect_err(|error| logger::error!(?error));
return Err(UserErrors::InvalidRecoveryCode.into());
};
tfa_utils::insert_recovery_code_in_redis(&state, user_from_db.get_user_id()).await?;
let _ = recovery_codes.remove(matching_index);
state
.global_store
.update_user_by_user_id(
user_from_db.get_user_id(),
storage_user::UserUpdate::TotpUpdate {
totp_status: None,
totp_secret: None,
totp_recovery_codes: Some(recovery_codes),
},
)
.await
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::StatusOk)
}
pub async fn terminate_two_factor_auth(
state: SessionState,
user_token: auth::UserFromSinglePurposeToken,
skip_two_factor_auth: bool,
) -> UserResponse<user_api::TokenResponse> {
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_id(&user_token.user_id)
.await
.change_context(UserErrors::InternalServerError)?
.into();
if state.conf.user.force_two_factor_auth || !skip_two_factor_auth {
if !tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await?
&& !tfa_utils::check_recovery_code_in_redis(&state, &user_token.user_id).await?
{
return Err(UserErrors::TwoFactorAuthRequired.into());
}
if user_from_db.get_recovery_codes().is_none() {
return Err(UserErrors::TwoFactorAuthNotSetup.into());
}
if user_from_db.get_totp_status() != TotpStatus::Set {
state
.global_store
.update_user_by_user_id(
user_from_db.get_user_id(),
storage_user::UserUpdate::TotpUpdate {
totp_status: Some(TotpStatus::Set),
totp_secret: None,
totp_recovery_codes: None,
},
)
.await
.change_context(UserErrors::InternalServerError)?;
}
}
let current_flow = domain::CurrentFlow::new(user_token.clone(), domain::SPTFlow::TOTP.into())?;
let next_flow = current_flow.next(user_from_db, &state).await?;
let token = next_flow.get_token(&state).await?;
let _ = tfa_utils::delete_totp_attempts_from_redis(&state, &user_token.user_id)
.await
.inspect_err(|error| logger::error!(?error));
let _ = tfa_utils::delete_recovery_code_attempts_from_redis(&state, &user_token.user_id)
.await
.inspect_err(|error| logger::error!(?error));
auth::cookies::set_cookie_response(
user_api::TokenResponse {
token: token.clone(),
token_type: next_flow.get_flow().into(),
},
token,
)
}
pub async fn check_two_factor_auth_status(
state: SessionState,
user_token: auth::UserFromToken,
) -> UserResponse<user_api::TwoFactorAuthStatusResponse> {
Ok(ApplicationResponse::Json(
user_api::TwoFactorAuthStatusResponse {
totp: tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await?,
recovery_code: tfa_utils::check_recovery_code_in_redis(&state, &user_token.user_id)
.await?,
},
))
}
pub async fn check_two_factor_auth_status_with_attempts(
state: SessionState,
user_token: auth::UserIdFromAuth,
) -> UserResponse<user_api::TwoFactorStatus> {
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_id(&user_token.user_id)
.await
.change_context(UserErrors::InternalServerError)?
.into();
let is_skippable = state.conf.user.force_two_factor_auth.not();
if user_from_db.get_totp_status() == TotpStatus::NotSet {
return Ok(ApplicationResponse::Json(user_api::TwoFactorStatus {
status: None,
is_skippable,
}));
};
let totp = user_api::TwoFactorAuthAttempts {
is_completed: tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await?,
remaining_attempts: consts::user::TOTP_MAX_ATTEMPTS
- tfa_utils::get_totp_attempts_from_redis(&state, &user_token.user_id).await?,
};
let recovery_code = user_api::TwoFactorAuthAttempts {
is_completed: tfa_utils::check_recovery_code_in_redis(&state, &user_token.user_id).await?,
remaining_attempts: consts::user::RECOVERY_CODE_MAX_ATTEMPTS
- tfa_utils::get_recovery_code_attempts_from_redis(&state, &user_token.user_id).await?,
};
Ok(ApplicationResponse::Json(user_api::TwoFactorStatus {
status: Some(user_api::TwoFactorAuthStatusResponseWithAttempts {
totp,
recovery_code,
}),
is_skippable,
}))
}
pub async fn create_user_authentication_method(
state: SessionState,
req: user_api::CreateUserAuthenticationMethodRequest,
) -> UserResponse<()> {
let user_auth_encryption_key = hex::decode(
state
.conf
.user_auth_methods
.get_inner()
.encryption_key
.clone()
.expose(),
)
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to decode DEK")?;
let id = uuid::Uuid::new_v4().to_string();
let (private_config, public_config) = utils::user::construct_public_and_private_db_configs(
&state,
&req.auth_method,
&user_auth_encryption_key,
id.clone(),
)
.await?;
let auth_methods = state
.store
.list_user_authentication_methods_for_owner_id(&req.owner_id)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to get list of auth methods for the owner id")?;
let (auth_id, email_domain) = if let Some(auth_method) = auth_methods.first() {
let email_domain = match req.email_domain {
Some(email_domain) => {
if email_domain != auth_method.email_domain {
return Err(report!(UserErrors::InvalidAuthMethodOperationWithMessage(
"Email domain mismatch".to_string()
)));
}
email_domain
}
None => auth_method.email_domain.clone(),
};
(auth_method.auth_id.clone(), email_domain)
} else {
let email_domain =
req.email_domain
.ok_or(UserErrors::InvalidAuthMethodOperationWithMessage(
"Email domain not found".to_string(),
))?;
(uuid::Uuid::new_v4().to_string(), email_domain)
};
for db_auth_method in auth_methods {
let is_type_same = db_auth_method.auth_type == (&req.auth_method).foreign_into();
let is_extra_identifier_same = match &req.auth_method {
user_api::AuthConfig::OpenIdConnect { public_config, .. } => {
let db_auth_name = db_auth_method
.public_config
.map(|config| {
utils::user::parse_value::<user_api::OpenIdConnectPublicConfig>(
config,
"OpenIdConnectPublicConfig",
)
})
.transpose()?
.map(|config| config.name);
let req_auth_name = public_config.name;
db_auth_name.is_some_and(|name| name == req_auth_name)
}
user_api::AuthConfig::Password | user_api::AuthConfig::MagicLink => true,
};
if is_type_same && is_extra_identifier_same {
return Err(report!(UserErrors::UserAuthMethodAlreadyExists));
}
}
let now = common_utils::date_time::now();
state
.store
.insert_user_authentication_method(UserAuthenticationMethodNew {
id,
auth_id,
owner_id: req.owner_id,
owner_type: req.owner_type,
auth_type: (&req.auth_method).foreign_into(),
private_config,
public_config,
allow_signup: req.allow_signup,
created_at: now,
last_modified_at: now,
email_domain,
})
.await
.to_duplicate_response(UserErrors::UserAuthMethodAlreadyExists)?;
Ok(ApplicationResponse::StatusOk)
}
pub async fn update_user_authentication_method(
state: SessionState,
req: user_api::UpdateUserAuthenticationMethodRequest,
) -> UserResponse<()> {
let user_auth_encryption_key = hex::decode(
state
.conf
.user_auth_methods
.get_inner()
.encryption_key
.clone()
.expose(),
)
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to decode DEK")?;
match req {
user_api::UpdateUserAuthenticationMethodRequest::AuthMethod {
id,
auth_config: auth_method,
} => {
let (private_config, public_config) =
utils::user::construct_public_and_private_db_configs(
&state,
&auth_method,
&user_auth_encryption_key,
id.clone(),
)
.await?;
state
.store
.update_user_authentication_method(
&id,
UserAuthenticationMethodUpdate::UpdateConfig {
private_config,
public_config,
},
)
.await
.map_err(|error| {
let user_error = match error.current_context() {
StorageError::ValueNotFound(_) => {
UserErrors::InvalidAuthMethodOperationWithMessage(
"Auth method not found".to_string(),
)
}
StorageError::DuplicateValue { .. } => {
UserErrors::UserAuthMethodAlreadyExists
}
_ => UserErrors::InternalServerError,
};
error.change_context(user_error)
})?;
}
user_api::UpdateUserAuthenticationMethodRequest::EmailDomain {
owner_id,
email_domain,
} => {
let auth_methods = state
.store
.list_user_authentication_methods_for_owner_id(&owner_id)
.await
.change_context(UserErrors::InternalServerError)?;
futures::future::try_join_all(auth_methods.iter().map(|auth_method| async {
state
.store
.update_user_authentication_method(
&auth_method.id,
UserAuthenticationMethodUpdate::EmailDomain {
email_domain: email_domain.clone(),
},
)
.await
.to_duplicate_response(UserErrors::UserAuthMethodAlreadyExists)
}))
.await?;
}
}
Ok(ApplicationResponse::StatusOk)
}
pub async fn list_user_authentication_methods(
state: SessionState,
req: user_api::GetUserAuthenticationMethodsRequest,
) -> UserResponse<Vec<user_api::UserAuthenticationMethodResponse>> {
let user_authentication_methods = match (req.auth_id, req.email_domain) {
(Some(auth_id), None) => state
.store
.list_user_authentication_methods_for_auth_id(&auth_id)
.await
.change_context(UserErrors::InternalServerError)?,
(None, Some(email_domain)) => state
.store
.list_user_authentication_methods_for_email_domain(&email_domain)
.await
.change_context(UserErrors::InternalServerError)?,
(Some(_), Some(_)) | (None, None) => {
return Err(UserErrors::InvalidUserAuthMethodOperation.into());
}
};
Ok(ApplicationResponse::Json(
user_authentication_methods
.into_iter()
.map(|auth_method| {
let auth_name = match (auth_method.auth_type, auth_method.public_config) {
(UserAuthType::OpenIdConnect, config) => {
let open_id_public_config: Option<user_api::OpenIdConnectPublicConfig> =
config
.map(|config| {
utils::user::parse_value(config, "OpenIdConnectPublicConfig")
})
.transpose()?;
if let Some(public_config) = open_id_public_config {
Ok(Some(public_config.name))
} else {
Err(report!(UserErrors::InternalServerError))
.attach_printable("Public config not found for OIDC auth type")
}
}
_ => Ok(None),
}?;
Ok(user_api::UserAuthenticationMethodResponse {
id: auth_method.id,
auth_id: auth_method.auth_id,
auth_method: user_api::AuthMethodDetails {
name: auth_name,
auth_type: auth_method.auth_type,
},
allow_signup: auth_method.allow_signup,
})
})
.collect::<UserResult<_>>()?,
))
}
#[cfg(feature = "v1")]
pub async fn get_sso_auth_url(
state: SessionState,
request: user_api::GetSsoAuthUrlRequest,
) -> UserResponse<()> {
let user_authentication_method = state
.store
.get_user_authentication_method_by_id(request.id.as_str())
.await
.to_not_found_response(UserErrors::InvalidUserAuthMethodOperation)?;
let open_id_private_config = utils::user::decrypt_oidc_private_config(
&state,
user_authentication_method.private_config,
request.id.clone(),
)
.await?;
let open_id_public_config = serde_json::from_value::<user_api::OpenIdConnectPublicConfig>(
user_authentication_method
.public_config
.ok_or(UserErrors::InternalServerError)
.attach_printable("Public config not present")?,
)
.change_context(UserErrors::InternalServerError)
.attach_printable("Unable to parse OpenIdConnectPublicConfig")?;
let oidc_state = Secret::new(nanoid::nanoid!());
utils::user::set_sso_id_in_redis(&state, oidc_state.clone(), request.id).await?;
let redirect_url =
utils::user::get_oidc_sso_redirect_url(&state, &open_id_public_config.name.to_string());
openidconnect::get_authorization_url(
state,
redirect_url,
oidc_state,
open_id_private_config.base_url.into(),
open_id_private_config.client_id,
)
.await
.map(|url| {
ApplicationResponse::JsonForRedirection(RedirectionResponse {
headers: Vec::with_capacity(0),
return_url: String::new(),
http_method: String::new(),
params: Vec::with_capacity(0),
return_url_with_query_params: url.to_string(),
})
})
}
pub async fn sso_sign(
state: SessionState,
request: user_api::SsoSignInRequest,
user_from_single_purpose_token: Option<auth::UserFromSinglePurposeToken>,
) -> UserResponse<user_api::TokenResponse> {
let authentication_method_id =
utils::user::get_sso_id_from_redis(&state, request.state.clone()).await?;
let user_authentication_method = state
.store
.get_user_authentication_method_by_id(&authentication_method_id)
.await
.change_context(UserErrors::InternalServerError)?;
let open_id_private_config = utils::user::decrypt_oidc_private_config(
&state,
user_authentication_method.private_config,
authentication_method_id,
)
.await?;
let open_id_public_config = serde_json::from_value::<user_api::OpenIdConnectPublicConfig>(
user_authentication_method
.public_config
.ok_or(UserErrors::InternalServerError)
.attach_printable("Public config not present")?,
)
.change_context(UserErrors::InternalServerError)
.attach_printable("Unable to parse OpenIdConnectPublicConfig")?;
let redirect_url =
utils::user::get_oidc_sso_redirect_url(&state, &open_id_public_config.name.to_string());
let email = openidconnect::get_user_email_from_oidc_provider(
&state,
redirect_url,
request.state,
open_id_private_config.base_url.into(),
open_id_private_config.client_id,
request.code,
open_id_private_config.client_secret,
)
.await?;
utils::user::validate_email_domain_auth_type_using_db(
&state,
&email,
UserAuthType::OpenIdConnect,
)
.await?;
// TODO: Use config to handle not found error
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_email(&email)
.await
.map(Into::into)
.to_not_found_response(UserErrors::UserNotFound)?;
if !user_from_db.is_verified() {
state
.global_store
.update_user_by_user_id(
user_from_db.get_user_id(),
storage_user::UserUpdate::VerifyUser,
)
.await
.change_context(UserErrors::InternalServerError)?;
}
let next_flow = if let Some(user_from_single_purpose_token) = user_from_single_purpose_token {
let current_flow =
domain::CurrentFlow::new(user_from_single_purpose_token, domain::SPTFlow::SSO.into())?;
current_flow.next(user_from_db, &state).await?
} else {
domain::NextFlow::from_origin(domain::Origin::SignInWithSSO, user_from_db, &state).await?
};
let token = next_flow.get_token(&state).await?;
let response = user_api::TokenResponse {
token: token.clone(),
token_type: next_flow.get_flow().into(),
};
auth::cookies::set_cookie_response(response, token)
}
pub async fn terminate_auth_select(
state: SessionState,
user_token: auth::UserFromSinglePurposeToken,
req: user_api::AuthSelectRequest,
) -> UserResponse<user_api::TokenResponse> {
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_id(&user_token.user_id)
.await
.change_context(UserErrors::InternalServerError)?
.into();
let user_email = domain::UserEmail::from_pii_email(user_from_db.get_email())?;
let auth_methods = state
.store
.list_user_authentication_methods_for_email_domain(user_email.extract_domain()?)
.await
.change_context(UserErrors::InternalServerError)?;
let user_authentication_method = match (req.id, auth_methods.is_empty()) {
(Some(id), _) => auth_methods
.into_iter()
.find(|auth_method| auth_method.id == id)
.ok_or(UserErrors::InvalidUserAuthMethodOperation)?,
(None, true) => DEFAULT_USER_AUTH_METHOD.clone(),
(None, false) => return Err(UserErrors::InvalidUserAuthMethodOperation.into()),
};
let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::AuthSelect.into())?;
let mut next_flow = current_flow.next(user_from_db.clone(), &state).await?;
// Skip SSO if continue with password(TOTP)
if next_flow.get_flow() == domain::UserFlow::SPTFlow(domain::SPTFlow::SSO)
&& !utils::user::is_sso_auth_type(user_authentication_method.auth_type)
{
next_flow = next_flow.skip(user_from_db, &state).await?;
}
let token = next_flow.get_token(&state).await?;
auth::cookies::set_cookie_response(
user_api::TokenResponse {
token: token.clone(),
token_type: next_flow.get_flow().into(),
},
token,
)
}
pub async fn list_orgs_for_user(
state: SessionState,
user_from_token: auth::UserFromToken,
) -> UserResponse<Vec<user_api::ListOrgsForUserResponse>> {
let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_from_token.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(UserErrors::InternalServerError)?;
if role_info.is_internal() {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"Internal roles are not allowed for this operation".to_string(),
)
.into());
}
let orgs = match role_info.get_entity_type() {
EntityType::Tenant => {
let key_manager_state = &(&state).into();
state
.store
.list_merchant_and_org_ids(
key_manager_state,
consts::user::ORG_LIST_LIMIT_FOR_TENANT,
None,
)
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.map(|(_, org_id)| org_id)
.collect::<HashSet<_>>()
}
EntityType::Organization | EntityType::Merchant | EntityType::Profile => state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: user_from_token.user_id.as_str(),
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
org_id: None,
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: Some(UserStatus::Active),
limit: None,
})
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.filter_map(|user_role| user_role.org_id)
.collect::<HashSet<_>>(),
};
let resp = futures::future::try_join_all(
orgs.iter()
.map(|org_id| state.accounts_store.find_organization_by_org_id(org_id)),
)
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.map(|org| user_api::ListOrgsForUserResponse {
org_id: org.get_organization_id(),
org_name: org.get_organization_name(),
org_type: org.organization_type.unwrap_or_default(),
})
.collect::<Vec<_>>();
if resp.is_empty() {
Err(UserErrors::InternalServerError).attach_printable("No orgs found for a user")?;
}
Ok(ApplicationResponse::Json(resp))
}
pub async fn list_merchants_for_user_in_org(
state: SessionState,
user_from_token: auth::UserFromToken,
) -> UserResponse<Vec<user_api::UserMerchantAccountResponse>> {
let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_from_token.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(UserErrors::InternalServerError)?;
if role_info.is_internal() {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"Internal roles are not allowed for this operation".to_string(),
)
.into());
}
let merchant_accounts = match role_info.get_entity_type() {
EntityType::Tenant | EntityType::Organization => state
.store
.list_merchant_accounts_by_organization_id(&(&state).into(), &user_from_token.org_id)
.await
.change_context(UserErrors::InternalServerError)?,
EntityType::Merchant | EntityType::Profile => {
let merchant_ids = state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: user_from_token.user_id.as_str(),
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
org_id: Some(&user_from_token.org_id),
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: Some(UserStatus::Active),
limit: None,
})
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.filter_map(|user_role| user_role.merchant_id)
.collect::<HashSet<_>>()
.into_iter()
.collect();
state
.store
.list_multiple_merchant_accounts(&(&state).into(), merchant_ids)
.await
.change_context(UserErrors::InternalServerError)?
}
};
// TODO: Add a check to see if merchant accounts are empty, and handle accordingly, when a single route will be used instead
// of having two separate routes.
Ok(ApplicationResponse::Json(
merchant_accounts
.into_iter()
.map(|merchant_account| user_api::UserMerchantAccountResponse {
merchant_name: merchant_account.merchant_name.clone(),
merchant_id: merchant_account.get_id().to_owned(),
product_type: merchant_account.product_type,
merchant_account_type: merchant_account.merchant_account_type,
version: merchant_account.version,
})
.collect::<Vec<_>>(),
))
}
pub async fn list_profiles_for_user_in_org_and_merchant_account(
state: SessionState,
user_from_token: auth::UserFromToken,
) -> UserResponse<Vec<user_api::ListProfilesForUserInOrgAndMerchantAccountResponse>> {
let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_from_token.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(UserErrors::InternalServerError)?;
let key_manager_state = &(&state).into();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&user_from_token.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(UserErrors::InternalServerError)?;
let profiles = match role_info.get_entity_type() {
EntityType::Tenant | EntityType::Organization | EntityType::Merchant => state
.store
.list_profile_by_merchant_id(
key_manager_state,
&key_store,
&user_from_token.merchant_id,
)
.await
.change_context(UserErrors::InternalServerError)?,
EntityType::Profile => {
let profile_ids = state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: user_from_token.user_id.as_str(),
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
org_id: Some(&user_from_token.org_id),
merchant_id: Some(&user_from_token.merchant_id),
profile_id: None,
entity_id: None,
version: None,
status: Some(UserStatus::Active),
limit: None,
})
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.filter_map(|user_role| user_role.profile_id)
.collect::<HashSet<_>>();
futures::future::try_join_all(profile_ids.iter().map(|profile_id| {
state.store.find_business_profile_by_profile_id(
key_manager_state,
&key_store,
profile_id,
)
}))
.await
.change_context(UserErrors::InternalServerError)?
}
};
if profiles.is_empty() {
Err(UserErrors::InternalServerError).attach_printable("No profile found for a user")?;
}
Ok(ApplicationResponse::Json(
profiles
.into_iter()
.map(
|profile| user_api::ListProfilesForUserInOrgAndMerchantAccountResponse {
profile_id: profile.get_id().to_owned(),
profile_name: profile.profile_name,
},
)
.collect::<Vec<_>>(),
))
}
pub async fn switch_org_for_user(
state: SessionState,
request: user_api::SwitchOrganizationRequest,
user_from_token: auth::UserFromToken,
) -> UserResponse<user_api::TokenResponse> {
if user_from_token.org_id == request.org_id {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"User switching to same org".to_string(),
)
.into());
}
let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_from_token.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to retrieve role information")?;
if role_info.is_internal() {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"Org switching not allowed for Internal role".to_string(),
)
.into());
}
let (merchant_id, profile_id, role_id) = match role_info.get_entity_type() {
EntityType::Tenant => {
let merchant_id = state
.store
.list_merchant_accounts_by_organization_id(&(&state).into(), &request.org_id)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to get merchant list for org")?
.pop()
.ok_or(UserErrors::InvalidRoleOperation)
.attach_printable("No merchants found for the org id")?
.get_id()
.to_owned();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
&(&state).into(),
&merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(UserErrors::InternalServerError)?;
let profile_id = state
.store
.list_profile_by_merchant_id(&(&state).into(), &key_store, &merchant_id)
.await
.change_context(UserErrors::InternalServerError)?
.pop()
.ok_or(UserErrors::InternalServerError)?
.get_id()
.to_owned();
(merchant_id, profile_id, user_from_token.role_id)
}
EntityType::Organization | EntityType::Merchant | EntityType::Profile => {
let user_role = state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: &user_from_token.user_id,
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
org_id: Some(&request.org_id),
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: Some(UserStatus::Active),
limit: Some(1),
})
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to list user roles by user_id and org_id")?
.pop()
.ok_or(UserErrors::InvalidRoleOperationWithMessage(
"No user role found for the requested org_id".to_string(),
))?;
let (merchant_id, profile_id) =
utils::user_role::get_single_merchant_id_and_profile_id(&state, &user_role).await?;
(merchant_id, profile_id, user_role.role_id)
}
};
let lineage_context = LineageContext {
user_id: user_from_token.user_id.clone(),
merchant_id: merchant_id.clone(),
role_id: role_id.clone(),
org_id: request.org_id.clone(),
profile_id: profile_id.clone(),
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id)
.clone(),
};
utils::user::spawn_async_lineage_context_update_to_db(
&state,
&user_from_token.user_id,
lineage_context,
);
let token = utils::user::generate_jwt_auth_token_with_attributes(
&state,
user_from_token.user_id,
merchant_id.clone(),
request.org_id.clone(),
role_id.clone(),
profile_id.clone(),
user_from_token.tenant_id.clone(),
)
.await?;
utils::user_role::set_role_info_in_cache_by_role_id_org_id(
&state,
&role_id,
&request.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await;
let response = user_api::TokenResponse {
token: token.clone(),
token_type: common_enums::TokenPurpose::UserInfo,
};
auth::cookies::set_cookie_response(response, token)
}
pub async fn switch_merchant_for_user_in_org(
state: SessionState,
request: user_api::SwitchMerchantRequest,
user_from_token: auth::UserFromToken,
) -> UserResponse<user_api::TokenResponse> {
if user_from_token.merchant_id == request.merchant_id {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"User switching to same merchant".to_string(),
)
.into());
}
let key_manager_state = &(&state).into();
let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_from_token.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
|
crates/router/src/core/user.rs#chunk2
|
router
|
chunk
| null | null | null | 8,187
| null | null | null | null | null | null | null |
// Function: get_customer_mandates
// File: crates/router/src/core/mandate.rs
// Module: router
pub fn get_customer_mandates(
state: SessionState,
merchant_context: domain::MerchantContext,
customer_id: id_type::CustomerId,
) -> RouterResponse<Vec<mandates::MandateResponse>>
|
crates/router/src/core/mandate.rs
|
router
|
function_signature
| null | null | null | 72
|
get_customer_mandates
| null | null | null | null | null | null |
// Implementation: impl api::PaymentSync for for Finix
// File: crates/hyperswitch_connectors/src/connectors/finix.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSync for for Finix
|
crates/hyperswitch_connectors/src/connectors/finix.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Finix
|
api::PaymentSync for
| 0
| 0
| null | null |
// Struct: ProfileResponse
// File: crates/api_models/src/admin.rs
// Module: api_models
// Implementations: 0
pub struct ProfileResponse
|
crates/api_models/src/admin.rs
|
api_models
|
struct_definition
|
ProfileResponse
| 0
|
[] | 33
| null | null | null | null | null | null | null |
// Struct: NexixpayCard
// File: crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct NexixpayCard
|
crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
NexixpayCard
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Implementation: impl ApiEvent
// File: crates/router/src/events/api_logs.rs
// Module: router
// Methods: 1 total (1 public)
impl ApiEvent
|
crates/router/src/events/api_logs.rs
|
router
|
impl_block
| null | null | null | 36
| null |
ApiEvent
| null | 1
| 1
| null | null |
// Implementation: impl api::RefundSync for for Nuvei
// File: crates/hyperswitch_connectors/src/connectors/nuvei.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundSync for for Nuvei
|
crates/hyperswitch_connectors/src/connectors/nuvei.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 63
| null |
Nuvei
|
api::RefundSync for
| 0
| 0
| null | null |
// Struct: AffirmRouterData
// File: crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct AffirmRouterData<T>
|
crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
AffirmRouterData
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/affirm.rs
// Module: hyperswitch_connectors
// Public functions: 1
// Public structs: 1
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts::BASE64_ENGINE,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{
Authorize, Capture, CompleteAuthorize, PSync, PaymentMethodToken, Session,
SetupMandate, Void,
},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefundSyncRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{Mask, PeekInterface};
use transformers as affirm;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Affirm {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Affirm {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Affirm {}
impl api::PaymentSession for Affirm {}
impl api::ConnectorAccessToken for Affirm {}
impl api::MandateSetup for Affirm {}
impl api::PaymentAuthorize for Affirm {}
impl api::PaymentsCompleteAuthorize for Affirm {}
impl api::PaymentSync for Affirm {}
impl api::PaymentCapture for Affirm {}
impl api::PaymentVoid for Affirm {}
impl api::Refund for Affirm {}
impl api::RefundExecute for Affirm {}
impl api::RefundSync for Affirm {}
impl api::PaymentToken for Affirm {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Affirm
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Affirm
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Affirm {
fn id(&self) -> &'static str {
"affirm"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.affirm.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = affirm::AffirmAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let encoded_api_key = BASE64_ENGINE.encode(format!(
"{}:{}",
auth.public_key.peek(),
auth.private_key.peek()
));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Basic {encoded_api_key}").into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: affirm::AffirmErrorResponse = res
.response
.parse_struct("AffirmErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: response.status_code,
code: response.code,
message: response.message,
reason: Some(response.error_type),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Affirm {
fn validate_mandate_payment(
&self,
_pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
match pm_data {
PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented(
"validate_mandate_payment does not support cards".to_string(),
)
.into()),
_ => Ok(()),
}
}
fn validate_psync_reference_id(
&self,
_data: &PaymentsSyncData,
_is_three_ds: bool,
_status: enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
Ok(())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Affirm {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Affirm {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Affirm {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Affirm {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = self.base_url(connectors);
Ok(format!("{endpoint}/v2/checkout/direct"))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = affirm::AffirmRouterData::from((amount, req));
let connector_req = affirm::AffirmPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: affirm::AffirmResponseWrapper = res
.response
.parse_struct("Affirm PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Affirm
{
fn get_headers(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = self.base_url(connectors);
Ok(format!("{endpoint}/v1/transactions"))
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = affirm::AffirmCompleteAuthorizeRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: affirm::AffirmCompleteAuthorizeResponse = res
.response
.parse_struct("Affirm PaymentsCompleteAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Affirm {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = self.base_url(connectors);
let transaction_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!("{endpoint}/v1/transactions/{transaction_id}",))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: affirm::AffirmResponseWrapper = res
.response
.parse_struct("affirm PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Affirm {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = self.base_url(connectors);
let transaction_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{endpoint}/v1/transactions/{transaction_id}/capture"
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = affirm::AffirmRouterData::from((amount, req));
let connector_req = affirm::AffirmCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: affirm::AffirmCaptureResponse = res
.response
.parse_struct("Affirm PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Affirm {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = self.base_url(connectors);
let transaction_id = req.request.connector_transaction_id.clone();
Ok(format!("{endpoint}/v1/transactions/{transaction_id}/void"))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = affirm::AffirmCancelRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsVoidType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: affirm::AffirmCancelResponse = res
.response
.parse_struct("GetnetPaymentsVoidResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Affirm {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = self.base_url(connectors);
let transaction_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{endpoint}/v1/transactions/{transaction_id}/refund"
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = affirm::AffirmRouterData::from((refund_amount, req));
let connector_req = affirm::AffirmRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: affirm::AffirmRefundResponse = res
.response
.parse_struct("affirm RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Affirm {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = self.base_url(connectors);
let transaction_id = req.request.connector_transaction_id.clone();
Ok(format!("{endpoint}/v1/transactions/{transaction_id}"))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: affirm::AffirmRsyncResponse = res
.response
.parse_struct("affirm RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Affirm {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static AFFIRM_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
];
let mut affirm_supported_payment_methods = SupportedPaymentMethods::new();
affirm_supported_payment_methods.add(
enums::PaymentMethod::PayLater,
enums::PaymentMethodType::Affirm,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
affirm_supported_payment_methods
});
static AFFIRM_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Affirm",
description: "Affirm connector is a payment gateway integration that processes Affirm’s buy now, pay later financing by managing payment authorization, capture, refunds, and transaction sync via Affirm’s API.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Alpha,
};
static AFFIRM_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Affirm {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&AFFIRM_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*AFFIRM_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&AFFIRM_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates/hyperswitch_connectors/src/connectors/affirm.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 6,161
| null | null | null | null | null | null | null |
// File: crates/router/tests/connectors/nmi.rs
// Module: router
use std::{str::FromStr, time::Duration};
use router::types::{self, domain, storage::enums};
use crate::{
connector_auth,
utils::{self, ConnectorActions},
};
struct NmiTest;
impl ConnectorActions for NmiTest {}
impl utils::Connector for NmiTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Nmi;
utils::construct_connector_data_old(
Box::new(Nmi::new()),
types::Connector::Nmi,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.nmi
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"nmi".to_string()
}
}
static CONNECTOR: NmiTest = NmiTest {};
fn get_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),
..utils::CCardType::default().0
}),
amount: 2023,
..utils::PaymentAuthorizeType::default().0
})
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_authorize_data(), None)
.await
.expect("Authorize payment response");
let transaction_id = utils::get_connector_transaction_id(response.response).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
// Assert the sync response, it will be authorized in case of manual capture, for automatic it will be Completed Success
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorizing);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
let capture_response = CONNECTOR
.capture_payment(transaction_id.clone(), None, None)
.await
.unwrap();
assert_eq!(
capture_response.status,
enums::AttemptStatus::CaptureInitiated
);
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorizing);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
let capture_response = CONNECTOR
.capture_payment(
transaction_id.clone(),
Some(types::PaymentsCaptureData {
amount_to_capture: 1000,
..utils::PaymentCaptureType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
capture_response.status,
enums::AttemptStatus::CaptureInitiated
);
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorizing);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
let void_response = CONNECTOR
.void_payment(
transaction_id.clone(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("user_cancel".to_string()),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(void_response.status, enums::AttemptStatus::VoidInitiated);
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Voided,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorizing);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
let capture_response = CONNECTOR
.capture_payment(transaction_id.clone(), None, None)
.await
.unwrap();
assert_eq!(
capture_response.status,
enums::AttemptStatus::CaptureInitiated
);
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
let refund_response = CONNECTOR
.refund_payment(transaction_id.clone(), None, None)
.await
.unwrap();
assert_eq!(refund_response.status, enums::AttemptStatus::Pending);
let sync_response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Pending,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
sync_response.response.unwrap().refund_status,
enums::RefundStatus::Pending
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorizing);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
let capture_response = CONNECTOR
.capture_payment(
transaction_id.clone(),
Some(types::PaymentsCaptureData {
amount_to_capture: 2023,
..utils::PaymentCaptureType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
capture_response.status,
enums::AttemptStatus::CaptureInitiated
);
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
let refund_response = CONNECTOR
.refund_payment(
transaction_id.clone(),
Some(types::RefundsData {
refund_amount: 1023,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(refund_response.status, enums::AttemptStatus::Pending);
let sync_response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Pending,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
sync_response.response.unwrap().refund_status,
enums::RefundStatus::Pending
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let response = CONNECTOR
.make_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
let refund_response = CONNECTOR
.refund_payment(transaction_id.clone(), None, None)
.await
.unwrap();
assert_eq!(refund_response.status, enums::AttemptStatus::Pending);
let sync_response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Pending,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
sync_response.response.unwrap().refund_status,
enums::RefundStatus::Pending
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let response = CONNECTOR
.make_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
let refund_response = CONNECTOR
.refund_payment(
transaction_id.clone(),
Some(types::RefundsData {
refund_amount: 1000,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(refund_response.status, enums::AttemptStatus::Pending);
let sync_response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Pending,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
sync_response.response.unwrap().refund_status,
enums::RefundStatus::Pending
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
let response = CONNECTOR
.make_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
//try refund for previous payment
let transaction_id = utils::get_connector_transaction_id(response.response).unwrap();
for _x in 0..2 {
tokio::time::sleep(Duration::from_secs(5)).await; // to avoid 404 error
let refund_response = CONNECTOR
.refund_payment(
transaction_id.clone(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
let sync_response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Pending,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
sync_response.response.unwrap().refund_status,
enums::RefundStatus::Pending,
);
}
}
// Creates a payment with incorrect CVC.
#[ignore = "Connector returns SUCCESS status in case of invalid CVC"]
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {}
// Creates a payment with incorrect expiry month.
#[ignore = "Connector returns SUCCESS status in case of expired month."]
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {}
// Creates a payment with incorrect expiry year.
#[ignore = "Connector returns SUCCESS status in case of expired year."]
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let response = CONNECTOR
.make_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
let void_response = CONNECTOR
.void_payment(transaction_id.clone(), None, None)
.await
.unwrap();
assert_eq!(void_response.status, enums::AttemptStatus::VoidFailed);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorizing);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
let capture_response = CONNECTOR
.capture_payment("9123456789".to_string(), None, None)
.await
.unwrap();
assert_eq!(capture_response.status, enums::AttemptStatus::CaptureFailed);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
let refund_response = CONNECTOR
.refund_payment(
transaction_id,
Some(types::RefundsData {
refund_amount: 3024,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Failure
);
}
|
crates/router/tests/connectors/nmi.rs
|
router
|
full_file
| null | null | null | 4,891
| null | null | null | null | null | null | null |
// Struct: SquareSessionResponse
// File: crates/hyperswitch_connectors/src/connectors/square/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct SquareSessionResponse
|
crates/hyperswitch_connectors/src/connectors/square/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
SquareSessionResponse
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentToken for for Braintree
// File: crates/hyperswitch_connectors/src/connectors/braintree.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentToken for for Braintree
|
crates/hyperswitch_connectors/src/connectors/braintree.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Braintree
|
api::PaymentToken for
| 0
| 0
| null | null |
// Struct: SelfLink
// File: crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct SelfLink
|
crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
|
hyperswitch_connectors
|
struct_definition
|
SelfLink
| 0
|
[] | 43
| null | null | null | null | null | null | null |
// Implementation: impl ConnectorSpecifications for for Stax
// File: crates/hyperswitch_connectors/src/connectors/stax.rs
// Module: hyperswitch_connectors
// Methods: 4 total (0 public)
impl ConnectorSpecifications for for Stax
|
crates/hyperswitch_connectors/src/connectors/stax.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 53
| null |
Stax
|
ConnectorSpecifications for
| 4
| 0
| null | null |
#[serde(rename_all = "snake_case")]
pub enum MerchantRecipientData {
ConnectorRecipientId(Secret<String>),
WalletId(Secret<String>),
AccountData(MerchantAccountData),
}
impl ForeignFrom<MerchantRecipientData> for api_models::admin::MerchantRecipientData {
fn foreign_from(value: MerchantRecipientData) -> Self {
match value {
MerchantRecipientData::ConnectorRecipientId(id) => Self::ConnectorRecipientId(id),
MerchantRecipientData::WalletId(id) => Self::WalletId(id),
MerchantRecipientData::AccountData(data) => {
Self::AccountData(api_models::admin::MerchantAccountData::foreign_from(data))
}
}
}
}
impl From<api_models::admin::MerchantRecipientData> for MerchantRecipientData {
fn from(value: api_models::admin::MerchantRecipientData) -> Self {
match value {
api_models::admin::MerchantRecipientData::ConnectorRecipientId(id) => {
Self::ConnectorRecipientId(id)
}
api_models::admin::MerchantRecipientData::WalletId(id) => Self::WalletId(id),
api_models::admin::MerchantRecipientData::AccountData(data) => {
Self::AccountData(data.into())
}
}
}
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AdditionalMerchantData {
OpenBankingRecipientData(MerchantRecipientData),
}
impl ForeignFrom<api_models::admin::AdditionalMerchantData> for AdditionalMerchantData {
fn foreign_from(value: api_models::admin::AdditionalMerchantData) -> Self {
match value {
api_models::admin::AdditionalMerchantData::OpenBankingRecipientData(data) => {
Self::OpenBankingRecipientData(MerchantRecipientData::from(data))
}
}
}
}
impl ForeignFrom<AdditionalMerchantData> for api_models::admin::AdditionalMerchantData {
fn foreign_from(value: AdditionalMerchantData) -> Self {
match value {
AdditionalMerchantData::OpenBankingRecipientData(data) => {
Self::OpenBankingRecipientData(
api_models::admin::MerchantRecipientData::foreign_from(data),
)
}
}
}
}
impl ForeignFrom<api_models::admin::ConnectorAuthType> for ConnectorAuthType {
fn foreign_from(value: api_models::admin::ConnectorAuthType) -> Self {
match value {
api_models::admin::ConnectorAuthType::TemporaryAuth => Self::TemporaryAuth,
api_models::admin::ConnectorAuthType::HeaderKey { api_key } => {
Self::HeaderKey { api_key }
}
api_models::admin::ConnectorAuthType::BodyKey { api_key, key1 } => {
Self::BodyKey { api_key, key1 }
}
api_models::admin::ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Self::SignatureKey {
api_key,
key1,
api_secret,
},
api_models::admin::ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Self::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
},
api_models::admin::ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
Self::CurrencyAuthKey { auth_key_map }
}
api_models::admin::ConnectorAuthType::NoKey => Self::NoKey,
api_models::admin::ConnectorAuthType::CertificateAuth {
certificate,
private_key,
} => Self::CertificateAuth {
certificate,
private_key,
},
}
}
}
impl ForeignFrom<ConnectorAuthType> for api_models::admin::ConnectorAuthType {
fn foreign_from(from: ConnectorAuthType) -> Self {
match from {
ConnectorAuthType::TemporaryAuth => Self::TemporaryAuth,
ConnectorAuthType::HeaderKey { api_key } => Self::HeaderKey { api_key },
ConnectorAuthType::BodyKey { api_key, key1 } => Self::BodyKey { api_key, key1 },
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Self::SignatureKey {
api_key,
key1,
api_secret,
},
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Self::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
},
ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
Self::CurrencyAuthKey { auth_key_map }
}
ConnectorAuthType::NoKey => Self::NoKey,
ConnectorAuthType::CertificateAuth {
certificate,
private_key,
} => Self::CertificateAuth {
certificate,
private_key,
},
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ConnectorsList {
pub connectors: Vec<String>,
}
impl ForeignFrom<&PaymentsAuthorizeRouterData> for AuthorizeSessionTokenData {
fn foreign_from(data: &PaymentsAuthorizeRouterData) -> Self {
Self {
amount_to_capture: data.amount_captured,
currency: data.request.currency,
connector_transaction_id: data.payment_id.clone(),
amount: Some(data.request.amount),
}
}
}
impl ForeignFrom<&ExternalVaultProxyPaymentsRouterData> for AuthorizeSessionTokenData {
fn foreign_from(data: &ExternalVaultProxyPaymentsRouterData) -> Self {
Self {
amount_to_capture: data.amount_captured,
currency: data.request.currency,
connector_transaction_id: data.payment_id.clone(),
amount: Some(data.request.amount),
}
}
}
impl<'a> ForeignFrom<&'a SetupMandateRouterData> for AuthorizeSessionTokenData {
fn foreign_from(data: &'a SetupMandateRouterData) -> Self {
Self {
amount_to_capture: data.request.amount,
currency: data.request.currency,
connector_transaction_id: data.payment_id.clone(),
amount: data.request.amount,
}
}
}
pub trait Tokenizable {
fn set_session_token(&mut self, token: Option<String>);
}
impl Tokenizable for SetupMandateRequestData {
fn set_session_token(&mut self, _token: Option<String>) {}
}
impl Tokenizable for PaymentsAuthorizeData {
fn set_session_token(&mut self, token: Option<String>) {
self.session_token = token;
}
}
impl Tokenizable for CompleteAuthorizeData {
fn set_session_token(&mut self, _token: Option<String>) {}
}
impl Tokenizable for ExternalVaultProxyPaymentsData {
fn set_session_token(&mut self, token: Option<String>) {
self.session_token = token;
}
}
impl ForeignFrom<&SetupMandateRouterData> for PaymentsAuthorizeData {
fn foreign_from(data: &SetupMandateRouterData) -> Self {
Self {
currency: data.request.currency,
payment_method_data: data.request.payment_method_data.clone(),
confirm: data.request.confirm,
statement_descriptor_suffix: data.request.statement_descriptor_suffix.clone(),
mandate_id: data.request.mandate_id.clone(),
setup_future_usage: data.request.setup_future_usage,
off_session: data.request.off_session,
setup_mandate_details: data.request.setup_mandate_details.clone(),
router_return_url: data.request.router_return_url.clone(),
email: data.request.email.clone(),
customer_name: data.request.customer_name.clone(),
amount: 0,
order_tax_amount: Some(MinorUnit::zero()),
minor_amount: MinorUnit::new(0),
statement_descriptor: None,
capture_method: None,
webhook_url: None,
complete_authorize_url: None,
browser_info: data.request.browser_info.clone(),
order_details: None,
order_category: None,
session_token: None,
enrolled_for_3ds: true,
related_transaction_id: None,
payment_experience: None,
payment_method_type: None,
customer_id: None,
surcharge_details: None,
request_incremental_authorization: data.request.request_incremental_authorization,
metadata: None,
request_extended_authorization: None,
authentication_data: None,
customer_acceptance: data.request.customer_acceptance.clone(),
split_payments: None, // TODO: allow charges on mandates?
merchant_order_reference_id: None,
integrity_object: None,
additional_payment_method_data: None,
shipping_cost: data.request.shipping_cost,
merchant_account_id: None,
merchant_config_currency: None,
connector_testing_data: data.request.connector_testing_data.clone(),
order_id: None,
locale: None,
payment_channel: None,
enable_partial_authorization: data.request.enable_partial_authorization,
enable_overcapture: None,
is_stored_credential: data.request.is_stored_credential,
}
}
}
impl<F1, F2, T1, T2> ForeignFrom<(&RouterData<F1, T1, PaymentsResponseData>, T2)>
for RouterData<F2, T2, PaymentsResponseData>
{
fn foreign_from(item: (&RouterData<F1, T1, PaymentsResponseData>, T2)) -> Self {
let data = item.0;
let request = item.1;
Self {
flow: PhantomData,
request,
merchant_id: data.merchant_id.clone(),
connector: data.connector.clone(),
attempt_id: data.attempt_id.clone(),
tenant_id: data.tenant_id.clone(),
status: data.status,
payment_method: data.payment_method,
connector_auth_type: data.connector_auth_type.clone(),
description: data.description.clone(),
address: data.address.clone(),
auth_type: data.auth_type,
connector_meta_data: data.connector_meta_data.clone(),
connector_wallets_details: data.connector_wallets_details.clone(),
amount_captured: data.amount_captured,
minor_amount_captured: data.minor_amount_captured,
access_token: data.access_token.clone(),
response: data.response.clone(),
payment_id: data.payment_id.clone(),
session_token: data.session_token.clone(),
reference_id: data.reference_id.clone(),
customer_id: data.customer_id.clone(),
payment_method_token: None,
preprocessing_id: None,
connector_customer: data.connector_customer.clone(),
recurring_mandate_payment_data: data.recurring_mandate_payment_data.clone(),
connector_request_reference_id: data.connector_request_reference_id.clone(),
#[cfg(feature = "payouts")]
payout_method_data: data.payout_method_data.clone(),
#[cfg(feature = "payouts")]
quote_id: data.quote_id.clone(),
test_mode: data.test_mode,
payment_method_status: None,
payment_method_balance: data.payment_method_balance.clone(),
connector_api_version: data.connector_api_version.clone(),
connector_http_status_code: data.connector_http_status_code,
external_latency: data.external_latency,
apple_pay_flow: data.apple_pay_flow.clone(),
frm_metadata: data.frm_metadata.clone(),
dispute_id: data.dispute_id.clone(),
refund_id: data.refund_id.clone(),
connector_response: data.connector_response.clone(),
integrity_check: Ok(()),
additional_merchant_data: data.additional_merchant_data.clone(),
header_payload: data.header_payload.clone(),
connector_mandate_request_reference_id: data
.connector_mandate_request_reference_id
.clone(),
authentication_id: data.authentication_id.clone(),
psd2_sca_exemption_type: data.psd2_sca_exemption_type,
raw_connector_response: data.raw_connector_response.clone(),
is_payment_id_from_merchant: data.is_payment_id_from_merchant,
l2_l3_data: data.l2_l3_data.clone(),
minor_amount_capturable: data.minor_amount_capturable,
}
}
}
#[cfg(feature = "payouts")]
impl<F1, F2>
ForeignFrom<(
&RouterData<F1, PayoutsData, PayoutsResponseData>,
PayoutsData,
)> for RouterData<F2, PayoutsData, PayoutsResponseData>
{
fn foreign_from(
item: (
&RouterData<F1, PayoutsData, PayoutsResponseData>,
PayoutsData,
),
) -> Self {
let data = item.0;
let request = item.1;
Self {
flow: PhantomData,
request,
merchant_id: data.merchant_id.clone(),
connector: data.connector.clone(),
attempt_id: data.attempt_id.clone(),
tenant_id: data.tenant_id.clone(),
status: data.status,
payment_method: data.payment_method,
connector_auth_type: data.connector_auth_type.clone(),
description: data.description.clone(),
address: data.address.clone(),
auth_type: data.auth_type,
connector_meta_data: data.connector_meta_data.clone(),
connector_wallets_details: data.connector_wallets_details.clone(),
amount_captured: data.amount_captured,
minor_amount_captured: data.minor_amount_captured,
access_token: data.access_token.clone(),
response: data.response.clone(),
payment_id: data.payment_id.clone(),
session_token: data.session_token.clone(),
reference_id: data.reference_id.clone(),
customer_id: data.customer_id.clone(),
payment_method_token: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
connector_customer: data.connector_customer.clone(),
connector_request_reference_id:
IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_PAYOUTS_FLOW.to_string(),
payout_method_data: data.payout_method_data.clone(),
quote_id: data.quote_id.clone(),
test_mode: data.test_mode,
payment_method_balance: None,
payment_method_status: None,
connector_api_version: None,
connector_http_status_code: data.connector_http_status_code,
external_latency: data.external_latency,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: data.connector_response.clone(),
integrity_check: Ok(()),
header_payload: data.header_payload.clone(),
authentication_id: None,
psd2_sca_exemption_type: None,
additional_merchant_data: data.additional_merchant_data.clone(),
connector_mandate_request_reference_id: None,
raw_connector_response: None,
is_payment_id_from_merchant: data.is_payment_id_from_merchant,
l2_l3_data: None,
minor_amount_capturable: None,
}
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<&domain::MerchantConnectorAccountFeatureMetadata>
for api_models::admin::MerchantConnectorAccountFeatureMetadata
{
fn foreign_from(item: &domain::MerchantConnectorAccountFeatureMetadata) -> Self {
let revenue_recovery = item
.revenue_recovery
.as_ref()
.map(
|revenue_recovery_metadata| api_models::admin::RevenueRecoveryMetadata {
max_retry_count: revenue_recovery_metadata.max_retry_count,
billing_connector_retry_threshold: revenue_recovery_metadata
.billing_connector_retry_threshold,
billing_account_reference: revenue_recovery_metadata
.mca_reference
.recovery_to_billing
.clone(),
},
);
Self { revenue_recovery }
}
}
#[cfg(feature = "v2")]
impl ForeignTryFrom<&api_models::admin::MerchantConnectorAccountFeatureMetadata>
for domain::MerchantConnectorAccountFeatureMetadata
{
type Error = errors::ApiErrorResponse;
fn foreign_try_from(
feature_metadata: &api_models::admin::MerchantConnectorAccountFeatureMetadata,
) -> Result<Self, Self::Error> {
let revenue_recovery = feature_metadata
.revenue_recovery
.as_ref()
.map(|revenue_recovery_metadata| {
domain::AccountReferenceMap::new(
revenue_recovery_metadata.billing_account_reference.clone(),
)
.map(|mca_reference| domain::RevenueRecoveryMetadata {
max_retry_count: revenue_recovery_metadata.max_retry_count,
billing_connector_retry_threshold: revenue_recovery_metadata
.billing_connector_retry_threshold,
mca_reference,
})
})
.transpose()?;
Ok(Self { revenue_recovery })
}
}
|
crates/router/src/types.rs#chunk1
|
router
|
chunk
| null | null | null | 3,493
| null | null | null | null | null | null | null |
// Implementation: impl api::ConnectorAccessToken for for Bluesnap
// File: crates/hyperswitch_connectors/src/connectors/bluesnap.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::ConnectorAccessToken for for Bluesnap
|
crates/hyperswitch_connectors/src/connectors/bluesnap.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Bluesnap
|
api::ConnectorAccessToken for
| 0
| 0
| null | null |
// Implementation: impl RiskFactorsInner
// File: crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
// Module: hyperswitch_connectors
// Methods: 1 total (1 public)
impl RiskFactorsInner
|
crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 48
| null |
RiskFactorsInner
| null | 1
| 1
| null | null |
// Struct: AddressData
// File: crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct AddressData
|
crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
AddressData
| 0
|
[] | 46
| null | null | null | null | null | null | null |
// Implementation: impl DisputeMetricAccumulator for for RateAccumulator
// File: crates/analytics/src/disputes/accumulators.rs
// Module: analytics
// Methods: 2 total (0 public)
impl DisputeMetricAccumulator for for RateAccumulator
|
crates/analytics/src/disputes/accumulators.rs
|
analytics
|
impl_block
| null | null | null | 60
| null |
RateAccumulator
|
DisputeMetricAccumulator for
| 2
| 0
| null | null |
// Struct: MonerisPaymentsCaptureRequest
// File: crates/hyperswitch_connectors/src/connectors/moneris/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct MonerisPaymentsCaptureRequest
|
crates/hyperswitch_connectors/src/connectors/moneris/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
MonerisPaymentsCaptureRequest
| 0
|
[] | 55
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentCapture for for Redsys
// File: crates/hyperswitch_connectors/src/connectors/redsys.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentCapture for for Redsys
|
crates/hyperswitch_connectors/src/connectors/redsys.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Redsys
|
api::PaymentCapture for
| 0
| 0
| null | null |
// Function: upsert_conditional_config
// File: crates/router/src/core/conditional_config.rs
// Module: router
pub fn upsert_conditional_config(
state: SessionState,
key_store: domain::MerchantKeyStore,
request: DecisionManagerRequest,
profile: domain::Profile,
) -> RouterResponse<common_types::payments::DecisionManagerRecord>
|
crates/router/src/core/conditional_config.rs
|
router
|
function_signature
| null | null | null | 78
|
upsert_conditional_config
| null | null | null | null | null | null |
// Implementation: impl NetworkTokenizationBuilder
// File: crates/router/src/core/payment_methods/tokenize/card_executor.rs
// Module: router
// Methods: 1 total (1 public)
impl NetworkTokenizationBuilder
|
crates/router/src/core/payment_methods/tokenize/card_executor.rs
|
router
|
impl_block
| null | null | null | 44
| null |
NetworkTokenizationBuilder
| null | 1
| 1
| null | null |
// Function: link_routing_config
// File: crates/router/src/core/routing.rs
// Module: router
pub fn link_routing_config(
state: SessionState,
merchant_context: domain::MerchantContext,
authentication_profile_id: Option<common_utils::id_type::ProfileId>,
algorithm_id: common_utils::id_type::RoutingId,
transaction_type: enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord>
|
crates/router/src/core/routing.rs
|
router
|
function_signature
| null | null | null | 94
|
link_routing_config
| null | null | null | null | null | null |
// Function: generate_signature
// File: crates/hyperswitch_connectors/src/connectors/wellsfargo.rs
// Module: hyperswitch_connectors
pub fn generate_signature(
&self,
auth: wellsfargo::WellsfargoAuthType,
host: String,
resource: &str,
payload: &String,
date: OffsetDateTime,
http_method: Method,
) -> CustomResult<String, errors::ConnectorError>
|
crates/hyperswitch_connectors/src/connectors/wellsfargo.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 97
|
generate_signature
| null | null | null | null | null | null |
// Struct: AuthEventsAnalyticsMetadata
// File: crates/api_models/src/analytics.rs
// Module: api_models
// Implementations: 0
pub struct AuthEventsAnalyticsMetadata
|
crates/api_models/src/analytics.rs
|
api_models
|
struct_definition
|
AuthEventsAnalyticsMetadata
| 0
|
[] | 38
| null | null | null | null | null | null | null |
// File: crates/router/src/db/configs.rs
// Module: router
use diesel_models::configs::ConfigUpdateInternal;
use error_stack::report;
use router_env::{instrument, tracing};
use storage_impl::redis::cache::{self, CacheKind, CONFIG_CACHE};
use super::{MockDb, Store};
use crate::{
connection,
core::errors::{self, CustomResult},
db::StorageInterface,
types::storage,
};
#[async_trait::async_trait]
pub trait ConfigInterface {
async fn insert_config(
&self,
config: storage::ConfigNew,
) -> CustomResult<storage::Config, errors::StorageError>;
async fn find_config_by_key(
&self,
key: &str,
) -> CustomResult<storage::Config, errors::StorageError>;
async fn find_config_by_key_unwrap_or(
&self,
key: &str,
// If the config is not found it will be created with the default value.
default_config: Option<String>,
) -> CustomResult<storage::Config, errors::StorageError>;
async fn find_config_by_key_from_db(
&self,
key: &str,
) -> CustomResult<storage::Config, errors::StorageError>;
async fn update_config_by_key(
&self,
key: &str,
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, errors::StorageError>;
async fn update_config_in_database(
&self,
key: &str,
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, errors::StorageError>;
async fn delete_config_by_key(
&self,
key: &str,
) -> CustomResult<storage::Config, errors::StorageError>;
}
#[async_trait::async_trait]
impl ConfigInterface for Store {
#[instrument(skip_all)]
async fn insert_config(
&self,
config: storage::ConfigNew,
) -> CustomResult<storage::Config, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
let inserted = config
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?;
cache::redact_from_redis_and_publish(
self.get_cache_store().as_ref(),
[CacheKind::Config((&inserted.key).into())],
)
.await?;
Ok(inserted)
}
#[instrument(skip_all)]
async fn update_config_in_database(
&self,
key: &str,
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::Config::update_by_key(&conn, key, config_update)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
//update in DB and remove in redis and cache
#[instrument(skip_all)]
async fn update_config_by_key(
&self,
key: &str,
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, errors::StorageError> {
cache::publish_and_redact(self, CacheKind::Config(key.into()), || {
self.update_config_in_database(key, config_update)
})
.await
}
#[instrument(skip_all)]
async fn find_config_by_key_from_db(
&self,
key: &str,
) -> CustomResult<storage::Config, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::Config::find_by_key(&conn, key)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
//check in cache, then redis then finally DB, and on the way back populate redis and cache
#[instrument(skip_all)]
async fn find_config_by_key(
&self,
key: &str,
) -> CustomResult<storage::Config, errors::StorageError> {
let find_config_by_key_from_db = || async {
let conn = connection::pg_connection_write(self).await?;
storage::Config::find_by_key(&conn, key)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
cache::get_or_populate_in_memory(self, key, find_config_by_key_from_db, &CONFIG_CACHE).await
}
#[instrument(skip_all)]
async fn find_config_by_key_unwrap_or(
&self,
key: &str,
// If the config is not found it will be cached with the default value.
default_config: Option<String>,
) -> CustomResult<storage::Config, errors::StorageError> {
let find_else_unwrap_or = || async {
let conn = connection::pg_connection_write(self).await?;
match storage::Config::find_by_key(&conn, key)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
{
Ok(a) => Ok(a),
Err(err) => {
if err.current_context().is_db_not_found() {
default_config
.map(|c| {
storage::ConfigNew {
key: key.to_string(),
config: c,
}
.into()
})
.ok_or(err)
} else {
Err(err)
}
}
}
};
cache::get_or_populate_in_memory(self, key, find_else_unwrap_or, &CONFIG_CACHE).await
}
#[instrument(skip_all)]
async fn delete_config_by_key(
&self,
key: &str,
) -> CustomResult<storage::Config, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
let deleted = storage::Config::delete_by_key(&conn, key)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?;
cache::redact_from_redis_and_publish(
self.get_cache_store().as_ref(),
[CacheKind::Config((&deleted.key).into())],
)
.await?;
Ok(deleted)
}
}
#[async_trait::async_trait]
impl ConfigInterface for MockDb {
#[instrument(skip_all)]
async fn insert_config(
&self,
config: storage::ConfigNew,
) -> CustomResult<storage::Config, errors::StorageError> {
let mut configs = self.configs.lock().await;
let config_new = storage::Config {
key: config.key,
config: config.config,
};
configs.push(config_new.clone());
Ok(config_new)
}
async fn update_config_in_database(
&self,
key: &str,
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, errors::StorageError> {
self.update_config_by_key(key, config_update).await
}
async fn update_config_by_key(
&self,
key: &str,
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, errors::StorageError> {
let result = self
.configs
.lock()
.await
.iter_mut()
.find(|c| c.key == key)
.ok_or_else(|| {
errors::StorageError::ValueNotFound("cannot find config to update".to_string())
.into()
})
.map(|c| {
let config_updated =
ConfigUpdateInternal::from(config_update).create_config(c.clone());
*c = config_updated.clone();
config_updated
});
result
}
async fn delete_config_by_key(
&self,
key: &str,
) -> CustomResult<storage::Config, errors::StorageError> {
let mut configs = self.configs.lock().await;
let result = configs
.iter()
.position(|c| c.key == key)
.map(|index| configs.remove(index))
.ok_or_else(|| {
errors::StorageError::ValueNotFound("cannot find config to delete".to_string())
.into()
});
result
}
async fn find_config_by_key(
&self,
key: &str,
) -> CustomResult<storage::Config, errors::StorageError> {
let configs = self.configs.lock().await;
let config = configs.iter().find(|c| c.key == key).cloned();
config.ok_or_else(|| {
errors::StorageError::ValueNotFound("cannot find config".to_string()).into()
})
}
async fn find_config_by_key_unwrap_or(
&self,
key: &str,
_default_config: Option<String>,
) -> CustomResult<storage::Config, errors::StorageError> {
self.find_config_by_key(key).await
}
async fn find_config_by_key_from_db(
&self,
key: &str,
) -> CustomResult<storage::Config, errors::StorageError> {
self.find_config_by_key(key).await
}
}
|
crates/router/src/db/configs.rs
|
router
|
full_file
| null | null | null | 1,973
| null | null | null | null | null | null | null |
// Struct: AdyenBalanceAccount
// File: crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct AdyenBalanceAccount
|
crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs
|
hyperswitch_connectors
|
struct_definition
|
AdyenBalanceAccount
| 0
|
[] | 54
| null | null | null | null | null | null | null |
// Implementation: impl api::RefundSync for for Zen
// File: crates/hyperswitch_connectors/src/connectors/zen.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundSync for for Zen
|
crates/hyperswitch_connectors/src/connectors/zen.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Zen
|
api::RefundSync for
| 0
| 0
| null | null |
// Function: add_having_clause
// File: crates/analytics/src/query.rs
// Module: analytics
pub fn add_having_clause<R>(
&mut self,
aggregate: Aggregate<R>,
filter_type: FilterTypes,
value: impl ToSql<T>,
) -> QueryResult<()>
where
Aggregate<R>: ToSql<T>,
|
crates/analytics/src/query.rs
|
analytics
|
function_signature
| null | null | null | 75
|
add_having_clause
| null | null | null | null | null | null |
// File: crates/router/src/db/blocklist_lookup.rs
// Module: router
use error_stack::report;
use router_env::{instrument, tracing};
use storage_impl::MockDb;
use super::Store;
use crate::{
connection,
core::errors::{self, CustomResult},
db::kafka_store::KafkaStore,
types::storage,
};
#[async_trait::async_trait]
pub trait BlocklistLookupInterface {
async fn insert_blocklist_lookup_entry(
&self,
blocklist_lookup_new: storage::BlocklistLookupNew,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError>;
async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError>;
async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError>;
}
#[async_trait::async_trait]
impl BlocklistLookupInterface for Store {
#[instrument(skip_all)]
async fn insert_blocklist_lookup_entry(
&self,
blocklist_lookup_entry: storage::BlocklistLookupNew,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
blocklist_lookup_entry
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::BlocklistLookup::find_by_merchant_id_fingerprint(&conn, merchant_id, fingerprint)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::BlocklistLookup::delete_by_merchant_id_fingerprint(&conn, merchant_id, fingerprint)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl BlocklistLookupInterface for MockDb {
#[instrument(skip_all)]
async fn insert_blocklist_lookup_entry(
&self,
_blocklist_lookup_entry: storage::BlocklistLookupNew,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
}
#[async_trait::async_trait]
impl BlocklistLookupInterface for KafkaStore {
#[instrument(skip_all)]
async fn insert_blocklist_lookup_entry(
&self,
blocklist_lookup_entry: storage::BlocklistLookupNew,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
self.diesel_store
.insert_blocklist_lookup_entry(blocklist_lookup_entry)
.await
}
#[instrument(skip_all)]
async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
self.diesel_store
.find_blocklist_lookup_entry_by_merchant_id_fingerprint(merchant_id, fingerprint)
.await
}
#[instrument(skip_all)]
async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
self.diesel_store
.delete_blocklist_lookup_entry_by_merchant_id_fingerprint(merchant_id, fingerprint)
.await
}
}
|
crates/router/src/db/blocklist_lookup.rs
|
router
|
full_file
| null | null | null | 1,108
| null | null | null | null | null | null | null |
// File: crates/router/tests/connectors/sift.rs
// Module: router
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData};
use masking::Secret;
use router::types::{self, api, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct SiftTest;
impl ConnectorActions for SiftTest {}
impl utils::Connector for SiftTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Sift;
utils::construct_connector_data_old(
Box::new(Sift::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.sift
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"sift".to_string()
}
}
static CONNECTOR: SiftTest = SiftTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
|
crates/router/tests/connectors/sift.rs
|
router
|
full_file
| null | null | null | 2,930
| null | null | null | null | null | null | null |
// File: crates/router/tests/connectors/facilitapay.rs
// Module: router
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData};
use masking::Secret;
use router::types::{self, api, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct FacilitapayTest;
impl ConnectorActions for FacilitapayTest {}
impl utils::Connector for FacilitapayTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Facilitapay;
utils::construct_connector_data_old(
Box::new(Facilitapay::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.facilitapay
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"facilitapay".to_string()
}
}
static CONNECTOR: FacilitapayTest = FacilitapayTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
|
crates/router/tests/connectors/facilitapay.rs
|
router
|
full_file
| null | null | null | 2,952
| null | null | null | null | null | null | null |
// Implementation: impl SecretStateContainer
// File: crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs
// Module: hyperswitch_interfaces
// Methods: 1 total (1 public)
impl SecretStateContainer
|
crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs
|
hyperswitch_interfaces
|
impl_block
| null | null | null | 47
| null |
SecretStateContainer
| null | 1
| 1
| null | null |
// Struct: AirwallexObjectData
// File: crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct AirwallexObjectData
|
crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
AirwallexObjectData
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentSync for for Nmi
// File: crates/hyperswitch_connectors/src/connectors/nmi.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSync for for Nmi
|
crates/hyperswitch_connectors/src/connectors/nmi.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Nmi
|
api::PaymentSync for
| 0
| 0
| null | null |
// Implementation: impl api::PaymentAuthorize for for Checkout
// File: crates/hyperswitch_connectors/src/connectors/checkout.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentAuthorize for for Checkout
|
crates/hyperswitch_connectors/src/connectors/checkout.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 55
| null |
Checkout
|
api::PaymentAuthorize for
| 0
| 0
| null | null |
// Module Structure
// File: crates/hyperswitch_connectors/src/connectors/netcetera.rs
// Module: hyperswitch_connectors
// Public submodules:
pub mod netcetera_types;
pub mod transformers;
|
crates/hyperswitch_connectors/src/connectors/netcetera.rs
|
hyperswitch_connectors
|
module_structure
| null | null | null | 48
| null | null | null | null | null | 2
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.