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
⌀ |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
// Struct: MaxLatency
// File: crates/analytics/src/api_event/metrics/latency.rs
// Module: analytics
// Implementations: 0
pub struct MaxLatency
|
crates/analytics/src/api_event/metrics/latency.rs
|
analytics
|
struct_definition
|
MaxLatency
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Struct: PayoutCreateResponse
// File: crates/api_models/src/payouts.rs
// Module: api_models
// Implementations: 0
pub struct PayoutCreateResponse
|
crates/api_models/src/payouts.rs
|
api_models
|
struct_definition
|
PayoutCreateResponse
| 0
|
[] | 39
| null | null | null | null | null | null | null |
// Struct: SquareTokenResponse
// File: crates/hyperswitch_connectors/src/connectors/square/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct SquareTokenResponse
|
crates/hyperswitch_connectors/src/connectors/square/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
SquareTokenResponse
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Struct: LoanInformation
// File: crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct LoanInformation
|
crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
LoanInformation
| 0
|
[] | 46
| null | null | null | null | null | null | null |
// Implementation: impl webhooks::IncomingWebhook for for Vgs
// File: crates/hyperswitch_connectors/src/connectors/vgs.rs
// Module: hyperswitch_connectors
// Methods: 3 total (0 public)
impl webhooks::IncomingWebhook for for Vgs
|
crates/hyperswitch_connectors/src/connectors/vgs.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Vgs
|
webhooks::IncomingWebhook for
| 3
| 0
| null | null |
// Struct: RefundResponse
// File: crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct RefundResponse
|
crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
RefundResponse
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// File: crates/router/src/types/storage/kv.rs
// Module: router
pub use diesel_models::kv::{
AddressUpdateMems, DBOperation, Insertable, PaymentAttemptUpdateMems, PaymentIntentUpdateMems,
RefundUpdateMems, TypedSql, Updateable,
};
|
crates/router/src/types/storage/kv.rs
|
router
|
full_file
| null | null | null | 63
| null | null | null | null | null | null | null |
// Function: get_gsm
// File: crates/router/src/core/payouts/retry.rs
// Module: router
pub fn get_gsm(
state: &app::SessionState,
original_connector_data: &api::ConnectorData,
payout_data: &PayoutData,
) -> RouterResult<Option<hyperswitch_domain_models::gsm::GatewayStatusMap>>
|
crates/router/src/core/payouts/retry.rs
|
router
|
function_signature
| null | null | null | 80
|
get_gsm
| null | null | null | null | null | null |
// Struct: PayuPaymentsRequest
// File: crates/hyperswitch_connectors/src/connectors/payu/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PayuPaymentsRequest
|
crates/hyperswitch_connectors/src/connectors/payu/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PayuPaymentsRequest
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Struct: PaymentMethodInfo
// File: crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaymentMethodInfo
|
crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaymentMethodInfo
| 0
|
[] | 46
| null | null | null | null | null | null | null |
// Implementation: impl ConnectorCommon for for Gpayments
// File: crates/hyperswitch_connectors/src/connectors/gpayments.rs
// Module: hyperswitch_connectors
// Methods: 6 total (0 public)
impl ConnectorCommon for for Gpayments
|
crates/hyperswitch_connectors/src/connectors/gpayments.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 53
| null |
Gpayments
|
ConnectorCommon for
| 6
| 0
| null | null |
// Implementation: impl ConnectorValidation for for Nuvei
// File: crates/hyperswitch_connectors/src/connectors/nuvei.rs
// Module: hyperswitch_connectors
// Methods: 1 total (0 public)
impl ConnectorValidation for for Nuvei
|
crates/hyperswitch_connectors/src/connectors/nuvei.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Nuvei
|
ConnectorValidation for
| 1
| 0
| null | null |
// Struct: ConfirmSubscriptionResponse
// File: crates/api_models/src/subscription.rs
// Module: api_models
// Implementations: 1
// Traits: ApiEventMetric
pub struct ConfirmSubscriptionResponse
|
crates/api_models/src/subscription.rs
|
api_models
|
struct_definition
|
ConfirmSubscriptionResponse
| 1
|
[
"ApiEventMetric"
] | 43
| null | null | null | null | null | null | null |
// Function: get_expiry_date_as_mmyy
// File: crates/common_types/src/payments.rs
// Module: common_types
// Documentation: Get the expiry date in MMYY format from the Apple Pay pre-decrypt data
pub fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ValidationError>
|
crates/common_types/src/payments.rs
|
common_types
|
function_signature
| null | null | null | 70
|
get_expiry_date_as_mmyy
| null | null | null | null | null | null |
// Struct: StripePaymentMethodData
// File: crates/router/src/compatibility/stripe/payment_intents/types.rs
// Module: router
// Implementations: 0
pub struct StripePaymentMethodData
|
crates/router/src/compatibility/stripe/payment_intents/types.rs
|
router
|
struct_definition
|
StripePaymentMethodData
| 0
|
[] | 43
| null | null | null | null | null | null | null |
// Function: list_webhook_delivery_attempts
// File: crates/router/src/routes/webhook_events.rs
// Module: router
pub fn list_webhook_delivery_attempts(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(common_utils::id_type::MerchantId, String)
|
crates/router/src/routes/webhook_events.rs
|
router
|
function_signature
| null | null | null | 66
|
list_webhook_delivery_attempts
| null | null | null | null | null | null |
// Function: payments_list
// File: crates/router/src/routes/payments.rs
// Module: router
pub fn payments_list(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Query<payment_types::PaymentListConstraints>,
) -> impl Responder
|
crates/router/src/routes/payments.rs
|
router
|
function_signature
| null | null | null | 66
|
payments_list
| null | null | null | null | null | null |
// Function: new
// File: crates/common_utils/src/request.rs
// Module: common_utils
pub fn new(method: Method, url: &str) -> Self
|
crates/common_utils/src/request.rs
|
common_utils
|
function_signature
| null | null | null | 35
|
new
| null | null | null | null | null | null |
// Function: get_mandate_reference
// File: crates/hyperswitch_connectors/src/connectors/celero/transformers.rs
// Module: hyperswitch_connectors
pub fn get_mandate_reference(&self) -> Box<Option<MandateReference>>
|
crates/hyperswitch_connectors/src/connectors/celero/transformers.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 56
|
get_mandate_reference
| null | null | null | null | null | null |
// Implementation: impl PaymentSync for for DummyConnector
// File: crates/hyperswitch_connectors/src/connectors/dummyconnector.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl PaymentSync for for DummyConnector
|
crates/hyperswitch_connectors/src/connectors/dummyconnector.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 54
| null |
DummyConnector
|
PaymentSync for
| 0
| 0
| null | null |
// Struct: PrimaryBusinessDetails
// File: crates/api_models/src/admin.rs
// Module: api_models
// Implementations: 0
pub struct PrimaryBusinessDetails
|
crates/api_models/src/admin.rs
|
api_models
|
struct_definition
|
PrimaryBusinessDetails
| 0
|
[] | 35
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentSession for for Gigadat
// File: crates/hyperswitch_connectors/src/connectors/gigadat.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSession for for Gigadat
|
crates/hyperswitch_connectors/src/connectors/gigadat.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Gigadat
|
api::PaymentSession for
| 0
| 0
| null | null |
// File: crates/drainer/src/connection.rs
// Module: drainer
// Public functions: 3
use bb8::PooledConnection;
use common_utils::DbConnectionParams;
use diesel::PgConnection;
use crate::{settings::Database, Settings};
pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>;
#[allow(clippy::expect_used)]
pub async fn redis_connection(conf: &Settings) -> redis_interface::RedisConnectionPool {
redis_interface::RedisConnectionPool::new(&conf.redis)
.await
.expect("Failed to create Redis connection Pool")
}
// TODO: use stores defined in storage_impl instead
/// # Panics
///
/// Will panic if could not create a db pool
#[allow(clippy::expect_used)]
pub async fn diesel_make_pg_pool(
database: &Database,
_test_transaction: bool,
schema: &str,
) -> PgPool {
let database_url = database.get_database_url(schema);
let manager = async_bb8_diesel::ConnectionManager::<PgConnection>::new(database_url);
let pool = bb8::Pool::builder()
.max_size(database.pool_size)
.connection_timeout(std::time::Duration::from_secs(database.connection_timeout));
pool.build(manager)
.await
.expect("Failed to create PostgreSQL connection pool")
}
#[allow(clippy::expect_used)]
pub async fn pg_connection(
pool: &PgPool,
) -> PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>> {
pool.get()
.await
.expect("Couldn't retrieve PostgreSQL connection")
}
|
crates/drainer/src/connection.rs
|
drainer
|
full_file
| null | null | null | 347
| null | null | null | null | null | null | null |
// Function: wrap
// File: crates/common_utils/src/id_type/payment.rs
// Module: common_utils
// Documentation: Wrap a string inside PaymentId
pub fn wrap(payment_id_string: String) -> CustomResult<Self, ValidationError>
|
crates/common_utils/src/id_type/payment.rs
|
common_utils
|
function_signature
| null | null | null | 49
|
wrap
| null | null | null | null | null | null |
// File: crates/router/src/core/fraud_check/flows/transaction_flow.rs
// Module: router
// Public functions: 1
use async_trait::async_trait;
use common_utils::ext_traits::ValueExt;
use error_stack::ResultExt;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
fraud_check::{FeatureFrm, FrmData},
payments::{self, flows::ConstructFlowSpecificData, helpers},
},
errors, services,
types::{
api::fraud_check as frm_api,
domain,
fraud_check::{
FraudCheckResponseData, FraudCheckTransactionData, FrmTransactionRouterData,
},
storage::enums as storage_enums,
ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData,
},
SessionState,
};
#[async_trait]
impl
ConstructFlowSpecificData<
frm_api::Transaction,
FraudCheckTransactionData,
FraudCheckResponseData,
> for FrmData
{
#[cfg(feature = "v2")]
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<MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<
RouterData<frm_api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>,
> {
todo!()
}
#[cfg(feature = "v1")]
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<MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<
RouterData<frm_api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>,
> {
let status = storage_enums::AttemptStatus::Pending;
let auth_type: ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: "ConnectorAuthType".to_string(),
})?;
let customer_id = customer.to_owned().map(|customer| customer.customer_id);
let payment_method = self.payment_attempt.payment_method;
let currency = self.payment_attempt.currency;
let router_data = RouterData {
flow: std::marker::PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
tenant_id: state.tenant.tenant_id.clone(),
customer_id,
connector: connector_id.to_string(),
payment_id: self.payment_intent.payment_id.get_string_repr().to_owned(),
attempt_id: self.payment_attempt.attempt_id.clone(),
status,
payment_method: self
.payment_attempt
.payment_method
.ok_or(errors::ApiErrorResponse::PaymentMethodNotFound)?,
connector_auth_type: auth_type,
description: None,
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
connector_wallets_details: None,
amount_captured: None,
minor_amount_captured: None,
request: FraudCheckTransactionData {
amount: self
.payment_attempt
.net_amount
.get_total_amount()
.get_amount_as_i64(),
order_details: self.order_details.clone(),
currency,
payment_method,
error_code: self.payment_attempt.error_code.clone(),
error_message: self.payment_attempt.error_message.clone(),
connector_transaction_id: self
.payment_attempt
.get_connector_payment_id()
.map(ToString::to_string),
connector: self.payment_attempt.connector.clone(),
}, // self.order_details
response: Ok(FraudCheckResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId("".to_string()),
connector_metadata: None,
status: storage_enums::FraudCheckStatus::Pending,
score: None,
reason: None,
}),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
preprocessing_id: None,
connector_request_reference_id: uuid::Uuid::new_v4().to_string(),
test_mode: None,
recurring_mandate_payment_data: None,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
payment_method_balance: None,
connector_http_status_code: None,
external_latency: None,
connector_api_version: None,
payment_method_status: None,
apple_pay_flow: None,
frm_metadata: self.frm_metadata.clone(),
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
};
Ok(router_data)
}
}
#[async_trait]
impl FeatureFrm<frm_api::Transaction, FraudCheckTransactionData> for FrmTransactionRouterData {
async fn decide_frm_flows<'a>(
mut self,
state: &SessionState,
connector: &frm_api::FraudCheckConnectorData,
call_connector_action: payments::CallConnectorAction,
merchant_context: &domain::MerchantContext,
) -> RouterResult<Self> {
decide_frm_flow(
&mut self,
state,
connector,
call_connector_action,
merchant_context,
)
.await
}
}
pub async fn decide_frm_flow(
router_data: &mut FrmTransactionRouterData,
state: &SessionState,
connector: &frm_api::FraudCheckConnectorData,
call_connector_action: payments::CallConnectorAction,
_merchant_context: &domain::MerchantContext,
) -> RouterResult<FrmTransactionRouterData> {
let connector_integration: services::BoxedFrmConnectorIntegrationInterface<
frm_api::Transaction,
FraudCheckTransactionData,
FraudCheckResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
router_data,
call_connector_action,
None,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
|
crates/router/src/core/fraud_check/flows/transaction_flow.rs
|
router
|
full_file
| null | null | null | 1,499
| null | null | null | null | null | null | null |
// Struct: SilverflowAuthType
// File: crates/hyperswitch_connectors/src/connectors/silverflow/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct SilverflowAuthType
|
crates/hyperswitch_connectors/src/connectors/silverflow/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
SilverflowAuthType
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Function: build_webhook_secrets_from_merchant_connector_account
// File: crates/router/src/core/unified_connector_service.rs
// Module: router
pub fn build_webhook_secrets_from_merchant_connector_account(
#[cfg(feature = "v1")
|
crates/router/src/core/unified_connector_service.rs
|
router
|
function_signature
| null | null | null | 54
|
build_webhook_secrets_from_merchant_connector_account
| null | null | null | null | null | null |
// Function: store_data_in_redis
// File: crates/router/src/routes/dummy_connector/utils.rs
// Module: router
pub fn store_data_in_redis(
state: &SessionState,
key: String,
data: impl serde::Serialize + Debug,
ttl: i64,
) -> types::DummyConnectorResult<()>
|
crates/router/src/routes/dummy_connector/utils.rs
|
router
|
function_signature
| null | null | null | 70
|
store_data_in_redis
| null | null | null | null | null | null |
// Module Structure
// File: crates/hyperswitch_connectors/src/connectors/coingate.rs
// Module: hyperswitch_connectors
// Public submodules:
pub mod transformers;
|
crates/hyperswitch_connectors/src/connectors/coingate.rs
|
hyperswitch_connectors
|
module_structure
| null | null | null | 39
| null | null | null | null | null | 1
| 0
|
// Function: retrieve_customer
// File: crates/router/src/core/customers.rs
// Module: router
pub fn retrieve_customer(
state: SessionState,
merchant_context: domain::MerchantContext,
_profile_id: Option<id_type::ProfileId>,
customer_id: id_type::CustomerId,
) -> errors::CustomerResponse<customers::CustomerResponse>
|
crates/router/src/core/customers.rs
|
router
|
function_signature
| null | null | null | 76
|
retrieve_customer
| null | null | null | null | null | null |
// Function: get_allowed_signals
// File: crates/common_utils/src/signals.rs
// Module: common_utils
pub fn get_allowed_signals() -> Result<signal_hook_tokio::SignalsInfo, std::io::Error>
|
crates/common_utils/src/signals.rs
|
common_utils
|
function_signature
| null | null | null | 47
|
get_allowed_signals
| null | null | null | null | null | null |
// Implementation: impl OperationsDeriveInputExt for for DeriveInput
// File: crates/router_derive/src/macros/operation.rs
// Module: router_derive
// Methods: 1 total (0 public)
impl OperationsDeriveInputExt for for DeriveInput
|
crates/router_derive/src/macros/operation.rs
|
router_derive
|
impl_block
| null | null | null | 57
| null |
DeriveInput
|
OperationsDeriveInputExt for
| 1
| 0
| null | null |
// Function: get_dispute_dimensions
// File: crates/analytics/src/utils.rs
// Module: analytics
pub fn get_dispute_dimensions() -> Vec<NameDescription>
|
crates/analytics/src/utils.rs
|
analytics
|
function_signature
| null | null | null | 36
|
get_dispute_dimensions
| null | null | null | null | null | null |
// Implementation: impl ConnectorCommon for for Payu
// File: crates/hyperswitch_connectors/src/connectors/payu.rs
// Module: hyperswitch_connectors
// Methods: 5 total (0 public)
impl ConnectorCommon for for Payu
|
crates/hyperswitch_connectors/src/connectors/payu.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 53
| null |
Payu
|
ConnectorCommon for
| 5
| 0
| null | null |
// Implementation: impl api::ConnectorAccessToken for for Stax
// File: crates/hyperswitch_connectors/src/connectors/stax.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::ConnectorAccessToken for for Stax
|
crates/hyperswitch_connectors/src/connectors/stax.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Stax
|
api::ConnectorAccessToken for
| 0
| 0
| null | null |
// Struct: DeutschebankMandatePostResponse
// File: crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct DeutschebankMandatePostResponse
|
crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
DeutschebankMandatePostResponse
| 0
|
[] | 56
| null | null | null | null | null | null | null |
// Function: store_card_and_token_in_locker
// File: crates/router/src/core/payment_methods/tokenize/card_executor.rs
// Module: router
pub fn store_card_and_token_in_locker(
&self,
network_token: &NetworkTokenizationResponse,
card: &domain::CardDetail,
customer_id: &id_type::CustomerId,
) -> RouterResult<StoreLockerResponse>
|
crates/router/src/core/payment_methods/tokenize/card_executor.rs
|
router
|
function_signature
| null | null | null | 84
|
store_card_and_token_in_locker
| null | null | null | null | null | null |
// Function: get_order_fulfillment_time
// File: crates/hyperswitch_domain_models/src/business_profile.rs
// Module: hyperswitch_domain_models
pub fn get_order_fulfillment_time(&self) -> Option<i64>
|
crates/hyperswitch_domain_models/src/business_profile.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 50
|
get_order_fulfillment_time
| null | null | null | null | null | null |
// Struct: TokenizedWalletValue2
// File: crates/api_models/src/payment_methods.rs
// Module: api_models
// Implementations: 0
pub struct TokenizedWalletValue2
|
crates/api_models/src/payment_methods.rs
|
api_models
|
struct_definition
|
TokenizedWalletValue2
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// File: crates/euclid/src/backend/interpreter/types.rs
// Module: euclid
// Public structs: 2
use std::{collections::HashMap, fmt, ops::Deref, string::ToString};
use serde::Serialize;
use crate::{backend::inputs, frontend::ast::ValueType, types::EuclidKey};
#[derive(Debug, Clone, Serialize, thiserror::Error)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum InterpreterErrorType {
#[error("Invalid key received '{0}'")]
InvalidKey(String),
#[error("Invalid Comparison")]
InvalidComparison,
}
#[derive(Debug, Clone, Serialize, thiserror::Error)]
pub struct InterpreterError {
pub error_type: InterpreterErrorType,
pub metadata: HashMap<String, serde_json::Value>,
}
impl fmt::Display for InterpreterError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
InterpreterErrorType::fmt(&self.error_type, f)
}
}
pub struct Context(HashMap<String, Option<ValueType>>);
impl Deref for Context {
type Target = HashMap<String, Option<ValueType>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<inputs::BackendInput> for Context {
fn from(input: inputs::BackendInput) -> Self {
let ctx = HashMap::<String, Option<ValueType>>::from_iter([
(
EuclidKey::PaymentMethod.to_string(),
input
.payment_method
.payment_method
.map(|pm| ValueType::EnumVariant(pm.to_string())),
),
(
EuclidKey::PaymentMethodType.to_string(),
input
.payment_method
.payment_method_type
.map(|pt| ValueType::EnumVariant(pt.to_string())),
),
(
EuclidKey::AuthenticationType.to_string(),
input
.payment
.authentication_type
.map(|at| ValueType::EnumVariant(at.to_string())),
),
(
EuclidKey::CaptureMethod.to_string(),
input
.payment
.capture_method
.map(|cm| ValueType::EnumVariant(cm.to_string())),
),
(
EuclidKey::PaymentAmount.to_string(),
Some(ValueType::Number(input.payment.amount)),
),
(
EuclidKey::PaymentCurrency.to_string(),
Some(ValueType::EnumVariant(input.payment.currency.to_string())),
),
]);
Self(ctx)
}
}
|
crates/euclid/src/backend/interpreter/types.rs
|
euclid
|
full_file
| null | null | null | 535
| null | null | null | null | null | null | null |
// Struct: CustombillingRouterData
// File: crates/hyperswitch_connectors/src/connectors/custombilling/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CustombillingRouterData<T>
|
crates/hyperswitch_connectors/src/connectors/custombilling/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CustombillingRouterData
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Implementation: impl PaymentMethodsUpdateForm
// File: crates/router/src/core/payment_methods/migration.rs
// Module: router
// Methods: 1 total (1 public)
impl PaymentMethodsUpdateForm
|
crates/router/src/core/payment_methods/migration.rs
|
router
|
impl_block
| null | null | null | 42
| null |
PaymentMethodsUpdateForm
| null | 1
| 1
| null | null |
// Function: find_by_id
// File: crates/diesel_models/src/query/merchant_connector_account.rs
// Module: diesel_models
pub fn find_by_id(
conn: &PgPooledConn,
id: &common_utils::id_type::MerchantConnectorAccountId,
) -> StorageResult<Self>
|
crates/diesel_models/src/query/merchant_connector_account.rs
|
diesel_models
|
function_signature
| null | null | null | 64
|
find_by_id
| null | null | null | null | null | null |
// Struct: ItaubankTokenErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ItaubankTokenErrorResponse
|
crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ItaubankTokenErrorResponse
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// Struct: AirwallexDisputeObject
// File: crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct AirwallexDisputeObject
|
crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
AirwallexDisputeObject
| 0
|
[] | 55
| null | null | null | null | null | null | null |
// Struct: BackendInput
// File: crates/euclid/src/backend/inputs.rs
// Module: euclid
// Implementations: 0
pub struct BackendInput
|
crates/euclid/src/backend/inputs.rs
|
euclid
|
struct_definition
|
BackendInput
| 0
|
[] | 36
| null | null | null | null | null | null | null |
// Function: vault_payment_method_external
// File: crates/router/src/core/payment_methods.rs
// Module: router
pub fn vault_payment_method_external(
state: &SessionState,
pmd: &domain::PaymentMethodVaultingData,
merchant_account: &domain::MerchantAccount,
merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
) -> RouterResult<pm_types::AddVaultResponse>
|
crates/router/src/core/payment_methods.rs
|
router
|
function_signature
| null | null | null | 86
|
vault_payment_method_external
| null | null | null | null | null | null |
// File: crates/router/tests/connectors/paysafe.rs
// Module: router
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData};
use masking::Secret;
use router::types::{self, api, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct PaysafeTest;
impl ConnectorActions for PaysafeTest {}
impl utils::Connector for PaysafeTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Paysafe;
utils::construct_connector_data_old(
Box::new(Paysafe::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.paysafe
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"paysafe".to_string()
}
}
static CONNECTOR: PaysafeTest = PaysafeTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
|
crates/router/tests/connectors/paysafe.rs
|
router
|
full_file
| null | null | null | 2,935
| null | null | null | null | null | null | null |
// Struct: StoreCardRespPayload
// File: crates/router/src/core/payment_methods/transformers.rs
// Module: router
// Implementations: 0
pub struct StoreCardRespPayload
|
crates/router/src/core/payment_methods/transformers.rs
|
router
|
struct_definition
|
StoreCardRespPayload
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Struct: FiuuAuthType
// File: crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct FiuuAuthType
|
crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
FiuuAuthType
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Implementation: impl ConnectorCommon for for Square
// File: crates/hyperswitch_connectors/src/connectors/square.rs
// Module: hyperswitch_connectors
// Methods: 5 total (0 public)
impl ConnectorCommon for for Square
|
crates/hyperswitch_connectors/src/connectors/square.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 51
| null |
Square
|
ConnectorCommon for
| 5
| 0
| null | null |
// File: crates/router/src/core/routing.rs
// Module: router
// Public functions: 34
// Public structs: 4
pub mod helpers;
pub mod transformers;
use std::collections::HashSet;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use api_models::routing::DynamicRoutingAlgoAccessor;
use api_models::{
enums, mandates as mandates_api,
open_router::{
DecideGatewayResponse, OpenRouterDecideGatewayRequest, UpdateScorePayload,
UpdateScoreResponse,
},
routing,
routing::{
self as routing_types, RoutingRetrieveQuery, RuleMigrationError, RuleMigrationResponse,
},
};
use async_trait::async_trait;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use common_utils::ext_traits::AsyncExt;
use common_utils::request::Method;
use diesel_models::routing_algorithm::RoutingAlgorithm;
use error_stack::ResultExt;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use external_services::grpc_client::dynamic_routing::{
contract_routing_client::ContractBasedDynamicRouting,
elimination_based_client::EliminationBasedRouting,
success_rate_client::SuccessBasedDynamicRouting,
};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use helpers::{
enable_decision_engine_dynamic_routing_setup, update_decision_engine_dynamic_routing_setup,
};
use hyperswitch_domain_models::{mandates, payment_address};
use payment_methods::helpers::StorageErrorExt;
use rustc_hash::FxHashSet;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use storage_impl::redis::cache;
#[cfg(feature = "payouts")]
use super::payouts;
use super::{
errors::RouterResult,
payments::{
routing::{
utils::*,
{self as payments_routing},
},
OperationSessionGetters,
},
};
#[cfg(feature = "v1")]
use crate::utils::ValueExt;
#[cfg(feature = "v2")]
use crate::{core::admin, utils::ValueExt};
use crate::{
core::{
errors::{self, CustomResult, RouterResponse},
metrics, utils as core_utils,
},
db::StorageInterface,
routes::SessionState,
services::api as service_api,
types::{
api, domain,
storage::{self, enums as storage_enums},
transformers::{ForeignInto, ForeignTryFrom},
},
utils::{self, OptionExt},
};
pub enum TransactionData<'a> {
Payment(PaymentsDslInput<'a>),
#[cfg(feature = "payouts")]
Payout(&'a payouts::PayoutData),
}
#[derive(Clone)]
pub struct PaymentsDslInput<'a> {
pub setup_mandate: Option<&'a mandates::MandateData>,
pub payment_attempt: &'a storage::PaymentAttempt,
pub payment_intent: &'a storage::PaymentIntent,
pub payment_method_data: Option<&'a domain::PaymentMethodData>,
pub address: &'a payment_address::PaymentAddress,
pub recurring_details: Option<&'a mandates_api::RecurringDetails>,
pub currency: storage_enums::Currency,
}
impl<'a> PaymentsDslInput<'a> {
pub fn new(
setup_mandate: Option<&'a mandates::MandateData>,
payment_attempt: &'a storage::PaymentAttempt,
payment_intent: &'a storage::PaymentIntent,
payment_method_data: Option<&'a domain::PaymentMethodData>,
address: &'a payment_address::PaymentAddress,
recurring_details: Option<&'a mandates_api::RecurringDetails>,
currency: storage_enums::Currency,
) -> Self {
Self {
setup_mandate,
payment_attempt,
payment_intent,
payment_method_data,
address,
recurring_details,
currency,
}
}
}
#[cfg(feature = "v2")]
struct RoutingAlgorithmUpdate(RoutingAlgorithm);
#[cfg(feature = "v2")]
impl RoutingAlgorithmUpdate {
pub fn create_new_routing_algorithm(
request: &routing_types::RoutingConfigRequest,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: common_utils::id_type::ProfileId,
transaction_type: enums::TransactionType,
) -> Self {
let algorithm_id = common_utils::generate_routing_id_of_default_length();
let timestamp = common_utils::date_time::now();
let algo = RoutingAlgorithm {
algorithm_id,
profile_id,
merchant_id: merchant_id.clone(),
name: request.name.clone(),
description: Some(request.description.clone()),
kind: request.algorithm.get_kind().foreign_into(),
algorithm_data: serde_json::json!(request.algorithm),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: transaction_type,
decision_engine_routing_id: None,
};
Self(algo)
}
pub async fn fetch_routing_algo(
merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: &common_utils::id_type::RoutingId,
db: &dyn StorageInterface,
) -> RouterResult<Self> {
let routing_algo = db
.find_routing_algorithm_by_algorithm_id_merchant_id(algorithm_id, merchant_id)
.await
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;
Ok(Self(routing_algo))
}
}
pub async fn retrieve_merchant_routing_dictionary(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
query_params: RoutingRetrieveQuery,
transaction_type: enums::TransactionType,
) -> RouterResponse<routing_types::RoutingKind> {
metrics::ROUTING_MERCHANT_DICTIONARY_RETRIEVE.add(1, &[]);
let routing_metadata: Vec<diesel_models::routing_algorithm::RoutingProfileMetadata> = state
.store
.list_routing_algorithm_metadata_by_merchant_id_transaction_type(
merchant_context.get_merchant_account().get_id(),
&transaction_type,
i64::from(query_params.limit.unwrap_or_default()),
i64::from(query_params.offset.unwrap_or_default()),
)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let routing_metadata = super::utils::filter_objects_based_on_profile_id_list(
profile_id_list.clone(),
routing_metadata,
);
let mut result = routing_metadata
.into_iter()
.map(ForeignInto::foreign_into)
.collect::<Vec<_>>();
if let Some(profile_ids) = profile_id_list {
let mut de_result: Vec<routing_types::RoutingDictionaryRecord> = vec![];
// DE_TODO: need to replace this with batch API call to reduce the number of network calls
for profile_id in &profile_ids {
let list_request = ListRountingAlgorithmsRequest {
created_by: profile_id.get_string_repr().to_string(),
};
list_de_euclid_routing_algorithms(&state, list_request)
.await
.map_err(|e| {
router_env::logger::error!(decision_engine_error=?e, "decision_engine_euclid");
})
.ok() // Avoid throwing error if Decision Engine is not available or other errors
.map(|mut de_routing| de_result.append(&mut de_routing));
// filter de_result based on transaction type
de_result.retain(|record| record.algorithm_for == Some(transaction_type));
// append dynamic routing algorithms to de_result
de_result.append(
&mut result
.clone()
.into_iter()
.filter(|record: &routing_types::RoutingDictionaryRecord| {
record.kind == routing_types::RoutingAlgorithmKind::Dynamic
})
.collect::<Vec<_>>(),
);
}
compare_and_log_result(
de_result.clone(),
result.clone(),
"list_routing".to_string(),
);
result = build_list_routing_result(
&state,
merchant_context,
&result,
&de_result,
profile_ids.clone(),
)
.await?;
}
metrics::ROUTING_MERCHANT_DICTIONARY_RETRIEVE_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(
routing_types::RoutingKind::RoutingAlgorithm(result),
))
}
async fn build_list_routing_result(
state: &SessionState,
merchant_context: domain::MerchantContext,
hs_results: &[routing_types::RoutingDictionaryRecord],
de_results: &[routing_types::RoutingDictionaryRecord],
profile_ids: Vec<common_utils::id_type::ProfileId>,
) -> RouterResult<Vec<routing_types::RoutingDictionaryRecord>> {
let db = state.store.as_ref();
let key_manager_state = &state.into();
let mut list_result: Vec<routing_types::RoutingDictionaryRecord> = vec![];
for profile_id in profile_ids.iter() {
let by_profile =
|rec: &&routing_types::RoutingDictionaryRecord| &rec.profile_id == profile_id;
let de_result_for_profile = de_results.iter().filter(by_profile).cloned().collect();
let hs_result_for_profile = hs_results.iter().filter(by_profile).cloned().collect();
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
list_result.append(
&mut select_routing_result(
state,
&business_profile,
hs_result_for_profile,
de_result_for_profile,
)
.await,
);
}
Ok(list_result)
}
#[cfg(feature = "v2")]
pub async fn create_routing_algorithm_under_profile(
state: SessionState,
merchant_context: domain::MerchantContext,
authentication_profile_id: Option<common_utils::id_type::ProfileId>,
request: routing_types::RoutingConfigRequest,
transaction_type: enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(1, &[]);
let db = &*state.store;
let key_manager_state = &(&state).into();
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&request.profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")?;
let merchant_id = merchant_context.get_merchant_account().get_id();
core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;
let all_mcas = state
.store
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
key_manager_state,
merchant_id,
true,
merchant_context.get_merchant_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_id.get_string_repr().to_owned(),
})?;
let name_mca_id_set = helpers::ConnectNameAndMCAIdForProfile(
all_mcas.filter_by_profile(business_profile.get_id(), |mca| {
(&mca.connector_name, mca.get_id())
}),
);
let name_set = helpers::ConnectNameForProfile(
all_mcas.filter_by_profile(business_profile.get_id(), |mca| &mca.connector_name),
);
let algorithm_helper = helpers::RoutingAlgorithmHelpers {
name_mca_id_set,
name_set,
routing_algorithm: &request.algorithm,
};
algorithm_helper.validate_connectors_in_routing_config()?;
let algo = RoutingAlgorithmUpdate::create_new_routing_algorithm(
&request,
merchant_context.get_merchant_account().get_id(),
business_profile.get_id().to_owned(),
transaction_type,
);
let record = state
.store
.as_ref()
.insert_routing_algorithm(algo.0)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let new_record = record.foreign_into();
metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(new_record))
}
#[cfg(feature = "v1")]
pub async fn create_routing_algorithm_under_profile(
state: SessionState,
merchant_context: domain::MerchantContext,
authentication_profile_id: Option<common_utils::id_type::ProfileId>,
request: routing_types::RoutingConfigRequest,
transaction_type: enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
use api_models::routing::StaticRoutingAlgorithm as EuclidAlgorithm;
metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let name = request
.name
.get_required_value("name")
.change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "name" })
.attach_printable("Name of config not given")?;
let description = request
.description
.get_required_value("description")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "description",
})
.attach_printable("Description of config not given")?;
let algorithm = request
.algorithm
.clone()
.get_required_value("algorithm")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "algorithm",
})
.attach_printable("Algorithm of config not given")?;
let algorithm_id = common_utils::generate_routing_id_of_default_length();
let profile_id = request
.profile_id
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "profile_id",
})
.attach_printable("Profile_id not provided")?;
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")?;
core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;
if algorithm.should_validate_connectors_in_routing_config() {
helpers::validate_connectors_in_routing_config(
&state,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().get_id(),
&profile_id,
&algorithm,
)
.await?;
}
let mut decision_engine_routing_id: Option<String> = None;
if let Some(euclid_algorithm) = request.algorithm.clone() {
let maybe_static_algorithm: Option<StaticRoutingAlgorithm> = match euclid_algorithm {
EuclidAlgorithm::Advanced(program) => match program.try_into() {
Ok(internal_program) => Some(StaticRoutingAlgorithm::Advanced(internal_program)),
Err(e) => {
router_env::logger::error!(decision_engine_error = ?e, "decision_engine_euclid");
None
}
},
EuclidAlgorithm::Single(conn) => {
Some(StaticRoutingAlgorithm::Single(Box::new(conn.into())))
}
EuclidAlgorithm::Priority(connectors) => {
let converted: Vec<ConnectorInfo> =
connectors.into_iter().map(Into::into).collect();
Some(StaticRoutingAlgorithm::Priority(converted))
}
EuclidAlgorithm::VolumeSplit(splits) => {
let converted: Vec<VolumeSplit<ConnectorInfo>> =
splits.into_iter().map(Into::into).collect();
Some(StaticRoutingAlgorithm::VolumeSplit(converted))
}
EuclidAlgorithm::ThreeDsDecisionRule(_) => {
router_env::logger::error!(
"decision_engine_euclid: ThreeDsDecisionRules are not yet implemented"
);
None
}
};
if let Some(static_algorithm) = maybe_static_algorithm {
let routing_rule = RoutingRule {
rule_id: Some(algorithm_id.clone().get_string_repr().to_owned()),
name: name.clone(),
description: Some(description.clone()),
created_by: profile_id.get_string_repr().to_string(),
algorithm: static_algorithm,
algorithm_for: transaction_type.into(),
metadata: Some(RoutingMetadata {
kind: algorithm.get_kind().foreign_into(),
}),
};
match create_de_euclid_routing_algo(&state, &routing_rule).await {
Ok(id) => {
decision_engine_routing_id = Some(id);
}
Err(e)
if matches!(
e.current_context(),
errors::RoutingError::DecisionEngineValidationError(_)
) =>
{
if let errors::RoutingError::DecisionEngineValidationError(msg) =
e.current_context()
{
router_env::logger::error!(
decision_engine_euclid_error = ?msg,
decision_engine_euclid_request = ?routing_rule,
"failed to create rule in decision_engine with validation error"
);
}
}
Err(e) => {
router_env::logger::error!(
decision_engine_euclid_error = ?e,
decision_engine_euclid_request = ?routing_rule,
"failed to create rule in decision_engine"
);
}
}
}
}
if decision_engine_routing_id.is_some() {
router_env::logger::info!(routing_flow=?"create_euclid_routing_algorithm", is_equal=?"true", "decision_engine_euclid");
} else {
router_env::logger::info!(routing_flow=?"create_euclid_routing_algorithm", is_equal=?"false", "decision_engine_euclid");
}
let timestamp = common_utils::date_time::now();
let algo = RoutingAlgorithm {
algorithm_id: algorithm_id.clone(),
profile_id,
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
name: name.clone(),
description: Some(description.clone()),
kind: algorithm.get_kind().foreign_into(),
algorithm_data: serde_json::json!(algorithm),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: transaction_type.to_owned(),
decision_engine_routing_id,
};
let record = db
.insert_routing_algorithm(algo)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let new_record = record.foreign_into();
metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(new_record))
}
#[cfg(feature = "v2")]
pub async fn link_routing_config_under_profile(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: common_utils::id_type::ProfileId,
algorithm_id: common_utils::id_type::RoutingId,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_LINK_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let routing_algorithm = RoutingAlgorithmUpdate::fetch_routing_algo(
merchant_context.get_merchant_account().get_id(),
&algorithm_id,
db,
)
.await?;
utils::when(routing_algorithm.0.profile_id != profile_id, || {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Profile Id is invalid for the routing config".to_string(),
})
})?;
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")?;
utils::when(
routing_algorithm.0.algorithm_for != *transaction_type,
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"Cannot use {}'s routing algorithm for {} operation",
routing_algorithm.0.algorithm_for, transaction_type
),
})
},
)?;
utils::when(
business_profile.routing_algorithm_id == Some(algorithm_id.clone())
|| business_profile.payout_routing_algorithm_id == Some(algorithm_id.clone()),
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Algorithm is already active".to_string(),
})
},
)?;
admin::ProfileWrapper::new(business_profile)
.update_profile_and_invalidate_routing_config_for_active_algorithm_id_update(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
algorithm_id,
transaction_type,
)
.await?;
metrics::ROUTING_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(
routing_algorithm.0.foreign_into(),
))
}
#[cfg(feature = "v1")]
pub async fn link_routing_config(
state: SessionState,
merchant_context: domain::MerchantContext,
authentication_profile_id: Option<common_utils::id_type::ProfileId>,
algorithm_id: common_utils::id_type::RoutingId,
transaction_type: enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_LINK_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let routing_algorithm = db
.find_routing_algorithm_by_algorithm_id_merchant_id(
&algorithm_id,
merchant_context.get_merchant_account().get_id(),
)
.await
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&routing_algorithm.profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: routing_algorithm.profile_id.get_string_repr().to_owned(),
})?;
core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;
match routing_algorithm.kind {
diesel_models::enums::RoutingAlgorithmKind::Dynamic => {
let mut dynamic_routing_ref: routing_types::DynamicRoutingAlgorithmRef =
business_profile
.dynamic_routing_algorithm
.clone()
.map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to deserialize Dynamic routing algorithm ref from business profile",
)?
.unwrap_or_default();
utils::when(
matches!(
dynamic_routing_ref.success_based_algorithm,
Some(routing::SuccessBasedAlgorithm {
algorithm_id_with_timestamp:
routing_types::DynamicAlgorithmWithTimestamp {
algorithm_id: Some(ref id),
timestamp: _
},
enabled_feature: _
}) if id == &algorithm_id
) || matches!(
dynamic_routing_ref.elimination_routing_algorithm,
Some(routing::EliminationRoutingAlgorithm {
algorithm_id_with_timestamp:
routing_types::DynamicAlgorithmWithTimestamp {
algorithm_id: Some(ref id),
timestamp: _
},
enabled_feature: _
}) if id == &algorithm_id
) || matches!(
dynamic_routing_ref.contract_based_routing,
Some(routing::ContractRoutingAlgorithm {
algorithm_id_with_timestamp:
routing_types::DynamicAlgorithmWithTimestamp {
algorithm_id: Some(ref id),
timestamp: _
},
enabled_feature: _
}) if id == &algorithm_id
),
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Algorithm is already active".to_string(),
})
},
)?;
if routing_algorithm.name == helpers::SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM {
dynamic_routing_ref.update_algorithm_id(
algorithm_id,
dynamic_routing_ref
.success_based_algorithm
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"missing success_based_algorithm in dynamic_algorithm_ref from business_profile table",
)?
.enabled_feature,
routing_types::DynamicRoutingType::SuccessRateBasedRouting,
);
// Call to DE here to update SR configs
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
{
if state.conf.open_router.dynamic_routing_enabled {
let existing_config = helpers::get_decision_engine_active_dynamic_routing_algorithm(
&state,
business_profile.get_id(),
api_models::open_router::DecisionEngineDynamicAlgorithmType::SuccessRate,
)
.await;
if let Ok(Some(_config)) = existing_config {
update_decision_engine_dynamic_routing_setup(
&state,
business_profile.get_id(),
routing_algorithm.algorithm_data.clone(),
routing_types::DynamicRoutingType::SuccessRateBasedRouting,
&mut dynamic_routing_ref,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to update the success rate routing config in Decision Engine",
)?;
} else {
let data: routing_types::SuccessBasedRoutingConfig =
routing_algorithm.algorithm_data
.clone()
.parse_value("SuccessBasedRoutingConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to deserialize SuccessBasedRoutingConfig from routing algorithm data",
)?;
enable_decision_engine_dynamic_routing_setup(
&state,
business_profile.get_id(),
routing_types::DynamicRoutingType::SuccessRateBasedRouting,
&mut dynamic_routing_ref,
Some(routing_types::DynamicRoutingPayload::SuccessBasedRoutingPayload(data)),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to setup decision engine dynamic routing")?;
}
}
}
} else if routing_algorithm.name == helpers::ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM
{
dynamic_routing_ref.update_algorithm_id(
algorithm_id,
dynamic_routing_ref
.elimination_routing_algorithm
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"missing elimination_routing_algorithm in dynamic_algorithm_ref from business_profile table",
)?
.enabled_feature,
routing_types::DynamicRoutingType::EliminationRouting,
);
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
{
if state.conf.open_router.dynamic_routing_enabled {
let existing_config = helpers::get_decision_engine_active_dynamic_routing_algorithm(
&state,
business_profile.get_id(),
api_models::open_router::DecisionEngineDynamicAlgorithmType::Elimination,
)
.await;
if let Ok(Some(_config)) = existing_config {
update_decision_engine_dynamic_routing_setup(
&state,
business_profile.get_id(),
routing_algorithm.algorithm_data.clone(),
routing_types::DynamicRoutingType::EliminationRouting,
&mut dynamic_routing_ref,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to update the elimination routing config in Decision Engine",
)?;
} else {
let data: routing_types::EliminationRoutingConfig =
routing_algorithm.algorithm_data
.clone()
.parse_value("EliminationRoutingConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to deserialize EliminationRoutingConfig from routing algorithm data",
)?;
enable_decision_engine_dynamic_routing_setup(
&state,
business_profile.get_id(),
routing_types::DynamicRoutingType::EliminationRouting,
&mut dynamic_routing_ref,
Some(
routing_types::DynamicRoutingPayload::EliminationRoutingPayload(
data,
),
),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to setup decision engine dynamic routing")?;
}
}
}
} else if routing_algorithm.name == helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM {
dynamic_routing_ref.update_algorithm_id(
algorithm_id,
dynamic_routing_ref
.contract_based_routing
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"missing contract_based_routing in dynamic_algorithm_ref from business_profile table",
)?
.enabled_feature,
routing_types::DynamicRoutingType::ContractBasedRouting,
);
}
helpers::update_business_profile_active_dynamic_algorithm_ref(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
business_profile.clone(),
dynamic_routing_ref,
)
.await?;
}
diesel_models::enums::RoutingAlgorithmKind::Single
| diesel_models::enums::RoutingAlgorithmKind::Priority
| diesel_models::enums::RoutingAlgorithmKind::Advanced
| diesel_models::enums::RoutingAlgorithmKind::VolumeSplit
| diesel_models::enums::RoutingAlgorithmKind::ThreeDsDecisionRule => {
let mut routing_ref: routing_types::RoutingAlgorithmRef = business_profile
.routing_algorithm
.clone()
.map(|val| val.parse_value("RoutingAlgorithmRef"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to deserialize routing algorithm ref from business profile",
)?
.unwrap_or_default();
utils::when(routing_algorithm.algorithm_for != transaction_type, || {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"Cannot use {}'s routing algorithm for {} operation",
routing_algorithm.algorithm_for, transaction_type
),
})
})?;
utils::when(
routing_ref.algorithm_id == Some(algorithm_id.clone()),
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Algorithm is already active".to_string(),
})
},
)?;
routing_ref.update_algorithm_id(algorithm_id);
helpers::update_profile_active_algorithm_ref(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
business_profile.clone(),
routing_ref,
&transaction_type,
)
.await?;
}
};
if let Some(euclid_routing_id) = routing_algorithm.decision_engine_routing_id.clone() {
let routing_algo = ActivateRoutingConfigRequest {
created_by: business_profile.get_id().get_string_repr().to_string(),
routing_algorithm_id: euclid_routing_id,
};
let link_result = link_de_euclid_routing_algorithm(&state, routing_algo).await;
match link_result {
Ok(_) => {
router_env::logger::info!(
routing_flow=?"link_routing_algorithm",
is_equal=?true,
"decision_engine_euclid"
);
}
Err(e) => {
router_env::logger::info!(
routing_flow=?"link_routing_algorithm",
is_equal=?false,
error=?e,
"decision_engine_euclid"
);
}
}
}
metrics::ROUTING_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(
routing_algorithm.foreign_into(),
))
}
#[cfg(feature = "v2")]
pub async fn retrieve_routing_algorithm_from_algorithm_id(
state: SessionState,
merchant_context: domain::MerchantContext,
authentication_profile_id: Option<common_utils::id_type::ProfileId>,
algorithm_id: common_utils::id_type::RoutingId,
) -> RouterResponse<routing_types::MerchantRoutingAlgorithm> {
metrics::ROUTING_RETRIEVE_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let routing_algorithm = RoutingAlgorithmUpdate::fetch_routing_algo(
merchant_context.get_merchant_account().get_id(),
&algorithm_id,
db,
)
.await?;
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&routing_algorithm.0.profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;
core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;
let response = routing_types::MerchantRoutingAlgorithm::foreign_try_from(routing_algorithm.0)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to parse routing algorithm")?;
metrics::ROUTING_RETRIEVE_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(response))
}
#[cfg(feature = "v1")]
pub async fn retrieve_routing_algorithm_from_algorithm_id(
state: SessionState,
merchant_context: domain::MerchantContext,
authentication_profile_id: Option<common_utils::id_type::ProfileId>,
algorithm_id: common_utils::id_type::RoutingId,
) -> RouterResponse<routing_types::MerchantRoutingAlgorithm> {
metrics::ROUTING_RETRIEVE_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let routing_algorithm = db
.find_routing_algorithm_by_algorithm_id_merchant_id(
&algorithm_id,
merchant_context.get_merchant_account().get_id(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&routing_algorithm.profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;
core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;
let response = routing_types::MerchantRoutingAlgorithm::foreign_try_from(routing_algorithm)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to parse routing algorithm")?;
metrics::ROUTING_RETRIEVE_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(response))
}
#[cfg(feature = "v2")]
pub async fn unlink_routing_config_under_profile(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: common_utils::id_type::ProfileId,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_UNLINK_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")?;
let routing_algo_id = match transaction_type {
enums::TransactionType::Payment => business_profile.routing_algorithm_id.clone(),
#[cfg(feature = "payouts")]
enums::TransactionType::Payout => business_profile.payout_routing_algorithm_id.clone(),
// TODO: Handle ThreeDsAuthentication Transaction Type for Three DS Decision Rule Algorithm configuration
enums::TransactionType::ThreeDsAuthentication => todo!(),
};
if let Some(algorithm_id) = routing_algo_id {
let record = RoutingAlgorithmUpdate::fetch_routing_algo(
merchant_context.get_merchant_account().get_id(),
&algorithm_id,
db,
)
.await?;
let response = record.0.foreign_into();
admin::ProfileWrapper::new(business_profile)
.update_profile_and_invalidate_routing_config_for_active_algorithm_id_update(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
algorithm_id,
transaction_type,
)
.await?;
metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(response))
} else {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Algorithm is already inactive".to_string(),
})?
}
}
#[cfg(feature = "v1")]
pub async fn unlink_routing_config(
state: SessionState,
merchant_context: domain::MerchantContext,
request: routing_types::RoutingConfigRequest,
authentication_profile_id: Option<common_utils::id_type::ProfileId>,
transaction_type: enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_UNLINK_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let profile_id = request
.profile_id
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "profile_id",
})
.attach_printable("Profile_id not provided")?;
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?;
match business_profile {
Some(business_profile) => {
core_utils::validate_profile_id_from_auth_layer(
authentication_profile_id,
&business_profile,
)?;
let routing_algo_ref: routing_types::RoutingAlgorithmRef = match transaction_type {
enums::TransactionType::Payment => business_profile.routing_algorithm.clone(),
#[cfg(feature = "payouts")]
enums::TransactionType::Payout => business_profile.payout_routing_algorithm.clone(),
enums::TransactionType::ThreeDsAuthentication => {
business_profile.three_ds_decision_rule_algorithm.clone()
}
}
|
crates/router/src/core/routing.rs#chunk0
|
router
|
chunk
| null | null | null | 8,182
| null | null | null | null | null | null | null |
// Implementation: impl PayoutAttemptInterface for for KVRouterStore
// File: crates/storage_impl/src/kv_router_store.rs
// Module: storage_impl
// Methods: 0 total (0 public)
impl PayoutAttemptInterface for for KVRouterStore
|
crates/storage_impl/src/kv_router_store.rs
|
storage_impl
|
impl_block
| null | null | null | 53
| null |
KVRouterStore
|
PayoutAttemptInterface for
| 0
| 0
| null | null |
// Struct: RefundSuccessRate
// File: crates/api_models/src/analytics/refunds.rs
// Module: api_models
// Implementations: 0
pub struct RefundSuccessRate
|
crates/api_models/src/analytics/refunds.rs
|
api_models
|
struct_definition
|
RefundSuccessRate
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Implementation: impl Theme
// File: crates/diesel_models/src/query/user/theme.rs
// Module: diesel_models
// Methods: 9 total (0 public)
impl Theme
|
crates/diesel_models/src/query/user/theme.rs
|
diesel_models
|
impl_block
| null | null | null | 37
| null |
Theme
| null | 9
| 0
| null | null |
// Function: log_event
// File: crates/router/src/events/event_logger.rs
// Module: router
pub fn log_event<T: KafkaMessage>(&self, event: &T)
|
crates/router/src/events/event_logger.rs
|
router
|
function_signature
| null | null | null | 38
|
log_event
| null | null | null | null | null | null |
// Implementation: impl Responder
// File: crates/router/src/routes/payments.rs
// Module: router
// Methods: 0 total (0 public)
impl Responder
|
crates/router/src/routes/payments.rs
|
router
|
impl_block
| null | null | null | 36
| null |
Responder
| null | 0
| 0
| null | null |
// Implementation: impl api::PaymentVoid for for Tokenio
// File: crates/hyperswitch_connectors/src/connectors/tokenio.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Tokenio
|
crates/hyperswitch_connectors/src/connectors/tokenio.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Tokenio
|
api::PaymentVoid for
| 0
| 0
| null | null |
// Implementation: impl common_utils::events::ApiEventMetric for for ThreeDsDecisionRuleExecuteResponse
// File: crates/api_models/src/three_ds_decision_rule.rs
// Module: api_models
// Methods: 1 total (0 public)
impl common_utils::events::ApiEventMetric for for ThreeDsDecisionRuleExecuteResponse
|
crates/api_models/src/three_ds_decision_rule.rs
|
api_models
|
impl_block
| null | null | null | 68
| null |
ThreeDsDecisionRuleExecuteResponse
|
common_utils::events::ApiEventMetric for
| 1
| 0
| null | null |
// Implementation: impl api::Payouts for for Nomupay
// File: crates/hyperswitch_connectors/src/connectors/nomupay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::Payouts for for Nomupay
|
crates/hyperswitch_connectors/src/connectors/nomupay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 63
| null |
Nomupay
|
api::Payouts for
| 0
| 0
| null | null |
// Function: get_payment_intent_filter_for_dimension
// File: crates/analytics/src/payment_intents/filters.rs
// Module: analytics
pub fn get_payment_intent_filter_for_dimension<T>(
dimension: PaymentIntentDimensions,
merchant_id: &common_utils::id_type::MerchantId,
time_range: &TimeRange,
pool: &T,
) -> FiltersResult<Vec<PaymentIntentFilterRow>>
where
T: AnalyticsDataSource + PaymentIntentFilterAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
|
crates/analytics/src/payment_intents/filters.rs
|
analytics
|
function_signature
| null | null | null | 145
|
get_payment_intent_filter_for_dimension
| null | null | null | null | null | null |
// Module Structure
// File: crates/router/src/compatibility/stripe/customers.rs
// Module: router
// Public submodules:
pub mod types;
|
crates/router/src/compatibility/stripe/customers.rs
|
router
|
module_structure
| null | null | null | 33
| null | null | null | null | null | 1
| 0
|
// Struct: SignifydRefund
// File: crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct SignifydRefund
|
crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs
|
hyperswitch_connectors
|
struct_definition
|
SignifydRefund
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentVoid for for Bambora
// File: crates/hyperswitch_connectors/src/connectors/bambora.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Bambora
|
crates/hyperswitch_connectors/src/connectors/bambora.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Bambora
|
api::PaymentVoid for
| 0
| 0
| null | null |
// Implementation: impl ThreeDSDecision
// File: crates/common_types/src/three_ds_decision_rule_engine.rs
// Module: common_types
// Methods: 1 total (1 public)
impl ThreeDSDecision
|
crates/common_types/src/three_ds_decision_rule_engine.rs
|
common_types
|
impl_block
| null | null | null | 43
| null |
ThreeDSDecision
| null | 1
| 1
| null | null |
// Function: entity_type
// File: crates/common_utils/src/types/user/theme.rs
// Module: common_utils
// Documentation: Get the entity_type from the lineage
pub fn entity_type(&self) -> EntityType
|
crates/common_utils/src/types/user/theme.rs
|
common_utils
|
function_signature
| null | null | null | 44
|
entity_type
| null | null | null | null | null | null |
// Function: get_message
// File: crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs
// Module: hyperswitch_connectors
pub fn get_message(&self) -> String
|
crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 43
|
get_message
| null | null | null | null | null | null |
// Function: insert
// File: crates/diesel_models/src/query/role.rs
// Module: diesel_models
pub fn insert(self, conn: &PgPooledConn) -> StorageResult<Role>
|
crates/diesel_models/src/query/role.rs
|
diesel_models
|
function_signature
| null | null | null | 42
|
insert
| null | null | null | null | null | null |
// Implementation: impl TraceUrlAssert
// File: crates/router_env/src/logger/setup.rs
// Module: router_env
// Methods: 1 total (0 public)
impl TraceUrlAssert
|
crates/router_env/src/logger/setup.rs
|
router_env
|
impl_block
| null | null | null | 39
| null |
TraceUrlAssert
| null | 1
| 0
| null | null |
// File: crates/hyperswitch_domain_models/src/merchant_context.rs
// Module: hyperswitch_domain_models
// Public functions: 2
// Public structs: 1
pub use crate::{merchant_account::MerchantAccount, merchant_key_store::MerchantKeyStore};
/// `MerchantContext` represents the authentication and operational context for a merchant.
///
/// This enum encapsulates the merchant's account information and cryptographic keys
/// needed for secure operations. Currently supports only normal merchant operations,
/// but the enum structure allows for future expansion to different merchant types for example a
/// **platform** context.
#[derive(Clone, Debug)]
pub enum MerchantContext {
/// Represents a normal operation merchant context.
NormalMerchant(Box<Context>),
}
/// `Context` holds the merchant account details and cryptographic key store.
#[derive(Clone, Debug)]
pub struct Context(pub MerchantAccount, pub MerchantKeyStore);
impl MerchantContext {
pub fn get_merchant_account(&self) -> &MerchantAccount {
match self {
Self::NormalMerchant(merchant_account) => &merchant_account.0,
}
}
pub fn get_merchant_key_store(&self) -> &MerchantKeyStore {
match self {
Self::NormalMerchant(merchant_account) => &merchant_account.1,
}
}
}
|
crates/hyperswitch_domain_models/src/merchant_context.rs
|
hyperswitch_domain_models
|
full_file
| null | null | null | 268
| null | null | null | null | null | null | null |
// Struct: RoutingVolumeSplit
// File: crates/api_models/src/routing.rs
// Module: api_models
// Implementations: 0
pub struct RoutingVolumeSplit
|
crates/api_models/src/routing.rs
|
api_models
|
struct_definition
|
RoutingVolumeSplit
| 0
|
[] | 36
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentSession for for Cashtocode
// File: crates/hyperswitch_connectors/src/connectors/cashtocode.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSession for for Cashtocode
|
crates/hyperswitch_connectors/src/connectors/cashtocode.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Cashtocode
|
api::PaymentSession for
| 0
| 0
| null | null |
// Function: payment_complete
// File: crates/router/src/routes/dummy_connector/core.rs
// Module: router
pub fn payment_complete(
state: SessionState,
req: types::DummyConnectorPaymentCompleteRequest,
) -> types::DummyConnectorResponse<()>
|
crates/router/src/routes/dummy_connector/core.rs
|
router
|
function_signature
| null | null | null | 54
|
payment_complete
| null | null | null | null | null | null |
// Implementation: impl Cache
// File: crates/router/src/routes/app.rs
// Module: router
// Methods: 1 total (1 public)
impl Cache
|
crates/router/src/routes/app.rs
|
router
|
impl_block
| null | null | null | 33
| null |
Cache
| null | 1
| 1
| null | null |
// Struct: PlaidLinkTokenResponse
// File: crates/hyperswitch_connectors/src/connectors/plaid/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PlaidLinkTokenResponse
|
crates/hyperswitch_connectors/src/connectors/plaid/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PlaidLinkTokenResponse
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Function: retrieve_routing_algorithm_from_algorithm_id
// File: crates/router/src/core/routing.rs
// Module: router
pub fn retrieve_routing_algorithm_from_algorithm_id(
state: SessionState,
merchant_context: domain::MerchantContext,
authentication_profile_id: Option<common_utils::id_type::ProfileId>,
algorithm_id: common_utils::id_type::RoutingId,
) -> RouterResponse<routing_types::MerchantRoutingAlgorithm>
|
crates/router/src/core/routing.rs
|
router
|
function_signature
| null | null | null | 91
|
retrieve_routing_algorithm_from_algorithm_id
| null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/finix.rs
// Module: hyperswitch_connectors
// Public functions: 1
// Public structs: 1
pub mod transformers;
use std::sync::LazyLock;
use common_enums::{enums, ConnectorIntegrationStatus};
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{ExposeInterface, Mask};
use transformers as finix;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Finix {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Finix {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Finix {}
impl api::PaymentSession for Finix {}
impl api::ConnectorAccessToken for Finix {}
impl api::MandateSetup for Finix {}
impl api::PaymentAuthorize for Finix {}
impl api::PaymentSync for Finix {}
impl api::PaymentCapture for Finix {}
impl api::PaymentVoid for Finix {}
impl api::Refund for Finix {}
impl api::RefundExecute for Finix {}
impl api::RefundSync for Finix {}
impl api::PaymentToken for Finix {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Finix
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Finix
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 Finix {
fn id(&self) -> &'static str {
"finix"
}
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.finix.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = finix::FinixAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.expose().into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: finix::FinixErrorResponse =
res.response
.parse_struct("FinixErrorResponse")
.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.code,
message: response.message,
reason: response.reason,
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 Finix {
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 Finix {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Finix {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Finix {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Finix {
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> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
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 = finix::FinixRouterData::from((amount, req));
let connector_req = finix::FinixPaymentsRequest::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: finix::FinixPaymentsResponse = res
.response
.parse_struct("Finix PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Finix {
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> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
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: finix::FinixPaymentsResponse = res
.response
.parse_struct("finix 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 Finix {
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: finix::FinixPaymentsResponse = res
.response
.parse_struct("Finix 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 Finix {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Finix {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
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 = finix::FinixRouterData::from((refund_amount, req));
let connector_req = finix::FinixRefundRequest::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: finix::RefundResponse = res
.response
.parse_struct("finix RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Finix {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: finix::RefundResponse = res
.response
.parse_struct("finix RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Finix {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static FINIX_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(SupportedPaymentMethods::new);
static FINIX_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Finix",
description: "Finix is a payments technology provider enabling businesses to accept and send payments online or in person",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: ConnectorIntegrationStatus::Alpha,
};
static FINIX_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Finix {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&FINIX_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*FINIX_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&FINIX_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates/hyperswitch_connectors/src/connectors/finix.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 4,658
| null | null | null | null | null | null | null |
// Struct: KlarnaDetails
// File: crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct KlarnaDetails
|
crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
KlarnaDetails
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Function: new
// File: crates/masking/src/bytes.rs
// Module: masking
// Documentation: Wrap bytes in `SecretBytesMut`
pub fn new(bytes: impl Into<BytesMut>) -> Self
|
crates/masking/src/bytes.rs
|
masking
|
function_signature
| null | null | null | 45
|
new
| null | null | null | null | null | null |
// Function: add_publishable_key
// File: crates/router/src/services/authentication/decision.rs
// Module: router
pub fn add_publishable_key(
state: &SessionState,
api_key: Secret<String>,
merchant_id: common_utils::id_type::MerchantId,
expiry: Option<u64>,
) -> CustomResult<(), ApiClientError>
|
crates/router/src/services/authentication/decision.rs
|
router
|
function_signature
| null | null | null | 76
|
add_publishable_key
| null | null | null | null | null | null |
// Struct: ConfiguredRouting
// File: crates/api_models/src/user/dashboard_metadata.rs
// Module: api_models
// Implementations: 0
pub struct ConfiguredRouting
|
crates/api_models/src/user/dashboard_metadata.rs
|
api_models
|
struct_definition
|
ConfiguredRouting
| 0
|
[] | 37
| null | null | null | null | null | null | null |
// Struct: ExchangeTokenRequest
// File: crates/pm_auth/src/types.rs
// Module: pm_auth
// Implementations: 0
pub struct ExchangeTokenRequest
|
crates/pm_auth/src/types.rs
|
pm_auth
|
struct_definition
|
ExchangeTokenRequest
| 0
|
[] | 35
| null | null | null | null | null | null | null |
// Function: is_vault_sdk_enabled
// File: crates/hyperswitch_domain_models/src/business_profile.rs
// Module: hyperswitch_domain_models
pub fn is_vault_sdk_enabled(&self) -> bool
|
crates/hyperswitch_domain_models/src/business_profile.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 44
|
is_vault_sdk_enabled
| null | null | null | null | null | null |
// File: crates/config_importer/src/cli.rs
// Module: config_importer
use std::path::PathBuf;
/// Utility to import a hyperswitch TOML configuration file, convert it into environment variable
/// key-value pairs, and export it in the specified format.
#[derive(clap::Parser, Debug)]
#[command(arg_required_else_help = true)]
pub(crate) struct Args {
/// Input TOML configuration file.
#[arg(short, long, value_name = "FILE")]
pub(crate) input_file: PathBuf,
/// The format to convert the environment variables to.
#[arg(
value_enum,
short = 'f',
long,
value_name = "FORMAT",
default_value = "kubernetes-json"
)]
pub(crate) output_format: OutputFormat,
/// Output file. Output will be written to stdout if not specified.
#[arg(short, long, value_name = "FILE")]
pub(crate) output_file: Option<PathBuf>,
/// Prefix to be used for each environment variable in the generated output.
#[arg(short, long, default_value = "ROUTER")]
pub(crate) prefix: String,
}
/// The output format to convert environment variables to.
#[derive(clap::ValueEnum, Clone, Copy, Debug)]
pub(crate) enum OutputFormat {
/// Converts each environment variable to an object containing `name` and `value` fields.
///
/// ```json
/// {
/// "name": "ENVIRONMENT",
/// "value": "PRODUCTION"
/// }
/// ```
KubernetesJson,
}
|
crates/config_importer/src/cli.rs
|
config_importer
|
full_file
| null | null | null | 337
| null | null | null | null | null | null | null |
// Implementation: impl UserKeyStoreNew
// File: crates/diesel_models/src/query/user_key_store.rs
// Module: diesel_models
// Methods: 1 total (0 public)
impl UserKeyStoreNew
|
crates/diesel_models/src/query/user_key_store.rs
|
diesel_models
|
impl_block
| null | null | null | 44
| null |
UserKeyStoreNew
| null | 1
| 0
| null | null |
// Struct: Datatrans3DSResponse
// File: crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct Datatrans3DSResponse
|
crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
Datatrans3DSResponse
| 0
|
[] | 54
| null | null | null | null | null | null | null |
// Struct: OrderInformationWithBill
// File: crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct OrderInformationWithBill
|
crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
OrderInformationWithBill
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Implementation: impl api::RefundExecute for for Affirm
// File: crates/hyperswitch_connectors/src/connectors/affirm.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundExecute for for Affirm
|
crates/hyperswitch_connectors/src/connectors/affirm.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Affirm
|
api::RefundExecute for
| 0
| 0
| null | null |
// Module Structure
// File: crates/hyperswitch_connectors/src/connectors/nomupay.rs
// Module: hyperswitch_connectors
// Public submodules:
pub mod transformers;
|
crates/hyperswitch_connectors/src/connectors/nomupay.rs
|
hyperswitch_connectors
|
module_structure
| null | null | null | 40
| null | null | null | null | null | 1
| 0
|
// Struct: CountAccumulator
// File: crates/analytics/src/sdk_events/accumulator.rs
// Module: analytics
// Implementations: 1
// Traits: SdkEventMetricAccumulator
pub struct CountAccumulator
|
crates/analytics/src/sdk_events/accumulator.rs
|
analytics
|
struct_definition
|
CountAccumulator
| 1
|
[
"SdkEventMetricAccumulator"
] | 50
| null | null | null | null | null | null | null |
// Struct: HostedUrlResponse
// File: crates/hyperswitch_connectors/src/connectors/boku/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct HostedUrlResponse
|
crates/hyperswitch_connectors/src/connectors/boku/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
HostedUrlResponse
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Function: find_last_successful_attempt_by_payment_id_merchant_id
// File: crates/diesel_models/src/query/payment_attempt.rs
// Module: diesel_models
pub fn find_last_successful_attempt_by_payment_id_merchant_id(
conn: &PgPooledConn,
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 | 90
|
find_last_successful_attempt_by_payment_id_merchant_id
| null | null | null | null | null | null |
// Function: set_stored_token_response
// File: crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
// Module: router
pub fn set_stored_token_response(
self,
store_token_response: &'a pm_transformers::StoreCardRespPayload,
) -> NetworkTokenizationBuilder<'a, PmTokenStored>
|
crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
|
router
|
function_signature
| null | null | null | 72
|
set_stored_token_response
| null | null | null | null | null | null |
// Implementation: impl api::Payment for for Itaubank
// File: crates/hyperswitch_connectors/src/connectors/itaubank.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::Payment for for Itaubank
|
crates/hyperswitch_connectors/src/connectors/itaubank.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Itaubank
|
api::Payment for
| 0
| 0
| null | null |
// Module Structure
// File: crates/hyperswitch_connectors/src/connectors/flexiti.rs
// Module: hyperswitch_connectors
// Public submodules:
pub mod transformers;
|
crates/hyperswitch_connectors/src/connectors/flexiti.rs
|
hyperswitch_connectors
|
module_structure
| null | null | null | 39
| null | null | null | null | null | 1
| 0
|
// File: crates/router/src/core/payments/flows/session_flow.rs
// Module: router
use api_models::{admin as admin_types, payments as payment_types};
use async_trait::async_trait;
use common_utils::{
ext_traits::ByteSliceExt,
request::RequestContent,
types::{AmountConvertor, StringMajorUnitForConnector},
};
use error_stack::{Report, ResultExt};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payments::PaymentIntentData;
use masking::{ExposeInterface, ExposeOptionInterface};
use super::{ConstructFlowSpecificData, Feature};
use crate::{
consts::PROTOCOL,
core::{
errors::{self, ConnectorErrorExt, RouterResult},
payments::{self, access_token, customers, helpers, transformers, PaymentData},
},
headers, logger,
routes::{self, app::settings, metrics},
services,
types::{
self,
api::{self, enums},
domain,
},
utils::OptionExt,
};
#[cfg(feature = "v2")]
#[async_trait]
impl
ConstructFlowSpecificData<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
for PaymentIntentData<api::Session>
{
async fn construct_router_data<'a>(
&self,
state: &routes::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<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsSessionRouterData> {
Box::pin(transformers::construct_payment_router_data_for_sdk_session(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
))
.await
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl
ConstructFlowSpecificData<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
for PaymentData<api::Session>
{
async fn construct_router_data<'a>(
&self,
state: &routes::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<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsSessionRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Session,
types::PaymentsSessionData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
))
.await
}
}
#[async_trait]
impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessionRouterData {
async fn decide_flows<'a>(
self,
state: &routes::SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
_connector_request: Option<services::Request>,
business_profile: &domain::Profile,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
metrics::SESSION_TOKEN_CREATED.add(
1,
router_env::metric_attributes!(("connector", connector.connector_name.to_string())),
);
self.decide_flow(
state,
connector,
Some(true),
call_connector_action,
business_profile,
header_payload,
)
.await
}
async fn add_access_token<'a>(
&self,
state: &routes::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 create_connector_customer<'a>(
&self,
state: &routes::SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Option<String>> {
customers::create_connector_customer(
state,
connector,
self,
types::ConnectorCustomerData::try_from(self)?,
)
.await
}
}
/// This function checks if for a given connector, payment_method and payment_method_type,
/// the list of required_field_type is present in dynamic fields
#[cfg(feature = "v1")]
fn is_dynamic_fields_required(
required_fields: &settings::RequiredFields,
payment_method: enums::PaymentMethod,
payment_method_type: enums::PaymentMethodType,
connector: types::Connector,
required_field_type: Vec<enums::FieldType>,
) -> bool {
required_fields
.0
.get(&payment_method)
.and_then(|pm_type| pm_type.0.get(&payment_method_type))
.and_then(|required_fields_for_connector| {
required_fields_for_connector.fields.get(&connector)
})
.map(|required_fields_final| {
required_fields_final
.non_mandate
.iter()
.any(|(_, val)| required_field_type.contains(&val.field_type))
|| required_fields_final
.mandate
.iter()
.any(|(_, val)| required_field_type.contains(&val.field_type))
|| required_fields_final
.common
.iter()
.any(|(_, val)| required_field_type.contains(&val.field_type))
})
.unwrap_or(false)
}
/// This function checks if for a given connector, payment_method and payment_method_type,
/// the list of required_field_type is present in dynamic fields
#[cfg(feature = "v2")]
fn is_dynamic_fields_required(
required_fields: &settings::RequiredFields,
payment_method: enums::PaymentMethod,
payment_method_type: enums::PaymentMethodType,
connector: types::Connector,
required_field_type: Vec<enums::FieldType>,
) -> bool {
required_fields
.0
.get(&payment_method)
.and_then(|pm_type| pm_type.0.get(&payment_method_type))
.and_then(|required_fields_for_connector| {
required_fields_for_connector.fields.get(&connector)
})
.map(|required_fields_final| {
required_fields_final
.non_mandate
.iter()
.flatten()
.any(|field_info| required_field_type.contains(&field_info.field_type))
|| required_fields_final
.mandate
.iter()
.flatten()
.any(|field_info| required_field_type.contains(&field_info.field_type))
|| required_fields_final
.common
.iter()
.flatten()
.any(|field_info| required_field_type.contains(&field_info.field_type))
})
.unwrap_or(false)
}
fn build_apple_pay_session_request(
state: &routes::SessionState,
request: payment_types::ApplepaySessionRequest,
apple_pay_merchant_cert: masking::Secret<String>,
apple_pay_merchant_cert_key: masking::Secret<String>,
) -> RouterResult<services::Request> {
let mut url = state.conf.connectors.applepay.base_url.to_owned();
url.push_str("paymentservices/paymentSession");
let session_request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(url.as_str())
.attach_default_headers()
.headers(vec![(
headers::CONTENT_TYPE.to_string(),
"application/json".to_string().into(),
)])
.set_body(RequestContent::Json(Box::new(request)))
.add_certificate(Some(apple_pay_merchant_cert))
.add_certificate_key(Some(apple_pay_merchant_cert_key))
.build();
Ok(session_request)
}
async fn create_applepay_session_token(
state: &routes::SessionState,
router_data: &types::PaymentsSessionRouterData,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<types::PaymentsSessionRouterData> {
let delayed_response = is_session_response_delayed(state, connector);
if delayed_response {
let delayed_response_apple_pay_session =
Some(payment_types::ApplePaySessionResponse::NoSessionResponse(
api_models::payments::NullObject,
));
create_apple_pay_session_response(
router_data,
delayed_response_apple_pay_session,
None, // Apple pay payment request will be none for delayed session response
connector.connector_name.to_string(),
delayed_response,
payment_types::NextActionCall::Confirm,
header_payload,
)
} else {
// Get the apple pay metadata
let apple_pay_metadata =
helpers::get_applepay_metadata(router_data.connector_meta_data.clone())
.attach_printable(
"Failed to to fetch apple pay certificates during session call",
)?;
// Get payment request data , apple pay session request and merchant keys
let (
payment_request_data,
apple_pay_session_request_optional,
apple_pay_merchant_cert,
apple_pay_merchant_cert_key,
apple_pay_merchant_identifier,
merchant_business_country,
merchant_configured_domain_optional,
) = match apple_pay_metadata {
payment_types::ApplepaySessionTokenMetadata::ApplePayCombined(
apple_pay_combined_metadata,
) => match apple_pay_combined_metadata {
payment_types::ApplePayCombinedMetadata::Simplified {
payment_request_data,
session_token_data,
} => {
logger::info!("Apple pay simplified flow");
let merchant_identifier = state
.conf
.applepay_merchant_configs
.get_inner()
.common_merchant_identifier
.clone()
.expose();
let merchant_business_country = session_token_data.merchant_business_country;
let apple_pay_session_request = get_session_request_for_simplified_apple_pay(
merchant_identifier.clone(),
session_token_data.clone(),
);
let apple_pay_merchant_cert = state
.conf
.applepay_decrypt_keys
.get_inner()
.apple_pay_merchant_cert
.clone();
let apple_pay_merchant_cert_key = state
.conf
.applepay_decrypt_keys
.get_inner()
.apple_pay_merchant_cert_key
.clone();
(
payment_request_data,
Ok(apple_pay_session_request),
apple_pay_merchant_cert,
apple_pay_merchant_cert_key,
merchant_identifier,
merchant_business_country,
Some(session_token_data.initiative_context),
)
}
payment_types::ApplePayCombinedMetadata::Manual {
payment_request_data,
session_token_data,
} => {
logger::info!("Apple pay manual flow");
let apple_pay_session_request = get_session_request_for_manual_apple_pay(
session_token_data.clone(),
header_payload.x_merchant_domain.clone(),
);
let merchant_business_country = session_token_data.merchant_business_country;
(
payment_request_data,
apple_pay_session_request,
session_token_data.certificate.clone(),
session_token_data.certificate_keys,
session_token_data.merchant_identifier,
merchant_business_country,
session_token_data.initiative_context,
)
}
},
payment_types::ApplepaySessionTokenMetadata::ApplePay(apple_pay_metadata) => {
logger::info!("Apple pay manual flow");
let apple_pay_session_request = get_session_request_for_manual_apple_pay(
apple_pay_metadata.session_token_data.clone(),
header_payload.x_merchant_domain.clone(),
);
let merchant_business_country = apple_pay_metadata
.session_token_data
.merchant_business_country;
(
apple_pay_metadata.payment_request_data,
apple_pay_session_request,
apple_pay_metadata.session_token_data.certificate.clone(),
apple_pay_metadata
.session_token_data
.certificate_keys
.clone(),
apple_pay_metadata.session_token_data.merchant_identifier,
merchant_business_country,
apple_pay_metadata.session_token_data.initiative_context,
)
}
};
// Get amount info for apple pay
let amount_info = get_apple_pay_amount_info(
payment_request_data.label.as_str(),
router_data.request.to_owned(),
)?;
let required_billing_contact_fields = if business_profile
.always_collect_billing_details_from_wallet_connector
.unwrap_or(false)
{
Some(payment_types::ApplePayBillingContactFields(vec![
payment_types::ApplePayAddressParameters::PostalAddress,
]))
} else if business_profile
.collect_billing_details_from_wallet_connector
.unwrap_or(false)
{
let billing_variants = enums::FieldType::get_billing_variants();
is_dynamic_fields_required(
&state.conf.required_fields,
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
connector.connector_name,
billing_variants,
)
.then_some(payment_types::ApplePayBillingContactFields(vec![
payment_types::ApplePayAddressParameters::PostalAddress,
]))
} else {
None
};
let required_shipping_contact_fields = if business_profile
.always_collect_shipping_details_from_wallet_connector
.unwrap_or(false)
{
Some(payment_types::ApplePayShippingContactFields(vec![
payment_types::ApplePayAddressParameters::PostalAddress,
payment_types::ApplePayAddressParameters::Phone,
payment_types::ApplePayAddressParameters::Email,
]))
} else if business_profile
.collect_shipping_details_from_wallet_connector
.unwrap_or(false)
{
let shipping_variants = enums::FieldType::get_shipping_variants();
is_dynamic_fields_required(
&state.conf.required_fields,
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
connector.connector_name,
shipping_variants,
)
.then_some(payment_types::ApplePayShippingContactFields(vec![
payment_types::ApplePayAddressParameters::PostalAddress,
payment_types::ApplePayAddressParameters::Phone,
payment_types::ApplePayAddressParameters::Email,
]))
} else {
None
};
// If collect_shipping_details_from_wallet_connector is false, we check if
// collect_billing_details_from_wallet_connector is true. If it is, then we pass the Email and Phone in
// ApplePayShippingContactFields as it is a required parameter and ApplePayBillingContactFields
// does not contain Email and Phone.
let required_shipping_contact_fields_updated = if required_billing_contact_fields.is_some()
&& required_shipping_contact_fields.is_none()
{
Some(payment_types::ApplePayShippingContactFields(vec![
payment_types::ApplePayAddressParameters::Phone,
payment_types::ApplePayAddressParameters::Email,
]))
} else {
required_shipping_contact_fields
};
// Get apple pay payment request
let applepay_payment_request = get_apple_pay_payment_request(
amount_info,
payment_request_data,
router_data.request.to_owned(),
apple_pay_merchant_identifier.as_str(),
merchant_business_country,
required_billing_contact_fields,
required_shipping_contact_fields_updated,
)?;
let apple_pay_session_response = match (
header_payload.browser_name.clone(),
header_payload.x_client_platform.clone(),
) {
(Some(common_enums::BrowserName::Safari), Some(common_enums::ClientPlatform::Web))
| (None, None) => {
let apple_pay_session_request = apple_pay_session_request_optional
.attach_printable("Failed to obtain apple pay session request")?;
let applepay_session_request = build_apple_pay_session_request(
state,
apple_pay_session_request.clone(),
apple_pay_merchant_cert.clone(),
apple_pay_merchant_cert_key.clone(),
)?;
let response = services::call_connector_api(
state,
applepay_session_request,
"create_apple_pay_session_token",
)
.await;
let updated_response = match (
response.as_ref().ok(),
header_payload.x_merchant_domain.clone(),
) {
(Some(Err(error)), Some(_)) => {
logger::error!(
"Retry apple pay session call with the merchant configured domain {error:?}"
);
let merchant_configured_domain = merchant_configured_domain_optional
.get_required_value("apple pay domain")
.attach_printable("Failed to get domain for apple pay session call")?;
let apple_pay_retry_session_request =
payment_types::ApplepaySessionRequest {
initiative_context: merchant_configured_domain,
..apple_pay_session_request
};
let applepay_retry_session_request = build_apple_pay_session_request(
state,
apple_pay_retry_session_request,
apple_pay_merchant_cert,
apple_pay_merchant_cert_key,
)?;
services::call_connector_api(
state,
applepay_retry_session_request,
"create_apple_pay_session_token",
)
.await
}
_ => response,
};
// logging the error if present in session call response
log_session_response_if_error(&updated_response);
updated_response
.ok()
.and_then(|apple_pay_res| {
apple_pay_res
.map(|res| {
let response: Result<
payment_types::NoThirdPartySdkSessionResponse,
Report<common_utils::errors::ParsingError>,
> = res.response.parse_struct("NoThirdPartySdkSessionResponse");
// logging the parsing failed error
if let Err(error) = response.as_ref() {
logger::error!(?error);
};
response.ok()
})
.ok()
})
.flatten()
}
_ => {
logger::debug!("Skipping apple pay session call based on the browser name");
None
}
};
let session_response =
apple_pay_session_response.map(payment_types::ApplePaySessionResponse::NoThirdPartySdk);
create_apple_pay_session_response(
router_data,
session_response,
Some(applepay_payment_request),
connector.connector_name.to_string(),
delayed_response,
payment_types::NextActionCall::Confirm,
header_payload,
)
}
}
fn create_paze_session_token(
router_data: &types::PaymentsSessionRouterData,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<types::PaymentsSessionRouterData> {
let paze_wallet_details = router_data
.connector_wallets_details
.clone()
.parse_value::<payment_types::PazeSessionTokenData>("PazeSessionTokenData")
.change_context(errors::ConnectorError::NoConnectorWalletDetails)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_wallets_details".to_string(),
expected_format: "paze_metadata_format".to_string(),
})?;
let required_amount_type = StringMajorUnitForConnector;
let transaction_currency_code = router_data.request.currency;
let transaction_amount = required_amount_type
.convert(router_data.request.minor_amount, transaction_currency_code)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert amount to string major unit for paze".to_string(),
})?;
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::Paze(Box::new(
payment_types::PazeSessionTokenResponse {
client_id: paze_wallet_details.data.client_id,
client_name: paze_wallet_details.data.client_name,
client_profile_id: paze_wallet_details.data.client_profile_id,
transaction_currency_code,
transaction_amount,
email_address: router_data.request.email.clone(),
},
)),
}),
..router_data.clone()
})
}
fn create_samsung_pay_session_token(
state: &routes::SessionState,
router_data: &types::PaymentsSessionRouterData,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
) -> RouterResult<types::PaymentsSessionRouterData> {
let samsung_pay_session_token_data = router_data
.connector_wallets_details
.clone()
.parse_value::<payment_types::SamsungPaySessionTokenData>("SamsungPaySessionTokenData")
.change_context(errors::ConnectorError::NoConnectorWalletDetails)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_wallets_details".to_string(),
expected_format: "samsung_pay_metadata_format".to_string(),
})?;
let required_amount_type = StringMajorUnitForConnector;
let samsung_pay_amount = required_amount_type
.convert(
router_data.request.minor_amount,
router_data.request.currency,
)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert amount to string major unit for Samsung Pay".to_string(),
})?;
let merchant_domain = match header_payload.x_client_platform {
Some(common_enums::ClientPlatform::Web) => Some(
header_payload
.x_merchant_domain
.get_required_value("samsung pay domain")
.attach_printable("Failed to get domain for samsung pay session call")?,
),
_ => None,
};
let samsung_pay_wallet_details = match samsung_pay_session_token_data.data {
payment_types::SamsungPayCombinedMetadata::MerchantCredentials(
samsung_pay_merchant_credentials,
) => samsung_pay_merchant_credentials,
payment_types::SamsungPayCombinedMetadata::ApplicationCredentials(
_samsung_pay_application_credentials,
) => Err(errors::ApiErrorResponse::NotSupported {
message: "Samsung Pay decryption flow with application credentials is not implemented"
.to_owned(),
})?,
};
let formatted_payment_id = router_data.payment_id.replace("_", "-");
let billing_address_required = is_billing_address_required_to_be_collected_from_wallet(
state,
connector,
business_profile,
enums::PaymentMethodType::SamsungPay,
);
let shipping_address_required = is_shipping_address_required_to_be_collected_form_wallet(
state,
connector,
business_profile,
enums::PaymentMethodType::SamsungPay,
);
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::SamsungPay(Box::new(
payment_types::SamsungPaySessionTokenResponse {
version: "2".to_string(),
service_id: samsung_pay_wallet_details.service_id,
order_number: formatted_payment_id,
merchant_payment_information:
payment_types::SamsungPayMerchantPaymentInformation {
name: samsung_pay_wallet_details.merchant_display_name,
url: merchant_domain,
country_code: samsung_pay_wallet_details.merchant_business_country,
},
amount: payment_types::SamsungPayAmountDetails {
amount_format: payment_types::SamsungPayAmountFormat::FormatTotalPriceOnly,
currency_code: router_data.request.currency,
total_amount: samsung_pay_amount,
},
protocol: payment_types::SamsungPayProtocolType::Protocol3ds,
allowed_brands: samsung_pay_wallet_details.allowed_brands,
billing_address_required,
shipping_address_required,
},
)),
}),
..router_data.clone()
})
}
/// Function to determine whether the billing address is required to be collected from the wallet,
/// based on business profile settings, the payment method type, and the connector's required fields
/// for the specific payment method.
///
/// If `always_collect_billing_details_from_wallet_connector` is enabled, it indicates that the
/// billing address is always required to be collected from the wallet.
///
/// If only `collect_billing_details_from_wallet_connector` is enabled, the billing address will be
/// collected only if the connector required fields for the specific payment method type contain
/// the billing fields.
fn is_billing_address_required_to_be_collected_from_wallet(
state: &routes::SessionState,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
payment_method_type: enums::PaymentMethodType,
) -> bool {
let always_collect_billing_details_from_wallet_connector = business_profile
.always_collect_billing_details_from_wallet_connector
.unwrap_or(false);
if always_collect_billing_details_from_wallet_connector {
always_collect_billing_details_from_wallet_connector
} else if business_profile
.collect_billing_details_from_wallet_connector
.unwrap_or(false)
{
let billing_variants = enums::FieldType::get_billing_variants();
is_dynamic_fields_required(
&state.conf.required_fields,
enums::PaymentMethod::Wallet,
payment_method_type,
connector.connector_name,
billing_variants,
)
} else {
false
}
}
/// Function to determine whether the shipping address is required to be collected from the wallet,
/// based on business profile settings, the payment method type, and the connector required fields
/// for the specific payment method type.
///
/// If `always_collect_shipping_details_from_wallet_connector` is enabled, it indicates that the
/// shipping address is always required to be collected from the wallet.
///
/// If only `collect_shipping_details_from_wallet_connector` is enabled, the shipping address will be
/// collected only if the connector required fields for the specific payment method type contain
/// the shipping fields.
fn is_shipping_address_required_to_be_collected_form_wallet(
state: &routes::SessionState,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
payment_method_type: enums::PaymentMethodType,
) -> bool {
let always_collect_shipping_details_from_wallet_connector = business_profile
.always_collect_shipping_details_from_wallet_connector
.unwrap_or(false);
if always_collect_shipping_details_from_wallet_connector {
always_collect_shipping_details_from_wallet_connector
} else if business_profile
.collect_shipping_details_from_wallet_connector
.unwrap_or(false)
{
let shipping_variants = enums::FieldType::get_shipping_variants();
is_dynamic_fields_required(
&state.conf.required_fields,
enums::PaymentMethod::Wallet,
payment_method_type,
connector.connector_name,
shipping_variants,
)
} else {
false
}
}
fn get_session_request_for_simplified_apple_pay(
apple_pay_merchant_identifier: String,
session_token_data: payment_types::SessionTokenForSimplifiedApplePay,
) -> payment_types::ApplepaySessionRequest {
payment_types::ApplepaySessionRequest {
merchant_identifier: apple_pay_merchant_identifier,
display_name: "Apple pay".to_string(),
initiative: "web".to_string(),
initiative_context: session_token_data.initiative_context,
}
}
fn get_session_request_for_manual_apple_pay(
session_token_data: payment_types::SessionTokenInfo,
merchant_domain: Option<String>,
) -> RouterResult<payment_types::ApplepaySessionRequest> {
let initiative_context = merchant_domain
.or_else(|| session_token_data.initiative_context.clone())
.get_required_value("apple pay domain")
.attach_printable("Failed to get domain for apple pay session call")?;
Ok(payment_types::ApplepaySessionRequest {
merchant_identifier: session_token_data.merchant_identifier.clone(),
display_name: session_token_data.display_name.clone(),
initiative: session_token_data.initiative.to_string(),
initiative_context,
})
}
fn get_apple_pay_amount_info(
label: &str,
session_data: types::PaymentsSessionData,
) -> RouterResult<payment_types::AmountInfo> {
let required_amount_type = StringMajorUnitForConnector;
let apple_pay_amount = required_amount_type
.convert(session_data.minor_amount, session_data.currency)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert amount to string major unit for applePay".to_string(),
})?;
let amount_info = payment_types::AmountInfo {
label: label.to_string(),
total_type: Some("final".to_string()),
amount: apple_pay_amount,
};
Ok(amount_info)
}
fn get_apple_pay_payment_request(
amount_info: payment_types::AmountInfo,
payment_request_data: payment_types::PaymentRequestMetadata,
session_data: types::PaymentsSessionData,
merchant_identifier: &str,
merchant_business_country: Option<api_models::enums::CountryAlpha2>,
required_billing_contact_fields: Option<payment_types::ApplePayBillingContactFields>,
required_shipping_contact_fields: Option<payment_types::ApplePayShippingContactFields>,
) -> RouterResult<payment_types::ApplePayPaymentRequest> {
let applepay_payment_request = payment_types::ApplePayPaymentRequest {
country_code: merchant_business_country.or(session_data.country).ok_or(
errors::ApiErrorResponse::MissingRequiredField {
field_name: "country_code",
},
)?,
currency_code: session_data.currency,
total: amount_info,
merchant_capabilities: Some(payment_request_data.merchant_capabilities),
supported_networks: Some(payment_request_data.supported_networks),
merchant_identifier: Some(merchant_identifier.to_string()),
required_billing_contact_fields,
required_shipping_contact_fields,
recurring_payment_request: session_data.apple_pay_recurring_details,
};
Ok(applepay_payment_request)
}
fn create_apple_pay_session_response(
router_data: &types::PaymentsSessionRouterData,
session_response: Option<payment_types::ApplePaySessionResponse>,
apple_pay_payment_request: Option<payment_types::ApplePayPaymentRequest>,
connector_name: String,
delayed_response: bool,
next_action: payment_types::NextActionCall,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<types::PaymentsSessionRouterData> {
match session_response {
Some(response) => Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::ApplePay(Box::new(
payment_types::ApplepaySessionTokenResponse {
session_token_data: Some(response),
payment_request_data: apple_pay_payment_request,
connector: connector_name,
delayed_session_token: delayed_response,
sdk_next_action: { payment_types::SdkNextAction { next_action } },
connector_reference_id: None,
connector_sdk_public_key: None,
connector_merchant_id: None,
},
)),
}),
..router_data.clone()
}),
None => {
match (
header_payload.browser_name,
header_payload.x_client_platform,
) {
(
Some(common_enums::BrowserName::Safari),
Some(common_enums::ClientPlatform::Web),
)
| (None, None) => Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::NoSessionTokenReceived,
}),
..router_data.clone()
}),
_ => Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::ApplePay(Box::new(
payment_types::ApplepaySessionTokenResponse {
session_token_data: None,
payment_request_data: apple_pay_payment_request,
connector: connector_name,
delayed_session_token: delayed_response,
sdk_next_action: { payment_types::SdkNextAction { next_action } },
connector_reference_id: None,
connector_sdk_public_key: None,
connector_merchant_id: None,
},
)),
}),
..router_data.clone()
}),
}
}
}
}
fn create_gpay_session_token(
state: &routes::SessionState,
router_data: &types::PaymentsSessionRouterData,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
) -> RouterResult<types::PaymentsSessionRouterData> {
// connector_wallet_details is being parse into admin types to check specifically if google_pay field is present
// this is being done because apple_pay details from metadata is also being filled into connector_wallets_details
let google_pay_wallets_details = router_data
.connector_wallets_details
.clone()
.parse_value::<admin_types::ConnectorWalletDetails>("ConnectorWalletDetails")
.change_context(errors::ConnectorError::NoConnectorWalletDetails)
.attach_printable(format!(
"cannot parse connector_wallets_details from the given value {:?}",
router_data.connector_wallets_details
))
.map_err(|err| {
logger::debug!(
"Failed to parse connector_wallets_details for google_pay flow: {:?}",
err
);
})
.ok()
.and_then(|connector_wallets_details| connector_wallets_details.google_pay);
let connector_metadata = router_data.connector_meta_data.clone();
let delayed_response = is_session_response_delayed(state, connector);
if delayed_response {
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::GooglePay(Box::new(
payment_types::GpaySessionTokenResponse::ThirdPartyResponse(
payment_types::GooglePayThirdPartySdk {
delayed_session_token: true,
connector: connector.connector_name.to_string(),
sdk_next_action: payment_types::SdkNextAction {
next_action: payment_types::NextActionCall::Confirm,
},
},
),
)),
}),
..router_data.clone()
})
} else {
let is_billing_details_required = is_billing_address_required_to_be_collected_from_wallet(
state,
connector,
business_profile,
enums::PaymentMethodType::GooglePay,
);
let required_amount_type = StringMajorUnitForConnector;
let google_pay_amount = required_amount_type
.convert(
router_data.request.minor_amount,
router_data.request.currency,
)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert amount to string major unit for googlePay".to_string(),
})?;
let session_data = router_data.request.clone();
let transaction_info = payment_types::GpayTransactionInfo {
country_code: session_data.country.unwrap_or_default(),
currency_code: router_data.request.currency,
total_price_status: "Final".to_string(),
total_price: google_pay_amount,
};
let required_shipping_contact_fields =
is_shipping_address_required_to_be_collected_form_wallet(
state,
connector,
business_profile,
enums::PaymentMethodType::GooglePay,
);
if google_pay_wallets_details.is_some() {
let gpay_data = router_data
.connector_wallets_details
.clone()
.parse_value::<payment_types::GooglePayWalletDetails>("GooglePayWalletDetails")
.change_context(errors::ConnectorError::NoConnectorWalletDetails)
.attach_printable(format!(
"cannot parse gpay connector_wallets_details from the given value {:?}",
router_data.connector_wallets_details
))
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_wallets_details".to_string(),
expected_format: "gpay_connector_wallets_details_format".to_string(),
})?;
let payment_types::GooglePayProviderDetails::GooglePayMerchantDetails(gpay_info) =
gpay_data.google_pay.provider_details.clone();
let gpay_allowed_payment_methods = get_allowed_payment_methods_from_cards(
gpay_data,
&gpay_info.merchant_info.tokenization_specification,
is_billing_details_required,
)?;
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::GooglePay(Box::new(
payment_types::GpaySessionTokenResponse::GooglePaySession(
payment_types::GooglePaySessionResponse {
merchant_info: payment_types::GpayMerchantInfo {
merchant_name: gpay_info.merchant_info.merchant_name,
merchant_id: gpay_info.merchant_info.merchant_id,
},
allowed_payment_methods: vec![gpay_allowed_payment_methods],
transaction_info,
connector: connector.connector_name.to_string(),
sdk_next_action: payment_types::SdkNextAction {
next_action: payment_types::NextActionCall::Confirm,
},
delayed_session_token: false,
secrets: None,
shipping_address_required: required_shipping_contact_fields,
// We pass Email as a required field irrespective of
// collect_billing_details_from_wallet_connector or
// collect_shipping_details_from_wallet_connector as it is common to both.
email_required: required_shipping_contact_fields
|| is_billing_details_required,
shipping_address_parameters:
api_models::payments::GpayShippingAddressParameters {
phone_number_required: required_shipping_contact_fields,
},
},
),
)),
}),
..router_data.clone()
})
} else {
let billing_address_parameters = is_billing_details_required.then_some(
payment_types::GpayBillingAddressParameters {
phone_number_required: is_billing_details_required,
format: payment_types::GpayBillingAddressFormat::FULL,
},
);
let gpay_data = connector_metadata
.clone()
.parse_value::<payment_types::GpaySessionTokenData>("GpaySessionTokenData")
.change_context(errors::ConnectorError::NoConnectorMetaData)
.attach_printable(format!(
"cannot parse gpay metadata from the given value {connector_metadata:?}"
))
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_metadata".to_string(),
expected_format: "gpay_metadata_format".to_string(),
})?;
let gpay_allowed_payment_methods = gpay_data
.data
.allowed_payment_methods
.into_iter()
.map(
|allowed_payment_methods| payment_types::GpayAllowedPaymentMethods {
parameters: payment_types::GpayAllowedMethodsParameters {
billing_address_required: Some(is_billing_details_required),
billing_address_parameters: billing_address_parameters.clone(),
..allowed_payment_methods.parameters
|
crates/router/src/core/payments/flows/session_flow.rs#chunk0
|
router
|
chunk
| null | null | null | 8,192
| null | null | null | null | null | null | null |
// Function: find_by_fingerprint_id
// File: crates/diesel_models/src/query/payment_method.rs
// Module: diesel_models
pub fn find_by_fingerprint_id(
conn: &PgPooledConn,
fingerprint_id: &str,
) -> StorageResult<Self>
|
crates/diesel_models/src/query/payment_method.rs
|
diesel_models
|
function_signature
| null | null | null | 59
|
find_by_fingerprint_id
| null | null | null | null | null | null |
// Struct: ProcessingOptions
// File: crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ProcessingOptions
|
crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ProcessingOptions
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Implementation: impl api::Payment for for Coinbase
// File: crates/hyperswitch_connectors/src/connectors/coinbase.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::Payment for for Coinbase
|
crates/hyperswitch_connectors/src/connectors/coinbase.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 54
| null |
Coinbase
|
api::Payment for
| 0
| 0
| null | null |
// Implementation: impl NetworkTokenizationBuilder
// File: crates/router/src/core/payment_methods/tokenize/card_executor.rs
// Module: router
// Methods: 1 total (1 public)
impl NetworkTokenizationBuilder
|
crates/router/src/core/payment_methods/tokenize/card_executor.rs
|
router
|
impl_block
| null | null | null | 44
| null |
NetworkTokenizationBuilder
| null | 1
| 1
| null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.