text
stringlengths 65
57.3k
| file_path
stringlengths 22
92
| module
stringclasses 38
values | type
stringclasses 7
values | struct_name
stringlengths 3
60
⌀ | impl_count
int64 0
60
⌀ | traits
listlengths 0
59
⌀ | tokens
int64 16
8.19k
| function_name
stringlengths 3
85
⌀ | type_name
stringlengths 1
67
⌀ | trait_name
stringclasses 573
values | method_count
int64 0
31
⌀ | public_method_count
int64 0
19
⌀ | submodule_count
int64 0
56
⌀ | export_count
int64 0
9
⌀ |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
// Function: retrieve_decision_manager_config
// File: crates/router/src/routes/routing.rs
// Module: router
pub fn retrieve_decision_manager_config(
state: web::Data<AppState>,
req: HttpRequest,
) -> impl Responder
|
crates/router/src/routes/routing.rs
|
router
|
function_signature
| null | null | null | 50
|
retrieve_decision_manager_config
| null | null | null | null | null | null |
// Struct: DummyConnectorCard
// File: crates/router/src/routes/dummy_connector/types.rs
// Module: router
// Implementations: 0
pub struct DummyConnectorCard
|
crates/router/src/routes/dummy_connector/types.rs
|
router
|
struct_definition
|
DummyConnectorCard
| 0
|
[] | 37
| null | null | null | null | null | null | null |
// File: crates/router/src/core/payments/flows/setup_mandate_flow.rs
// Module: router
// Public functions: 1
use std::str::FromStr;
use async_trait::async_trait;
use common_types::payments as common_payments_types;
use common_utils::{id_type, ucs_types};
use error_stack::ResultExt;
use external_services::grpc_client;
use hyperswitch_domain_models::payments as domain_payments;
use router_env::logger;
use unified_connector_service_client::payments as payments_grpc;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult},
mandate,
payments::{
self, access_token, customers, helpers, tokenization, transformers, PaymentData,
},
unified_connector_service::{
build_unified_connector_service_auth_metadata,
handle_unified_connector_service_response_for_payment_register, ucs_logging_wrapper,
},
},
routes::SessionState,
services,
types::{
self, api, domain,
transformers::{ForeignFrom, ForeignTryFrom},
},
};
#[cfg(feature = "v1")]
#[async_trait]
impl
ConstructFlowSpecificData<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
> for PaymentData<api::SetupMandate>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
) -> RouterResult<types::SetupMandateRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::SetupMandate,
types::SetupMandateRequestData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
))
.await
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl
ConstructFlowSpecificData<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
> for hyperswitch_domain_models::payments::PaymentConfirmData<api::SetupMandate>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
) -> RouterResult<types::SetupMandateRouterData> {
Box::pin(
transformers::construct_payment_router_data_for_setup_mandate(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
),
)
.await
}
}
#[async_trait]
impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::SetupMandateRouterData {
async fn decide_flows<'a>(
mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: domain_payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
// Change the authentication_type to ThreeDs, for google_pay wallet if card_holder_authenticated or account_verified in assurance_details is false
if let hyperswitch_domain_models::payment_method_data::PaymentMethodData::Wallet(
hyperswitch_domain_models::payment_method_data::WalletData::GooglePay(google_pay_data),
) = &self.request.payment_method_data
{
if let Some(assurance_details) = google_pay_data.info.assurance_details.as_ref() {
// Step up the transaction to 3DS when either assurance_details.card_holder_authenticated or assurance_details.account_verified is false
if !assurance_details.card_holder_authenticated
|| !assurance_details.account_verified
{
logger::info!("Googlepay transaction stepped up to 3DS");
self.auth_type = diesel_models::enums::AuthenticationType::ThreeDs;
}
}
}
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action.clone(),
connector_request,
None,
)
.await
.to_setup_mandate_failed_response()?;
Ok(resp)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
async fn add_session_token<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self>
where
Self: Sized,
{
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::AuthorizeSessionToken,
types::AuthorizeSessionTokenData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let authorize_data = &types::PaymentsAuthorizeSessionTokenRouterData::foreign_from((
&self,
types::AuthorizeSessionTokenData::foreign_from(&self),
));
let resp = services::execute_connector_processing_step(
state,
connector_integration,
authorize_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
let mut router_data = self;
router_data.session_token = resp.session_token;
Ok(router_data)
}
async fn add_payment_method_token<'a>(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
tokenization_action: &payments::TokenizationAction,
should_continue_payment: bool,
) -> RouterResult<types::PaymentMethodTokenResult> {
let request = self.request.clone();
tokenization::add_payment_method_token(
state,
connector,
tokenization_action,
self,
types::PaymentMethodTokenizationData::try_from(request)?,
should_continue_payment,
)
.await
}
async fn create_connector_customer<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Option<String>> {
customers::create_connector_customer(
state,
connector,
self,
types::ConnectorCustomerData::try_from(self.request.to_owned())?,
)
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
Ok((
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?,
true,
))
}
_ => Ok((None, true)),
}
}
async fn preprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
setup_mandate_preprocessing_steps(state, &self, true, connector).await
}
async fn call_unified_connector_service<'a>(
&mut self,
state: &SessionState,
header_payload: &domain_payments::HeaderPayload,
lineage_ids: grpc_client::LineageIds,
#[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
#[cfg(feature = "v2")]
merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
merchant_context: &domain::MerchantContext,
) -> RouterResult<()> {
let client = state
.grpc_client
.unified_connector_service_client
.clone()
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let payment_register_request =
payments_grpc::PaymentServiceRegisterRequest::foreign_try_from(&*self)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct Payment Setup Mandate Request")?;
let connector_auth_metadata = build_unified_connector_service_auth_metadata(
merchant_connector_account,
merchant_context,
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct request metadata")?;
let merchant_reference_id = header_payload
.x_reference_id
.clone()
.map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
.transpose()
.inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
.ok()
.flatten()
.map(ucs_types::UcsReferenceId::Payment);
let header_payload = state
.get_grpc_headers_ucs()
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
let updated_router_data = Box::pin(ucs_logging_wrapper(
self.clone(),
state,
payment_register_request,
header_payload,
|mut router_data, payment_register_request, grpc_headers| async move {
let response = client
.payment_setup_mandate(
payment_register_request,
connector_auth_metadata,
grpc_headers,
)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to Setup Mandate payment")?;
let payment_register_response = response.into_inner();
let (router_data_response, status_code) =
handle_unified_connector_service_response_for_payment_register(
payment_register_response.clone(),
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response = router_data_response.map(|(response, status)| {
router_data.status = status;
response
});
router_data.response = router_data_response;
router_data.connector_http_status_code = Some(status_code);
Ok((router_data, payment_register_response))
},
))
.await?;
// Copy back the updated data
*self = updated_router_data;
Ok(())
}
}
impl mandate::MandateBehaviour for types::SetupMandateRequestData {
fn get_amount(&self) -> i64 {
0
}
fn get_setup_future_usage(&self) -> Option<diesel_models::enums::FutureUsage> {
self.setup_future_usage
}
fn get_mandate_id(&self) -> Option<&api_models::payments::MandateIds> {
self.mandate_id.as_ref()
}
fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>) {
self.mandate_id = new_mandate_id;
}
fn get_payment_method_data(&self) -> domain::payments::PaymentMethodData {
self.payment_method_data.clone()
}
fn get_setup_mandate_details(
&self,
) -> Option<&hyperswitch_domain_models::mandates::MandateData> {
self.setup_mandate_details.as_ref()
}
fn get_customer_acceptance(&self) -> Option<common_payments_types::CustomerAcceptance> {
self.customer_acceptance.clone()
}
}
pub async fn setup_mandate_preprocessing_steps<F: Clone>(
state: &SessionState,
router_data: &types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData>,
confirm: bool,
connector: &api::ConnectorData,
) -> RouterResult<types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData>>
{
if confirm {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PreProcessing,
types::PaymentsPreProcessingData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let preprocessing_request_data =
types::PaymentsPreProcessingData::try_from(router_data.request.clone())?;
let preprocessing_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let preprocessing_router_data =
helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>(
router_data.clone(),
preprocessing_request_data,
preprocessing_response_data,
);
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&preprocessing_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
let mut setup_mandate_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>(
resp.clone(),
router_data.request.to_owned(),
resp.response.clone(),
);
if connector.connector_name == api_models::enums::Connector::Nuvei {
let (enrolled_for_3ds, related_transaction_id) =
match &setup_mandate_router_data.response {
Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse {
enrolled_v2,
related_transaction_id,
}) => (*enrolled_v2, related_transaction_id.clone()),
_ => (false, None),
};
setup_mandate_router_data.request.enrolled_for_3ds = enrolled_for_3ds;
setup_mandate_router_data.request.related_transaction_id = related_transaction_id;
}
Ok(setup_mandate_router_data)
} else {
Ok(router_data.clone())
}
}
|
crates/router/src/core/payments/flows/setup_mandate_flow.rs
|
router
|
full_file
| null | null | null | 3,184
| null | null | null | null | null | null | null |
// Function: perform_surcharge_ops
// File: crates/router/src/core/payment_methods/cards.rs
// Module: router
pub fn perform_surcharge_ops(
_payment_intent: Option<storage::PaymentIntent>,
_state: &routes::SessionState,
_merchant_context: &domain::MerchantContext,
_business_profile: Option<Profile>,
_response: &mut api_models::payment_methods::CustomerPaymentMethodsListResponse,
) -> Result<(), error_stack::Report<errors::ApiErrorResponse>>
|
crates/router/src/core/payment_methods/cards.rs
|
router
|
function_signature
| null | null | null | 106
|
perform_surcharge_ops
| null | null | null | null | null | null |
// Struct: GetUserRoleDetailsRequest
// File: crates/api_models/src/user.rs
// Module: api_models
// Implementations: 0
pub struct GetUserRoleDetailsRequest
|
crates/api_models/src/user.rs
|
api_models
|
struct_definition
|
GetUserRoleDetailsRequest
| 0
|
[] | 37
| null | null | null | null | null | null | null |
// Function: find_resource_by_id
// File: crates/storage_impl/src/kv_router_store.rs
// Module: storage_impl
pub fn find_resource_by_id<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
find_resource_db_fut: R,
find_by: FindResourceBy<'_>,
) -> error_stack::Result<D, errors::StorageError>
where
D: DomainType,
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 | 138
|
find_resource_by_id
| null | null | null | null | null | null |
// Function: remove_entry_from_blocklist
// File: crates/openapi/src/routes/blocklist.rs
// Module: openapi
pub fn remove_entry_from_blocklist()
|
crates/openapi/src/routes/blocklist.rs
|
openapi
|
function_signature
| null | null | null | 35
|
remove_entry_from_blocklist
| null | null | null | null | null | null |
// Function: generate_sample_data
// File: crates/router/src/routes/user.rs
// Module: router
pub fn generate_sample_data(
state: web::Data<AppState>,
http_req: HttpRequest,
payload: web::Json<SampleDataRequest>,
) -> impl actix_web::Responder
|
crates/router/src/routes/user.rs
|
router
|
function_signature
| null | null | null | 62
|
generate_sample_data
| null | null | null | null | null | null |
// Struct: FacilitapayCustomerResponse
// File: crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct FacilitapayCustomerResponse
|
crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs
|
hyperswitch_connectors
|
struct_definition
|
FacilitapayCustomerResponse
| 0
|
[] | 55
| null | null | null | null | null | null | null |
// Struct: AlwaysEnableOvercaptureBool
// File: crates/common_types/src/primitive_wrappers.rs
// Module: common_types
// Implementations: 2
// Traits: Default
pub struct AlwaysEnableOvercaptureBool
|
crates/common_types/src/primitive_wrappers.rs
|
common_types
|
struct_definition
|
AlwaysEnableOvercaptureBool
| 2
|
[
"Default"
] | 47
| null | null | null | null | null | null | null |
// File: crates/diesel_models/src/query/customers.rs
// Module: diesel_models
// Public functions: 10
// Public structs: 1
use common_utils::id_type;
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use super::generics;
#[cfg(feature = "v1")]
use crate::schema::customers::dsl;
#[cfg(feature = "v2")]
use crate::schema_v2::customers::dsl;
use crate::{
customers::{Customer, CustomerNew, CustomerUpdateInternal},
errors, PgPooledConn, StorageResult,
};
impl CustomerNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Customer> {
generics::generic_insert(conn, self).await
}
}
pub struct CustomerListConstraints {
pub limit: i64,
pub offset: Option<i64>,
}
impl Customer {
#[cfg(feature = "v2")]
pub async fn update_by_id(
conn: &PgPooledConn,
id: id_type::GlobalCustomerId,
customer: CustomerUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
conn,
id.clone(),
customer,
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id).await
}
_ => Err(error),
},
result => result,
}
}
#[cfg(feature = "v2")]
pub async fn find_by_global_id(
conn: &PgPooledConn,
id: &id_type::GlobalCustomerId,
) -> StorageResult<Self> {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id.to_owned()).await
}
pub async fn list_by_merchant_id(
conn: &PgPooledConn,
merchant_id: &id_type::MerchantId,
constraints: CustomerListConstraints,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::merchant_id.eq(merchant_id.to_owned()),
Some(constraints.limit),
constraints.offset,
Some(dsl::created_at),
)
.await
}
#[cfg(feature = "v2")]
pub async fn find_optional_by_merchant_id_merchant_reference_id(
conn: &PgPooledConn,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Option<Self>> {
generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::merchant_reference_id.eq(customer_id.to_owned())),
)
.await
}
#[cfg(feature = "v1")]
pub async fn find_optional_by_customer_id_merchant_id(
conn: &PgPooledConn,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Option<Self>> {
generics::generic_find_by_id_optional::<<Self as HasTable>::Table, _, _>(
conn,
(customer_id.to_owned(), merchant_id.to_owned()),
)
.await
}
#[cfg(feature = "v1")]
pub async fn update_by_customer_id_merchant_id(
conn: &PgPooledConn,
customer_id: id_type::CustomerId,
merchant_id: id_type::MerchantId,
customer: CustomerUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
conn,
(customer_id.clone(), merchant_id.clone()),
customer,
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(
conn,
(customer_id, merchant_id),
)
.await
}
_ => Err(error),
},
result => result,
}
}
#[cfg(feature = "v1")]
pub async fn delete_by_customer_id_merchant_id(
conn: &PgPooledConn,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
conn,
dsl::customer_id
.eq(customer_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned())),
)
.await
}
#[cfg(feature = "v2")]
pub async fn find_by_merchant_reference_id_merchant_id(
conn: &PgPooledConn,
merchant_reference_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::merchant_reference_id.eq(merchant_reference_id.to_owned())),
)
.await
}
#[cfg(feature = "v1")]
pub async fn find_by_customer_id_merchant_id(
conn: &PgPooledConn,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(
conn,
(customer_id.to_owned(), merchant_id.to_owned()),
)
.await
}
}
|
crates/diesel_models/src/query/customers.rs
|
diesel_models
|
full_file
| null | null | null | 1,283
| null | null | null | null | null | null | null |
pub offset: Option<u32>,
/// The time at which payment is created
#[param(example = "2022-09-10T10:11:12Z")]
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub created: Option<PrimitiveDateTime>,
/// Time less than the payment created time
#[param(example = "2022-09-10T10:11:12Z")]
#[serde(
default,
with = "common_utils::custom_serde::iso8601::option",
rename = "created.lt"
)]
pub created_lt: Option<PrimitiveDateTime>,
/// Time greater than the payment created time
#[param(example = "2022-09-10T10:11:12Z")]
#[serde(
default,
with = "common_utils::custom_serde::iso8601::option",
rename = "created.gt"
)]
pub created_gt: Option<PrimitiveDateTime>,
/// Time less than or equals to the payment created time
#[param(example = "2022-09-10T10:11:12Z")]
#[serde(
default,
with = "common_utils::custom_serde::iso8601::option",
rename = "created.lte"
)]
pub created_lte: Option<PrimitiveDateTime>,
/// Time greater than or equals to the payment created time
#[param(example = "2022-09-10T10:11:12Z")]
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
#[serde(rename = "created.gte")]
pub created_gte: Option<PrimitiveDateTime>,
/// The start amount to filter list of transactions which are greater than or equal to the start amount
pub start_amount: Option<i64>,
/// The end amount to filter list of transactions which are less than or equal to the end amount
pub end_amount: Option<i64>,
/// The connector to filter payments list
#[param(value_type = Option<Vec<Connector>>)]
#[serde(deserialize_with = "parse_comma_separated", default)]
pub connector: Option<Vec<api_enums::Connector>>,
/// The currency to filter payments list
#[param(value_type = Option<Vec<Currency>>)]
#[serde(deserialize_with = "parse_comma_separated", default)]
pub currency: Option<Vec<enums::Currency>>,
/// The payment status to filter payments list
#[param(value_type = Option<Vec<IntentStatus>>)]
#[serde(deserialize_with = "parse_comma_separated", default)]
pub status: Option<Vec<enums::IntentStatus>>,
/// The payment method type to filter payments list
#[param(value_type = Option<Vec<PaymentMethod>>)]
#[serde(deserialize_with = "parse_comma_separated", default)]
pub payment_method_type: Option<Vec<enums::PaymentMethod>>,
/// The payment method subtype to filter payments list
#[param(value_type = Option<Vec<PaymentMethodType>>)]
#[serde(deserialize_with = "parse_comma_separated", default)]
pub payment_method_subtype: Option<Vec<enums::PaymentMethodType>>,
/// The authentication type to filter payments list
#[param(value_type = Option<Vec<AuthenticationType>>)]
#[serde(deserialize_with = "parse_comma_separated", default)]
pub authentication_type: Option<Vec<enums::AuthenticationType>>,
/// The merchant connector id to filter payments list
#[param(value_type = Option<Vec<String>>)]
#[serde(deserialize_with = "parse_comma_separated", default)]
pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
/// The field on which the payments list should be sorted
#[serde(default)]
pub order_on: SortOn,
/// The order in which payments list should be sorted
#[serde(default)]
pub order_by: SortBy,
/// The card networks to filter payments list
#[param(value_type = Option<Vec<CardNetwork>>)]
#[serde(deserialize_with = "parse_comma_separated", default)]
pub card_network: Option<Vec<enums::CardNetwork>>,
/// The identifier for merchant order reference id
pub merchant_order_reference_id: Option<String>,
}
#[cfg(feature = "v2")]
impl PaymentListConstraints {
pub fn has_no_attempt_filters(&self) -> bool {
self.connector.is_none()
&& self.payment_method_type.is_none()
&& self.payment_method_subtype.is_none()
&& self.authentication_type.is_none()
&& self.merchant_connector_id.is_none()
&& self.card_network.is_none()
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, serde::Serialize, ToSchema)]
pub struct PaymentListResponse {
/// The number of payments included in the list
pub size: usize,
// The list of payments response objects
pub data: Vec<PaymentsResponse>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize, ToSchema)]
pub struct PaymentListResponse {
/// The number of payments included in the current response
pub count: usize,
/// The total number of available payments for given constraints
pub total_count: i64,
/// The list of payments response objects
pub data: Vec<PaymentsListResponseItem>,
}
#[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)]
pub struct IncrementalAuthorizationResponse {
/// The unique identifier of authorization
pub authorization_id: String,
/// Amount the authorization has been made for
#[schema(value_type = i64, example = 6540)]
pub amount: MinorUnit,
#[schema(value_type= AuthorizationStatus)]
/// The status of the authorization
pub status: common_enums::AuthorizationStatus,
/// Error code sent by the connector for authorization
pub error_code: Option<String>,
/// Error message sent by the connector for authorization
pub error_message: Option<String>,
/// Previously authorized amount for the payment
pub previously_authorized_amount: MinorUnit,
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, serde::Serialize)]
pub struct PaymentListResponseV2 {
/// The number of payments included in the list for given constraints
pub count: usize,
/// The total number of available payments for given constraints
pub total_count: i64,
/// The list of payments response objects
pub data: Vec<PaymentsResponse>,
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct PaymentListFilterConstraints {
/// The identifier for payment
pub payment_id: Option<id_type::PaymentId>,
/// The identifier for business profile
pub profile_id: Option<id_type::ProfileId>,
/// The identifier for customer
pub customer_id: Option<id_type::CustomerId>,
/// The limit on the number of objects. The default limit is 10 and max limit is 20
#[serde(default = "default_payments_list_limit")]
pub limit: u32,
/// The starting point within a list of objects
pub offset: Option<u32>,
/// The amount to filter payments list
pub amount_filter: Option<AmountFilter>,
/// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).
#[serde(flatten)]
pub time_range: Option<common_utils::types::TimeRange>,
/// The list of connectors to filter payments list
pub connector: Option<Vec<api_enums::Connector>>,
/// The list of currencies to filter payments list
pub currency: Option<Vec<enums::Currency>>,
/// The list of payment status to filter payments list
pub status: Option<Vec<enums::IntentStatus>>,
/// The list of payment methods to filter payments list
pub payment_method: Option<Vec<enums::PaymentMethod>>,
/// The list of payment method types to filter payments list
pub payment_method_type: Option<Vec<enums::PaymentMethodType>>,
/// The list of authentication types to filter payments list
pub authentication_type: Option<Vec<enums::AuthenticationType>>,
/// The list of merchant connector ids to filter payments list for selected label
pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
/// The order in which payments list should be sorted
#[serde(default)]
pub order: Order,
/// The List of all the card networks to filter payments list
pub card_network: Option<Vec<enums::CardNetwork>>,
/// The identifier for merchant order reference id
pub merchant_order_reference_id: Option<String>,
/// Indicates the method by which a card is discovered during a payment
pub card_discovery: Option<Vec<enums::CardDiscovery>>,
}
#[cfg(feature = "v1")]
impl PaymentListFilterConstraints {
pub fn has_no_attempt_filters(&self) -> bool {
self.connector.is_none()
&& self.payment_method.is_none()
&& self.payment_method_type.is_none()
&& self.authentication_type.is_none()
&& self.merchant_connector_id.is_none()
&& self.card_network.is_none()
&& self.card_discovery.is_none()
}
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct PaymentListFilters {
/// The list of available connector filters
pub connector: Vec<String>,
/// The list of available currency filters
pub currency: Vec<enums::Currency>,
/// The list of available payment status filters
pub status: Vec<enums::IntentStatus>,
/// The list of available payment method filters
pub payment_method: Vec<enums::PaymentMethod>,
/// The list of available payment method types
pub payment_method_type: Vec<enums::PaymentMethodType>,
/// The list of available authentication types
pub authentication_type: Vec<enums::AuthenticationType>,
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct PaymentListFiltersV2 {
/// The list of available connector filters
pub connector: HashMap<String, Vec<MerchantConnectorInfo>>,
/// The list of available currency filters
pub currency: Vec<enums::Currency>,
/// The list of available payment status filters
pub status: Vec<enums::IntentStatus>,
/// The list payment method and their corresponding types
pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>,
/// The list of available authentication types
pub authentication_type: Vec<enums::AuthenticationType>,
/// The list of available card networks
pub card_network: Vec<enums::CardNetwork>,
/// The list of available Card discovery methods
pub card_discovery: Vec<enums::CardDiscovery>,
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct PaymentsAggregateResponse {
/// The list of intent status with their count
pub status_with_count: HashMap<enums::IntentStatus, i64>,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct AmountFilter {
/// The start amount to filter list of transactions which are greater than or equal to the start amount
pub start_amount: Option<i64>,
/// The end amount to filter list of transactions which are less than or equal to the end amount
pub end_amount: Option<i64>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct Order {
/// The field to sort, such as Amount or Created etc.
pub on: SortOn,
/// The order in which to sort the items, either Ascending or Descending
pub by: SortBy,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum SortOn {
/// Sort by the amount field
Amount,
/// Sort by the created_at field
#[default]
Created,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum SortBy {
/// Sort in ascending order
Asc,
/// Sort in descending order
#[default]
Desc,
}
#[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)]
pub struct VerifyResponse {
pub verify_id: Option<id_type::PaymentId>,
pub merchant_id: Option<id_type::MerchantId>,
// pub status: enums::VerifyStatus,
pub client_secret: Option<Secret<String>>,
pub customer_id: Option<id_type::CustomerId>,
pub email: crypto::OptionalEncryptableEmail,
pub name: crypto::OptionalEncryptableName,
pub phone: crypto::OptionalEncryptablePhone,
pub mandate_id: Option<String>,
#[auth_based]
pub payment_method: Option<api_enums::PaymentMethod>,
#[auth_based]
pub payment_method_data: Option<PaymentMethodDataResponse>,
pub payment_token: Option<String>,
pub error_code: Option<String>,
pub error_message: Option<String>,
}
#[derive(Default, Debug, serde::Deserialize, serde::Serialize)]
pub struct PaymentsRedirectionResponse {
pub redirect_url: String,
}
pub struct MandateValidationFields {
pub recurring_details: Option<RecurringDetails>,
pub confirm: Option<bool>,
pub customer_id: Option<id_type::CustomerId>,
pub mandate_data: Option<MandateData>,
pub setup_future_usage: Option<api_enums::FutureUsage>,
pub off_session: Option<bool>,
}
#[cfg(feature = "v1")]
impl From<&PaymentsRequest> for MandateValidationFields {
fn from(req: &PaymentsRequest) -> Self {
let recurring_details = req
.mandate_id
.clone()
.map(RecurringDetails::MandateId)
.or(req.recurring_details.clone());
Self {
recurring_details,
confirm: req.confirm,
customer_id: req
.customer
.as_ref()
.map(|customer_details| &customer_details.id)
.or(req.customer_id.as_ref())
.map(ToOwned::to_owned),
mandate_data: req.mandate_data.clone(),
setup_future_usage: req.setup_future_usage,
off_session: req.off_session,
}
}
}
impl From<&VerifyRequest> for MandateValidationFields {
fn from(req: &VerifyRequest) -> Self {
Self {
recurring_details: None,
confirm: Some(true),
customer_id: req.customer_id.clone(),
mandate_data: req.mandate_data.clone(),
off_session: req.off_session,
setup_future_usage: req.setup_future_usage,
}
}
}
// #[cfg(all(feature = "v2", feature = "payment_v2"))]
// impl From<PaymentsSessionRequest> for PaymentsSessionResponse {
// fn from(item: PaymentsSessionRequest) -> Self {
// let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret);
// Self {
// session_token: vec![],
// payment_id: item.payment_id,
// client_secret,
// }
// }
// }
#[cfg(feature = "v1")]
impl From<PaymentsSessionRequest> for PaymentsSessionResponse {
fn from(item: PaymentsSessionRequest) -> Self {
let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret);
Self {
session_token: vec![],
payment_id: item.payment_id,
client_secret,
}
}
}
#[cfg(feature = "v1")]
impl From<PaymentsStartRequest> for PaymentsRequest {
fn from(item: PaymentsStartRequest) -> Self {
Self {
payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)),
merchant_id: Some(item.merchant_id),
..Default::default()
}
}
}
impl From<AdditionalCardInfo> for CardResponse {
fn from(card: AdditionalCardInfo) -> Self {
Self {
last4: card.last4,
card_type: card.card_type,
card_network: card.card_network,
card_issuer: card.card_issuer,
card_issuing_country: card.card_issuing_country,
card_isin: card.card_isin,
card_extended_bin: card.card_extended_bin,
card_exp_month: card.card_exp_month,
card_exp_year: card.card_exp_year,
card_holder_name: card.card_holder_name,
payment_checks: card.payment_checks,
authentication_data: card.authentication_data,
}
}
}
impl From<KlarnaSdkPaymentMethod> for PaylaterResponse {
fn from(klarna_sdk: KlarnaSdkPaymentMethod) -> Self {
Self {
klarna_sdk: Some(KlarnaSdkPaymentMethodResponse {
payment_type: klarna_sdk.payment_type,
}),
}
}
}
impl From<AdditionalPaymentData> for PaymentMethodDataResponse {
fn from(payment_method_data: AdditionalPaymentData) -> Self {
match payment_method_data {
AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))),
AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk {
Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))),
None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })),
},
AdditionalPaymentData::Wallet {
apple_pay,
google_pay,
samsung_pay,
} => match (apple_pay, google_pay, samsung_pay) {
(Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse {
details: Some(WalletResponseData::ApplePay(Box::new(
additional_info::WalletAdditionalDataForCard {
last4: apple_pay_pm
.display_name
.clone()
.chars()
.rev()
.take(4)
.collect::<String>()
.chars()
.rev()
.collect::<String>(),
card_network: apple_pay_pm.network.clone(),
card_type: Some(apple_pay_pm.pm_type.clone()),
},
))),
})),
(_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse {
details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))),
})),
(_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse {
details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))),
})),
_ => Self::Wallet(Box::new(WalletResponse { details: None })),
},
AdditionalPaymentData::BankRedirect { bank_name, details } => {
Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details }))
}
AdditionalPaymentData::Crypto { details } => {
Self::Crypto(Box::new(CryptoResponse { details }))
}
AdditionalPaymentData::BankDebit { details } => {
Self::BankDebit(Box::new(BankDebitResponse { details }))
}
AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {},
AdditionalPaymentData::Reward {} => Self::Reward {},
AdditionalPaymentData::RealTimePayment { details } => {
Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details }))
}
AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })),
AdditionalPaymentData::BankTransfer { details } => {
Self::BankTransfer(Box::new(BankTransferResponse { details }))
}
AdditionalPaymentData::Voucher { details } => {
Self::Voucher(Box::new(VoucherResponse { details }))
}
AdditionalPaymentData::GiftCard { details } => {
Self::GiftCard(Box::new(GiftCardResponse { details }))
}
AdditionalPaymentData::CardRedirect { details } => {
Self::CardRedirect(Box::new(CardRedirectResponse { details }))
}
AdditionalPaymentData::CardToken { details } => {
Self::CardToken(Box::new(CardTokenResponse { details }))
}
AdditionalPaymentData::OpenBanking { details } => {
Self::OpenBanking(Box::new(OpenBankingResponse { details }))
}
AdditionalPaymentData::MobilePayment { details } => {
Self::MobilePayment(Box::new(MobilePaymentResponse { details }))
}
}
}
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct PgRedirectResponse {
pub payment_id: id_type::PaymentId,
pub status: api_enums::IntentStatus,
pub gateway_id: String,
pub customer_id: Option<id_type::CustomerId>,
pub amount: Option<MinorUnit>,
}
#[cfg(feature = "v1")]
#[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)]
pub struct RedirectionResponse {
pub return_url: String,
pub params: Vec<(String, String)>,
pub return_url_with_query_params: String,
pub http_method: String,
pub headers: Vec<(String, String)>,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)]
pub struct RedirectionResponse {
pub return_url_with_query_params: String,
}
#[derive(Debug, serde::Deserialize)]
pub struct PaymentsResponseForm {
pub transaction_id: String,
// pub transaction_reference_id: String,
pub merchant_id: id_type::MerchantId,
pub order_id: String,
}
#[cfg(feature = "v1")]
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct PaymentsRetrieveRequest {
/// The type of ID (ex: payment intent id, payment attempt id or connector txn id)
#[schema(value_type = String)]
pub resource_id: PaymentIdType,
/// The identifier for the Merchant Account.
#[schema(value_type = Option<String>)]
pub merchant_id: Option<id_type::MerchantId>,
/// Decider to enable or disable the connector call for retrieve request
pub force_sync: bool,
/// Optional query parameters that might be specific to a connector or flow, passed through during the retrieve operation. Use with caution and refer to specific connector documentation if applicable.
pub param: Option<String>,
/// Optionally specifies the connector to be used for a 'force_sync' retrieve operation. If provided, Hyperswitch will attempt to sync the payment status from this specific connector.
pub connector: Option<String>,
/// Merchant connector details used to make payments.
#[schema(value_type = Option<MerchantConnectorDetailsWrap>)]
pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,
/// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK
pub client_secret: Option<String>,
/// If enabled provides list of captures linked to latest attempt
pub expand_captures: Option<bool>,
/// If enabled provides list of attempts linked to payment intent
pub expand_attempts: Option<bool>,
/// If enabled, provides whole connector response
pub all_keys_required: Option<bool>,
}
#[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct OrderDetailsWithAmount {
/// Name of the product that is being purchased
#[schema(max_length = 255, example = "shirt")]
pub product_name: String,
/// The quantity of the product to be purchased
#[schema(example = 1)]
pub quantity: u16,
/// the amount per quantity of product
#[schema(value_type = i64)]
pub amount: MinorUnit,
/// tax rate applicable to the product
pub tax_rate: Option<f64>,
/// total tax amount applicable to the product
#[schema(value_type = Option<i64>)]
pub total_tax_amount: Option<MinorUnit>,
// Does the order includes shipping
pub requires_shipping: Option<bool>,
/// The image URL of the product
pub product_img_link: Option<String>,
/// ID of the product that is being purchased
pub product_id: Option<String>,
/// Category of the product that is being purchased
pub category: Option<String>,
/// Sub category of the product that is being purchased
pub sub_category: Option<String>,
/// Brand of the product that is being purchased
pub brand: Option<String>,
/// Type of the product that is being purchased
pub product_type: Option<ProductType>,
/// The tax code for the product
pub product_tax_code: Option<String>,
/// Description for the item
pub description: Option<String>,
/// Stock Keeping Unit (SKU) or the item identifier for this item.
pub sku: Option<String>,
/// Universal Product Code for the item.
pub upc: Option<String>,
/// Code describing a commodity or a group of commodities pertaining to goods classification.
pub commodity_code: Option<String>,
/// Unit of measure used for the item quantity.
pub unit_of_measure: Option<String>,
/// Total amount for the item.
#[schema(value_type = Option<i64>)]
pub total_amount: Option<MinorUnit>, // total_amount,
/// Discount amount applied to this item.
#[schema(value_type = Option<i64>)]
pub unit_discount_amount: Option<MinorUnit>,
}
impl masking::SerializableSecret for OrderDetailsWithAmount {}
#[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct RedirectResponse {
#[schema(value_type = Option<String>)]
pub param: Option<Secret<String>>,
#[schema(value_type = Option<Object>)]
pub json_payload: Option<pii::SecretSerdeValue>,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct PaymentsSessionRequest {}
#[cfg(feature = "v1")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct PaymentsSessionRequest {
/// The identifier for the payment
#[schema(value_type = String)]
pub payment_id: id_type::PaymentId,
/// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK
pub client_secret: String,
/// The list of the supported wallets
#[schema(value_type = Vec<PaymentMethodType>)]
pub wallets: Vec<api_enums::PaymentMethodType>,
/// Merchant connector details used to make payments.
#[schema(value_type = Option<MerchantConnectorDetailsWrap>)]
pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct PaymentsUpdateMetadataRequest {
/// The unique identifier for the payment
#[serde(skip_deserializing)]
#[schema(value_type = String)]
pub payment_id: id_type::PaymentId,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Object, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)]
pub metadata: pii::SecretSerdeValue,
}
#[derive(Debug, serde::Serialize, Clone, ToSchema)]
pub struct PaymentsUpdateMetadataResponse {
/// The identifier for the payment
#[schema(value_type = String)]
pub payment_id: id_type::PaymentId,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct PaymentsPostSessionTokensRequest {
/// The unique identifier for the payment
#[serde(skip_deserializing)]
#[schema(value_type = String)]
pub payment_id: id_type::PaymentId,
/// It's a token used for client side verification.
#[schema(value_type = String)]
pub client_secret: Secret<String>,
/// Payment method type
#[schema(value_type = PaymentMethodType)]
pub payment_method_type: api_enums::PaymentMethodType,
/// The payment method that is to be used for the payment
#[schema(value_type = PaymentMethod, example = "card")]
pub payment_method: api_enums::PaymentMethod,
}
#[derive(Debug, serde::Serialize, Clone, ToSchema)]
pub struct PaymentsPostSessionTokensResponse {
/// The identifier for the payment
#[schema(value_type = String)]
pub payment_id: id_type::PaymentId,
/// Additional information required for redirection
pub next_action: Option<NextActionData>,
#[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")]
pub status: api_enums::IntentStatus,
}
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
pub struct PaymentsDynamicTaxCalculationRequest {
/// The unique identifier for the payment
#[serde(skip_deserializing)]
#[schema(value_type = String)]
pub payment_id: id_type::PaymentId,
/// The shipping address for the payment
pub shipping: Address,
/// Client Secret
#[schema(value_type = String)]
pub client_secret: Secret<String>,
/// Payment method type
#[schema(value_type = PaymentMethodType)]
pub payment_method_type: api_enums::PaymentMethodType,
/// Session Id
pub session_id: Option<String>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
pub struct PaymentsDynamicTaxCalculationResponse {
/// The identifier for the payment
#[schema(value_type = String)]
pub payment_id: id_type::PaymentId,
/// net amount = amount + order_tax_amount + shipping_cost
pub net_amount: MinorUnit,
/// order tax amount calculated by tax connectors
pub order_tax_amount: Option<MinorUnit>,
/// shipping cost for the order
pub shipping_cost: Option<MinorUnit>,
/// amount in Base Unit display format
pub display_amount: DisplayAmountOnSdk,
}
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
pub struct DisplayAmountOnSdk {
/// net amount = amount + order_tax_amount + shipping_cost
#[schema(value_type = String)]
pub net_amount: StringMajorUnit,
/// order tax amount calculated by tax connectors
#[schema(value_type = String)]
pub order_tax_amount: Option<StringMajorUnit>,
/// shipping cost for the order
#[schema(value_type = String)]
pub shipping_cost: Option<StringMajorUnit>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct GpayAllowedMethodsParameters {
/// The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc)
pub allowed_auth_methods: Vec<String>,
/// The list of allowed card networks (ex: AMEX,JCB etc)
pub allowed_card_networks: Vec<String>,
/// Is billing address required
#[serde(skip_serializing_if = "Option::is_none")]
pub billing_address_required: Option<bool>,
/// Billing address parameters
#[serde(skip_serializing_if = "Option::is_none")]
pub billing_address_parameters: Option<GpayBillingAddressParameters>,
/// Whether assurance details are required
#[serde(skip_serializing_if = "Option::is_none")]
pub assurance_details_required: Option<bool>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct GpayBillingAddressParameters {
/// Is billing phone number required
pub phone_number_required: bool,
/// Billing address format
pub format: GpayBillingAddressFormat,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub enum GpayBillingAddressFormat {
FULL,
MIN,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct GpayTokenParameters {
/// The name of the connector
#[serde(skip_serializing_if = "Option::is_none")]
pub gateway: Option<String>,
/// The merchant ID registered in the connector associated
#[serde(skip_serializing_if = "Option::is_none")]
pub gateway_merchant_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")]
pub stripe_version: Option<String>,
#[serde(
skip_serializing_if = "Option::is_none",
rename = "stripe:publishableKey"
)]
pub stripe_publishable_key: Option<String>,
/// The protocol version for encryption
#[serde(skip_serializing_if = "Option::is_none")]
pub protocol_version: Option<String>,
/// The public key provided by the merchant
#[serde(skip_serializing_if = "Option::is_none")]
#[schema(value_type = Option<String>)]
pub public_key: Option<Secret<String>>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct GpayTokenizationSpecification {
/// The token specification type(ex: PAYMENT_GATEWAY)
#[serde(rename = "type")]
pub token_specification_type: String,
/// The parameters for the token specification Google Pay
pub parameters: GpayTokenParameters,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct GpayAllowedPaymentMethods {
/// The type of payment method
#[serde(rename = "type")]
pub payment_method_type: String,
/// The parameters Google Pay requires
pub parameters: GpayAllowedMethodsParameters,
/// The tokenization specification for Google Pay
pub tokenization_specification: GpayTokenizationSpecification,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct GpayTransactionInfo {
/// The country code
#[schema(value_type = CountryAlpha2, example = "US")]
pub country_code: api_enums::CountryAlpha2,
/// The currency code
#[schema(value_type = Currency, example = "USD")]
pub currency_code: api_enums::Currency,
/// The total price status (ex: 'FINAL')
pub total_price_status: String,
/// The total price
#[schema(value_type = String, example = "38.02")]
pub total_price: StringMajorUnit,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct GpayMerchantInfo {
/// The merchant Identifier that needs to be passed while invoking Gpay SDK
#[serde(skip_serializing_if = "Option::is_none")]
pub merchant_id: Option<String>,
/// The name of the merchant that needs to be displayed on Gpay PopUp
pub merchant_name: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GpayMetaData {
pub merchant_info: GpayMerchantInfo,
pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GpaySessionTokenData {
#[serde(rename = "google_pay")]
pub data: GpayMetaData,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PazeSessionTokenData {
#[serde(rename = "paze")]
pub data: PazeMetadata,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PazeMetadata {
pub client_id: String,
pub client_name: String,
pub client_profile_id: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SamsungPayCombinedMetadata {
// This is to support the Samsung Pay decryption flow with application credentials,
// where the private key, certificates, or any other information required for decryption
// will be obtained from the application configuration.
ApplicationCredentials(SamsungPayApplicationCredentials),
MerchantCredentials(SamsungPayMerchantCredentials),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SamsungPaySessionTokenData {
#[serde(rename = "samsung_pay")]
pub data: SamsungPayCombinedMetadata,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SamsungPayMerchantCredentials {
pub service_id: String,
pub merchant_display_name: String,
pub merchant_business_country: api_enums::CountryAlpha2,
pub allowed_brands: Vec<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SamsungPayApplicationCredentials {
pub merchant_display_name: String,
pub merchant_business_country: api_enums::CountryAlpha2,
pub allowed_brands: Vec<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaypalSdkMetaData {
pub client_id: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaypalSdkSessionTokenData {
#[serde(rename = "paypal_sdk")]
pub data: PaypalSdkMetaData,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplepaySessionRequest {
|
crates/api_models/src/payments.rs#chunk8
|
api_models
|
chunk
| null | null | null | 8,192
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/riskified/transformers/auth.rs
// Module: hyperswitch_connectors
// Public structs: 1
use error_stack;
use hyperswitch_domain_models::router_data::ConnectorAuthType;
use hyperswitch_interfaces::errors::ConnectorError;
use masking::{ExposeInterface, Secret};
pub struct RiskifiedAuthType {
pub secret_token: Secret<String>,
pub domain_name: String,
}
impl TryFrom<&ConnectorAuthType> for RiskifiedAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
secret_token: api_key.to_owned(),
domain_name: key1.to_owned().expose(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
|
crates/hyperswitch_connectors/src/connectors/riskified/transformers/auth.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 209
| null | null | null | null | null | null | null |
// Implementation: impl IncomingWebhook for for Billwerk
// File: crates/hyperswitch_connectors/src/connectors/billwerk.rs
// Module: hyperswitch_connectors
// Methods: 3 total (0 public)
impl IncomingWebhook for for Billwerk
|
crates/hyperswitch_connectors/src/connectors/billwerk.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 56
| null |
Billwerk
|
IncomingWebhook for
| 3
| 0
| null | null |
// Module Structure
// File: crates/hyperswitch_connectors/src/connectors/plaid.rs
// Module: hyperswitch_connectors
// Public submodules:
pub mod transformers;
|
crates/hyperswitch_connectors/src/connectors/plaid.rs
|
hyperswitch_connectors
|
module_structure
| null | null | null | 38
| null | null | null | null | null | 1
| 0
|
// Struct: RedsysTransaction
// File: crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct RedsysTransaction
|
crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
RedsysTransaction
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// File: crates/router/tests/connectors/worldline.rs
// Module: router
use std::str::FromStr;
use hyperswitch_domain_models::address::{Address, AddressDetails};
use masking::Secret;
use router::{
connector::Worldline,
core::errors,
types::{self, storage::enums, PaymentAddress},
};
use crate::{
connector_auth::ConnectorAuthentication,
utils::{self, ConnectorActions, PaymentInfo},
};
struct WorldlineTest;
impl ConnectorActions for WorldlineTest {}
impl utils::Connector for WorldlineTest {
fn get_data(&self) -> types::api::ConnectorData {
utils::construct_connector_data_old(
Box::new(&Worldline),
types::Connector::Worldline,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
ConnectorAuthentication::new()
.worldline
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
String::from("worldline")
}
}
impl WorldlineTest {
fn get_payment_info() -> Option<PaymentInfo> {
Some(PaymentInfo {
address: Some(PaymentAddress::new(
None,
Some(Address {
address: Some(AddressDetails {
country: Some(api_models::enums::CountryAlpha2::US),
first_name: Some(Secret::new(String::from("John"))),
last_name: Some(Secret::new(String::from("Dough"))),
..Default::default()
}),
phone: None,
email: None,
}),
None,
None,
)),
..Default::default()
})
}
fn get_payment_authorize_data(
card_number: &str,
card_exp_month: &str,
card_exp_year: &str,
card_cvc: &str,
capture_method: enums::CaptureMethod,
) -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount: 3500,
currency: enums::Currency::USD,
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_number: cards::CardNumber::from_str(card_number).unwrap(),
card_exp_month: Secret::new(card_exp_month.to_string()),
card_exp_year: Secret::new(card_exp_year.to_string()),
card_cvc: Secret::new(card_cvc.to_string()),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: Some(Secret::new("nick_name".into())),
card_holder_name: Some(Secret::new("card holder name".into())),
co_badged_card_data: None,
}),
confirm: true,
statement_descriptor_suffix: None,
statement_descriptor: None,
setup_future_usage: None,
mandate_id: None,
off_session: None,
setup_mandate_details: None,
capture_method: Some(capture_method),
browser_info: None,
order_details: None,
order_category: None,
email: None,
customer_name: None,
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
payment_experience: None,
payment_method_type: None,
router_return_url: None,
webhook_url: None,
complete_authorize_url: None,
customer_id: None,
surcharge_details: None,
request_incremental_authorization: false,
metadata: None,
authentication_data: None,
customer_acceptance: None,
..utils::PaymentAuthorizeType::default().0
})
}
}
#[actix_web::test]
async fn should_requires_manual_authorization() {
let authorize_data = WorldlineTest::get_payment_authorize_data(
"5424 1802 7979 1732",
"10",
"25",
"123",
enums::CaptureMethod::Manual,
);
let response = WorldlineTest {}
.authorize_payment(authorize_data, WorldlineTest::get_payment_info())
.await;
assert_eq!(response.unwrap().status, enums::AttemptStatus::Authorized);
}
#[actix_web::test]
async fn should_auto_authorize_and_request_capture() {
let authorize_data = WorldlineTest::get_payment_authorize_data(
"4012000033330026",
"10",
"2025",
"123",
enums::CaptureMethod::Automatic,
);
let response = WorldlineTest {}
.make_payment(authorize_data, WorldlineTest::get_payment_info())
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Pending);
}
#[actix_web::test]
async fn should_throw_not_implemented_for_unsupported_issuer() {
let authorize_data = WorldlineTest::get_payment_authorize_data(
"630495060000000000",
"10",
"25",
"123",
enums::CaptureMethod::Automatic,
);
let response = WorldlineTest {}
.make_payment(authorize_data, WorldlineTest::get_payment_info())
.await;
assert_eq!(
*response.unwrap_err().current_context(),
errors::ConnectorError::NotSupported {
message: "Maestro".to_string(),
connector: "worldline",
}
)
}
#[actix_web::test]
async fn should_throw_missing_required_field_for_country() {
let authorize_data = WorldlineTest::get_payment_authorize_data(
"4012 0000 3333 0026",
"10",
"2025",
"123",
enums::CaptureMethod::Automatic,
);
let response = WorldlineTest {}
.make_payment(
authorize_data,
Some(PaymentInfo {
address: Some(PaymentAddress::new(None, None, None, None)),
..Default::default()
}),
)
.await;
assert_eq!(
*response.unwrap_err().current_context(),
errors::ConnectorError::MissingRequiredField {
field_name: "billing.address.country"
}
)
}
#[actix_web::test]
async fn should_fail_payment_for_invalid_cvc() {
let authorize_data = WorldlineTest::get_payment_authorize_data(
"4012000033330026",
"10",
"25",
"",
enums::CaptureMethod::Automatic,
);
let response = WorldlineTest {}
.make_payment(authorize_data, WorldlineTest::get_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"NULL VALUE NOT ALLOWED FOR cardPaymentMethodSpecificInput.card.cvv".to_string(),
);
}
#[actix_web::test]
async fn should_sync_manual_auth_payment() {
let connector = WorldlineTest {};
let authorize_data = WorldlineTest::get_payment_authorize_data(
"4012 0000 3333 0026",
"10",
"2025",
"123",
enums::CaptureMethod::Manual,
);
let response = connector
.authorize_payment(authorize_data, WorldlineTest::get_payment_info())
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized);
let connector_payment_id =
utils::get_connector_transaction_id(response.response).unwrap_or_default();
let sync_response = connector
.sync_payment(
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
connector_payment_id,
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
}
#[actix_web::test]
async fn should_sync_auto_auth_payment() {
let connector = WorldlineTest {};
let authorize_data = WorldlineTest::get_payment_authorize_data(
"4012000033330026",
"10",
"25",
"123",
enums::CaptureMethod::Automatic,
);
let response = connector
.make_payment(authorize_data, WorldlineTest::get_payment_info())
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Pending);
let connector_payment_id =
utils::get_connector_transaction_id(response.response).unwrap_or_default();
let sync_response = connector
.sync_payment(
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
connector_payment_id,
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
}
#[actix_web::test]
async fn should_capture_authorized_payment() {
let connector = WorldlineTest {};
let authorize_data = WorldlineTest::get_payment_authorize_data(
"4012 0000 3333 0026",
"10",
"2025",
"123",
enums::CaptureMethod::Manual,
);
let response = connector
.authorize_payment(authorize_data, WorldlineTest::get_payment_info())
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized);
let connector_payment_id =
utils::get_connector_transaction_id(response.response).unwrap_or_default();
let capture_response = WorldlineTest {}
.capture_payment(connector_payment_id, None, None)
.await
.unwrap();
assert_eq!(
capture_response.status,
enums::AttemptStatus::CaptureInitiated
);
}
#[actix_web::test]
async fn should_fail_capture_payment() {
let capture_response = WorldlineTest {}
.capture_payment("123456789".to_string(), None, None)
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
"UNKNOWN_PAYMENT_ID".to_string()
);
}
#[actix_web::test]
async fn should_cancel_unauthorized_payment() {
let connector = WorldlineTest {};
let authorize_data = WorldlineTest::get_payment_authorize_data(
"4012 0000 3333 0026",
"10",
"25",
"123",
enums::CaptureMethod::Manual,
);
let response = connector
.authorize_payment(authorize_data, WorldlineTest::get_payment_info())
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized);
let connector_payment_id =
utils::get_connector_transaction_id(response.response).unwrap_or_default();
let cancel_response = connector
.void_payment(connector_payment_id, None, None)
.await
.unwrap();
assert_eq!(cancel_response.status, enums::AttemptStatus::Voided);
}
#[actix_web::test]
async fn should_cancel_uncaptured_payment() {
let connector = WorldlineTest {};
let authorize_data = WorldlineTest::get_payment_authorize_data(
"4012000033330026",
"10",
"2025",
"123",
enums::CaptureMethod::Automatic,
);
let response = connector
.make_payment(authorize_data, WorldlineTest::get_payment_info())
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Pending);
let connector_payment_id =
utils::get_connector_transaction_id(response.response).unwrap_or_default();
let cancel_response = connector
.void_payment(connector_payment_id, None, None)
.await
.unwrap();
assert_eq!(cancel_response.status, enums::AttemptStatus::Voided);
}
#[actix_web::test]
async fn should_fail_cancel_with_invalid_payment_id() {
let response = WorldlineTest {}
.void_payment("123456789".to_string(), None, None)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"UNKNOWN_PAYMENT_ID".to_string(),
);
}
#[actix_web::test]
async fn should_fail_refund_with_invalid_payment_status() {
let connector = WorldlineTest {};
let authorize_data = WorldlineTest::get_payment_authorize_data(
"4012 0000 3333 0026",
"10",
"25",
"123",
enums::CaptureMethod::Manual,
);
let response = connector
.authorize_payment(authorize_data, WorldlineTest::get_payment_info())
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized);
let connector_payment_id =
utils::get_connector_transaction_id(response.response).unwrap_or_default();
let refund_response = connector
.refund_payment(connector_payment_id, None, None)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap_err().message,
"ORDER WITHOUT REFUNDABLE PAYMENTS".to_string(),
);
}
|
crates/router/tests/connectors/worldline.rs
|
router
|
full_file
| null | null | null | 2,984
| null | null | null | null | null | null | null |
// Function: comparison_type
// File: crates/euclid/src/frontend/ast/parser.rs
// Module: euclid
pub fn comparison_type(input: &str) -> ParseResult<&str, ast::ComparisonType>
|
crates/euclid/src/frontend/ast/parser.rs
|
euclid
|
function_signature
| null | null | null | 46
|
comparison_type
| null | null | null | null | null | null |
// Function: get_forex_enabled
// File: crates/analytics/src/lib.rs
// Module: analytics
pub fn get_forex_enabled(&self) -> bool
|
crates/analytics/src/lib.rs
|
analytics
|
function_signature
| null | null | null | 34
|
get_forex_enabled
| null | null | null | null | null | null |
// Function: user_from_email
// File: crates/router/src/core/user.rs
// Module: router
pub fn user_from_email(
state: SessionState,
req: user_api::UserFromEmailRequest,
) -> UserResponse<user_api::TokenResponse>
|
crates/router/src/core/user.rs
|
router
|
function_signature
| null | null | null | 56
|
user_from_email
| null | null | null | null | null | null |
// Implementation: impl api::MandateSetup for for Facilitapay
// File: crates/hyperswitch_connectors/src/connectors/facilitapay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::MandateSetup for for Facilitapay
|
crates/hyperswitch_connectors/src/connectors/facilitapay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 68
| null |
Facilitapay
|
api::MandateSetup for
| 0
| 0
| null | null |
// Struct: PayoneAuthType
// File: crates/hyperswitch_connectors/src/connectors/payone/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PayoneAuthType
|
crates/hyperswitch_connectors/src/connectors/payone/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PayoneAuthType
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Function: spawn_async_lineage_context_update_to_db
// File: crates/router/src/utils/user.rs
// Module: router
pub fn spawn_async_lineage_context_update_to_db(
state: &SessionState,
user_id: &str,
lineage_context: LineageContext,
)
|
crates/router/src/utils/user.rs
|
router
|
function_signature
| null | null | null | 61
|
spawn_async_lineage_context_update_to_db
| null | null | null | null | null | null |
// Struct: SupportedConnectorsForMandate
// File: crates/payment_methods/src/configs/settings.rs
// Module: payment_methods
// Implementations: 0
pub struct SupportedConnectorsForMandate
|
crates/payment_methods/src/configs/settings.rs
|
payment_methods
|
struct_definition
|
SupportedConnectorsForMandate
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// Struct: ProductionAgreementValue
// File: crates/router/src/types/domain/user/dashboard_metadata.rs
// Module: router
// Implementations: 0
pub struct ProductionAgreementValue
|
crates/router/src/types/domain/user/dashboard_metadata.rs
|
router
|
struct_definition
|
ProductionAgreementValue
| 0
|
[] | 39
| null | null | null | null | null | null | null |
// Module Structure
// File: crates/drainer/src/lib.rs
// Module: drainer
// Public submodules:
pub mod errors;
pub mod logger;
pub mod services;
pub mod settings;
|
crates/drainer/src/lib.rs
|
drainer
|
module_structure
| null | null | null | 41
| null | null | null | null | null | 4
| 0
|
// File: crates/hyperswitch_connectors/src/connectors/gigadat.rs
// Module: hyperswitch_connectors
// Public functions: 1
// Public structs: 1
pub mod transformers;
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
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, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts as api_consts, errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use lazy_static::lazy_static;
use masking::{Mask, PeekInterface};
use transformers as gigadat;
use uuid::Uuid;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Gigadat {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Gigadat {
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Gigadat {}
impl api::PaymentSession for Gigadat {}
impl api::ConnectorAccessToken for Gigadat {}
impl api::MandateSetup for Gigadat {}
impl api::PaymentAuthorize for Gigadat {}
impl api::PaymentSync for Gigadat {}
impl api::PaymentCapture for Gigadat {}
impl api::PaymentVoid for Gigadat {}
impl api::Refund for Gigadat {}
impl api::RefundExecute for Gigadat {}
impl api::RefundSync for Gigadat {}
impl api::PaymentToken for Gigadat {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Gigadat
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Gigadat
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 Gigadat {
fn id(&self) -> &'static str {
"gigadat"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.gigadat.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = gigadat::GigadatAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_key = format!(
"{}:{}",
auth.access_token.peek(),
auth.security_token.peek()
);
let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth_header.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: gigadat::GigadatErrorResponse = res
.response
.parse_struct("GigadatErrorResponse")
.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: res.status_code,
code: response.err.clone(),
message: response.err.clone(),
reason: Some(response.err).clone(),
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 Gigadat {
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 Gigadat {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Gigadat {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Gigadat {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Gigadat {
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 auth = gigadat::GigadatAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(format!(
"{}api/payment-token/{}",
self.base_url(connectors),
auth.campaign_id.peek()
))
}
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 = gigadat::GigadatRouterData::from((amount, req));
let connector_req = gigadat::GigadatCpiRequest::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: gigadat::GigadatPaymentResponse = res
.response
.parse_struct("GigadatPaymentResponse")
.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 Gigadat {
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 transaction_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}api/transactions/{transaction_id}",
self.base_url(connectors)
))
}
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: gigadat::GigadatTransactionStatusResponse = res
.response
.parse_struct("gigadat 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 Gigadat {
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> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
}
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: gigadat::GigadatTransactionStatusResponse = res
.response
.parse_struct("Gigadat 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 Gigadat {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Gigadat {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = gigadat::GigadatAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_key = format!(
"{}:{}",
auth.access_token.peek(),
auth.security_token.peek()
);
let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key));
Ok(vec![
(
headers::AUTHORIZATION.to_string(),
auth_header.into_masked(),
),
(
headers::IDEMPOTENCY_KEY.to_string(),
Uuid::new_v4().to_string().into_masked(),
),
])
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}refunds", self.base_url(connectors),))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = gigadat::GigadatRouterData::from((refund_amount, req));
let connector_req = gigadat::GigadatRefundRequest::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: gigadat::RefundResponse = res
.response
.parse_struct("gigadat 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> {
let response: gigadat::GigadatRefundErrorResponse = res
.response
.parse_struct("GigadatRefundErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let code = response
.error
.first()
.and_then(|error_detail| error_detail.code.clone())
.unwrap_or(api_consts::NO_ERROR_CODE.to_string());
let message = response
.error
.first()
.map(|error_detail| error_detail.detail.clone())
.unwrap_or(api_consts::NO_ERROR_MESSAGE.to_string());
Ok(ErrorResponse {
status_code: res.status_code,
code,
message,
reason: Some(response.message).clone(),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Gigadat {
//Gigadat does not support Refund Sync
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Gigadat {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
lazy_static! {
static ref GIGADAT_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
let supported_capture_methods = vec![enums::CaptureMethod::Automatic];
let mut gigadat_supported_payment_methods = SupportedPaymentMethods::new();
gigadat_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Interac,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
gigadat_supported_payment_methods
};
static ref GIGADAT_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Gigadat",
description: "Gigadat is a financial services product that offers a single API for payment integration. It provides Canadian businesses with a secure payment gateway and various pay-in and pay-out solutions, including Interac e-Transfer",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static ref GIGADAT_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new();
}
impl ConnectorSpecifications for Gigadat {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*GIGADAT_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*GIGADAT_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&*GIGADAT_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates/hyperswitch_connectors/src/connectors/gigadat.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 4,914
| null | null | null | null | null | null | null |
// Function: get_id
// File: crates/diesel_models/src/merchant_account.rs
// Module: diesel_models
// Documentation: Get the unique identifier of MerchantAccount
pub fn get_id(&self) -> &common_utils::id_type::MerchantId
|
crates/diesel_models/src/merchant_account.rs
|
diesel_models
|
function_signature
| null | null | null | 53
|
get_id
| null | null | null | null | null | null |
// Struct: Theme
// File: crates/diesel_models/src/user/theme.rs
// Module: diesel_models
// Implementations: 1
pub struct Theme
|
crates/diesel_models/src/user/theme.rs
|
diesel_models
|
struct_definition
|
Theme
| 1
|
[] | 33
| null | null | null | null | null | null | null |
// Struct: RefundsCreateRequest
// File: crates/api_models/src/refunds.rs
// Module: api_models
// Implementations: 0
pub struct RefundsCreateRequest
|
crates/api_models/src/refunds.rs
|
api_models
|
struct_definition
|
RefundsCreateRequest
| 0
|
[] | 38
| null | null | null | null | null | null | null |
// Implementation: impl super::disputes::metrics::DisputeMetricAnalytics for for SqlxClient
// File: crates/analytics/src/sqlx.rs
// Module: analytics
// Methods: 0 total (0 public)
impl super::disputes::metrics::DisputeMetricAnalytics for for SqlxClient
|
crates/analytics/src/sqlx.rs
|
analytics
|
impl_block
| null | null | null | 66
| null |
SqlxClient
|
super::disputes::metrics::DisputeMetricAnalytics for
| 0
| 0
| null | null |
// Struct: RequiredFieldInfo
// File: crates/api_models/src/payment_methods.rs
// Module: api_models
// Implementations: 0
pub struct RequiredFieldInfo
|
crates/api_models/src/payment_methods.rs
|
api_models
|
struct_definition
|
RequiredFieldInfo
| 0
|
[] | 36
| null | null | null | null | null | null | null |
// Implementation: impl EuclidAnalysable for for ConnectorSelection
// File: crates/api_models/src/routing.rs
// Module: api_models
// Methods: 1 total (0 public)
impl EuclidAnalysable for for ConnectorSelection
|
crates/api_models/src/routing.rs
|
api_models
|
impl_block
| null | null | null | 51
| null |
ConnectorSelection
|
EuclidAnalysable for
| 1
| 0
| null | null |
// Struct: PaymentsGenericRequestWithResourceId
// File: crates/router/src/routes/payments.rs
// Module: router
// Implementations: 2
// Traits: GetLockingInput, common_utils::events::ApiEventMetric
pub struct PaymentsGenericRequestWithResourceId<T: serde::Serialize>
|
crates/router/src/routes/payments.rs
|
router
|
struct_definition
|
PaymentsGenericRequestWithResourceId
| 2
|
[
"GetLockingInput",
"common_utils::events::ApiEventMetric"
] | 62
| null | null | null | null | null | null | null |
// Function: update_router_data_with_access_token_result
// File: crates/router/src/core/payments/access_token.rs
// Module: router
// Documentation: After we get the access token, check if there was an error and if the flow should proceed further Returns bool true - Everything is well, continue with the flow false - There was an error, cannot proceed further
pub fn update_router_data_with_access_token_result<F, Req, Res>(
add_access_token_result: &types::AddAccessTokenResult,
router_data: &mut types::RouterData<F, Req, Res>,
call_connector_action: &payments::CallConnectorAction,
) -> bool
|
crates/router/src/core/payments/access_token.rs
|
router
|
function_signature
| null | null | null | 134
|
update_router_data_with_access_token_result
| null | null | null | null | null | null |
// Function: update_algorithm_id
// File: crates/api_models/src/routing.rs
// Module: api_models
pub fn update_algorithm_id(
&mut self,
new_id: common_utils::id_type::RoutingId,
enabled_feature: DynamicRoutingFeatures,
dynamic_routing_type: DynamicRoutingType,
)
|
crates/api_models/src/routing.rs
|
api_models
|
function_signature
| null | null | null | 67
|
update_algorithm_id
| null | null | null | null | null | null |
// Struct: SecureAcceptance
// File: crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct SecureAcceptance
|
crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
SecureAcceptance
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Implementation: impl EuclidDirFilter for for SurchargeDecisionConfigs
// File: crates/api_models/src/surcharge_decision_configs.rs
// Module: api_models
// Methods: 0 total (0 public)
impl EuclidDirFilter for for SurchargeDecisionConfigs
|
crates/api_models/src/surcharge_decision_configs.rs
|
api_models
|
impl_block
| null | null | null | 56
| null |
SurchargeDecisionConfigs
|
EuclidDirFilter for
| 0
| 0
| null | null |
// Struct: PaysafeApplepayPayment
// File: crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaysafeApplepayPayment
|
crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaysafeApplepayPayment
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Implementation: impl FraudCheckCheckout for for Signifyd
// File: crates/hyperswitch_connectors/src/connectors/signifyd.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl FraudCheckCheckout for for Signifyd
|
crates/hyperswitch_connectors/src/connectors/signifyd.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Signifyd
|
FraudCheckCheckout for
| 0
| 0
| null | null |
// Implementation: impl api::PaymentVoid for for Hipay
// File: crates/hyperswitch_connectors/src/connectors/hipay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Hipay
|
crates/hyperswitch_connectors/src/connectors/hipay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Hipay
|
api::PaymentVoid for
| 0
| 0
| null | null |
// Implementation: impl api::RefundSync for for Stripebilling
// File: crates/hyperswitch_connectors/src/connectors/stripebilling.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundSync for for Stripebilling
|
crates/hyperswitch_connectors/src/connectors/stripebilling.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Stripebilling
|
api::RefundSync for
| 0
| 0
| null | null |
// Struct: CeleroErrorDetails
// File: crates/hyperswitch_connectors/src/connectors/celero/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 1
pub struct CeleroErrorDetails
|
crates/hyperswitch_connectors/src/connectors/celero/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CeleroErrorDetails
| 1
|
[] | 50
| null | null | null | null | null | null | null |
// Function: new
// File: crates/hyperswitch_connectors/src/connectors/barclaycard.rs
// Module: hyperswitch_connectors
pub fn new() -> &'static Self
|
crates/hyperswitch_connectors/src/connectors/barclaycard.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 40
|
new
| null | null | null | null | null | null |
// Struct: DatatransRefundRequest
// File: crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct DatatransRefundRequest
|
crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
DatatransRefundRequest
| 0
|
[] | 54
| null | null | null | null | null | null | null |
// Function: get_refund_status
// File: crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs
// Module: hyperswitch_connectors
pub fn get_refund_status(&self) -> enums::RefundStatus
|
crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 52
|
get_refund_status
| null | null | null | null | null | null |
// Struct: AuthEventMetricsAccumulator
// File: crates/analytics/src/auth_events/accumulator.rs
// Module: analytics
// Implementations: 1
pub struct AuthEventMetricsAccumulator
|
crates/analytics/src/auth_events/accumulator.rs
|
analytics
|
struct_definition
|
AuthEventMetricsAccumulator
| 1
|
[] | 43
| null | null | null | null | null | null | null |
// Struct: PaymentLink
// File: crates/router/src/routes/app.rs
// Module: router
// Implementations: 1
pub struct PaymentLink
|
crates/router/src/routes/app.rs
|
router
|
struct_definition
|
PaymentLink
| 1
|
[] | 32
| null | null | null | null | null | null | null |
// Implementation: impl Customers
// File: crates/router/src/routes/app.rs
// Module: router
// Methods: 1 total (1 public)
impl Customers
|
crates/router/src/routes/app.rs
|
router
|
impl_block
| null | null | null | 33
| null |
Customers
| null | 1
| 1
| null | null |
// File: crates/analytics/src/sdk_events/core.rs
// Module: analytics
// Public functions: 3
use std::collections::HashMap;
use api_models::analytics::{
sdk_events::{
MetricsBucketResponse, SdkEventMetrics, SdkEventMetricsBucketIdentifier, SdkEventsRequest,
},
AnalyticsMetadata, GetSdkEventFiltersRequest, GetSdkEventMetricRequest, MetricsResponse,
SdkEventFiltersResponse,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use router_env::{instrument, logger, tracing};
use super::{
events::{get_sdk_event, SdkEventsResult},
SdkEventMetricsAccumulator,
};
use crate::{
errors::{AnalyticsError, AnalyticsResult},
sdk_events::SdkEventMetricAccumulator,
types::FiltersError,
AnalyticsProvider,
};
#[instrument(skip_all)]
pub async fn sdk_events_core(
pool: &AnalyticsProvider,
req: SdkEventsRequest,
publishable_key: &String,
) -> AnalyticsResult<Vec<SdkEventsResult>> {
match pool {
AnalyticsProvider::Sqlx(_) => Err(FiltersError::NotImplemented(
"SDK Events not implemented for SQLX",
))
.attach_printable("SQL Analytics is not implemented for Sdk Events"),
AnalyticsProvider::Clickhouse(pool) => get_sdk_event(publishable_key, req, pool).await,
AnalyticsProvider::CombinedSqlx(_sqlx_pool, ckh_pool)
| AnalyticsProvider::CombinedCkh(_sqlx_pool, ckh_pool) => {
get_sdk_event(publishable_key, req, ckh_pool).await
}
}
.switch()
}
#[instrument(skip_all)]
pub async fn get_metrics(
pool: &AnalyticsProvider,
publishable_key: &String,
req: GetSdkEventMetricRequest,
) -> AnalyticsResult<MetricsResponse<MetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<
SdkEventMetricsBucketIdentifier,
SdkEventMetricsAccumulator,
> = HashMap::new();
let mut set = tokio::task::JoinSet::new();
for metric_type in req.metrics.iter().cloned() {
let req = req.clone();
let publishable_key_scoped = publishable_key.to_owned();
let pool = pool.clone();
set.spawn(async move {
let data = pool
.get_sdk_event_metrics(
&metric_type,
&req.group_by_names.clone(),
&publishable_key_scoped,
&req.filters,
req.time_series.map(|t| t.granularity),
&req.time_range,
)
.await
.change_context(AnalyticsError::UnknownError);
(metric_type, data)
});
}
while let Some((metric, data)) = set
.join_next()
.await
.transpose()
.change_context(AnalyticsError::UnknownError)?
{
logger::info!("Logging Result {:?}", data);
for (id, value) in data? {
let metrics_builder = metrics_accumulator.entry(id).or_default();
match metric {
SdkEventMetrics::PaymentAttempts => {
metrics_builder.payment_attempts.add_metrics_bucket(&value)
}
SdkEventMetrics::PaymentMethodsCallCount => metrics_builder
.payment_methods_call_count
.add_metrics_bucket(&value),
SdkEventMetrics::SdkRenderedCount => metrics_builder
.sdk_rendered_count
.add_metrics_bucket(&value),
SdkEventMetrics::SdkInitiatedCount => metrics_builder
.sdk_initiated_count
.add_metrics_bucket(&value),
SdkEventMetrics::PaymentMethodSelectedCount => metrics_builder
.payment_method_selected_count
.add_metrics_bucket(&value),
SdkEventMetrics::PaymentDataFilledCount => metrics_builder
.payment_data_filled_count
.add_metrics_bucket(&value),
SdkEventMetrics::AveragePaymentTime => metrics_builder
.average_payment_time
.add_metrics_bucket(&value),
SdkEventMetrics::LoadTime => metrics_builder.load_time.add_metrics_bucket(&value),
}
}
logger::debug!(
"Analytics Accumulated Results: metric: {}, results: {:#?}",
metric,
metrics_accumulator
);
}
let query_data: Vec<MetricsBucketResponse> = metrics_accumulator
.into_iter()
.map(|(id, val)| MetricsBucketResponse {
values: val.collect(),
dimensions: id,
})
.collect();
Ok(MetricsResponse {
query_data,
meta_data: [AnalyticsMetadata {
current_time_range: req.time_range,
}],
})
}
#[allow(dead_code)]
pub async fn get_filters(
pool: &AnalyticsProvider,
req: GetSdkEventFiltersRequest,
publishable_key: &String,
) -> AnalyticsResult<SdkEventFiltersResponse> {
use api_models::analytics::{sdk_events::SdkEventDimensions, SdkEventFilterValue};
use super::filters::get_sdk_event_filter_for_dimension;
use crate::sdk_events::filters::SdkEventFilter;
let mut res = SdkEventFiltersResponse::default();
for dim in req.group_by_names {
let values = match pool {
AnalyticsProvider::Sqlx(_pool) => Err(FiltersError::NotImplemented(
"SDK Events not implemented for SQLX",
))
.attach_printable("SQL Analytics is not implemented for SDK Events"),
AnalyticsProvider::Clickhouse(pool) => {
get_sdk_event_filter_for_dimension(dim, publishable_key, &req.time_range, pool)
.await
}
AnalyticsProvider::CombinedSqlx(_sqlx_pool, ckh_pool)
| AnalyticsProvider::CombinedCkh(_sqlx_pool, ckh_pool) => {
get_sdk_event_filter_for_dimension(dim, publishable_key, &req.time_range, ckh_pool)
.await
}
}
.change_context(AnalyticsError::UnknownError)?
.into_iter()
.filter_map(|fil: SdkEventFilter| match dim {
SdkEventDimensions::PaymentMethod => fil.payment_method,
SdkEventDimensions::Platform => fil.platform,
SdkEventDimensions::BrowserName => fil.browser_name,
SdkEventDimensions::Source => fil.source,
SdkEventDimensions::Component => fil.component,
SdkEventDimensions::PaymentExperience => fil.payment_experience,
})
.collect::<Vec<String>>();
res.query_data.push(SdkEventFilterValue {
dimension: dim,
values,
})
}
Ok(res)
}
|
crates/analytics/src/sdk_events/core.rs
|
analytics
|
full_file
| null | null | null | 1,403
| null | null | null | null | null | null | null |
// Function: get_session_state
// File: crates/router/src/routes/app.rs
// Module: router
pub fn get_session_state<E, F>(
self: Arc<Self>,
tenant: &id_type::TenantId,
locale: Option<String>,
err: F,
) -> Result<SessionState, E>
where
F: FnOnce() -> E + Copy,
|
crates/router/src/routes/app.rs
|
router
|
function_signature
| null | null | null | 82
|
get_session_state
| null | null | null | null | null | null |
// Function: new
// File: crates/hyperswitch_connectors/src/connectors/paysafe.rs
// Module: hyperswitch_connectors
pub fn new() -> &'static Self
|
crates/hyperswitch_connectors/src/connectors/paysafe.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 39
|
new
| null | null | null | null | null | null |
// Function: get_refund_sync_body
// File: crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs
// Module: hyperswitch_connectors
pub fn get_refund_sync_body(req: &types::RefundSyncRouterData) -> Result<Vec<u8>, Error>
|
crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 66
|
get_refund_sync_body
| null | null | null | null | null | null |
// Struct: FlexitiSyncResponse
// File: crates/hyperswitch_connectors/src/connectors/flexiti/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct FlexitiSyncResponse
|
crates/hyperswitch_connectors/src/connectors/flexiti/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
FlexitiSyncResponse
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Function: new
// File: crates/hyperswitch_connectors/src/connectors/paystack.rs
// Module: hyperswitch_connectors
pub fn new() -> &'static Self
|
crates/hyperswitch_connectors/src/connectors/paystack.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 38
|
new
| null | null | null | null | null | null |
// Struct: PeachpaymentsRouterData
// File: crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PeachpaymentsRouterData<T>
|
crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PeachpaymentsRouterData
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// File: crates/analytics/src/refunds/metrics/sessionized_metrics/refund_reason.rs
// Module: analytics
use std::collections::HashSet;
use api_models::analytics::{
refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::RefundMetricRow;
use crate::{
enums::AuthInfo,
query::{
Aggregate, FilterTypes, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket,
ToSql, Window,
},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(crate) struct RefundReason;
#[async_trait::async_trait]
impl<T> super::RefundMetric<T> for RefundReason
where
T: AnalyticsDataSource + super::RefundMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[RefundDimensions],
auth: &AuthInfo,
filters: &RefundFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> {
let mut inner_query_builder: QueryBuilder<T> =
QueryBuilder::new(AnalyticsCollection::RefundSessionized);
inner_query_builder
.add_select_column("sum(sign_flag)")
.switch()?;
inner_query_builder
.add_custom_filter_clause(
RefundDimensions::RefundReason,
"NULL",
FilterTypes::IsNotNull,
)
.switch()?;
time_range
.set_filter_clause(&mut inner_query_builder)
.attach_printable("Error filtering time range for inner query")
.switch()?;
let inner_query_string = inner_query_builder
.build_query()
.attach_printable("Error building inner query")
.change_context(MetricsError::QueryBuildingError)?;
let mut outer_query_builder: QueryBuilder<T> =
QueryBuilder::new(AnalyticsCollection::RefundSessionized);
for dim in dimensions.iter() {
outer_query_builder.add_select_column(dim).switch()?;
}
outer_query_builder
.add_select_column("sum(sign_flag) AS count")
.switch()?;
outer_query_builder
.add_select_column(format!("({inner_query_string}) AS total"))
.switch()?;
outer_query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
outer_query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
filters
.set_filter_clause(&mut outer_query_builder)
.switch()?;
auth.set_filter_clause(&mut outer_query_builder).switch()?;
time_range
.set_filter_clause(&mut outer_query_builder)
.attach_printable("Error filtering time range for outer query")
.switch()?;
outer_query_builder
.add_custom_filter_clause(
RefundDimensions::RefundReason,
"NULL",
FilterTypes::IsNotNull,
)
.switch()?;
for dim in dimensions.iter() {
outer_query_builder
.add_group_by_clause(dim)
.attach_printable("Error grouping by dimensions")
.switch()?;
}
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut outer_query_builder)
.attach_printable("Error adding granularity")
.switch()?;
}
outer_query_builder
.add_order_by_clause("count", Order::Descending)
.attach_printable("Error adding order by clause")
.switch()?;
let filtered_dimensions: Vec<&RefundDimensions> = dimensions
.iter()
.filter(|&&dim| dim != RefundDimensions::RefundReason)
.collect();
for dim in &filtered_dimensions {
outer_query_builder
.add_order_by_clause(*dim, Order::Ascending)
.attach_printable("Error adding order by clause")
.switch()?;
}
outer_query_builder
.execute_query::<RefundMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
RefundMetricsBucketIdentifier::new(
i.currency.as_ref().map(|i| i.0),
None,
i.connector.clone(),
i.refund_type.as_ref().map(|i| i.0.to_string()),
i.profile_id.clone(),
i.refund_reason.clone(),
i.refund_error_message.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
},
),
i,
))
})
.collect::<error_stack::Result<
HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>,
crate::query::PostProcessingError,
>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
|
crates/analytics/src/refunds/metrics/sessionized_metrics/refund_reason.rs
|
analytics
|
full_file
| null | null | null | 1,234
| null | null | null | null | null | null | null |
// Struct: CardData
// File: crates/router/src/types/payment_methods.rs
// Module: router
// Implementations: 0
pub struct CardData
|
crates/router/src/types/payment_methods.rs
|
router
|
struct_definition
|
CardData
| 0
|
[] | 33
| null | null | null | null | null | null | null |
// Implementation: impl api::PayoutCancel for for Ebanx
// File: crates/hyperswitch_connectors/src/connectors/ebanx.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PayoutCancel for for Ebanx
|
crates/hyperswitch_connectors/src/connectors/ebanx.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 63
| null |
Ebanx
|
api::PayoutCancel for
| 0
| 0
| null | null |
// Implementation: impl webhooks::IncomingWebhook for for Cybersource
// File: crates/hyperswitch_connectors/src/connectors/cybersource.rs
// Module: hyperswitch_connectors
// Methods: 3 total (0 public)
impl webhooks::IncomingWebhook for for Cybersource
|
crates/hyperswitch_connectors/src/connectors/cybersource.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 65
| null |
Cybersource
|
webhooks::IncomingWebhook for
| 3
| 0
| null | null |
// Implementation: impl api::PaymentCapture for for Nexinets
// File: crates/hyperswitch_connectors/src/connectors/nexinets.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentCapture for for Nexinets
|
crates/hyperswitch_connectors/src/connectors/nexinets.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Nexinets
|
api::PaymentCapture for
| 0
| 0
| null | null |
// Struct: PaymentRequestBankTransfer
// File: crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaymentRequestBankTransfer
|
crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaymentRequestBankTransfer
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Struct: ExpiryDate
// File: crates/hyperswitch_connectors/src/connectors/authipay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ExpiryDate
|
crates/hyperswitch_connectors/src/connectors/authipay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ExpiryDate
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Function: retrieve_extended_card_info
// File: crates/router/src/routes/payments.rs
// Module: router
pub fn retrieve_extended_card_info(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder
|
crates/router/src/routes/payments.rs
|
router
|
function_signature
| null | null | null | 72
|
retrieve_extended_card_info
| null | null | null | null | null | null |
// Implementation: impl api::PaymentSession for for Paytm
// File: crates/hyperswitch_connectors/src/connectors/paytm.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSession for for Paytm
|
crates/hyperswitch_connectors/src/connectors/paytm.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Paytm
|
api::PaymentSession for
| 0
| 0
| null | null |
// Function: add_granularity_in_mins
// File: crates/analytics/src/query.rs
// Module: analytics
pub fn add_granularity_in_mins(&mut self, granularity: Granularity) -> QueryResult<()>
|
crates/analytics/src/query.rs
|
analytics
|
function_signature
| null | null | null | 48
|
add_granularity_in_mins
| null | null | null | null | null | null |
// File: crates/router/src/core/payments/tokenization.rs
// Module: router
// Public functions: 17
// Public structs: 2
use std::collections::HashMap;
use ::payment_methods::controller::PaymentMethodsController;
#[cfg(feature = "v1")]
use api_models::payment_methods::PaymentMethodsData;
use api_models::{
payment_methods::PaymentMethodDataWalletInfo, payments::ConnectorMandateReferenceId,
};
use common_enums::{ConnectorMandateStatus, PaymentMethod};
use common_types::callback_mapper::CallbackMapperData;
use common_utils::{
crypto::Encryptable,
ext_traits::{AsyncExt, Encode, ValueExt},
id_type,
metrics::utils::record_operation_time,
pii,
};
use diesel_models::business_profile::ExternalVaultConnectorDetails;
use error_stack::{report, ResultExt};
#[cfg(feature = "v1")]
use hyperswitch_domain_models::{
callback_mapper::CallbackMapper,
mandates::{CommonMandateReference, PaymentsMandateReference, PaymentsMandateReferenceRecord},
payment_method_data,
};
use masking::{ExposeInterface, Secret};
use router_env::{instrument, tracing};
use super::helpers;
#[cfg(feature = "v1")]
use crate::core::payment_methods::vault_payment_method_external_v1;
use crate::{
consts,
core::{
errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt},
mandate,
payment_methods::{
self,
cards::{create_encrypted_data, PmCards},
network_tokenization,
},
payments,
},
logger,
routes::{metrics, SessionState},
services,
types::{
self,
api::{self, CardDetailFromLocker, CardDetailsPaymentMethod, PaymentMethodCreateExt},
domain, payment_methods as pm_types,
storage::enums as storage_enums,
},
utils::{generate_id, OptionExt},
};
#[cfg(feature = "v1")]
async fn save_in_locker(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_method_request: api::PaymentMethodCreate,
card_detail: Option<api::CardDetail>,
business_profile: &domain::Profile,
) -> RouterResult<(
api_models::payment_methods::PaymentMethodResponse,
Option<payment_methods::transformers::DataDuplicationCheck>,
)> {
match &business_profile.external_vault_details {
domain::ExternalVaultDetails::ExternalVaultEnabled(external_vault_details) => {
logger::info!("External vault is enabled, using vault_payment_method_external_v1");
Box::pin(save_in_locker_external(
state,
merchant_context,
payment_method_request,
card_detail,
external_vault_details,
))
.await
}
domain::ExternalVaultDetails::Skip => {
// Use internal vault (locker)
save_in_locker_internal(state, merchant_context, payment_method_request, card_detail)
.await
}
}
}
pub struct SavePaymentMethodData<Req> {
request: Req,
response: Result<types::PaymentsResponseData, types::ErrorResponse>,
payment_method_token: Option<types::PaymentMethodToken>,
payment_method: PaymentMethod,
attempt_status: common_enums::AttemptStatus,
}
impl<F, Req: Clone> From<&types::RouterData<F, Req, types::PaymentsResponseData>>
for SavePaymentMethodData<Req>
{
fn from(router_data: &types::RouterData<F, Req, types::PaymentsResponseData>) -> Self {
Self {
request: router_data.request.clone(),
response: router_data.response.clone(),
payment_method_token: router_data.payment_method_token.clone(),
payment_method: router_data.payment_method,
attempt_status: router_data.status,
}
}
}
pub struct SavePaymentMethodDataResponse {
pub payment_method_id: Option<String>,
pub payment_method_status: Option<common_enums::PaymentMethodStatus>,
pub connector_mandate_reference_id: Option<ConnectorMandateReferenceId>,
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn save_payment_method<FData>(
state: &SessionState,
connector_name: String,
save_payment_method_data: SavePaymentMethodData<FData>,
customer_id: Option<id_type::CustomerId>,
merchant_context: &domain::MerchantContext,
payment_method_type: Option<storage_enums::PaymentMethodType>,
billing_name: Option<Secret<String>>,
payment_method_billing_address: Option<&hyperswitch_domain_models::address::Address>,
business_profile: &domain::Profile,
mut original_connector_mandate_reference_id: Option<ConnectorMandateReferenceId>,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
vault_operation: Option<hyperswitch_domain_models::payments::VaultOperation>,
payment_method_info: Option<domain::PaymentMethod>,
) -> RouterResult<SavePaymentMethodDataResponse>
where
FData: mandate::MandateBehaviour + Clone,
{
let mut pm_status = None;
let cards = PmCards {
state,
merchant_context,
};
match save_payment_method_data.response {
Ok(responses) => {
let db = &*state.store;
let token_store = state
.conf
.tokenization
.0
.get(&connector_name.to_string())
.map(|token_filter| token_filter.long_lived_token)
.unwrap_or(false);
let network_transaction_id = match &responses {
types::PaymentsResponseData::TransactionResponse { network_txn_id, .. } => {
network_txn_id.clone()
}
_ => None,
};
let network_transaction_id =
if save_payment_method_data.request.get_setup_future_usage()
== Some(storage_enums::FutureUsage::OffSession)
{
if network_transaction_id.is_some() {
network_transaction_id
} else {
logger::info!("Skip storing network transaction id");
None
}
} else {
None
};
let connector_token = if token_store {
let tokens = save_payment_method_data
.payment_method_token
.to_owned()
.get_required_value("payment_token")?;
let token = match tokens {
types::PaymentMethodToken::Token(connector_token) => connector_token.expose(),
types::PaymentMethodToken::ApplePayDecrypt(_) => {
Err(errors::ApiErrorResponse::NotSupported {
message: "Apple Pay Decrypt token is not supported".to_string(),
})?
}
types::PaymentMethodToken::PazeDecrypt(_) => {
Err(errors::ApiErrorResponse::NotSupported {
message: "Paze Decrypt token is not supported".to_string(),
})?
}
types::PaymentMethodToken::GooglePayDecrypt(_) => {
Err(errors::ApiErrorResponse::NotSupported {
message: "Google Pay Decrypt token is not supported".to_string(),
})?
}
};
Some((connector_name, token))
} else {
None
};
let mandate_data_customer_acceptance = save_payment_method_data
.request
.get_setup_mandate_details()
.and_then(|mandate_data| mandate_data.customer_acceptance.clone());
let customer_acceptance = save_payment_method_data
.request
.get_customer_acceptance()
.or(mandate_data_customer_acceptance.clone())
.map(|ca| ca.encode_to_value())
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize customer acceptance to value")?;
let (connector_mandate_id, mandate_metadata, connector_mandate_request_reference_id) =
match responses {
types::PaymentsResponseData::TransactionResponse {
mandate_reference, ..
} => {
if let Some(ref mandate_ref) = *mandate_reference {
(
mandate_ref.connector_mandate_id.clone(),
mandate_ref.mandate_metadata.clone(),
mandate_ref.connector_mandate_request_reference_id.clone(),
)
} else {
(None, None, None)
}
}
_ => (None, None, None),
};
let pm_id = if customer_acceptance.is_some() {
let payment_method_data =
save_payment_method_data.request.get_payment_method_data();
let payment_method_create_request =
payment_methods::get_payment_method_create_request(
Some(&payment_method_data),
Some(save_payment_method_data.payment_method),
payment_method_type,
&customer_id.clone(),
billing_name,
payment_method_billing_address,
)
.await?;
let payment_methods_data =
&save_payment_method_data.request.get_payment_method_data();
let co_badged_card_data = payment_methods_data.get_co_badged_card_data();
let customer_id = customer_id.to_owned().get_required_value("customer_id")?;
let merchant_id = merchant_context.get_merchant_account().get_id();
let is_network_tokenization_enabled =
business_profile.is_network_tokenization_enabled;
let (
(mut resp, duplication_check, network_token_requestor_ref_id),
network_token_resp,
) = if !state.conf.locker.locker_enabled {
let (res, dc) = skip_saving_card_in_locker(
merchant_context,
payment_method_create_request.to_owned(),
)
.await?;
((res, dc, None), None)
} else {
let payment_method_status = common_enums::PaymentMethodStatus::from(
save_payment_method_data.attempt_status,
);
pm_status = Some(payment_method_status);
save_card_and_network_token_in_locker(
state,
customer_id.clone(),
payment_method_status,
payment_method_data.clone(),
vault_operation,
payment_method_info,
merchant_context,
payment_method_create_request.clone(),
is_network_tokenization_enabled,
business_profile,
)
.await?
};
let network_token_locker_id = match network_token_resp {
Some(ref token_resp) => {
if network_token_requestor_ref_id.is_some() {
Some(token_resp.payment_method_id.clone())
} else {
None
}
}
None => None,
};
let optional_pm_details = match (resp.card.as_ref(), payment_method_data) {
(Some(card), _) => Some(PaymentMethodsData::Card(
CardDetailsPaymentMethod::from((card.clone(), co_badged_card_data)),
)),
(
_,
domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(applepay)),
) => Some(PaymentMethodsData::WalletDetails(
PaymentMethodDataWalletInfo::from(applepay),
)),
(
_,
domain::PaymentMethodData::Wallet(domain::WalletData::GooglePay(googlepay)),
) => Some(PaymentMethodsData::WalletDetails(
PaymentMethodDataWalletInfo::from(googlepay),
)),
_ => None,
};
let key_manager_state = state.into();
let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> =
optional_pm_details
.async_map(|pm| {
create_encrypted_data(
&key_manager_state,
merchant_context.get_merchant_key_store(),
pm,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
let pm_network_token_data_encrypted: Option<
Encryptable<Secret<serde_json::Value>>,
> = match network_token_resp {
Some(token_resp) => {
let pm_token_details = token_resp.card.as_ref().map(|card| {
PaymentMethodsData::Card(CardDetailsPaymentMethod::from((
card.clone(),
None,
)))
});
pm_token_details
.async_map(|pm_card| {
create_encrypted_data(
&key_manager_state,
merchant_context.get_merchant_key_store(),
pm_card,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?
}
None => None,
};
let encrypted_payment_method_billing_address: Option<
Encryptable<Secret<serde_json::Value>>,
> = payment_method_billing_address
.async_map(|address| {
create_encrypted_data(
&key_manager_state,
merchant_context.get_merchant_key_store(),
address.clone(),
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method billing address")?;
let mut payment_method_id = resp.payment_method_id.clone();
let mut locker_id = None;
let (external_vault_details, vault_type) = match &business_profile.external_vault_details{
hyperswitch_domain_models::business_profile::ExternalVaultDetails::ExternalVaultEnabled(external_vault_connector_details) => {
(Some(external_vault_connector_details), Some(common_enums::VaultType::External))
},
hyperswitch_domain_models::business_profile::ExternalVaultDetails::Skip => (None, Some(common_enums::VaultType::Internal)),
};
let external_vault_mca_id = external_vault_details
.map(|connector_details| connector_details.vault_connector_id.clone());
let vault_source_details = domain::PaymentMethodVaultSourceDetails::try_from((
vault_type,
external_vault_mca_id,
))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to create vault source details")?;
match duplication_check {
Some(duplication_check) => match duplication_check {
payment_methods::transformers::DataDuplicationCheck::Duplicated => {
let payment_method = {
let existing_pm_by_pmid = db
.find_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
&payment_method_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await;
if let Err(err) = existing_pm_by_pmid {
if err.current_context().is_db_not_found() {
locker_id = Some(payment_method_id.clone());
let existing_pm_by_locker_id = db
.find_payment_method_by_locker_id(
&(state.into()),
merchant_context.get_merchant_key_store(),
&payment_method_id,
merchant_context
.get_merchant_account()
.storage_scheme,
)
.await;
match &existing_pm_by_locker_id {
Ok(pm) => {
payment_method_id.clone_from(&pm.payment_method_id);
}
Err(_) => {
payment_method_id =
generate_id(consts::ID_LENGTH, "pm")
}
};
existing_pm_by_locker_id
} else {
Err(err)
}
} else {
existing_pm_by_pmid
}
};
resp.payment_method_id = payment_method_id;
match payment_method {
Ok(pm) => {
let pm_metadata = create_payment_method_metadata(
pm.metadata.as_ref(),
connector_token,
)?;
payment_methods::cards::update_payment_method_metadata_and_last_used(
state,
merchant_context.get_merchant_key_store(),
db,
pm.clone(),
pm_metadata,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
}
Err(err) => {
if err.current_context().is_db_not_found() {
let pm_metadata =
create_payment_method_metadata(None, connector_token)?;
cards
.create_payment_method(
&payment_method_create_request,
&customer_id,
&resp.payment_method_id,
locker_id,
merchant_id,
pm_metadata,
customer_acceptance,
pm_data_encrypted,
None,
pm_status,
network_transaction_id,
encrypted_payment_method_billing_address,
resp.card.and_then(|card| {
card.card_network.map(|card_network| {
card_network.to_string()
})
}),
network_token_requestor_ref_id,
network_token_locker_id,
pm_network_token_data_encrypted,
Some(vault_source_details),
)
.await
} else {
Err(err)
.change_context(
errors::ApiErrorResponse::InternalServerError,
)
.attach_printable("Error while finding payment method")
}?;
}
};
}
payment_methods::transformers::DataDuplicationCheck::MetaDataChanged => {
if let Some(card) = payment_method_create_request.card.clone() {
let payment_method = {
let existing_pm_by_pmid = db
.find_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
&payment_method_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await;
if let Err(err) = existing_pm_by_pmid {
if err.current_context().is_db_not_found() {
locker_id = Some(payment_method_id.clone());
let existing_pm_by_locker_id = db
.find_payment_method_by_locker_id(
&(state.into()),
merchant_context.get_merchant_key_store(),
&payment_method_id,
merchant_context
.get_merchant_account()
.storage_scheme,
)
.await;
match &existing_pm_by_locker_id {
Ok(pm) => {
payment_method_id
.clone_from(&pm.payment_method_id);
}
Err(_) => {
payment_method_id =
generate_id(consts::ID_LENGTH, "pm")
}
};
existing_pm_by_locker_id
} else {
Err(err)
}
} else {
existing_pm_by_pmid
}
};
resp.payment_method_id = payment_method_id;
let existing_pm = match payment_method {
Ok(pm) => {
let mandate_details = pm
.connector_mandate_details
.clone()
.map(|val| {
val.parse_value::<PaymentsMandateReference>(
"PaymentsMandateReference",
)
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize to Payment Mandate Reference ")?;
if let Some((mandate_details, merchant_connector_id)) =
mandate_details.zip(merchant_connector_id)
{
let connector_mandate_details =
update_connector_mandate_details_status(
merchant_connector_id,
mandate_details,
ConnectorMandateStatus::Inactive,
)?;
payment_methods::cards::update_payment_method_connector_mandate_details(
state,
merchant_context.get_merchant_key_store(),
db,
pm.clone(),
connector_mandate_details,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
}
Ok(pm)
}
Err(err) => {
if err.current_context().is_db_not_found() {
cards
.create_payment_method(
&payment_method_create_request,
&customer_id,
&resp.payment_method_id,
locker_id,
merchant_id,
resp.metadata.clone().map(|val| val.expose()),
customer_acceptance,
pm_data_encrypted,
None,
pm_status,
network_transaction_id,
encrypted_payment_method_billing_address,
resp.card.and_then(|card| {
card.card_network.map(|card_network| {
card_network.to_string()
})
}),
network_token_requestor_ref_id,
network_token_locker_id,
pm_network_token_data_encrypted,
Some(vault_source_details),
)
.await
} else {
Err(err)
.change_context(
errors::ApiErrorResponse::InternalServerError,
)
.attach_printable(
"Error while finding payment method",
)
}
}
}?;
cards
.delete_card_from_locker(
&customer_id,
merchant_id,
existing_pm
.locker_id
.as_ref()
.unwrap_or(&existing_pm.payment_method_id),
)
.await?;
let add_card_resp = cards
.add_card_hs(
payment_method_create_request,
&card,
&customer_id,
api::enums::LockerChoice::HyperswitchCardVault,
Some(
existing_pm
.locker_id
.as_ref()
.unwrap_or(&existing_pm.payment_method_id),
),
)
.await;
if let Err(err) = add_card_resp {
logger::error!(vault_err=?err);
db.delete_payment_method_by_merchant_id_payment_method_id(
&(state.into()),
merchant_context.get_merchant_key_store(),
merchant_id,
&resp.payment_method_id,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::PaymentMethodNotFound,
)?;
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed while updating card metadata changes",
))?
};
let existing_pm_data = cards
.get_card_details_without_locker_fallback(&existing_pm)
.await?;
// scheme should be updated in case of co-badged cards
let card_scheme = card
.card_network
.clone()
.map(|card_network| card_network.to_string())
.or(existing_pm_data.scheme.clone());
let updated_card = Some(CardDetailFromLocker {
scheme: card_scheme.clone(),
last4_digits: Some(card.card_number.get_last4()),
issuer_country: card
.card_issuing_country
.or(existing_pm_data.issuer_country),
card_isin: Some(card.card_number.get_card_isin()),
card_number: Some(card.card_number),
expiry_month: Some(card.card_exp_month),
expiry_year: Some(card.card_exp_year),
card_token: None,
card_fingerprint: None,
card_holder_name: card
.card_holder_name
.or(existing_pm_data.card_holder_name),
nick_name: card.nick_name.or(existing_pm_data.nick_name),
card_network: card
.card_network
.or(existing_pm_data.card_network),
card_issuer: card.card_issuer.or(existing_pm_data.card_issuer),
card_type: card.card_type.or(existing_pm_data.card_type),
saved_to_locker: true,
});
let updated_pmd = updated_card.as_ref().map(|card| {
PaymentMethodsData::Card(CardDetailsPaymentMethod::from((
card.clone(),
co_badged_card_data,
)))
});
let pm_data_encrypted: Option<
Encryptable<Secret<serde_json::Value>>,
> = updated_pmd
.async_map(|pmd| {
create_encrypted_data(
&key_manager_state,
merchant_context.get_merchant_key_store(),
pmd,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
payment_methods::cards::update_payment_method_and_last_used(
state,
merchant_context.get_merchant_key_store(),
db,
existing_pm,
pm_data_encrypted.map(Into::into),
merchant_context.get_merchant_account().storage_scheme,
card_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
}
}
},
None => {
let customer_saved_pm_option = if payment_method_type
.map(|payment_method_type_value| {
payment_method_type_value
.should_check_for_customer_saved_payment_method_type()
})
.unwrap_or(false)
{
match state
.store
.find_payment_method_by_customer_id_merchant_id_list(
&(state.into()),
merchant_context.get_merchant_key_store(),
&customer_id,
merchant_id,
None,
)
.await
{
Ok(customer_payment_methods) => Ok(customer_payment_methods
.iter()
.find(|payment_method| {
payment_method.get_payment_method_subtype()
== payment_method_type
})
.cloned()),
Err(error) => {
if error.current_context().is_db_not_found() {
Ok(None)
} else {
Err(error)
.change_context(
errors::ApiErrorResponse::InternalServerError,
)
.attach_printable(
"failed to find payment methods for a customer",
)
}
}
}
} else {
Ok(None)
}?;
if let Some(customer_saved_pm) = customer_saved_pm_option {
payment_methods::cards::update_last_used_at(
&customer_saved_pm,
state,
merchant_context.get_merchant_account().storage_scheme,
merchant_context.get_merchant_key_store(),
)
.await
.map_err(|e| {
logger::error!("Failed to update last used at: {:?}", e);
})
.ok();
resp.payment_method_id = customer_saved_pm.payment_method_id;
} else {
let pm_metadata =
create_payment_method_metadata(None, connector_token)?;
locker_id = resp.payment_method.and_then(|pm| {
if pm == PaymentMethod::Card {
Some(resp.payment_method_id)
} else {
None
}
});
resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
cards
.create_payment_method(
&payment_method_create_request,
&customer_id,
&resp.payment_method_id,
locker_id,
merchant_id,
pm_metadata,
customer_acceptance,
pm_data_encrypted,
None,
pm_status,
network_transaction_id,
encrypted_payment_method_billing_address,
resp.card.and_then(|card| {
card.card_network
.map(|card_network| card_network.to_string())
}),
network_token_requestor_ref_id.clone(),
network_token_locker_id,
pm_network_token_data_encrypted,
Some(vault_source_details),
)
.await?;
match network_token_requestor_ref_id {
Some(network_token_requestor_ref_id) => {
//Insert the network token reference ID along with merchant id, customer id in CallbackMapper table for its respective webooks
let callback_mapper_data =
CallbackMapperData::NetworkTokenWebhook {
merchant_id: merchant_context
.get_merchant_account()
.get_id()
.clone(),
customer_id,
payment_method_id: resp.payment_method_id.clone(),
};
let callback_mapper = CallbackMapper::new(
network_token_requestor_ref_id,
common_enums::CallbackMapperIdType::NetworkTokenRequestorReferenceID,
callback_mapper_data,
common_utils::date_time::now(),
common_utils::date_time::now(),
);
db.insert_call_back_mapper(callback_mapper)
.await
.change_context(
errors::ApiErrorResponse::InternalServerError,
)
.attach_printable(
"Failed to insert in Callback Mapper table",
)?;
}
None => {
logger::info!("Network token requestor reference ID is not available, skipping callback mapper insertion");
}
};
};
}
}
Some(resp.payment_method_id)
} else {
None
};
// check if there needs to be a config if yes then remove it to a different place
let connector_mandate_reference_id = if connector_mandate_id.is_some() {
if let Some(ref mut record) = original_connector_mandate_reference_id {
record.update(
connector_mandate_id,
None,
None,
mandate_metadata,
connector_mandate_request_reference_id,
);
Some(record.clone())
} else {
Some(ConnectorMandateReferenceId::new(
connector_mandate_id,
None,
None,
mandate_metadata,
connector_mandate_request_reference_id,
))
}
} else {
None
};
Ok(SavePaymentMethodDataResponse {
payment_method_id: pm_id,
payment_method_status: pm_status,
connector_mandate_reference_id,
})
}
Err(_) => Ok(SavePaymentMethodDataResponse {
payment_method_id: None,
payment_method_status: None,
connector_mandate_reference_id: None,
}),
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn save_payment_method<FData>(
_state: &SessionState,
_connector_name: String,
_save_payment_method_data: SavePaymentMethodData<FData>,
_customer_id: Option<id_type::CustomerId>,
_merchant_context: &domain::MerchantContext,
_payment_method_type: Option<storage_enums::PaymentMethodType>,
_billing_name: Option<Secret<String>>,
_payment_method_billing_address: Option<&api::Address>,
_business_profile: &domain::Profile,
_connector_mandate_request_reference_id: Option<String>,
) -> RouterResult<SavePaymentMethodDataResponse>
where
FData: mandate::MandateBehaviour + Clone,
{
todo!()
}
#[cfg(feature = "v1")]
pub async fn pre_payment_tokenization(
state: &SessionState,
customer_id: id_type::CustomerId,
card: &payment_method_data::Card,
) -> RouterResult<(Option<pm_types::TokenResponse>, Option<String>)> {
let network_tokenization_supported_card_networks = &state
.conf
.network_tokenization_supported_card_networks
.card_networks;
if card
.card_network
.as_ref()
.filter(|cn| network_tokenization_supported_card_networks.contains(cn))
.is_some()
{
let optional_card_cvc = Some(card.card_cvc.clone());
let card_detail = payment_method_data::CardDetail::from(card);
match network_tokenization::make_card_network_tokenization_request(
state,
&card_detail,
optional_card_cvc,
&customer_id,
)
.await
{
Ok((_token_response, network_token_requestor_ref_id)) => {
let network_tokenization_service = &state.conf.network_tokenization_service;
match (
network_token_requestor_ref_id.clone(),
network_tokenization_service,
) {
(Some(token_ref), Some(network_tokenization_service)) => {
let network_token = record_operation_time(
async {
network_tokenization::get_network_token(
state,
customer_id,
token_ref,
network_tokenization_service.get_inner(),
)
.await
},
&metrics::FETCH_NETWORK_TOKEN_TIME,
&[],
)
.await;
match network_token {
Ok(token_response) => {
Ok((Some(token_response), network_token_requestor_ref_id.clone()))
}
_ => {
logger::error!(
"Error while fetching token from tokenization service"
);
Ok((None, network_token_requestor_ref_id.clone()))
}
}
}
(Some(token_ref), _) => Ok((None, Some(token_ref))),
_ => Ok((None, None)),
}
}
Err(err) => {
logger::error!("Failed to tokenize card: {:?}", err);
Ok((None, None)) //None will be returned in case of error when calling network tokenization service
}
}
} else {
Ok((None, None)) //None will be returned in case of unsupported card network.
}
}
#[cfg(feature = "v1")]
async fn skip_saving_card_in_locker(
merchant_context: &domain::MerchantContext,
payment_method_request: api::PaymentMethodCreate,
) -> RouterResult<(
api_models::payment_methods::PaymentMethodResponse,
Option<payment_methods::transformers::DataDuplicationCheck>,
)> {
let merchant_id = merchant_context.get_merchant_account().get_id();
let customer_id = payment_method_request
.clone()
.customer_id
.clone()
.get_required_value("customer_id")?;
let payment_method_id = common_utils::generate_id(consts::ID_LENGTH, "pm");
let last4_digits = payment_method_request
.card
.clone()
.map(|c| c.card_number.get_last4());
let card_isin = payment_method_request
.card
.clone()
.map(|c| c.card_number.get_card_isin());
match payment_method_request.card.clone() {
Some(card) => {
let card_detail = CardDetailFromLocker {
scheme: None,
issuer_country: card.card_issuing_country.clone(),
last4_digits: last4_digits.clone(),
card_number: None,
expiry_month: Some(card.card_exp_month.clone()),
expiry_year: Some(card.card_exp_year),
card_token: None,
card_holder_name: card.card_holder_name.clone(),
card_fingerprint: None,
nick_name: None,
card_isin: card_isin.clone(),
card_issuer: card.card_issuer.clone(),
card_network: card.card_network.clone(),
card_type: card.card_type.clone(),
saved_to_locker: false,
};
let pm_resp = api::PaymentMethodResponse {
merchant_id: merchant_id.to_owned(),
customer_id: Some(customer_id),
payment_method_id,
payment_method: payment_method_request.payment_method,
payment_method_type: payment_method_request.payment_method_type,
card: Some(card_detail),
recurring_enabled: Some(false),
installment_payment_enabled: Some(false),
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
metadata: None,
created: Some(common_utils::date_time::now()),
#[cfg(feature = "payouts")]
bank_transfer: None,
last_used_at: Some(common_utils::date_time::now()),
client_secret: None,
};
Ok((pm_resp, None))
}
None => {
let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm");
let payment_method_response = api::PaymentMethodResponse {
merchant_id: merchant_id.to_owned(),
customer_id: Some(customer_id),
payment_method_id: pm_id,
payment_method: payment_method_request.payment_method,
payment_method_type: payment_method_request.payment_method_type,
card: None,
metadata: None,
created: Some(common_utils::date_time::now()),
recurring_enabled: Some(false),
installment_payment_enabled: Some(false),
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
#[cfg(feature = "payouts")]
bank_transfer: None,
last_used_at: Some(common_utils::date_time::now()),
client_secret: None,
};
Ok((payment_method_response, None))
}
}
}
#[cfg(feature = "v2")]
async fn skip_saving_card_in_locker(
merchant_context: &domain::MerchantContext,
payment_method_request: api::PaymentMethodCreate,
) -> RouterResult<(
api_models::payment_methods::PaymentMethodResponse,
Option<payment_methods::transformers::DataDuplicationCheck>,
)> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn save_in_locker_internal(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_method_request: api::PaymentMethodCreate,
card_detail: Option<api::CardDetail>,
) -> RouterResult<(
api_models::payment_methods::PaymentMethodResponse,
Option<payment_methods::transformers::DataDuplicationCheck>,
)> {
payment_method_request.validate()?;
let merchant_id = merchant_context.get_merchant_account().get_id();
let customer_id = payment_method_request
.customer_id
.clone()
.get_required_value("customer_id")?;
match (payment_method_request.card.clone(), card_detail) {
(_, Some(card)) | (Some(card), _) => Box::pin(
PmCards {
state,
merchant_context,
}
.add_card_to_locker(payment_method_request, &card, &customer_id, None),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Card Failed"),
_ => {
let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm");
let payment_method_response = api::PaymentMethodResponse {
merchant_id: merchant_id.clone(),
customer_id: Some(customer_id),
payment_method_id: pm_id,
payment_method: payment_method_request.payment_method,
payment_method_type: payment_method_request.payment_method_type,
#[cfg(feature = "payouts")]
bank_transfer: None,
card: None,
metadata: None,
created: Some(common_utils::date_time::now()),
recurring_enabled: Some(false),
installment_payment_enabled: Some(false),
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219]
last_used_at: Some(common_utils::date_time::now()),
client_secret: None,
};
Ok((payment_method_response, None))
}
}
}
#[cfg(feature = "v1")]
pub async fn save_in_locker_external(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_method_request: api::PaymentMethodCreate,
card_detail: Option<api::CardDetail>,
external_vault_connector_details: &ExternalVaultConnectorDetails,
) -> RouterResult<(
api_models::payment_methods::PaymentMethodResponse,
Option<payment_methods::transformers::DataDuplicationCheck>,
)> {
let customer_id = payment_method_request
.customer_id
.clone()
.get_required_value("customer_id")?;
// For external vault, we need to convert the card data to PaymentMethodVaultingData
if let Some(card) = card_detail {
let payment_method_vaulting_data =
|
crates/router/src/core/payments/tokenization.rs#chunk0
|
router
|
chunk
| null | null | null | 8,180
| null | null | null | null | null | null | null |
// Struct: AddCardRequest
// File: crates/router/src/core/payment_methods/transformers.rs
// Module: router
// Implementations: 0
pub struct AddCardRequest
|
crates/router/src/core/payment_methods/transformers.rs
|
router
|
struct_definition
|
AddCardRequest
| 0
|
[] | 38
| null | null | null | null | null | null | null |
// Implementation: impl api::MandateSetup for for Worldpay
// File: crates/hyperswitch_connectors/src/connectors/worldpay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::MandateSetup for for Worldpay
|
crates/hyperswitch_connectors/src/connectors/worldpay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Worldpay
|
api::MandateSetup for
| 0
| 0
| null | null |
// Struct: OnboardSubAccountRequest
// File: crates/hyperswitch_connectors/src/connectors/nomupay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct OnboardSubAccountRequest
|
crates/hyperswitch_connectors/src/connectors/nomupay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
OnboardSubAccountRequest
| 0
|
[] | 53
| null | null | null | null | null | null | null |
billing_address: billing_details_encoded,
shipping_address: shipping_details_encoded,
},
),
),
common_utils::types::keymanager::Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt authentication data".to_string())?;
let encrypted_data = hyperswitch_domain_models::authentication::FromRequestEncryptableAuthentication::from_encryptable(encrypted_data)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to get encrypted data for authentication after encryption")?;
let email_encrypted = req
.email
.clone()
.async_lift(|inner| async {
domain::types::crypto_operation(
&key_manager_state,
common_utils::type_name!(Authentication),
domain::types::CryptoOperation::EncryptOptional(inner.map(|inner| inner.expose())),
common_utils::types::keymanager::Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt email")?;
let browser_info = req
.browser_information
.as_ref()
.map(common_utils::ext_traits::Encode::encode_to_value)
.transpose()
.change_context(ApiErrorResponse::InvalidDataValue {
field_name: "browser_information",
})?;
let updated_authentication = utils::external_authentication_update_trackers(
&state,
pre_auth_response,
authentication.clone(),
None,
merchant_context.get_merchant_key_store(),
encrypted_data
.billing_address
.map(common_utils::encryption::Encryption::from),
encrypted_data
.shipping_address
.map(common_utils::encryption::Encryption::from),
email_encrypted
.clone()
.map(common_utils::encryption::Encryption::from),
browser_info,
)
.await?;
let response = AuthenticationEligibilityResponse::foreign_try_from((
updated_authentication,
req.get_next_action_api(
state.base_url,
authentication_id.get_string_repr().to_string(),
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to get next action api")?,
profile_id,
req.get_billing_address(),
req.get_shipping_address(),
req.get_browser_information(),
email_encrypted,
))?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
#[cfg(feature = "v1")]
pub async fn authentication_authenticate_core(
state: SessionState,
merchant_context: domain::MerchantContext,
req: AuthenticationAuthenticateRequest,
auth_flow: AuthFlow,
) -> RouterResponse<AuthenticationAuthenticateResponse> {
let authentication_id = req.authentication_id.clone();
let merchant_account = merchant_context.get_merchant_account();
let merchant_id = merchant_account.get_id();
let db = &*state.store;
let authentication = db
.find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id)
.await
.to_not_found_response(ApiErrorResponse::AuthenticationNotFound {
id: authentication_id.get_string_repr().to_owned(),
})?;
req.client_secret
.map(|client_secret| {
utils::authenticate_authentication_client_secret_and_check_expiry(
client_secret.peek(),
&authentication,
)
})
.transpose()?;
ensure_not_terminal_status(authentication.trans_status.clone())?;
let key_manager_state = (&state).into();
let profile_id = authentication.profile_id.clone();
let business_profile = db
.find_business_profile_by_profile_id(
&key_manager_state,
merchant_context.get_merchant_key_store(),
&profile_id,
)
.await
.to_not_found_response(ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let email_encrypted = authentication
.email
.clone()
.async_lift(|inner| async {
domain::types::crypto_operation(
&key_manager_state,
common_utils::type_name!(Authentication),
domain::types::CryptoOperation::DecryptOptional(inner),
common_utils::types::keymanager::Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decrypt email from authentication table")?;
let browser_info = authentication
.browser_info
.clone()
.map(|browser_info| browser_info.parse_value::<BrowserInformation>("BrowserInformation"))
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to parse browser information from authentication table")?;
let (authentication_connector, three_ds_connector_account) =
auth_utils::get_authentication_connector_data(
&state,
merchant_context.get_merchant_key_store(),
&business_profile,
authentication.authentication_connector.clone(),
)
.await?;
let authentication_details = business_profile
.authentication_connector_details
.clone()
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("authentication_connector_details not configured by the merchant")?;
let connector_name_string = authentication_connector.to_string();
let mca_id_option = three_ds_connector_account.get_mca_id();
let merchant_connector_account_id_or_connector_name = mca_id_option
.as_ref()
.map(|mca_id| mca_id.get_string_repr())
.unwrap_or(&connector_name_string);
let webhook_url = helpers::create_webhook_url(
&state.base_url,
merchant_id,
merchant_connector_account_id_or_connector_name,
);
let auth_response = <ExternalAuthentication as UnifiedAuthenticationService>::authentication(
&state,
&business_profile,
&common_enums::PaymentMethod::Card,
browser_info,
authentication.amount,
authentication.currency,
MessageCategory::Payment,
req.device_channel,
authentication.clone(),
None,
req.sdk_information,
req.threeds_method_comp_ind,
email_encrypted.map(common_utils::pii::Email::from),
webhook_url,
&three_ds_connector_account,
&authentication_connector.to_string(),
None,
)
.await?;
let authentication = utils::external_authentication_update_trackers(
&state,
auth_response,
authentication.clone(),
None,
merchant_context.get_merchant_key_store(),
None,
None,
None,
None,
)
.await?;
let (authentication_value, eci) = match auth_flow {
AuthFlow::Client => (None, None),
AuthFlow::Merchant => {
if let Some(common_enums::TransactionStatus::Success) = authentication.trans_status {
let tokenised_data = crate::core::payment_methods::vault::get_tokenized_data(
&state,
authentication_id.get_string_repr(),
false,
merchant_context.get_merchant_key_store().key.get_inner(),
)
.await
.inspect_err(|err| router_env::logger::error!(tokenized_data_result=?err))
.attach_printable("cavv not present after authentication status is success")?;
(
Some(masking::Secret::new(tokenised_data.value1)),
authentication.eci.clone(),
)
} else {
(None, None)
}
}
};
let response = AuthenticationAuthenticateResponse::foreign_try_from((
&authentication,
authentication_value,
eci,
authentication_details,
))?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
impl
ForeignTryFrom<(
&Authentication,
Option<masking::Secret<String>>,
Option<String>,
diesel_models::business_profile::AuthenticationConnectorDetails,
)> for AuthenticationAuthenticateResponse
{
type Error = error_stack::Report<ApiErrorResponse>;
fn foreign_try_from(
(authentication, authentication_value, eci, authentication_details): (
&Authentication,
Option<masking::Secret<String>>,
Option<String>,
diesel_models::business_profile::AuthenticationConnectorDetails,
),
) -> Result<Self, Self::Error> {
let authentication_connector = authentication
.authentication_connector
.as_ref()
.map(|connector| common_enums::AuthenticationConnectors::from_str(connector))
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Incorrect authentication connector stored in table")?;
let acs_url = authentication
.acs_url
.clone()
.map(|acs_url| url::Url::parse(&acs_url))
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to parse the url with param")?;
let acquirer_details = AcquirerDetails {
acquirer_bin: authentication.acquirer_bin.clone(),
acquirer_merchant_id: authentication.acquirer_merchant_id.clone(),
merchant_country_code: authentication.acquirer_country_code.clone(),
};
Ok(Self {
transaction_status: authentication.trans_status.clone(),
acs_url,
challenge_request: authentication.challenge_request.clone(),
acs_reference_number: authentication.acs_reference_number.clone(),
acs_trans_id: authentication.acs_trans_id.clone(),
three_ds_server_transaction_id: authentication.threeds_server_transaction_id.clone(),
acs_signed_content: authentication.acs_signed_content.clone(),
three_ds_requestor_url: authentication_details.three_ds_requestor_url.clone(),
three_ds_requestor_app_url: authentication_details.three_ds_requestor_app_url.clone(),
error_code: None,
error_message: authentication.error_message.clone(),
authentication_value,
status: authentication.authentication_status,
authentication_connector,
eci,
authentication_id: authentication.authentication_id.clone(),
acquirer_details: Some(acquirer_details),
})
}
}
#[cfg(feature = "v1")]
pub async fn authentication_sync_core(
state: SessionState,
merchant_context: domain::MerchantContext,
auth_flow: AuthFlow,
req: AuthenticationSyncRequest,
) -> RouterResponse<AuthenticationSyncResponse> {
let authentication_id = req.authentication_id;
let merchant_account = merchant_context.get_merchant_account();
let merchant_id = merchant_account.get_id();
let db = &*state.store;
let authentication = db
.find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id)
.await
.to_not_found_response(ApiErrorResponse::AuthenticationNotFound {
id: authentication_id.get_string_repr().to_owned(),
})?;
req.client_secret
.map(|client_secret| {
utils::authenticate_authentication_client_secret_and_check_expiry(
client_secret.peek(),
&authentication,
)
})
.transpose()?;
let key_manager_state = (&state).into();
let profile_id = authentication.profile_id.clone();
let business_profile = db
.find_business_profile_by_profile_id(
&key_manager_state,
merchant_context.get_merchant_key_store(),
&profile_id,
)
.await
.to_not_found_response(ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let (authentication_connector, three_ds_connector_account) =
auth_utils::get_authentication_connector_data(
&state,
merchant_context.get_merchant_key_store(),
&business_profile,
authentication.authentication_connector.clone(),
)
.await?;
let updated_authentication = match authentication.trans_status.clone() {
Some(trans_status) if trans_status.clone().is_pending() => {
let post_auth_response = ExternalAuthentication::post_authentication(
&state,
&business_profile,
None,
&three_ds_connector_account,
&authentication_connector.to_string(),
&authentication_id,
common_enums::PaymentMethod::Card,
merchant_id,
Some(&authentication),
)
.await?;
utils::external_authentication_update_trackers(
&state,
post_auth_response,
authentication.clone(),
None,
merchant_context.get_merchant_key_store(),
None,
None,
None,
None,
)
.await?
}
_ => authentication,
};
let (authentication_value, eci) = match auth_flow {
AuthFlow::Client => (None, None),
AuthFlow::Merchant => {
if let Some(common_enums::TransactionStatus::Success) =
updated_authentication.trans_status
{
let tokenised_data = crate::core::payment_methods::vault::get_tokenized_data(
&state,
authentication_id.get_string_repr(),
false,
merchant_context.get_merchant_key_store().key.get_inner(),
)
.await
.inspect_err(|err| router_env::logger::error!(tokenized_data_result=?err))
.attach_printable("cavv not present after authentication status is success")?;
(
Some(masking::Secret::new(tokenised_data.value1)),
updated_authentication.eci.clone(),
)
} else {
(None, None)
}
}
};
let acquirer_details = Some(AcquirerDetails {
acquirer_bin: updated_authentication.acquirer_bin.clone(),
acquirer_merchant_id: updated_authentication.acquirer_merchant_id.clone(),
merchant_country_code: updated_authentication.acquirer_country_code.clone(),
});
let encrypted_data = domain::types::crypto_operation(
&key_manager_state,
common_utils::type_name!(hyperswitch_domain_models::authentication::Authentication),
domain::types::CryptoOperation::BatchDecrypt(
hyperswitch_domain_models::authentication::EncryptedAuthentication::to_encryptable(
hyperswitch_domain_models::authentication::EncryptedAuthentication {
billing_address: updated_authentication.billing_address,
shipping_address: updated_authentication.shipping_address,
},
),
),
common_utils::types::keymanager::Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt authentication data".to_string())?;
let encrypted_data = hyperswitch_domain_models::authentication::FromRequestEncryptableAuthentication::from_encryptable(encrypted_data)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to get encrypted data for authentication after encryption")?;
let email_decrypted = updated_authentication
.email
.clone()
.async_lift(|inner| async {
domain::types::crypto_operation(
&key_manager_state,
common_utils::type_name!(Authentication),
domain::types::CryptoOperation::DecryptOptional(inner),
common_utils::types::keymanager::Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt email")?;
let browser_info = updated_authentication
.browser_info
.clone()
.map(|browser_info| {
browser_info.parse_value::<payments::BrowserInformation>("BrowserInformation")
})
.transpose()
.change_context(ApiErrorResponse::InternalServerError)?;
let amount = updated_authentication
.amount
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("amount failed to get amount from authentication table")?;
let currency = updated_authentication
.currency
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("currency failed to get currency from authentication table")?;
let authentication_connector = updated_authentication
.authentication_connector
.map(|connector| common_enums::AuthenticationConnectors::from_str(&connector))
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Incorrect authentication connector stored in table")?;
let billing = encrypted_data
.billing_address
.map(|billing| {
billing
.into_inner()
.expose()
.parse_value::<payments::Address>("Address")
})
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse billing address")?;
let shipping = encrypted_data
.shipping_address
.map(|shipping| {
shipping
.into_inner()
.expose()
.parse_value::<payments::Address>("Address")
})
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse shipping address")?;
let response = AuthenticationSyncResponse {
authentication_id: authentication_id.clone(),
merchant_id: merchant_id.clone(),
status: updated_authentication.authentication_status,
client_secret: updated_authentication
.authentication_client_secret
.map(masking::Secret::new),
amount,
currency,
authentication_connector,
force_3ds_challenge: updated_authentication.force_3ds_challenge,
return_url: updated_authentication.return_url.clone(),
created_at: updated_authentication.created_at,
profile_id: updated_authentication.profile_id.clone(),
psd2_sca_exemption_type: updated_authentication.psd2_sca_exemption_type,
acquirer_details,
error_message: updated_authentication.error_message.clone(),
error_code: updated_authentication.error_code.clone(),
authentication_value,
threeds_server_transaction_id: updated_authentication.threeds_server_transaction_id.clone(),
maximum_supported_3ds_version: updated_authentication.maximum_supported_version.clone(),
connector_authentication_id: updated_authentication.connector_authentication_id.clone(),
three_ds_method_data: updated_authentication.three_ds_method_data.clone(),
three_ds_method_url: updated_authentication.three_ds_method_url.clone(),
message_version: updated_authentication.message_version.clone(),
connector_metadata: updated_authentication.connector_metadata.clone(),
directory_server_id: updated_authentication.directory_server_id.clone(),
billing,
shipping,
browser_information: browser_info,
email: email_decrypted,
transaction_status: updated_authentication.trans_status.clone(),
acs_url: updated_authentication.acs_url.clone(),
challenge_request: updated_authentication.challenge_request.clone(),
acs_reference_number: updated_authentication.acs_reference_number.clone(),
acs_trans_id: updated_authentication.acs_trans_id.clone(),
acs_signed_content: updated_authentication.acs_signed_content,
three_ds_requestor_url: business_profile
.authentication_connector_details
.clone()
.map(|details| details.three_ds_requestor_url),
three_ds_requestor_app_url: business_profile
.authentication_connector_details
.and_then(|details| details.three_ds_requestor_app_url),
profile_acquirer_id: updated_authentication.profile_acquirer_id.clone(),
eci,
};
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
#[cfg(feature = "v1")]
pub async fn authentication_post_sync_core(
state: SessionState,
merchant_context: domain::MerchantContext,
req: AuthenticationSyncPostUpdateRequest,
) -> RouterResponse<()> {
let authentication_id = req.authentication_id;
let merchant_account = merchant_context.get_merchant_account();
let merchant_id = merchant_account.get_id();
let db = &*state.store;
let authentication = db
.find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id)
.await
.to_not_found_response(ApiErrorResponse::AuthenticationNotFound {
id: authentication_id.get_string_repr().to_owned(),
})?;
ensure_not_terminal_status(authentication.trans_status.clone())?;
let key_manager_state = (&state).into();
let business_profile = db
.find_business_profile_by_profile_id(
&key_manager_state,
merchant_context.get_merchant_key_store(),
&authentication.profile_id,
)
.await
.to_not_found_response(ApiErrorResponse::ProfileNotFound {
id: authentication.profile_id.get_string_repr().to_owned(),
})?;
let (authentication_connector, three_ds_connector_account) =
auth_utils::get_authentication_connector_data(
&state,
merchant_context.get_merchant_key_store(),
&business_profile,
authentication.authentication_connector.clone(),
)
.await?;
let post_auth_response =
<ExternalAuthentication as UnifiedAuthenticationService>::post_authentication(
&state,
&business_profile,
None,
&three_ds_connector_account,
&authentication_connector.to_string(),
&authentication_id,
common_enums::PaymentMethod::Card,
merchant_id,
Some(&authentication),
)
.await?;
let updated_authentication = utils::external_authentication_update_trackers(
&state,
post_auth_response,
authentication.clone(),
None,
merchant_context.get_merchant_key_store(),
None,
None,
None,
None,
)
.await?;
let authentication_details = business_profile
.authentication_connector_details
.clone()
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("authentication_connector_details not configured by the merchant")?;
let authentication_response = AuthenticationAuthenticateResponse::foreign_try_from((
&updated_authentication,
None,
None,
authentication_details,
))?;
let redirect_response = helpers::get_handle_response_url_for_modular_authentication(
authentication_id,
&business_profile,
&authentication_response,
authentication_connector.to_string(),
authentication.return_url,
updated_authentication
.authentication_client_secret
.clone()
.map(masking::Secret::new)
.as_ref(),
updated_authentication.amount,
)?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::JsonForRedirection(redirect_response))
}
fn ensure_not_terminal_status(
status: Option<common_enums::TransactionStatus>,
) -> Result<(), error_stack::Report<ApiErrorResponse>> {
status
.filter(|s| s.clone().is_terminal_state())
.map(|s| {
Err(error_stack::Report::new(
ApiErrorResponse::UnprocessableEntity {
message: format!(
"authentication status for the given authentication_id is already in {s}"
),
},
))
})
.unwrap_or(Ok(()))
}
|
crates/router/src/core/unified_authentication_service.rs#chunk1
|
router
|
chunk
| null | null | null | 4,880
| null | null | null | null | null | null | null |
// File: crates/router/src/routes/fraud_check.rs
// Module: router
// Public functions: 1
use actix_web::{web, HttpRequest, HttpResponse};
use router_env::Flow;
use crate::{
core::{api_locking, fraud_check as frm_core},
services::{self, api},
types::domain,
AppState,
};
#[cfg(feature = "v1")]
pub async fn frm_fulfillment(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<frm_core::types::FrmFulfillmentRequest>,
) -> HttpResponse {
let flow = Flow::FrmFulfillment;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, auth: services::authentication::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
frm_core::frm_fulfillment_core(state, merchant_context, req)
},
&services::authentication::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/fraud_check.rs
|
router
|
full_file
| null | null | null | 275
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentSession for for Volt
// File: crates/hyperswitch_connectors/src/connectors/volt.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSession for for Volt
|
crates/hyperswitch_connectors/src/connectors/volt.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 55
| null |
Volt
|
api::PaymentSession for
| 0
| 0
| null | null |
// Implementation: impl Loonio
// File: crates/hyperswitch_connectors/src/connectors/loonio.rs
// Module: hyperswitch_connectors
// Methods: 1 total (1 public)
impl Loonio
|
crates/hyperswitch_connectors/src/connectors/loonio.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 46
| null |
Loonio
| null | 1
| 1
| null | null |
// Implementation: impl MerchantConnectorAccountInterface for for KafkaStore
// File: crates/router/src/db/kafka_store.rs
// Module: router
// Methods: 13 total (0 public)
impl MerchantConnectorAccountInterface for for KafkaStore
|
crates/router/src/db/kafka_store.rs
|
router
|
impl_block
| null | null | null | 50
| null |
KafkaStore
|
MerchantConnectorAccountInterface for
| 13
| 0
| null | null |
// Implementation: impl api::Refund for for Archipel
// File: crates/hyperswitch_connectors/src/connectors/archipel.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::Refund for for Archipel
|
crates/hyperswitch_connectors/src/connectors/archipel.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Archipel
|
api::Refund for
| 0
| 0
| null | null |
// Function: find_by_connector_transaction_id_payment_id_merchant_id
// File: crates/diesel_models/src/query/payment_attempt.rs
// Module: diesel_models
pub fn find_by_connector_transaction_id_payment_id_merchant_id(
conn: &PgPooledConn,
connector_transaction_id: &common_utils::types::ConnectorTransactionId,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self>
|
crates/diesel_models/src/query/payment_attempt.rs
|
diesel_models
|
function_signature
| null | null | null | 105
|
find_by_connector_transaction_id_payment_id_merchant_id
| null | null | null | null | null | null |
// Struct: ActivateRoutingConfigRequest
// File: crates/router/src/core/payments/routing/utils.rs
// Module: router
// Implementations: 0
pub struct ActivateRoutingConfigRequest
|
crates/router/src/core/payments/routing/utils.rs
|
router
|
struct_definition
|
ActivateRoutingConfigRequest
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Struct: ProcessedAmountAccumulator
// File: crates/analytics/src/payment_intents/accumulator.rs
// Module: analytics
// Implementations: 1
// Traits: PaymentIntentMetricAccumulator
pub struct ProcessedAmountAccumulator
|
crates/analytics/src/payment_intents/accumulator.rs
|
analytics
|
struct_definition
|
ProcessedAmountAccumulator
| 1
|
[
"PaymentIntentMetricAccumulator"
] | 54
| null | null | null | null | null | null | null |
// Function: get_external_vault_token
// File: crates/router/src/core/payment_methods.rs
// Module: router
pub fn get_external_vault_token(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
payment_token: String,
vault_token: domain::VaultToken,
payment_method_type: &storage_enums::PaymentMethod,
) -> CustomResult<domain::ExternalVaultPaymentMethodData, errors::ApiErrorResponse>
|
crates/router/src/core/payment_methods.rs
|
router
|
function_signature
| null | null | null | 107
|
get_external_vault_token
| null | null | null | null | null | null |
// Struct: DwollaAuthType
// File: crates/hyperswitch_connectors/src/connectors/dwolla/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct DwollaAuthType
|
crates/hyperswitch_connectors/src/connectors/dwolla/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
DwollaAuthType
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Struct: NexixpayPaymentsCancelRequest
// File: crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct NexixpayPaymentsCancelRequest
|
crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
NexixpayPaymentsCancelRequest
| 0
|
[] | 55
| null | null | null | null | null | null | null |
// Implementation: impl api::RefundExecute for for Worldpayxml
// File: crates/hyperswitch_connectors/src/connectors/worldpayxml.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundExecute for for Worldpayxml
|
crates/hyperswitch_connectors/src/connectors/worldpayxml.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 62
| null |
Worldpayxml
|
api::RefundExecute for
| 0
| 0
| null | null |
// Implementation: impl RoutingApproach
// File: crates/router/src/core/payments/routing/utils.rs
// Module: router
// Methods: 1 total (1 public)
impl RoutingApproach
|
crates/router/src/core/payments/routing/utils.rs
|
router
|
impl_block
| null | null | null | 41
| null |
RoutingApproach
| null | 1
| 1
| null | null |
// Implementation: impl std::fmt::Display for for PartitionKey
// File: crates/storage_impl/src/redis/kv_store.rs
// Module: storage_impl
// Methods: 1 total (0 public)
impl std::fmt::Display for for PartitionKey
|
crates/storage_impl/src/redis/kv_store.rs
|
storage_impl
|
impl_block
| null | null | null | 54
| null |
PartitionKey
|
std::fmt::Display for
| 1
| 0
| null | null |
// Struct: ClientProcessorInformation
// File: crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ClientProcessorInformation
|
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ClientProcessorInformation
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Struct: Affirm
// File: crates/hyperswitch_connectors/src/connectors/affirm.rs
// Module: hyperswitch_connectors
// Implementations: 18
// Traits: api::Payment, api::PaymentSession, api::ConnectorAccessToken, api::MandateSetup, api::PaymentAuthorize, api::PaymentsCompleteAuthorize, api::PaymentSync, api::PaymentCapture, api::PaymentVoid, api::Refund, api::RefundExecute, api::RefundSync, api::PaymentToken, ConnectorCommon, ConnectorValidation, webhooks::IncomingWebhook, ConnectorSpecifications
pub struct Affirm
|
crates/hyperswitch_connectors/src/connectors/affirm.rs
|
hyperswitch_connectors
|
struct_definition
|
Affirm
| 18
|
[
"api::Payment",
"api::PaymentSession",
"api::ConnectorAccessToken",
"api::MandateSetup",
"api::PaymentAuthorize",
"api::PaymentsCompleteAuthorize",
"api::PaymentSync",
"api::PaymentCapture",
"api::PaymentVoid",
"api::Refund",
"api::RefundExecute",
"api::RefundSync",
"api::PaymentToken",
"ConnectorCommon",
"ConnectorValidation",
"webhooks::IncomingWebhook",
"ConnectorSpecifications"
] | 132
| null | null | null | null | null | null | null |
// Implementation: impl ConnectorValidation for for Klarna
// File: crates/hyperswitch_connectors/src/connectors/klarna.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl ConnectorValidation for for Klarna
|
crates/hyperswitch_connectors/src/connectors/klarna.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 54
| null |
Klarna
|
ConnectorValidation for
| 0
| 0
| null | null |
// Struct: SRApiClient
// File: crates/router/src/core/payments/routing/utils.rs
// Module: router
// Implementations: 1
// Traits: DecisionEngineApiHandler
pub struct SRApiClient
|
crates/router/src/core/payments/routing/utils.rs
|
router
|
struct_definition
|
SRApiClient
| 1
|
[
"DecisionEngineApiHandler"
] | 48
| null | null | null | null | null | null | null |
// Implementation: impl NovalnetSyncResponseTransactionData
// File: crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
// Module: hyperswitch_connectors
// Methods: 1 total (1 public)
impl NovalnetSyncResponseTransactionData
|
crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
NovalnetSyncResponseTransactionData
| null | 1
| 1
| null | null |
// Struct: DigitalvirgoErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/digitalvirgo/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct DigitalvirgoErrorResponse
|
crates/hyperswitch_connectors/src/connectors/digitalvirgo/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
DigitalvirgoErrorResponse
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Trait: EmailClient
// File: crates/external_services/src/email.rs
// Module: external_services
pub trait EmailClient: Sync + Send + dyn_clone::DynClone
|
crates/external_services/src/email.rs
|
external_services
|
trait_definition
| null | null | null | 37
| null | null |
EmailClient
| null | null | null | null |
// Implementation: impl api::RefundSync for for Dlocal
// File: crates/hyperswitch_connectors/src/connectors/dlocal.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundSync for for Dlocal
|
crates/hyperswitch_connectors/src/connectors/dlocal.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Dlocal
|
api::RefundSync for
| 0
| 0
| null | null |
// Implementation: impl ConnectorEvent
// File: crates/hyperswitch_interfaces/src/events/connector_api_logs.rs
// Module: hyperswitch_interfaces
// Methods: 8 total (4 public)
impl ConnectorEvent
|
crates/hyperswitch_interfaces/src/events/connector_api_logs.rs
|
hyperswitch_interfaces
|
impl_block
| null | null | null | 44
| null |
ConnectorEvent
| null | 8
| 4
| null | null |
// Function: get_cache_key_from_role_id
// File: crates/router/src/services/authorization.rs
// Module: router
pub fn get_cache_key_from_role_id(role_id: &str) -> String
|
crates/router/src/services/authorization.rs
|
router
|
function_signature
| null | null | null | 42
|
get_cache_key_from_role_id
| null | null | null | null | null | null |
// Function: encrypt
// File: crates/external_services/src/no_encryption/core.rs
// Module: external_services
// Documentation: Encryption functionality
pub fn encrypt(&self, data: impl AsRef<[u8]>) -> Vec<u8>
|
crates/external_services/src/no_encryption/core.rs
|
external_services
|
function_signature
| null | null | null | 52
|
encrypt
| null | null | null | null | null | null |
// Implementation: impl PaymentRedirectFlow for for PaymentRedirectCompleteAuthorize
// File: crates/router/src/core/payments.rs
// Module: router
// Methods: 3 total (0 public)
impl PaymentRedirectFlow for for PaymentRedirectCompleteAuthorize
|
crates/router/src/core/payments.rs
|
router
|
impl_block
| null | null | null | 50
| null |
PaymentRedirectCompleteAuthorize
|
PaymentRedirectFlow for
| 3
| 0
| null | null |
// Struct: FeatureMetadata
// File: crates/diesel_models/src/types.rs
// Module: diesel_models
// Implementations: 1
pub struct FeatureMetadata
|
crates/diesel_models/src/types.rs
|
diesel_models
|
struct_definition
|
FeatureMetadata
| 1
|
[] | 34
| null | null | null | null | null | null | null |
// Function: build_auth_array
// File: crates/analytics/src/opensearch.rs
// Module: analytics
pub fn build_auth_array(&self) -> Vec<Value>
|
crates/analytics/src/opensearch.rs
|
analytics
|
function_signature
| null | null | null | 36
|
build_auth_array
| null | null | null | null | null | null |
// Function: get_create_file_request
// File: crates/router/src/routes/files/transformers.rs
// Module: router
pub fn get_create_file_request(
mut payload: Multipart,
) -> CustomResult<CreateFileRequest, errors::ApiErrorResponse>
|
crates/router/src/routes/files/transformers.rs
|
router
|
function_signature
| null | null | null | 54
|
get_create_file_request
| null | null | null | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.