text
string | file_path
string | module
string | type
string | tokens
int64 | language
string | struct_name
string | type_name
string | trait_name
string | impl_type
string | function_name
string | source
string | section
string | keys
list | macro_type
string | url
string | title
string | chunk_index
int64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pub struct KafkaPaymentIntentEvent<'a> {
pub payment_id: &'a id_type::GlobalPaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: common_types::MinorUnit,
pub currency: storage_enums::Currency,
pub amount_captured: Option<common_types::MinorUnit>,
pub customer_id: Option<&'a id_type::GlobalCustomerId>,
pub description: Option<&'a common_types::Description>,
pub return_url: Option<&'a common_types::Url>,
pub metadata: Option<&'a Secret<Value>>,
pub statement_descriptor: Option<&'a common_types::StatementDescriptor>,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub modified_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::nanoseconds::option")]
pub last_synced: Option<OffsetDateTime>,
pub setup_future_usage: storage_enums::FutureUsage,
pub off_session: bool,
pub active_attempt_id: Option<&'a id_type::GlobalAttemptId>,
pub attempt_count: i16,
pub profile_id: &'a id_type::ProfileId,
pub customer_email: Option<HashedString<pii::EmailStrategy>>,
pub feature_metadata: Option<&'a diesel_types::FeatureMetadata>,
pub organization_id: &'a id_type::OrganizationId,
pub order_details: Option<&'a Vec<Secret<OrderDetailsWithAmount>>>,
pub allowed_payment_method_types: Option<&'a Vec<common_enums::PaymentMethodType>>,
pub connector_metadata: Option<&'a Secret<Value>>,
pub payment_link_id: Option<&'a String>,
pub updated_by: &'a String,
pub surcharge_applicable: Option<bool>,
pub request_incremental_authorization: RequestIncrementalAuthorization,
pub split_txns_enabled: common_enums::SplitTxnsEnabled,
pub authorization_count: Option<i32>,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub session_expiry: OffsetDateTime,
pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest,
pub frm_metadata: Option<Secret<&'a Value>>,
pub customer_details: Option<Secret<&'a Value>>,
pub shipping_cost: Option<common_types::MinorUnit>,
pub tax_details: Option<TaxDetails>,
pub skip_external_tax_calculation: bool,
pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>,
pub split_payments: Option<&'a payments::SplitPaymentsRequest>,
pub platform_merchant_id: Option<&'a id_type::MerchantId>,
pub force_3ds_challenge: Option<bool>,
pub force_3ds_challenge_trigger: Option<bool>,
pub processor_merchant_id: &'a id_type::MerchantId,
pub created_by: Option<&'a common_types::CreatedBy>,
pub is_iframe_redirection_enabled: Option<bool>,
pub merchant_reference_id: Option<&'a id_type::PaymentReferenceId>,
pub capture_method: storage_enums::CaptureMethod,
pub authentication_type: Option<common_enums::AuthenticationType>,
pub prerouting_algorithm: Option<&'a routing::PaymentRoutingInfo>,
pub surcharge_amount: Option<common_types::MinorUnit>,
pub billing_address: Option<Secret<&'a address::Address>>,
pub shipping_address: Option<Secret<&'a address::Address>>,
pub tax_on_surcharge: Option<common_types::MinorUnit>,
pub frm_merchant_decision: Option<common_enums::MerchantDecision>,
pub enable_payment_link: common_enums::EnablePaymentLinkRequest,
pub apply_mit_exemption: common_enums::MitExemptionRequest,
pub customer_present: common_enums::PresenceOfCustomerDuringPayment,
pub routing_algorithm_id: Option<&'a id_type::RoutingId>,
pub payment_link_config: Option<&'a PaymentLinkConfigRequestForPayments>,
#[serde(flatten)]
infra_values: Option<Value>,
}
|
crates/router/src/services/kafka/payment_intent_event.rs
|
router
|
struct_definition
| 912
|
rust
|
KafkaPaymentIntentEvent
| null | null | null | null | null | null | null | null | null | null | null |
pub struct DwollaFundingSourceRequest {
routing_number: Secret<String>,
account_number: Secret<String>,
#[serde(rename = "type")]
account_type: common_enums::BankType,
name: Secret<String>,
}
|
crates/hyperswitch_connectors/src/connectors/dwolla/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 49
|
rust
|
DwollaFundingSourceRequest
| null | null | null | null | null | null | null | null | null | null | null |
impl api::PaymentToken for Nmi {}
|
crates/hyperswitch_connectors/src/connectors/nmi.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Nmi
|
api::PaymentToken for
|
impl api::PaymentToken for for Nmi
| null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.Connector
{
"type": "string",
"enum": [
"authipay",
"adyenplatform",
"stripe_billing_test",
"phonypay",
"fauxpay",
"pretendpay",
"stripe_test",
"adyen_test",
"checkout_test",
"paypal_test",
"aci",
"adyen",
"affirm",
"airwallex",
"amazonpay",
"archipel",
"authorizedotnet",
"bambora",
"bamboraapac",
"bankofamerica",
"barclaycard",
"billwerk",
"bitpay",
"bluesnap",
"blackhawknetwork",
"bluecode",
"boku",
"braintree",
"breadpay",
"cashtocode",
"celero",
"chargebee",
"checkbook",
"checkout",
"coinbase",
"coingate",
"custombilling",
"cryptopay",
"ctp_mastercard",
"ctp_visa",
"cybersource",
"datatrans",
"deutschebank",
"digitalvirgo",
"dlocal",
"dwolla",
"ebanx",
"elavon",
"facilitapay",
"fiserv",
"fiservemea",
"fiuu",
"flexiti",
"forte",
"getnet",
"globalpay",
"globepay",
"gocardless",
"gpayments",
"hipay",
"helcim",
"hyperswitch_vault",
"inespay",
"iatapay",
"itaubank",
"jpmorgan",
"juspaythreedsserver",
"klarna",
"mifinity",
"mollie",
"moneris",
"multisafepay",
"netcetera",
"nexinets",
"nexixpay",
"nmi",
"nomupay",
"noon",
"nordea",
"novalnet",
"nuvei",
"opennode",
"paybox",
"payload",
"payme",
"payone",
"paypal",
"paysafe",
"paystack",
"paytm",
"payu",
"phonepe",
"placetopay",
"powertranz",
"prophetpay",
"rapyd",
"razorpay",
"recurly",
"redsys",
"santander",
"shift4",
"silverflow",
"square",
"stax",
"stripe",
"stripebilling",
"taxjar",
"threedsecureio",
"tokenio",
"trustpay",
"tsys",
"vgs",
"volt",
"wellsfargo",
"wise",
"worldline",
"worldpay",
"worldpayvantiv",
"worldpayxml",
"signifyd",
"plaid",
"riskified",
"xendit",
"zen",
"zsl"
]
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 720
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"Connector"
] | null | null | null | null |
pub fn get_order_tax_amount(&self) -> Option<MinorUnit> {
self.order_tax_amount
}
|
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
|
hyperswitch_domain_models
|
function_signature
| 24
|
rust
| null | null | null | null |
get_order_tax_amount
| null | null | null | null | null | null | null |
File: crates/analytics/src/refunds/metrics/refund_count.rs
use std::collections::HashSet;
use api_models::analytics::{
refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::RefundMetricRow;
use crate::{
enums::AuthInfo,
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(super) struct RefundCount {}
#[async_trait::async_trait]
impl<T> super::RefundMetric<T> for RefundCount
where
T: AnalyticsDataSource + super::RefundMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[RefundDimensions],
auth: &AuthInfo,
filters: &RefundFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> {
let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Refund);
for dim in dimensions.iter() {
query_builder.add_select_column(dim).switch()?;
}
query_builder
.add_select_column(Aggregate::Count {
field: None,
alias: Some("count"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
auth.set_filter_clause(&mut query_builder).switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
for dim in dimensions.iter() {
query_builder
.add_group_by_clause(dim)
.attach_printable("Error grouping by dimensions")
.switch()?;
}
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.attach_printable("Error adding granularity")
.switch()?;
}
query_builder
.execute_query::<RefundMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
RefundMetricsBucketIdentifier::new(
i.currency.as_ref().map(|i| i.0),
i.refund_status.as_ref().map(|i| i.0.to_string()),
i.connector.clone(),
i.refund_type.as_ref().map(|i| i.0.to_string()),
i.profile_id.clone(),
i.refund_reason.clone(),
i.refund_error_message.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
},
),
i,
))
})
.collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
|
crates/analytics/src/refunds/metrics/refund_count.rs
|
analytics
|
full_file
| 865
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct PaymentIntentFilterRow {
pub status: Option<DBEnumWrapper<IntentStatus>>,
pub currency: Option<DBEnumWrapper<Currency>>,
pub profile_id: Option<String>,
pub connector: Option<String>,
pub authentication_type: Option<DBEnumWrapper<AuthenticationType>>,
pub payment_method: Option<String>,
pub payment_method_type: Option<String>,
pub card_network: Option<String>,
pub merchant_id: Option<String>,
pub card_last_4: Option<String>,
pub card_issuer: Option<String>,
pub error_reason: Option<String>,
pub customer_id: Option<String>,
}
|
crates/analytics/src/payment_intents/filters.rs
|
analytics
|
struct_definition
| 130
|
rust
|
PaymentIntentFilterRow
| null | null | null | null | null | null | null | null | null | null | null |
impl SecretsHandler for Database {
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
let secured_db_config = value.get_inner();
let raw_db_password = secret_management_client
.get_secret(secured_db_config.password.clone())
.await?;
Ok(value.transition_state(|db| Self {
password: raw_db_password,
..db
}))
}
}
|
crates/drainer/src/secrets_transformers.rs
|
drainer
|
impl_block
| 117
|
rust
| null |
Database
|
SecretsHandler for
|
impl SecretsHandler for for Database
| null | null | null | null | null | null | null | null |
pub struct JpmorganValidationErrors {
pub code: Option<String>,
pub message: Option<String>,
pub entity: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 30
|
rust
|
JpmorganValidationErrors
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/router/src/routes/metrics/bg_metrics_collector.rs
Public functions: 1
use storage_impl::redis::cache;
const DEFAULT_BG_METRICS_COLLECTION_INTERVAL_IN_SECS: u16 = 15;
pub fn spawn_metrics_collector(metrics_collection_interval_in_secs: Option<u16>) {
let metrics_collection_interval = metrics_collection_interval_in_secs
.unwrap_or(DEFAULT_BG_METRICS_COLLECTION_INTERVAL_IN_SECS);
let cache_instances = [
&cache::CONFIG_CACHE,
&cache::ACCOUNTS_CACHE,
&cache::ROUTING_CACHE,
&cache::CGRAPH_CACHE,
&cache::PM_FILTERS_CGRAPH_CACHE,
&cache::DECISION_MANAGER_CACHE,
&cache::SURCHARGE_CACHE,
&cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE,
&cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE,
&cache::ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE,
];
tokio::spawn(async move {
loop {
for instance in cache_instances {
instance.record_entry_count_metric().await
}
tokio::time::sleep(std::time::Duration::from_secs(
metrics_collection_interval.into(),
))
.await
}
});
}
|
crates/router/src/routes/metrics/bg_metrics_collector.rs
|
router
|
full_file
| 260
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn network_tokenize_and_vault_the_pmd(
state: &SessionState,
payment_method_data: &domain::PaymentMethodVaultingData,
merchant_context: &domain::MerchantContext,
network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,
network_tokenization_enabled_for_profile: bool,
customer_id: &id_type::GlobalCustomerId,
) -> Option<NetworkTokenPaymentMethodDetails> {
let network_token_pm_details_result: CustomResult<
NetworkTokenPaymentMethodDetails,
errors::NetworkTokenizationError,
> = async {
when(!network_tokenization_enabled_for_profile, || {
Err(report!(
errors::NetworkTokenizationError::NetworkTokenizationNotEnabledForProfile
))
})?;
let is_network_tokenization_enabled_for_pm = network_tokenization
.as_ref()
.map(|nt| matches!(nt.enable, common_enums::NetworkTokenizationToggle::Enable))
.unwrap_or(false);
let card_data = payment_method_data
.get_card()
.and_then(|card| is_network_tokenization_enabled_for_pm.then_some(card))
.ok_or_else(|| {
report!(errors::NetworkTokenizationError::NotSupported {
message: "Payment method".to_string(),
})
})?;
let (resp, network_token_req_ref_id) =
network_tokenization::make_card_network_tokenization_request(
state,
card_data,
customer_id,
)
.await?;
let network_token_vaulting_data = domain::PaymentMethodVaultingData::NetworkToken(resp);
let vaulting_resp = vault::add_payment_method_to_vault(
state,
merchant_context,
&network_token_vaulting_data,
None,
customer_id,
)
.await
.change_context(errors::NetworkTokenizationError::SaveNetworkTokenFailed)
.attach_printable("Failed to vault network token")?;
let key_manager_state = &(state).into();
let network_token_pmd = cards::create_encrypted_data(
key_manager_state,
merchant_context.get_merchant_key_store(),
network_token_vaulting_data.get_payment_methods_data(),
)
.await
.change_context(errors::NetworkTokenizationError::NetworkTokenDetailsEncryptionFailed)
.attach_printable("Failed to encrypt PaymentMethodsData")?;
Ok(NetworkTokenPaymentMethodDetails {
network_token_requestor_reference_id: network_token_req_ref_id,
network_token_locker_id: vaulting_resp.vault_id.get_string_repr().clone(),
network_token_pmd,
})
}
.await;
network_token_pm_details_result.ok()
}
|
crates/router/src/core/payment_methods.rs
|
router
|
function_signature
| 561
|
rust
| null | null | null | null |
network_tokenize_and_vault_the_pmd
| null | null | null | null | null | null | null |
pub struct PaymentDetails {
pub pan: cards::CardNumber,
pub digital_card_id: Option<String>,
pub payment_data_type: Option<String>,
pub encrypted_src_card_details: Option<String>,
pub card_expiry_month: Secret<String>,
pub card_expiry_year: Secret<String>,
pub cardholder_name: Option<Secret<String>>,
pub card_token_number: Option<Secret<String>>,
pub account_type: Option<common_enums::PaymentMethodType>,
pub card_cvc: Option<Secret<String>>,
}
|
crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs
|
hyperswitch_domain_models
|
struct_definition
| 109
|
rust
|
PaymentDetails
| null | null | null | null | null | null | null | null | null | null | null |
pub struct ClientReferenceInformation {
code: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 13
|
rust
|
ClientReferenceInformation
| null | null | null | null | null | null | null | null | null | null | null |
pub fn update_target_count(&mut self, new: &Self) {
self.target_count = new.target_count;
}
|
crates/api_models/src/routing.rs
|
api_models
|
function_signature
| 26
|
rust
| null | null | null | null |
update_target_count
| null | null | null | null | null | null | null |
impl AuthenticationType {
pub fn get_merchant_id(&self) -> Option<&id_type::MerchantId> {
match self {
Self::ApiKey {
merchant_id,
key_id: _,
}
| Self::AdminApiAuthWithMerchantId { merchant_id }
| Self::MerchantId { merchant_id }
| Self::PublishableKey { merchant_id }
| Self::MerchantJwt {
merchant_id,
user_id: _,
}
| Self::MerchantJwtWithProfileId { merchant_id, .. }
| Self::WebhookAuth { merchant_id } => Some(merchant_id),
Self::AdminApiKey
| Self::OrganizationJwt { .. }
| Self::UserJwt { .. }
| Self::SinglePurposeJwt { .. }
| Self::SinglePurposeOrLoginJwt { .. }
| Self::NoAuth => None,
}
}
}
|
crates/router/src/services/authentication.rs
|
router
|
impl_block
| 191
|
rust
| null |
AuthenticationType
| null |
impl AuthenticationType
| null | null | null | null | null | null | null | null |
File: crates/diesel_models/src/query/customers.rs
Public functions: 10
Public structs: 1
use common_utils::id_type;
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use super::generics;
#[cfg(feature = "v1")]
use crate::schema::customers::dsl;
#[cfg(feature = "v2")]
use crate::schema_v2::customers::dsl;
use crate::{
customers::{Customer, CustomerNew, CustomerUpdateInternal},
errors, PgPooledConn, StorageResult,
};
impl CustomerNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Customer> {
generics::generic_insert(conn, self).await
}
}
pub struct CustomerListConstraints {
pub limit: i64,
pub offset: Option<i64>,
}
impl Customer {
#[cfg(feature = "v2")]
pub async fn update_by_id(
conn: &PgPooledConn,
id: id_type::GlobalCustomerId,
customer: CustomerUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
conn,
id.clone(),
customer,
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id).await
}
_ => Err(error),
},
result => result,
}
}
#[cfg(feature = "v2")]
pub async fn find_by_global_id(
conn: &PgPooledConn,
id: &id_type::GlobalCustomerId,
) -> StorageResult<Self> {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id.to_owned()).await
}
pub async fn list_by_merchant_id(
conn: &PgPooledConn,
merchant_id: &id_type::MerchantId,
constraints: CustomerListConstraints,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::merchant_id.eq(merchant_id.to_owned()),
Some(constraints.limit),
constraints.offset,
Some(dsl::created_at),
)
.await
}
#[cfg(feature = "v2")]
pub async fn find_optional_by_merchant_id_merchant_reference_id(
conn: &PgPooledConn,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Option<Self>> {
generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::merchant_reference_id.eq(customer_id.to_owned())),
)
.await
}
#[cfg(feature = "v1")]
pub async fn find_optional_by_customer_id_merchant_id(
conn: &PgPooledConn,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Option<Self>> {
generics::generic_find_by_id_optional::<<Self as HasTable>::Table, _, _>(
conn,
(customer_id.to_owned(), merchant_id.to_owned()),
)
.await
}
#[cfg(feature = "v1")]
pub async fn update_by_customer_id_merchant_id(
conn: &PgPooledConn,
customer_id: id_type::CustomerId,
merchant_id: id_type::MerchantId,
customer: CustomerUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
conn,
(customer_id.clone(), merchant_id.clone()),
customer,
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(
conn,
(customer_id, merchant_id),
)
.await
}
_ => Err(error),
},
result => result,
}
}
#[cfg(feature = "v1")]
pub async fn delete_by_customer_id_merchant_id(
conn: &PgPooledConn,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
conn,
dsl::customer_id
.eq(customer_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned())),
)
.await
}
#[cfg(feature = "v2")]
pub async fn find_by_merchant_reference_id_merchant_id(
conn: &PgPooledConn,
merchant_reference_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::merchant_reference_id.eq(merchant_reference_id.to_owned())),
)
.await
}
#[cfg(feature = "v1")]
pub async fn find_by_customer_id_merchant_id(
conn: &PgPooledConn,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(
conn,
(customer_id.to_owned(), merchant_id.to_owned()),
)
.await
}
}
|
crates/diesel_models/src/query/customers.rs
|
diesel_models
|
full_file
| 1,274
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub fn set_order_amount(&mut self, order_amount: MinorUnit) {
self.order_amount = order_amount;
}
|
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
|
hyperswitch_domain_models
|
function_signature
| 26
|
rust
| null | null | null | null |
set_order_amount
| null | null | null | null | null | null | null |
pub struct UpdateNexixpayConnectorMetaData {
pub three_d_s_auth_result: Option<ThreeDSAuthResult>,
pub three_d_s_auth_response: Option<Secret<String>>,
pub authorization_operation_id: Option<String>,
pub capture_operation_id: Option<String>,
pub cancel_operation_id: Option<String>,
pub psync_flow: Option<NexixpayPaymentIntent>,
pub meta_data: serde_json::Value,
pub is_auto_capture: bool,
}
|
crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 98
|
rust
|
UpdateNexixpayConnectorMetaData
| null | null | null | null | null | null | null | null | null | null | null |
pub struct GlobalpayRefreshTokenRequest {
pub app_id: Secret<String>,
pub nonce: Secret<String>,
pub secret: Secret<String>,
pub grant_type: String,
}
|
crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs
|
hyperswitch_connectors
|
struct_definition
| 38
|
rust
|
GlobalpayRefreshTokenRequest
| null | null | null | null | null | null | null | null | null | null | null |
pub struct WorkflowRunner;
|
crates/router/src/bin/scheduler.rs
|
router
|
struct_definition
| 5
|
rust
|
WorkflowRunner
| null | null | null | null | null | null | null | null | null | null | null |
impl<F> PaymentAttemptRecordData<F>
where
F: Clone,
{
pub fn get_updated_feature_metadata(
&self,
) -> CustomResult<Option<FeatureMetadata>, errors::api_error_response::ApiErrorResponse> {
let payment_intent_feature_metadata = self.payment_intent.get_feature_metadata();
let revenue_recovery = self.payment_intent.get_revenue_recovery_metadata();
let payment_attempt_connector = self.payment_attempt.connector.clone();
let feature_metadata_first_pg_error_code = revenue_recovery
.as_ref()
.and_then(|data| data.first_payment_attempt_pg_error_code.clone());
let (first_pg_error_code, first_network_advice_code, first_network_decline_code) =
feature_metadata_first_pg_error_code.map_or_else(
|| {
let first_pg_error_code = self
.payment_attempt
.error
.as_ref()
.map(|error| error.code.clone());
let first_network_advice_code = self
.payment_attempt
.error
.as_ref()
.and_then(|error| error.network_advice_code.clone());
let first_network_decline_code = self
.payment_attempt
.error
.as_ref()
.and_then(|error| error.network_decline_code.clone());
(
first_pg_error_code,
first_network_advice_code,
first_network_decline_code,
)
},
|pg_code| {
let advice_code = revenue_recovery
.as_ref()
.and_then(|data| data.first_payment_attempt_network_advice_code.clone());
let decline_code = revenue_recovery
.as_ref()
.and_then(|data| data.first_payment_attempt_network_decline_code.clone());
(Some(pg_code), advice_code, decline_code)
},
);
let billing_connector_payment_method_details = Some(
diesel_models::types::BillingConnectorPaymentMethodDetails::Card(
diesel_models::types::BillingConnectorAdditionalCardInfo {
card_network: self.revenue_recovery_data.card_network.clone(),
card_issuer: self.revenue_recovery_data.card_issuer.clone(),
},
),
);
let payment_revenue_recovery_metadata = match payment_attempt_connector {
Some(connector) => Some(diesel_models::types::PaymentRevenueRecoveryMetadata {
// Update retry count by one.
total_retry_count: revenue_recovery.as_ref().map_or(
self.revenue_recovery_data
.retry_count
.map_or_else(|| 1, |retry_count| retry_count),
|data| (data.total_retry_count + 1),
),
// Since this is an external system call, marking this payment_connector_transmission to ConnectorCallSucceeded.
payment_connector_transmission:
common_enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,
billing_connector_id: self.revenue_recovery_data.billing_connector_id.clone(),
active_attempt_payment_connector_id: self
.payment_attempt
.get_attempt_merchant_connector_account_id()?,
billing_connector_payment_details:
diesel_models::types::BillingConnectorPaymentDetails {
payment_processor_token: self
.revenue_recovery_data
.processor_payment_method_token
.clone(),
connector_customer_id: self
.revenue_recovery_data
.connector_customer_id
.clone(),
},
payment_method_type: self.payment_attempt.payment_method_type,
payment_method_subtype: self.payment_attempt.payment_method_subtype,
connector: connector.parse().map_err(|err| {
router_env::logger::error!(?err, "Failed to parse connector string to enum");
errors::api_error_response::ApiErrorResponse::InternalServerError
})?,
invoice_next_billing_time: self.revenue_recovery_data.invoice_next_billing_time,
invoice_billing_started_at_time: self
.revenue_recovery_data
.invoice_next_billing_time,
billing_connector_payment_method_details,
first_payment_attempt_network_advice_code: first_network_advice_code,
first_payment_attempt_network_decline_code: first_network_decline_code,
first_payment_attempt_pg_error_code: first_pg_error_code,
}),
None => Err(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Connector not found in payment attempt")?,
};
Ok(Some(FeatureMetadata {
redirect_response: payment_intent_feature_metadata
.as_ref()
.and_then(|data| data.redirect_response.clone()),
search_tags: payment_intent_feature_metadata
.as_ref()
.and_then(|data| data.search_tags.clone()),
apple_pay_recurring_details: payment_intent_feature_metadata
.as_ref()
.and_then(|data| data.apple_pay_recurring_details.clone()),
payment_revenue_recovery_metadata,
}))
}
}
|
crates/hyperswitch_domain_models/src/payments.rs
|
hyperswitch_domain_models
|
impl_block
| 987
|
rust
| null |
PaymentAttemptRecordData
| null |
impl PaymentAttemptRecordData
| null | null | null | null | null | null | null | null |
impl ConnectorSpecifications for Ebanx {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&EBANX_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
None
}
fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> {
None
}
}
|
crates/hyperswitch_connectors/src/connectors/ebanx.rs
|
hyperswitch_connectors
|
impl_block
| 94
|
rust
| null |
Ebanx
|
ConnectorSpecifications for
|
impl ConnectorSpecifications for for Ebanx
| null | null | null | null | null | null | null | null |
pub struct ExternalVaultDeleteFlow;
|
crates/hyperswitch_domain_models/src/router_flow_types/vault.rs
|
hyperswitch_domain_models
|
struct_definition
| 7
|
rust
|
ExternalVaultDeleteFlow
| null | null | null | null | null | null | null | null | null | null | null |
impl api::RefundSync for Shift4 {}
|
crates/hyperswitch_connectors/src/connectors/shift4.rs
|
hyperswitch_connectors
|
impl_block
| 10
|
rust
| null |
Shift4
|
api::RefundSync for
|
impl api::RefundSync for for Shift4
| null | null | null | null | null | null | null | null |
pub struct DetailsType {
pub loc: Vec<String>,
#[serde(rename = "type")]
pub error_type: String,
}
|
crates/hyperswitch_connectors/src/connectors/nomupay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 28
|
rust
|
DetailsType
| null | null | null | null | null | null | null | null | null | null | null |
pub fn number_comparison_array_value(input: &str) -> ParseResult<&str, ast::ValueType> {
let many_with_comma = multi::many0(sequence::preceded(
skip_ws(complete::tag(",")),
skip_ws(number_comparison),
));
let full_sequence = sequence::pair(skip_ws(number_comparison), many_with_comma);
error::context(
"number_comparison_array_value",
combinator::map(
sequence::delimited(
skip_ws(complete::tag("(")),
full_sequence,
skip_ws(complete::tag(")")),
),
|tup: (ast::NumberComparison, Vec<ast::NumberComparison>)| {
let mut rest = tup.1;
rest.insert(0, tup.0);
ast::ValueType::NumberComparisonArray(rest)
},
),
)(input)
}
|
crates/euclid/src/frontend/ast/parser.rs
|
euclid
|
function_signature
| 180
|
rust
| null | null | null | null |
number_comparison_array_value
| null | null | null | null | null | null | null |
pub struct PaymeErrorResponse {
pub status_code: u16,
pub status_error_details: String,
pub status_additional_info: serde_json::Value,
pub status_error_code: u32,
}
|
crates/hyperswitch_connectors/src/connectors/payme/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 45
|
rust
|
PaymeErrorResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub struct DummyConnectorRefundRequest {
pub amount: i64,
pub payment_id: Option<common_utils::id_type::PaymentId>,
}
|
crates/router/src/routes/dummy_connector/types.rs
|
router
|
struct_definition
| 33
|
rust
|
DummyConnectorRefundRequest
| null | null | null | null | null | null | null | null | null | null | null |
impl AuthenticationNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Authentication> {
generics::generic_insert(conn, self).await
}
}
|
crates/diesel_models/src/query/authentication.rs
|
diesel_models
|
impl_block
| 40
|
rust
| null |
AuthenticationNew
| null |
impl AuthenticationNew
| null | null | null | null | null | null | null | null |
impl ConnectorCommon for Zen {
fn id(&self) -> &'static str {
"zen"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
mime::APPLICATION_JSON.essence_str()
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.zen.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = zen::ZenAuthType::try_from(auth_type)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", auth.api_key.peek()).into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: zen::ZenErrorResponse = res
.response
.parse_struct("Zen ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response
.error
.clone()
.map_or(NO_ERROR_CODE.to_string(), |error| error.code),
message: response.error.map_or_else(
|| response.message.unwrap_or(NO_ERROR_MESSAGE.to_string()),
|error| error.message,
),
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
|
crates/hyperswitch_connectors/src/connectors/zen.rs
|
hyperswitch_connectors
|
impl_block
| 421
|
rust
| null |
Zen
|
ConnectorCommon for
|
impl ConnectorCommon for for Zen
| null | null | null | null | null | null | null | null |
pub struct Recurly {
// amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
|
crates/hyperswitch_connectors/src/connectors/recurly.rs
|
hyperswitch_connectors
|
struct_definition
| 29
|
rust
|
Recurly
| null | null | null | null | null | null | null | null | null | null | null |
pub struct GlobalPayPaymentMethodsRequest {
pub reference: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub usage_mode: Option<UsageMode>,
#[serde(skip_serializing_if = "Option::is_none")]
pub card: Option<Card>,
}
|
crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs
|
hyperswitch_connectors
|
struct_definition
| 60
|
rust
|
GlobalPayPaymentMethodsRequest
| null | null | null | null | null | null | null | null | null | null | null |
Documentation: api-reference/v1/payouts/payouts--fulfill.mdx
# Type: Doc File
---
openapi: post /payouts/{payout_id}/fulfill
---
|
api-reference/v1/payouts/payouts--fulfill.mdx
| null |
doc_file
| 42
|
doc
| null | null | null | null | null | null | null | null | null | null | null | null |
pub struct ValuedComparison {
pub values: Vec<EuclidValue>,
pub logic: ValuedComparisonLogic,
pub metadata: Metadata,
}
|
crates/euclid/src/frontend/vir.rs
|
euclid
|
struct_definition
| 32
|
rust
|
ValuedComparison
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn find_by_merchant_id_payment_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
_,
<<Self as HasTable>::Table as Table>::PrimaryKey,
_,
>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::payment_id.eq(payment_id.to_owned())),
None,
None,
None,
)
.await
}
|
crates/diesel_models/src/query/dispute.rs
|
diesel_models
|
function_signature
| 145
|
rust
| null | null | null | null |
find_by_merchant_id_payment_id
| null | null | null | null | null | null | null |
pub struct TaxjarPaymentsResponse {
tax: Tax,
}
|
crates/hyperswitch_connectors/src/connectors/taxjar/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 13
|
rust
|
TaxjarPaymentsResponse
| null | null | null | null | null | null | null | null | null | null | null |
impl api::ConnectorCustomer for Facilitapay {}
|
crates/hyperswitch_connectors/src/connectors/facilitapay.rs
|
hyperswitch_connectors
|
impl_block
| 11
|
rust
| null |
Facilitapay
|
api::ConnectorCustomer for
|
impl api::ConnectorCustomer for for Facilitapay
| null | null | null | null | null | null | null | null |
pub struct BamboraapacErrorResponse {
pub declined_code: Option<String>,
pub declined_message: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 26
|
rust
|
BamboraapacErrorResponse
| null | null | null | null | null | null | null | null | null | null | null |
impl ConnectorCommon for Wellsfargo {
fn id(&self) -> &'static str {
"wellsfargo"
}
fn common_get_content_type(&self) -> &'static str {
"application/json;charset=utf-8"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.wellsfargo.base_url.as_ref()
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: Result<
wellsfargo::WellsfargoErrorResponse,
Report<common_utils::errors::ParsingError>,
> = res.response.parse_struct("Wellsfargo ErrorResponse");
let error_message = if res.status_code == 401 {
constants::CONNECTOR_UNAUTHORIZED_ERROR
} else {
hyperswitch_interfaces::consts::NO_ERROR_MESSAGE
};
match response {
Ok(transformers::WellsfargoErrorResponse::StandardError(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let (code, message, reason) = match response.error_information {
Some(ref error_info) => {
let detailed_error_info = error_info.details.as_ref().map(|details| {
details
.iter()
.map(|det| format!("{} : {}", det.field, det.reason))
.collect::<Vec<_>>()
.join(", ")
});
(
error_info.reason.clone(),
error_info.reason.clone(),
transformers::get_error_reason(
Some(error_info.message.clone()),
detailed_error_info,
None,
),
)
}
None => {
let detailed_error_info = response.details.map(|details| {
details
.iter()
.map(|det| format!("{} : {}", det.field, det.reason))
.collect::<Vec<_>>()
.join(", ")
});
(
response.reason.clone().map_or(
hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
|reason| reason.to_string(),
),
response
.reason
.map_or(error_message.to_string(), |reason| reason.to_string()),
transformers::get_error_reason(
response.message,
detailed_error_info,
None,
),
)
}
};
Ok(ErrorResponse {
status_code: res.status_code,
code,
message,
reason,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Ok(transformers::WellsfargoErrorResponse::AuthenticationError(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
message: response.response.rmsg.clone(),
reason: Some(response.response.rmsg),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Ok(transformers::WellsfargoErrorResponse::NotAvailableError(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_response = response
.errors
.iter()
.map(|error_info| {
format!(
"{}: {}",
error_info.error_type.clone().unwrap_or("".to_string()),
error_info.message.clone().unwrap_or("".to_string())
)
})
.collect::<Vec<String>>()
.join(" & ");
Ok(ErrorResponse {
status_code: res.status_code,
code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
message: error_response.clone(),
reason: Some(error_response),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Err(error_msg) => {
event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
router_env::logger::error!(deserialization_error =? error_msg);
utils::handle_json_response_deserialization_failure(res, "wellsfargo")
}
}
}
}
|
crates/hyperswitch_connectors/src/connectors/wellsfargo.rs
|
hyperswitch_connectors
|
impl_block
| 1,040
|
rust
| null |
Wellsfargo
|
ConnectorCommon for
|
impl ConnectorCommon for for Wellsfargo
| null | null | null | null | null | null | null | null |
pub async fn refresh_pm_filters_cache(
state: &SessionState,
key: &str,
graph: cgraph::ConstraintGraph<dir::DirValue>,
) -> Arc<hyperswitch_constraint_graph::ConstraintGraph<dir::DirValue>> {
let pm_filter_graph = Arc::new(graph);
PM_FILTERS_CGRAPH_CACHE
.push(
CacheKey {
key: key.to_string(),
prefix: state.tenant.redis_key_prefix.clone(),
},
pm_filter_graph.clone(),
)
.await;
pm_filter_graph
}
|
crates/router/src/core/payment_methods/utils.rs
|
router
|
function_signature
| 119
|
rust
| null | null | null | null |
refresh_pm_filters_cache
| null | null | null | null | null | null | null |
pub fn generate_signature(
&self,
auth: cybersource::CybersourceAuthType,
host: String,
resource: &str,
payload: &String,
date: OffsetDateTime,
http_method: Method,
) -> CustomResult<String, errors::ConnectorError> {
let cybersource::CybersourceAuthType {
api_key,
merchant_account,
api_secret,
} = auth;
let is_post_method = matches!(http_method, Method::Post);
let is_patch_method = matches!(http_method, Method::Patch);
let is_delete_method = matches!(http_method, Method::Delete);
let digest_str = if is_post_method || is_patch_method {
"digest "
} else {
""
};
let headers = format!("host date (request-target) {digest_str}v-c-merchant-id");
let request_target = if is_post_method {
format!("(request-target): post {resource}\ndigest: SHA-256={payload}\n")
} else if is_patch_method {
format!("(request-target): patch {resource}\ndigest: SHA-256={payload}\n")
} else if is_delete_method {
format!("(request-target): delete {resource}\n")
} else {
format!("(request-target): get {resource}\n")
};
let signature_string = format!(
"host: {host}\ndate: {date}\n{request_target}v-c-merchant-id: {}",
merchant_account.peek()
);
let key_value = consts::BASE64_ENGINE
.decode(api_secret.expose())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "connector_account_details.api_secret",
})?;
let key = hmac::Key::new(hmac::HMAC_SHA256, &key_value);
let signature_value =
consts::BASE64_ENGINE.encode(hmac::sign(&key, signature_string.as_bytes()).as_ref());
let signature_header = format!(
r#"keyid="{}", algorithm="HmacSHA256", headers="{headers}", signature="{signature_value}""#,
api_key.peek()
);
Ok(signature_header)
}
|
crates/hyperswitch_connectors/src/connectors/cybersource.rs
|
hyperswitch_connectors
|
function_signature
| 478
|
rust
| null | null | null | null |
generate_signature
| null | null | null | null | null | null | null |
impl api::PaymentCapture for Nmi {}
|
crates/hyperswitch_connectors/src/connectors/nmi.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Nmi
|
api::PaymentCapture for
|
impl api::PaymentCapture for for Nmi
| null | null | null | null | null | null | null | null |
pub async fn update_by_customer_id_merchant_id(
conn: &PgPooledConn,
customer_id: id_type::CustomerId,
merchant_id: id_type::MerchantId,
customer: CustomerUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
conn,
(customer_id.clone(), merchant_id.clone()),
customer,
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(
conn,
(customer_id, merchant_id),
)
.await
}
_ => Err(error),
},
result => result,
}
}
|
crates/diesel_models/src/query/customers.rs
|
diesel_models
|
function_signature
| 176
|
rust
| null | null | null | null |
update_by_customer_id_merchant_id
| null | null | null | null | null | null | null |
/// Getter for the `module_name` field
pub fn get_module_name(&self) -> Option<Module> {
self.module_name
}
|
crates/test_utils/src/newman_runner.rs
|
test_utils
|
function_signature
| 32
|
rust
| null | null | null | null |
get_module_name
| null | null | null | null | null | null | null |
pub async fn payouts_list_profile() {}
|
crates/openapi/src/routes/payouts.rs
|
openapi
|
function_signature
| 8
|
rust
| null | null | null | null |
payouts_list_profile
| null | null | null | null | null | null | null |
impl<T, I> Serialize for Secret<T, I>
where
T: SerializableSecret + Serialize + Sized,
I: Strategy<T>,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
pii_serializer::pii_serialize(self, serializer)
}
}
|
crates/masking/src/serde.rs
|
masking
|
impl_block
| 75
|
rust
| null |
Secret
|
Serialize for
|
impl Serialize for for Secret
| null | null | null | null | null | null | null | null |
pub struct Payload {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
|
crates/hyperswitch_connectors/src/connectors/payload.rs
|
hyperswitch_connectors
|
struct_definition
| 26
|
rust
|
Payload
| null | null | null | null | null | null | null | null | null | null | null |
pub struct IndomaretVoucherData {}
|
crates/hyperswitch_domain_models/src/payment_method_data.rs
|
hyperswitch_domain_models
|
struct_definition
| 9
|
rust
|
IndomaretVoucherData
| null | null | null | null | null | null | null | null | null | null | null |
impl Configs {
pub fn server(config: AppState) -> Scope {
web::scope("/configs")
.app_data(web::Data::new(config))
.service(web::resource("/").route(web::post().to(config_key_create)))
.service(
web::resource("/{key}")
.route(web::get().to(config_key_retrieve))
.route(web::post().to(config_key_update))
.route(web::delete().to(config_key_delete)),
)
}
}
|
crates/router/src/routes/app.rs
|
router
|
impl_block
| 104
|
rust
| null |
Configs
| null |
impl Configs
| null | null | null | null | null | null | null | null |
pub struct ConnectorAgnosticMitChoice {
pub enabled: bool,
}
|
crates/api_models/src/admin.rs
|
api_models
|
struct_definition
| 17
|
rust
|
ConnectorAgnosticMitChoice
| null | null | null | null | null | null | null | null | null | null | null |
pub struct PreProcessing;
|
crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
|
hyperswitch_domain_models
|
struct_definition
| 5
|
rust
|
PreProcessing
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn start_web_server(
state: routes::AppState,
service: String,
) -> errors::ApplicationResult<Server> {
let server = state
.conf
.scheduler
.as_ref()
.ok_or(ApplicationError::InvalidConfigurationValueError(
"Scheduler server is invalidly configured".into(),
))?
.server
.clone();
let web_server = actix_web::HttpServer::new(move || {
actix_web::App::new().service(Health::server(state.clone(), service.clone()))
})
.bind((server.host.as_str(), server.port))
.change_context(ApplicationError::ConfigurationError)?
.workers(server.workers)
.run();
let _ = web_server.handle();
Ok(web_server)
}
|
crates/router/src/bin/scheduler.rs
|
router
|
function_signature
| 167
|
rust
| null | null | null | null |
start_web_server
| null | null | null | null | null | null | null |
pub struct RecurlyInvoiceTransactionsStatus {
pub status: String,
}
|
crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 16
|
rust
|
RecurlyInvoiceTransactionsStatus
| null | null | null | null | null | null | null | null | null | null | null |
impl Responder {
let flow = Flow::PaymentsList;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::apply_filters_on_payments(
state,
merchant_context,
auth.profile_id.map(|profile_id| vec![profile_id]),
req,
)
},
&auth::JWTAuth {
permission: Permission::ProfilePaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/payments.rs
|
router
|
impl_block
| 162
|
rust
| null |
Responder
| null |
impl Responder
| null | null | null | null | null | null | null | null |
pub struct PaymentIntents;
|
crates/router/src/compatibility/stripe/app.rs
|
router
|
struct_definition
| 6
|
rust
|
PaymentIntents
| null | null | null | null | null | null | null | null | null | null | null |
pub struct FiuuWebhookStatus {
pub capture_method: Option<CaptureMethod>,
pub status: FiuuPaymentWebhookStatus,
}
|
crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 32
|
rust
|
FiuuWebhookStatus
| null | null | null | null | null | null | null | null | null | null | null |
for key in DirKeyKind::iter() {
if matches!(key, DirKeyKind::Connector) {
continue;
}
let json_str = if let DirKeyKind::MetaData = key {
r#""metadata""#.to_string()
} else {
serde_json::to_string(&key).expect("JSON Serialization")
};
let display_str = key.to_string();
assert_eq!(
json_str.get(1..json_str.len() - 1).expect("Value metadata"),
display_str
);
key_names.insert(key, display_str);
}
let values = vec![
dirval!(PaymentMethod = Card),
dirval!(CardBin s= "123456"),
dirval!(CardType = Credit),
dirval!(CardNetwork = Visa),
dirval!(PayLaterType = Klarna),
dirval!(WalletType = Paypal),
dirval!(BankRedirectType = Sofort),
dirval!(BankDebitType = Bacs),
dirval!(CryptoType = CryptoCurrency),
dirval!("" = "metadata"),
dirval!(PaymentAmount = 100),
dirval!(PaymentCurrency = USD),
dirval!(CardRedirectType = Benefit),
dirval!(AuthenticationType = ThreeDs),
dirval!(CaptureMethod = Manual),
dirval!(BillingCountry = UnitedStatesOfAmerica),
dirval!(BusinessCountry = France),
];
for val in values {
let json_val = serde_json::to_value(&val).expect("JSON Value Serialization");
let json_key = json_val
.as_object()
.expect("Serialized Object")
.get("key")
.expect("Object Key");
let value_str = json_key.as_str().expect("Value string");
let dir_key = val.get_key();
let key_name = key_names.get(&dir_key.kind).expect("Key name");
assert_eq!(key_name, value_str);
}
}
#[cfg(feature = "ast_parser")]
#[test]
fn test_allowed_dir_keys() {
use crate::types::DummyOutput;
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
payment_method = card
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let out = ast::lowering::lower_program::<DummyOutput>(program);
assert!(out.is_ok())
}
#[cfg(feature = "ast_parser")]
#[test]
fn test_not_allowed_dir_keys() {
use crate::types::DummyOutput;
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
bank_debit = ach
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let out = ast::lowering::lower_program::<DummyOutput>(program);
assert!(out.is_err())
}
}
|
crates/euclid/src/frontend/dir.rs#chunk1
|
euclid
|
chunk
| 672
| null | null | null | null | null | null | null | null | null | null | null | null | null |
backend_input,
eligible_connectors,
profile_id,
&api_enums::TransactionType::from(transaction_data),
)
.await
}
pub async fn perform_fallback_routing(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
transaction_data: &routing::TransactionData<'_>,
eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
business_profile: &domain::Profile,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
#[cfg(feature = "v1")]
let fallback_config = routing::helpers::get_merchant_default_config(
&*state.store,
match transaction_data {
routing::TransactionData::Payment(payment_data) => payment_data
.payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::RoutingError::ProfileIdMissing)?
.get_string_repr(),
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(payout_data) => {
payout_data.payout_attempt.profile_id.get_string_repr()
}
},
&api_enums::TransactionType::from(transaction_data),
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
#[cfg(feature = "v2")]
let fallback_config = admin::ProfileWrapper::new(business_profile.clone())
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
let backend_input = match transaction_data {
routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?,
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?,
};
perform_cgraph_filtering(
state,
key_store,
fallback_config,
backend_input,
eligible_connectors,
business_profile.get_id(),
&api_enums::TransactionType::from(transaction_data),
)
.await
}
pub async fn perform_eligibility_analysis_with_fallback(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
chosen: Vec<routing_types::RoutableConnectorChoice>,
transaction_data: &routing::TransactionData<'_>,
eligible_connectors: Option<Vec<api_enums::RoutableConnectors>>,
business_profile: &domain::Profile,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
logger::debug!("euclid_routing: performing eligibility");
let mut final_selection = perform_eligibility_analysis(
state,
key_store,
chosen,
transaction_data,
eligible_connectors.as_ref(),
business_profile.get_id(),
)
.await?;
let fallback_selection = perform_fallback_routing(
state,
key_store,
transaction_data,
eligible_connectors.as_ref(),
business_profile,
)
.await;
final_selection.append(
&mut fallback_selection
.unwrap_or_default()
.iter()
.filter(|&routable_connector_choice| {
!final_selection.contains(routable_connector_choice)
})
.cloned()
.collect::<Vec<_>>(),
);
let final_selected_connectors = final_selection
.iter()
.map(|item| item.connector)
.collect::<Vec<_>>();
logger::debug!(final_selected_connectors_for_routing=?final_selected_connectors, "euclid_routing: List of final selected connectors for routing");
Ok(final_selection)
}
#[cfg(feature = "v2")]
pub async fn perform_session_flow_routing<'a>(
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
session_input: SessionFlowRoutingInput<'_>,
business_profile: &domain::Profile,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<FxHashMap<api_enums::PaymentMethodType, Vec<routing_types::SessionRoutingChoice>>>
{
let mut pm_type_map: FxHashMap<api_enums::PaymentMethodType, FxHashMap<String, api::GetToken>> =
FxHashMap::default();
let profile_id = business_profile.get_id().clone();
let routing_algorithm =
MerchantAccountRoutingAlgorithm::V1(business_profile.routing_algorithm_id.clone());
let payment_method_input = dsl_inputs::PaymentMethodInput {
payment_method: None,
payment_method_type: None,
card_network: None,
};
let payment_input = dsl_inputs::PaymentInput {
amount: session_input
.payment_intent
.amount_details
.calculate_net_amount(),
currency: session_input.payment_intent.amount_details.currency,
authentication_type: session_input.payment_intent.authentication_type,
card_bin: None,
capture_method: Option::<euclid_enums::CaptureMethod>::foreign_from(
session_input.payment_intent.capture_method,
),
// business_country not available in payment_intent anymore
business_country: None,
billing_country: session_input
.country
.map(storage_enums::Country::from_alpha2),
// business_label not available in payment_intent anymore
business_label: None,
setup_future_usage: Some(session_input.payment_intent.setup_future_usage),
};
let metadata = session_input
.payment_intent
.parse_and_get_metadata("routing_parameters")
.change_context(errors::RoutingError::MetadataParsingError)
.attach_printable("Unable to parse routing_parameters from metadata of payment_intent")
.unwrap_or(None);
let mut backend_input = dsl_inputs::BackendInput {
metadata,
payment: payment_input,
payment_method: payment_method_input,
mandate: dsl_inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
};
for connector_data in session_input.chosen.iter() {
pm_type_map
.entry(connector_data.payment_method_sub_type)
.or_default()
.insert(
connector_data.connector.connector_name.to_string(),
connector_data.connector.get_token.clone(),
);
}
let mut result: FxHashMap<
api_enums::PaymentMethodType,
Vec<routing_types::SessionRoutingChoice>,
> = FxHashMap::default();
for (pm_type, allowed_connectors) in pm_type_map {
let euclid_pmt: euclid_enums::PaymentMethodType = pm_type;
let euclid_pm: euclid_enums::PaymentMethod = euclid_pmt.into();
backend_input.payment_method.payment_method = Some(euclid_pm);
backend_input.payment_method.payment_method_type = Some(euclid_pmt);
let session_pm_input = SessionRoutingPmTypeInput {
routing_algorithm: &routing_algorithm,
backend_input: backend_input.clone(),
allowed_connectors,
profile_id: &profile_id,
};
let routable_connector_choice_option = perform_session_routing_for_pm_type(
state,
key_store,
&session_pm_input,
transaction_type,
business_profile,
)
.await?;
if let Some(routable_connector_choice) = routable_connector_choice_option {
let mut session_routing_choice: Vec<routing_types::SessionRoutingChoice> = Vec::new();
for selection in routable_connector_choice {
let connector_name = selection.connector.to_string();
if let Some(get_token) = session_pm_input.allowed_connectors.get(&connector_name) {
let connector_data = api::ConnectorData::get_connector_by_name(
&state.clone().conf.connectors,
&connector_name,
get_token.clone(),
selection.merchant_connector_id,
)
.change_context(errors::RoutingError::InvalidConnectorName(connector_name))?;
session_routing_choice.push(routing_types::SessionRoutingChoice {
connector: connector_data,
payment_method_type: pm_type,
});
}
}
if !session_routing_choice.is_empty() {
result.insert(pm_type, session_routing_choice);
}
}
}
Ok(result)
}
#[cfg(feature = "v1")]
pub async fn perform_session_flow_routing(
session_input: SessionFlowRoutingInput<'_>,
business_profile: &domain::Profile,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<(
FxHashMap<api_enums::PaymentMethodType, Vec<routing_types::SessionRoutingChoice>>,
Option<common_enums::RoutingApproach>,
)> {
let mut pm_type_map: FxHashMap<api_enums::PaymentMethodType, FxHashMap<String, api::GetToken>> =
FxHashMap::default();
let profile_id = session_input
.payment_intent
.profile_id
.clone()
.get_required_value("profile_id")
.change_context(errors::RoutingError::ProfileIdMissing)?;
let routing_algorithm: MerchantAccountRoutingAlgorithm = {
business_profile
.routing_algorithm
.clone()
.map(|val| val.parse_value("MerchantAccountRoutingAlgorithm"))
.transpose()
.change_context(errors::RoutingError::InvalidRoutingAlgorithmStructure)?
.unwrap_or_default()
};
let payment_method_input = dsl_inputs::PaymentMethodInput {
payment_method: None,
payment_method_type: None,
card_network: None,
};
let payment_input = dsl_inputs::PaymentInput {
amount: session_input.payment_attempt.get_total_amount(),
currency: session_input
.payment_intent
.currency
.get_required_value("Currency")
.change_context(errors::RoutingError::DslMissingRequiredField {
field_name: "currency".to_string(),
})?,
authentication_type: session_input.payment_attempt.authentication_type,
card_bin: None,
capture_method: session_input
.payment_attempt
.capture_method
.and_then(Option::<euclid_enums::CaptureMethod>::foreign_from),
business_country: session_input
.payment_intent
.business_country
.map(api_enums::Country::from_alpha2),
billing_country: session_input
.country
.map(storage_enums::Country::from_alpha2),
business_label: session_input.payment_intent.business_label.clone(),
setup_future_usage: session_input.payment_intent.setup_future_usage,
};
let metadata = session_input
.payment_intent
.parse_and_get_metadata("routing_parameters")
.change_context(errors::RoutingError::MetadataParsingError)
.attach_printable("Unable to parse routing_parameters from metadata of payment_intent")
.unwrap_or(None);
let mut backend_input = dsl_inputs::BackendInput {
metadata,
payment: payment_input,
payment_method: payment_method_input,
mandate: dsl_inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
};
for connector_data in session_input.chosen.iter() {
pm_type_map
.entry(connector_data.payment_method_sub_type)
.or_default()
.insert(
connector_data.connector.connector_name.to_string(),
connector_data.connector.get_token.clone(),
);
}
let mut result: FxHashMap<
api_enums::PaymentMethodType,
Vec<routing_types::SessionRoutingChoice>,
> = FxHashMap::default();
let mut final_routing_approach = None;
for (pm_type, allowed_connectors) in pm_type_map {
let euclid_pmt: euclid_enums::PaymentMethodType = pm_type;
let euclid_pm: euclid_enums::PaymentMethod = euclid_pmt.into();
backend_input.payment_method.payment_method = Some(euclid_pm);
backend_input.payment_method.payment_method_type = Some(euclid_pmt);
let session_pm_input = SessionRoutingPmTypeInput {
state: session_input.state,
key_store: session_input.key_store,
attempt_id: session_input.payment_attempt.get_id(),
routing_algorithm: &routing_algorithm,
backend_input: backend_input.clone(),
allowed_connectors,
profile_id: &profile_id,
};
let (routable_connector_choice_option, routing_approach) =
perform_session_routing_for_pm_type(
&session_pm_input,
transaction_type,
business_profile,
)
.await?;
final_routing_approach = routing_approach;
if let Some(routable_connector_choice) = routable_connector_choice_option {
let mut session_routing_choice: Vec<routing_types::SessionRoutingChoice> = Vec::new();
for selection in routable_connector_choice {
let connector_name = selection.connector.to_string();
if let Some(get_token) = session_pm_input.allowed_connectors.get(&connector_name) {
let connector_data = api::ConnectorData::get_connector_by_name(
&session_pm_input.state.clone().conf.connectors,
&connector_name,
get_token.clone(),
selection.merchant_connector_id,
)
.change_context(errors::RoutingError::InvalidConnectorName(connector_name))?;
session_routing_choice.push(routing_types::SessionRoutingChoice {
connector: connector_data,
payment_method_type: pm_type,
});
}
}
if !session_routing_choice.is_empty() {
result.insert(pm_type, session_routing_choice);
}
}
}
Ok((result, final_routing_approach))
}
#[cfg(feature = "v1")]
async fn perform_session_routing_for_pm_type(
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
_business_profile: &domain::Profile,
) -> RoutingResult<(
Option<Vec<api_models::routing::RoutableConnectorChoice>>,
Option<common_enums::RoutingApproach>,
)> {
let merchant_id = &session_pm_input.key_store.merchant_id;
let algorithm_id = match session_pm_input.routing_algorithm {
MerchantAccountRoutingAlgorithm::V1(algorithm_ref) => &algorithm_ref.algorithm_id,
};
let (chosen_connectors, routing_approach) = if let Some(ref algorithm_id) = algorithm_id {
let cached_algorithm = ensure_algorithm_cached_v1(
&session_pm_input.state.clone(),
merchant_id,
algorithm_id,
session_pm_input.profile_id,
transaction_type,
)
.await?;
match cached_algorithm.as_ref() {
CachedAlgorithm::Single(conn) => (
vec![(**conn).clone()],
Some(common_enums::RoutingApproach::StraightThroughRouting),
),
CachedAlgorithm::Priority(plist) => (plist.clone(), None),
CachedAlgorithm::VolumeSplit(splits) => (
perform_volume_split(splits.to_vec())
.change_context(errors::RoutingError::ConnectorSelectionFailed)?,
Some(common_enums::RoutingApproach::VolumeBasedRouting),
),
CachedAlgorithm::Advanced(interpreter) => (
execute_dsl_and_get_connector_v1(
session_pm_input.backend_input.clone(),
interpreter,
)?,
Some(common_enums::RoutingApproach::RuleBasedRouting),
),
}
} else {
(
routing::helpers::get_merchant_default_config(
&*session_pm_input.state.clone().store,
session_pm_input.profile_id.get_string_repr(),
transaction_type,
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?,
None,
)
};
let mut final_selection = perform_cgraph_filtering(
&session_pm_input.state.clone(),
session_pm_input.key_store,
chosen_connectors,
session_pm_input.backend_input.clone(),
None,
session_pm_input.profile_id,
transaction_type,
)
.await?;
if final_selection.is_empty() {
let fallback = routing::helpers::get_merchant_default_config(
&*session_pm_input.state.clone().store,
session_pm_input.profile_id.get_string_repr(),
transaction_type,
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
final_selection = perform_cgraph_filtering(
&session_pm_input.state.clone(),
session_pm_input.key_store,
fallback,
session_pm_input.backend_input.clone(),
None,
session_pm_input.profile_id,
transaction_type,
)
.await?;
}
if final_selection.is_empty() {
Ok((None, routing_approach))
} else {
Ok((Some(final_selection), routing_approach))
}
}
#[cfg(feature = "v2")]
async fn get_chosen_connectors<'a>(
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
profile_wrapper: &admin::ProfileWrapper,
) -> RoutingResult<Vec<api_models::routing::RoutableConnectorChoice>> {
let merchant_id = &key_store.merchant_id;
let MerchantAccountRoutingAlgorithm::V1(algorithm_id) = session_pm_input.routing_algorithm;
let chosen_connectors = if let Some(ref algorithm_id) = algorithm_id {
let cached_algorithm = ensure_algorithm_cached_v1(
state,
merchant_id,
algorithm_id,
session_pm_input.profile_id,
transaction_type,
)
.await?;
match cached_algorithm.as_ref() {
CachedAlgorithm::Single(conn) => vec![(**conn).clone()],
CachedAlgorithm::Priority(plist) => plist.clone(),
CachedAlgorithm::VolumeSplit(splits) => perform_volume_split(splits.to_vec())
.change_context(errors::RoutingError::ConnectorSelectionFailed)?,
CachedAlgorithm::Advanced(interpreter) => execute_dsl_and_get_connector_v1(
session_pm_input.backend_input.clone(),
interpreter,
)?,
}
} else {
profile_wrapper
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?
};
Ok(chosen_connectors)
}
#[cfg(feature = "v2")]
async fn perform_session_routing_for_pm_type<'a>(
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
business_profile: &domain::Profile,
) -> RoutingResult<Option<Vec<api_models::routing::RoutableConnectorChoice>>> {
let profile_wrapper = admin::ProfileWrapper::new(business_profile.clone());
let chosen_connectors = get_chosen_connectors(
state,
key_store,
session_pm_input,
transaction_type,
&profile_wrapper,
)
.await?;
let mut final_selection = perform_cgraph_filtering(
state,
key_store,
chosen_connectors,
session_pm_input.backend_input.clone(),
None,
session_pm_input.profile_id,
transaction_type,
)
.await?;
if final_selection.is_empty() {
let fallback = profile_wrapper
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
final_selection = perform_cgraph_filtering(
state,
key_store,
fallback,
session_pm_input.backend_input.clone(),
None,
session_pm_input.profile_id,
transaction_type,
)
.await?;
}
if final_selection.is_empty() {
Ok(None)
} else {
Ok(Some(final_selection))
}
}
#[cfg(feature = "v2")]
pub fn make_dsl_input_for_surcharge(
_payment_attempt: &oss_storage::PaymentAttempt,
_payment_intent: &oss_storage::PaymentIntent,
_billing_address: Option<Address>,
) -> RoutingResult<dsl_inputs::BackendInput> {
todo!()
}
#[cfg(feature = "v1")]
pub fn make_dsl_input_for_surcharge(
payment_attempt: &oss_storage::PaymentAttempt,
payment_intent: &oss_storage::PaymentIntent,
billing_address: Option<Address>,
) -> RoutingResult<dsl_inputs::BackendInput> {
let mandate_data = dsl_inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
};
let payment_input = dsl_inputs::PaymentInput {
amount: payment_attempt.get_total_amount(),
// currency is always populated in payment_attempt during payment create
currency: payment_attempt
.currency
.get_required_value("currency")
.change_context(errors::RoutingError::DslMissingRequiredField {
field_name: "currency".to_string(),
})?,
authentication_type: payment_attempt.authentication_type,
card_bin: None,
capture_method: payment_attempt.capture_method,
business_country: payment_intent
.business_country
.map(api_enums::Country::from_alpha2),
billing_country: billing_address
.and_then(|bic| bic.address)
.and_then(|add| add.country)
.map(api_enums::Country::from_alpha2),
business_label: payment_intent.business_label.clone(),
setup_future_usage: payment_intent.setup_future_usage,
};
let metadata = payment_intent
.parse_and_get_metadata("routing_parameters")
.change_context(errors::RoutingError::MetadataParsingError)
.attach_printable("Unable to parse routing_parameters from metadata of payment_intent")
.unwrap_or(None);
let payment_method_input = dsl_inputs::PaymentMethodInput {
payment_method: None,
payment_method_type: None,
card_network: None,
};
let backend_input = dsl_inputs::BackendInput {
metadata,
payment: payment_input,
payment_method: payment_method_input,
mandate: mandate_data,
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
};
Ok(backend_input)
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn perform_dynamic_routing_with_open_router<F, D>(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile: &domain::Profile,
payment_data: oss_storage::PaymentAttempt,
old_payment_data: &mut D,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef = profile
.dynamic_routing_algorithm
.clone()
.map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
.transpose()
.change_context(errors::RoutingError::DeserializationError {
from: "JSON".to_string(),
to: "DynamicRoutingAlgorithmRef".to_string(),
})
.attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?
.ok_or(errors::RoutingError::GenericNotFoundError {
field: "dynamic_routing_algorithm".to_string(),
})?;
logger::debug!(
"performing dynamic_routing with open_router for profile {}",
profile.get_id().get_string_repr()
);
let is_success_rate_routing_enabled =
dynamic_routing_algo_ref.is_success_rate_routing_enabled();
let is_elimination_enabled = dynamic_routing_algo_ref.is_elimination_enabled();
// Since success_based and elimination routing is being done in 1 api call, we call decide_gateway when either of it enabled
let connectors = if is_success_rate_routing_enabled || is_elimination_enabled {
let connectors = perform_decide_gateway_call_with_open_router(
state,
routable_connectors.clone(),
profile.get_id(),
&payment_data,
is_elimination_enabled,
old_payment_data,
)
.await?;
if is_elimination_enabled {
// This will initiate the elimination process for the connector.
// Penalize the elimination score of the connector before making a payment.
// Once the payment is made, we will update the score based on the payment status
if let Some(connector) = connectors.first() {
logger::debug!(
"penalizing the elimination score of the gateway with id {} in open_router for profile {}",
connector, profile.get_id().get_string_repr()
);
update_gateway_score_with_open_router(
state,
connector.clone(),
profile.get_id(),
&payment_data.merchant_id,
&payment_data.payment_id,
common_enums::AttemptStatus::AuthenticationPending,
)
.await?
}
}
connectors
} else {
routable_connectors
};
Ok(connectors)
}
#[cfg(feature = "v1")]
pub async fn perform_open_routing_for_debit_routing<F, D>(
state: &SessionState,
co_badged_card_request: or_types::CoBadgedCardRequest,
card_isin: Option<Secret<String>>,
old_payment_data: &mut D,
) -> RoutingResult<or_types::DebitRoutingOutput>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let payment_attempt = old_payment_data.get_payment_attempt().clone();
logger::debug!(
"performing debit routing with open_router for profile {}",
payment_attempt.profile_id.get_string_repr()
);
let metadata = Some(
serde_json::to_string(&co_badged_card_request)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode Vaulting data to string")
.change_context(errors::RoutingError::MetadataParsingError)?,
);
let open_router_req_body = OpenRouterDecideGatewayRequest::construct_debit_request(
&payment_attempt,
metadata,
card_isin,
Some(or_types::RankingAlgorithm::NtwBasedRouting),
);
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_attempt.payment_id.get_string_repr().to_string(),
payment_attempt.profile_id.to_owned(),
payment_attempt.merchant_id.to_owned(),
"DecisionEngine: Debit Routing".to_string(),
Some(open_router_req_body.clone()),
true,
true,
);
let response: RoutingResult<utils::RoutingEventsResponse<DecidedGateway>> =
utils::EuclidApiClient::send_decision_engine_request(
state,
services::Method::Post,
"decide-gateway",
Some(open_router_req_body),
None,
Some(routing_events_wrapper),
)
.await;
let output = match response {
Ok(events_response) => {
let response =
events_response
.response
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
let debit_routing_output = response
.debit_routing_output
.get_required_value("debit_routing_output")
.change_context(errors::RoutingError::OpenRouterError(
"Failed to parse the response from open_router".into(),
))
.attach_printable("debit_routing_output is missing in the open routing response")?;
old_payment_data.set_routing_approach_in_attempt(Some(
common_enums::RoutingApproach::from_decision_engine_approach(
&response.routing_approach,
),
));
Ok(debit_routing_output)
}
Err(error_response) => {
logger::error!("open_router_error_response: {:?}", error_response);
Err(errors::RoutingError::OpenRouterError(
"Failed to perform debit routing in open router".into(),
))
}
}?;
Ok(output)
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn perform_dynamic_routing_with_intelligent_router<F, D>(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile: &domain::Profile,
dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,
payment_data: &mut D,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef = profile
.dynamic_routing_algorithm
.clone()
.map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
.transpose()
.change_context(errors::RoutingError::DeserializationError {
from: "JSON".to_string(),
to: "DynamicRoutingAlgorithmRef".to_string(),
})
.attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?
.ok_or(errors::RoutingError::GenericNotFoundError {
field: "dynamic_routing_algorithm".to_string(),
})?;
logger::debug!(
"performing dynamic_routing for profile {}",
profile.get_id().get_string_repr()
);
let payment_attempt = payment_data.get_payment_attempt().clone();
let mut connector_list = match dynamic_routing_algo_ref
.success_based_algorithm
.as_ref()
.async_map(|algorithm| {
perform_success_based_routing(
state,
routable_connectors.clone(),
profile.get_id(),
&payment_attempt.merchant_id,
&payment_attempt.payment_id,
dynamic_routing_config_params_interpolator.clone(),
algorithm.clone(),
payment_data,
)
})
.await
.transpose()
.inspect_err(|e| logger::error!(dynamic_routing_error=?e))
.ok()
.flatten()
{
Some(success_based_list) => success_based_list,
None => {
// Only run contract based if success based returns None
dynamic_routing_algo_ref
.contract_based_routing
.as_ref()
.async_map(|algorithm| {
perform_contract_based_routing(
state,
routable_connectors.clone(),
profile.get_id(),
&payment_attempt.merchant_id,
&payment_attempt.payment_id,
dynamic_routing_config_params_interpolator.clone(),
algorithm.clone(),
payment_data,
)
})
.await
.transpose()
.inspect_err(|e| logger::error!(dynamic_routing_error=?e))
.ok()
.flatten()
.unwrap_or(routable_connectors.clone())
}
};
connector_list = dynamic_routing_algo_ref
.elimination_routing_algorithm
.as_ref()
.async_map(|algorithm| {
perform_elimination_routing(
state,
connector_list.clone(),
profile.get_id(),
&payment_attempt.merchant_id,
&payment_attempt.payment_id,
dynamic_routing_config_params_interpolator.clone(),
algorithm.clone(),
)
})
.await
.transpose()
.inspect_err(|e| logger::error!(dynamic_routing_error=?e))
.ok()
.flatten()
.unwrap_or(connector_list);
Ok(connector_list)
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn perform_decide_gateway_call_with_open_router<F, D>(
state: &SessionState,
mut routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile_id: &common_utils::id_type::ProfileId,
payment_attempt: &oss_storage::PaymentAttempt,
is_elimination_enabled: bool,
old_payment_data: &mut D,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
logger::debug!(
"performing decide_gateway call with open_router for profile {}",
profile_id.get_string_repr()
);
let open_router_req_body = OpenRouterDecideGatewayRequest::construct_sr_request(
payment_attempt,
routable_connectors.clone(),
Some(or_types::RankingAlgorithm::SrBasedRouting),
is_elimination_enabled,
);
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_attempt.payment_id.get_string_repr().to_string(),
payment_attempt.profile_id.to_owned(),
payment_attempt.merchant_id.to_owned(),
"DecisionEngine: SuccessRate decide_gateway".to_string(),
Some(open_router_req_body.clone()),
true,
false,
);
let response: RoutingResult<utils::RoutingEventsResponse<DecidedGateway>> =
utils::SRApiClient::send_decision_engine_request(
state,
services::Method::Post,
"decide-gateway",
Some(open_router_req_body),
None,
Some(routing_events_wrapper),
)
.await;
let sr_sorted_connectors = match response {
Ok(resp) => {
let decided_gateway: DecidedGateway =
resp.response.ok_or(errors::RoutingError::OpenRouterError(
"Empty response received from open_router".into(),
))?;
let mut routing_event = resp.event.ok_or(errors::RoutingError::RoutingEventsError {
message: "Decision-Engine: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})?;
routing_event.set_response_body(&decided_gateway);
routing_event.set_routing_approach(
utils::RoutingApproach::from_decision_engine_approach(
&decided_gateway.routing_approach,
)
.to_string(),
);
old_payment_data.set_routing_approach_in_attempt(Some(
common_enums::RoutingApproach::from_decision_engine_approach(
&decided_gateway.routing_approach,
),
));
if let Some(gateway_priority_map) = decided_gateway.gateway_priority_map {
logger::debug!(gateway_priority_map=?gateway_priority_map, routing_approach=decided_gateway.routing_approach, "open_router decide_gateway call response");
routable_connectors.sort_by(|connector_choice_a, connector_choice_b| {
let connector_choice_a_score = gateway_priority_map
.get(&connector_choice_a.to_string())
.copied()
.unwrap_or(0.0);
let connector_choice_b_score = gateway_priority_map
.get(&connector_choice_b.to_string())
.copied()
.unwrap_or(0.0);
connector_choice_b_score
.partial_cmp(&connector_choice_a_score)
.unwrap_or(std::cmp::Ordering::Equal)
});
}
routing_event.set_routable_connectors(routable_connectors.clone());
state.event_handler().log_event(&routing_event);
Ok(routable_connectors)
}
Err(err) => {
logger::error!("open_router_error_response: {:?}", err);
Err(errors::RoutingError::OpenRouterError(
"Failed to perform decide_gateway call in open_router".into(),
))
}
}?;
Ok(sr_sorted_connectors)
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn update_gateway_score_with_open_router(
state: &SessionState,
payment_connector: api_routing::RoutableConnectorChoice,
profile_id: &common_utils::id_type::ProfileId,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
payment_status: common_enums::AttemptStatus,
) -> RoutingResult<()> {
let open_router_req_body = or_types::UpdateScorePayload {
merchant_id: profile_id.clone(),
gateway: payment_connector.to_string(),
status: payment_status.foreign_into(),
payment_id: payment_id.clone(),
};
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
merchant_id.to_owned(),
"DecisionEngine: SuccessRate update_gateway_score".to_string(),
Some(open_router_req_body.clone()),
true,
false,
);
let response: RoutingResult<utils::RoutingEventsResponse<or_types::UpdateScoreResponse>> =
utils::SRApiClient::send_decision_engine_request(
state,
services::Method::Post,
"update-gateway-score",
Some(open_router_req_body),
None,
Some(routing_events_wrapper),
)
.await;
match response {
Ok(resp) => {
let update_score_resp = resp.response.ok_or(errors::RoutingError::OpenRouterError(
"Failed to parse the response from open_router".into(),
))?;
let mut routing_event = resp.event.ok_or(errors::RoutingError::RoutingEventsError {
message: "Decision-Engine: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})?;
logger::debug!(
"open_router update_gateway_score response for gateway with id {}: {:?}",
payment_connector,
update_score_resp.message
);
routing_event.set_response_body(&update_score_resp);
routing_event.set_payment_connector(payment_connector.clone()); // check this in review
state.event_handler().log_event(&routing_event);
Ok(())
}
Err(err) => {
logger::error!("open_router_update_gateway_score_error: {:?}", err);
Err(errors::RoutingError::OpenRouterError(
"Failed to update gateway score in open_router".into(),
))
}
}?;
Ok(())
}
/// success based dynamic routing
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn perform_success_based_routing<F, D>(
state: &SessionState,
|
crates/router/src/core/payments/routing.rs#chunk1
|
router
|
chunk
| 8,187
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct PaypalSyncBatchResponse {
pub payout_batch_id: Option<String>,
pub sender_batch_id: Option<String>,
pub batch_status: PaypalFulfillStatus,
}
|
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 36
|
rust
|
PaypalSyncBatchResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub fn get_resolved_relation(prev_relation: Self, curr_relation: Self) -> Self {
if prev_relation != curr_relation {
Self::Contradiction
} else {
curr_relation
}
}
|
crates/hyperswitch_constraint_graph/src/types.rs
|
hyperswitch_constraint_graph
|
function_signature
| 46
|
rust
| null | null | null | null |
get_resolved_relation
| null | null | null | null | null | null | null |
pub struct Program<O> {
pub default_selection: O,
#[schema(value_type=RuleConnectorSelection)]
pub rules: Vec<Rule<O>>,
#[schema(value_type=HashMap<String, serde_json::Value>)]
pub metadata: Metadata,
}
|
crates/euclid/src/frontend/ast.rs
|
euclid
|
struct_definition
| 54
|
rust
|
Program
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn payouts_list_by_filter() {}
|
crates/openapi/src/routes/payouts.rs
|
openapi
|
function_signature
| 9
|
rust
| null | null | null | null |
payouts_list_by_filter
| null | null | null | null | null | null | null |
pub struct PaymentStatus;
|
crates/router/src/core/payments/operations/payment_status.rs
|
router
|
struct_definition
| 5
|
rust
|
PaymentStatus
| null | null | null | null | null | null | null | null | null | null | null |
pub fn check_presence(&self, value: &EuclidValue) -> bool {
let key = value.get_key();
match key.key_type() {
types::DataType::MetadataValue => self.atomic_values.contains(value),
types::DataType::StrValue => self.atomic_values.contains(value),
types::DataType::EnumVariant => self.atomic_values.contains(value),
types::DataType::Number => {
let ctx_num_value = self
.numeric_values
.get(&key)
.and_then(|value| value.get_num_value());
value.get_num_value().zip(ctx_num_value).is_some_and(
|(program_value, ctx_value)| {
let program_num = program_value.number;
let ctx_num = ctx_value.number;
match &program_value.refinement {
None => program_num == ctx_num,
Some(NumValueRefinement::NotEqual) => ctx_num != program_num,
Some(NumValueRefinement::GreaterThan) => ctx_num > program_num,
Some(NumValueRefinement::GreaterThanEqual) => ctx_num >= program_num,
Some(NumValueRefinement::LessThanEqual) => ctx_num <= program_num,
Some(NumValueRefinement::LessThan) => ctx_num < program_num,
}
},
)
}
}
}
|
crates/euclid/src/backend/vir_interpreter/types.rs
|
euclid
|
function_signature
| 275
|
rust
| null | null | null | null |
check_presence
| null | null | null | null | null | null | null |
File: crates/diesel_models/src/dynamic_routing_stats.rs
Public structs: 3
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use crate::schema::dynamic_routing_stats;
#[derive(Clone, Debug, Eq, Insertable, PartialEq)]
#[diesel(table_name = dynamic_routing_stats)]
pub struct DynamicRoutingStatsNew {
pub payment_id: common_utils::id_type::PaymentId,
pub attempt_id: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_id: common_utils::id_type::ProfileId,
pub amount: common_utils::types::MinorUnit,
pub success_based_routing_connector: String,
pub payment_connector: String,
pub currency: Option<common_enums::Currency>,
pub payment_method: Option<common_enums::PaymentMethod>,
pub capture_method: Option<common_enums::CaptureMethod>,
pub authentication_type: Option<common_enums::AuthenticationType>,
pub payment_status: common_enums::AttemptStatus,
pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState,
pub created_at: time::PrimitiveDateTime,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub global_success_based_connector: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Insertable)]
#[diesel(table_name = dynamic_routing_stats, primary_key(attempt_id, merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct DynamicRoutingStats {
pub payment_id: common_utils::id_type::PaymentId,
pub attempt_id: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_id: common_utils::id_type::ProfileId,
pub amount: common_utils::types::MinorUnit,
pub success_based_routing_connector: String,
pub payment_connector: String,
pub currency: Option<common_enums::Currency>,
pub payment_method: Option<common_enums::PaymentMethod>,
pub capture_method: Option<common_enums::CaptureMethod>,
pub authentication_type: Option<common_enums::AuthenticationType>,
pub payment_status: common_enums::AttemptStatus,
pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState,
pub created_at: time::PrimitiveDateTime,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub global_success_based_connector: Option<String>,
}
#[derive(
Clone, Debug, Eq, PartialEq, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize,
)]
#[diesel(table_name = dynamic_routing_stats)]
pub struct DynamicRoutingStatsUpdate {
pub amount: common_utils::types::MinorUnit,
pub success_based_routing_connector: String,
pub payment_connector: String,
pub currency: Option<common_enums::Currency>,
pub payment_method: Option<common_enums::PaymentMethod>,
pub capture_method: Option<common_enums::CaptureMethod>,
pub authentication_type: Option<common_enums::AuthenticationType>,
pub payment_status: common_enums::AttemptStatus,
pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub global_success_based_connector: Option<String>,
}
|
crates/diesel_models/src/dynamic_routing_stats.rs
|
diesel_models
|
full_file
| 709
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl Display for CustomJsonError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(
serde_json::to_string(&serde_json::json!({
"error": {
"error_type": "invalid_request",
"message": self.err.to_string(),
"code": "IR_06",
}
}))
.as_deref()
.unwrap_or("Invalid Json Error"),
)
}
}
|
crates/router/src/utils.rs
|
router
|
impl_block
| 108
|
rust
| null |
CustomJsonError
|
Display for
|
impl Display for for CustomJsonError
| null | null | null | null | null | null | null | null |
pub fn perform_integrity_check<F>(
mut router_data: RouterData<F, types::RefundsData, types::RefundsResponseData>,
) -> RouterData<F, types::RefundsData, types::RefundsResponseData>
where
F: Debug + Clone + 'static,
{
// Initiating Integrity check
let integrity_result = check_refund_integrity(&router_data.request, &router_data.response);
router_data.integrity_check = integrity_result;
router_data
}
|
crates/router/src/core/refunds_v2.rs
|
router
|
function_signature
| 104
|
rust
| null | null | null | null |
perform_integrity_check
| null | null | null | null | null | null | null |
pub async fn routing_unlink_config(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::ProfileId>,
transaction_type: &enums::TransactionType,
) -> impl Responder {
let flow = Flow::RoutingUnlinkConfig;
let path = path.into_inner();
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
path.clone(),
|state, auth: auth::AuthenticationData, path, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
routing::unlink_routing_config_under_profile(
state,
merchant_context,
path,
transaction_type,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuthProfileFromRoute {
profile_id: path,
required_permission: Permission::MerchantRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuthProfileFromRoute {
profile_id: path,
required_permission: Permission::MerchantRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/routing.rs
|
router
|
function_signature
| 301
|
rust
| null | null | null | null |
routing_unlink_config
| null | null | null | null | null | null | null |
pub struct StripebillingErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
pub reason: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 35
|
rust
|
StripebillingErrorResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub struct AirwallexAuthType {
pub x_api_key: Secret<String>,
pub x_client_id: Secret<String>,
}
|
crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 27
|
rust
|
AirwallexAuthType
| null | null | null | null | null | null | null | null | null | null | null |
pub struct InitPayment;
|
crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
|
hyperswitch_domain_models
|
struct_definition
| 5
|
rust
|
InitPayment
| null | null | null | null | null | null | null | null | null | null | null |
pub struct MandateRevokeRequestData {
pub mandate_id: String,
pub connector_mandate_id: Option<String>,
}
|
crates/hyperswitch_domain_models/src/router_request_types.rs
|
hyperswitch_domain_models
|
struct_definition
| 28
|
rust
|
MandateRevokeRequestData
| null | null | null | null | null | null | null | null | null | null | null |
pub struct FlexitiPaymentsResponse {
redirection_url: url::Url,
online_order_id: String,
}
|
crates/hyperswitch_connectors/src/connectors/flexiti/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 23
|
rust
|
FlexitiPaymentsResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub struct DlocalPaymentsCancelResponse {
status: DlocalPaymentStatus,
order_id: String,
}
|
crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 23
|
rust
|
DlocalPaymentsCancelResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub struct SCAResult {
pub version: String,
pub directory_server_trans_id: String,
}
|
crates/hyperswitch_connectors/src/connectors/silverflow/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 23
|
rust
|
SCAResult
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn retrieve_surcharge_decision_manager_config(
state: web::Data<AppState>,
req: HttpRequest,
) -> impl Responder {
let flow = Flow::DecisionManagerRetrieveConfig;
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
surcharge_decision_config::retrieve_surcharge_decision_config(state, merchant_context)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantSurchargeDecisionManagerRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::MerchantSurchargeDecisionManagerRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/routing.rs
|
router
|
function_signature
| 245
|
rust
| null | null | null | null |
retrieve_surcharge_decision_manager_config
| null | null | null | null | null | null | null |
pub struct FacilitapayCardDetails {
#[serde(rename = "card_number")]
pub number: cards::CardNumber,
#[serde(rename = "card_expiration_date")]
pub expiry_date: Secret<String>, // Format: "MM/YYYY"
#[serde(rename = "card_security_code")]
pub cvc: Secret<String>,
#[serde(rename = "card_brand")]
pub brand: String,
pub fullname: Secret<String>,
}
|
crates/hyperswitch_connectors/src/connectors/facilitapay/requests.rs
|
hyperswitch_connectors
|
struct_definition
| 94
|
rust
|
FacilitapayCardDetails
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/test_utils/tests/connectors/bluesnap_wh_ui.rs
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct BluesnapSeleniumTest;
impl SeleniumTest for BluesnapSeleniumTest {
fn get_connector_name(&self) -> String {
"bluesnap".to_string()
}
}
async fn should_make_webhook(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = BluesnapSeleniumTest {};
conn.make_webhook_test(
web_driver,
&format!("{CHECKOUT_BASE_URL}/saved/199"),
vec![
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
10,
"succeeded",
)
.await?;
Ok(())
}
#[test]
fn should_make_webhook_test() {
tester!(should_make_webhook);
}
|
crates/test_utils/tests/connectors/bluesnap_wh_ui.rs
|
test_utils
|
full_file
| 204
| null | null | null | null | null | null | null | null | null | null | null | null | null |
File: crates/hyperswitch_domain_models/src/payment_methods.rs
Public functions: 14
Public structs: 7
#[cfg(feature = "v2")]
use api_models::payment_methods::PaymentMethodsData;
use api_models::{customers, payment_methods, payments};
// specific imports because of using the macro
use common_enums::enums::MerchantStorageScheme;
#[cfg(feature = "v1")]
use common_utils::crypto::OptionalEncryptableValue;
#[cfg(feature = "v2")]
use common_utils::{crypto::Encryptable, encryption::Encryption, types::keymanager::ToEncryptable};
use common_utils::{
errors::{CustomResult, ParsingError, ValidationError},
id_type, pii, type_name,
types::keymanager,
};
pub use diesel_models::{enums as storage_enums, PaymentMethodUpdate};
use error_stack::ResultExt;
#[cfg(feature = "v1")]
use masking::ExposeInterface;
use masking::{PeekInterface, Secret};
#[cfg(feature = "v1")]
use router_env::logger;
#[cfg(feature = "v2")]
use rustc_hash::FxHashMap;
#[cfg(feature = "v2")]
use serde_json::Value;
use time::PrimitiveDateTime;
#[cfg(feature = "v2")]
use crate::address::Address;
#[cfg(feature = "v1")]
use crate::type_encryption::AsyncLift;
use crate::{
mandates::{self, CommonMandateReference},
merchant_key_store::MerchantKeyStore,
payment_method_data as domain_payment_method_data,
transformers::ForeignTryFrom,
type_encryption::{crypto_operation, CryptoOperation},
};
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct VaultId(String);
#[cfg(any(feature = "v2", feature = "tokenization_v2"))]
impl VaultId {
pub fn get_string_repr(&self) -> &String {
&self.0
}
pub fn generate(id: String) -> Self {
Self(id)
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug)]
pub struct PaymentMethod {
pub customer_id: id_type::CustomerId,
pub merchant_id: id_type::MerchantId,
pub payment_method_id: String,
pub accepted_currency: Option<Vec<storage_enums::Currency>>,
pub scheme: Option<String>,
pub token: Option<String>,
pub cardholder_name: Option<Secret<String>>,
pub issuer_name: Option<String>,
pub issuer_country: Option<String>,
pub payer_country: Option<Vec<String>>,
pub is_stored: Option<bool>,
pub swift_code: Option<String>,
pub direct_debit_token: Option<String>,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub payment_method: Option<storage_enums::PaymentMethod>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub payment_method_issuer: Option<String>,
pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: OptionalEncryptableValue,
pub locker_id: Option<String>,
pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<serde_json::Value>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
pub client_secret: Option<String>,
pub payment_method_billing_address: OptionalEncryptableValue,
pub updated_by: Option<String>,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
pub network_token_payment_method_data: OptionalEncryptableValue,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct PaymentMethod {
/// The identifier for the payment method. Using this recurring payments can be made
pub id: id_type::GlobalPaymentMethodId,
/// The customer id against which the payment method is saved
pub customer_id: id_type::GlobalCustomerId,
/// The merchant id against which the payment method is saved
pub merchant_id: id_type::MerchantId,
/// The merchant connector account id of the external vault where the payment method is saved
pub external_vault_source: Option<id_type::MerchantConnectorAccountId>,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub payment_method_type: Option<storage_enums::PaymentMethod>,
pub payment_method_subtype: Option<storage_enums::PaymentMethodType>,
#[encrypt(ty = Value)]
pub payment_method_data: Option<Encryptable<PaymentMethodsData>>,
pub locker_id: Option<VaultId>,
pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<CommonMandateReference>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
pub client_secret: Option<String>,
#[encrypt(ty = Value)]
pub payment_method_billing_address: Option<Encryptable<Address>>,
pub updated_by: Option<String>,
pub locker_fingerprint_id: Option<String>,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
#[encrypt(ty = Value)]
pub network_token_payment_method_data:
Option<Encryptable<domain_payment_method_data::PaymentMethodsData>>,
#[encrypt(ty = Value)]
pub external_vault_token_data:
Option<Encryptable<api_models::payment_methods::ExternalVaultTokenData>>,
}
impl PaymentMethod {
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &String {
&self.payment_method_id
}
#[cfg(feature = "v1")]
pub fn get_payment_methods_data(
&self,
) -> Option<domain_payment_method_data::PaymentMethodsData> {
self.payment_method_data
.clone()
.map(|value| value.into_inner().expose())
.and_then(|value| {
serde_json::from_value::<domain_payment_method_data::PaymentMethodsData>(value)
.map_err(|error| {
logger::warn!(
?error,
"Failed to parse payment method data in payment method info"
);
})
.ok()
})
}
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &id_type::GlobalPaymentMethodId {
&self.id
}
#[cfg(feature = "v1")]
pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethod> {
self.payment_method
}
#[cfg(feature = "v2")]
pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethod> {
self.payment_method_type
}
#[cfg(feature = "v1")]
pub fn get_payment_method_subtype(&self) -> Option<storage_enums::PaymentMethodType> {
self.payment_method_type
}
#[cfg(feature = "v2")]
pub fn get_payment_method_subtype(&self) -> Option<storage_enums::PaymentMethodType> {
self.payment_method_subtype
}
#[cfg(feature = "v1")]
pub fn get_common_mandate_reference(&self) -> Result<CommonMandateReference, ParsingError> {
let payments_data = self
.connector_mandate_details
.clone()
.map(|mut mandate_details| {
mandate_details
.as_object_mut()
.map(|obj| obj.remove("payouts"));
serde_json::from_value::<mandates::PaymentsMandateReference>(mandate_details)
.inspect_err(|err| {
router_env::logger::error!("Failed to parse payments data: {:?}", err);
})
})
.transpose()
.map_err(|err| {
router_env::logger::error!("Failed to parse payments data: {:?}", err);
ParsingError::StructParseFailure("Failed to parse payments data")
})?;
let payouts_data = self
.connector_mandate_details
.clone()
.map(|mandate_details| {
serde_json::from_value::<Option<CommonMandateReference>>(mandate_details)
.inspect_err(|err| {
router_env::logger::error!("Failed to parse payouts data: {:?}", err);
})
.map(|optional_common_mandate_details| {
optional_common_mandate_details
.and_then(|common_mandate_details| common_mandate_details.payouts)
})
})
.transpose()
.map_err(|err| {
router_env::logger::error!("Failed to parse payouts data: {:?}", err);
ParsingError::StructParseFailure("Failed to parse payouts data")
})?
.flatten();
Ok(CommonMandateReference {
payments: payments_data,
payouts: payouts_data,
})
}
#[cfg(feature = "v2")]
pub fn get_common_mandate_reference(&self) -> Result<CommonMandateReference, ParsingError> {
if let Some(value) = &self.connector_mandate_details {
Ok(value.clone())
} else {
Ok(CommonMandateReference {
payments: None,
payouts: None,
})
}
}
#[cfg(feature = "v2")]
pub fn set_payment_method_type(&mut self, payment_method_type: common_enums::PaymentMethod) {
self.payment_method_type = Some(payment_method_type);
}
#[cfg(feature = "v2")]
pub fn set_payment_method_subtype(
&mut self,
payment_method_subtype: common_enums::PaymentMethodType,
) {
self.payment_method_subtype = Some(payment_method_subtype);
}
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl super::behaviour::Conversion for PaymentMethod {
type DstType = diesel_models::payment_method::PaymentMethod;
type NewDstType = diesel_models::payment_method::PaymentMethodNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(Self::DstType {
customer_id: self.customer_id,
merchant_id: self.merchant_id,
payment_method_id: self.payment_method_id,
accepted_currency: self.accepted_currency,
scheme: self.scheme,
token: self.token,
cardholder_name: self.cardholder_name,
issuer_name: self.issuer_name,
issuer_country: self.issuer_country,
payer_country: self.payer_country,
is_stored: self.is_stored,
swift_code: self.swift_code,
direct_debit_token: self.direct_debit_token,
created_at: self.created_at,
last_modified: self.last_modified,
payment_method: self.payment_method,
payment_method_type: self.payment_method_type,
payment_method_issuer: self.payment_method_issuer,
payment_method_issuer_code: self.payment_method_issuer_code,
metadata: self.metadata,
payment_method_data: self.payment_method_data.map(|val| val.into()),
locker_id: self.locker_id,
last_used_at: self.last_used_at,
connector_mandate_details: self.connector_mandate_details,
customer_acceptance: self.customer_acceptance,
status: self.status,
network_transaction_id: self.network_transaction_id,
client_secret: self.client_secret,
payment_method_billing_address: self
.payment_method_billing_address
.map(|val| val.into()),
updated_by: self.updated_by,
version: self.version,
network_token_requestor_reference_id: self.network_token_requestor_reference_id,
network_token_locker_id: self.network_token_locker_id,
network_token_payment_method_data: self
.network_token_payment_method_data
.map(|val| val.into()),
})
}
async fn convert_back(
state: &keymanager::KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
async {
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
customer_id: item.customer_id,
merchant_id: item.merchant_id,
payment_method_id: item.payment_method_id,
accepted_currency: item.accepted_currency,
scheme: item.scheme,
token: item.token,
cardholder_name: item.cardholder_name,
issuer_name: item.issuer_name,
issuer_country: item.issuer_country,
payer_country: item.payer_country,
is_stored: item.is_stored,
swift_code: item.swift_code,
direct_debit_token: item.direct_debit_token,
created_at: item.created_at,
last_modified: item.last_modified,
payment_method: item.payment_method,
payment_method_type: item.payment_method_type,
payment_method_issuer: item.payment_method_issuer,
payment_method_issuer_code: item.payment_method_issuer_code,
metadata: item.metadata,
payment_method_data: item
.payment_method_data
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
locker_id: item.locker_id,
last_used_at: item.last_used_at,
connector_mandate_details: item.connector_mandate_details,
customer_acceptance: item.customer_acceptance,
status: item.status,
network_transaction_id: item.network_transaction_id,
client_secret: item.client_secret,
payment_method_billing_address: item
.payment_method_billing_address
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
updated_by: item.updated_by,
version: item.version,
network_token_requestor_reference_id: item.network_token_requestor_reference_id,
network_token_locker_id: item.network_token_locker_id,
network_token_payment_method_data: item
.network_token_payment_method_data
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
})
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting payment method data".to_string(),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(Self::NewDstType {
customer_id: self.customer_id,
merchant_id: self.merchant_id,
payment_method_id: self.payment_method_id,
accepted_currency: self.accepted_currency,
scheme: self.scheme,
token: self.token,
cardholder_name: self.cardholder_name,
issuer_name: self.issuer_name,
issuer_country: self.issuer_country,
payer_country: self.payer_country,
is_stored: self.is_stored,
swift_code: self.swift_code,
direct_debit_token: self.direct_debit_token,
created_at: self.created_at,
last_modified: self.last_modified,
payment_method: self.payment_method,
payment_method_type: self.payment_method_type,
payment_method_issuer: self.payment_method_issuer,
payment_method_issuer_code: self.payment_method_issuer_code,
metadata: self.metadata,
payment_method_data: self.payment_method_data.map(|val| val.into()),
locker_id: self.locker_id,
last_used_at: self.last_used_at,
connector_mandate_details: self.connector_mandate_details,
customer_acceptance: self.customer_acceptance,
status: self.status,
network_transaction_id: self.network_transaction_id,
client_secret: self.client_secret,
payment_method_billing_address: self
.payment_method_billing_address
.map(|val| val.into()),
updated_by: self.updated_by,
version: self.version,
network_token_requestor_reference_id: self.network_token_requestor_reference_id,
network_token_locker_id: self.network_token_locker_id,
network_token_payment_method_data: self
.network_token_payment_method_data
.map(|val| val.into()),
})
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl super::behaviour::Conversion for PaymentMethod {
type DstType = diesel_models::payment_method::PaymentMethod;
type NewDstType = diesel_models::payment_method::PaymentMethodNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(Self::DstType {
customer_id: self.customer_id,
merchant_id: self.merchant_id,
id: self.id,
created_at: self.created_at,
last_modified: self.last_modified,
payment_method_type_v2: self.payment_method_type,
payment_method_subtype: self.payment_method_subtype,
payment_method_data: self.payment_method_data.map(|val| val.into()),
locker_id: self.locker_id.map(|id| id.get_string_repr().clone()),
last_used_at: self.last_used_at,
connector_mandate_details: self.connector_mandate_details.map(|cmd| cmd.into()),
customer_acceptance: self.customer_acceptance,
status: self.status,
network_transaction_id: self.network_transaction_id,
client_secret: self.client_secret,
payment_method_billing_address: self
.payment_method_billing_address
.map(|val| val.into()),
updated_by: self.updated_by,
locker_fingerprint_id: self.locker_fingerprint_id,
version: self.version,
network_token_requestor_reference_id: self.network_token_requestor_reference_id,
network_token_locker_id: self.network_token_locker_id,
network_token_payment_method_data: self
.network_token_payment_method_data
.map(|val| val.into()),
external_vault_source: self.external_vault_source,
external_vault_token_data: self.external_vault_token_data.map(|val| val.into()),
})
}
async fn convert_back(
state: &keymanager::KeyManagerState,
storage_model: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
use common_utils::ext_traits::ValueExt;
async {
let decrypted_data = crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::BatchDecrypt(EncryptedPaymentMethod::to_encryptable(
EncryptedPaymentMethod {
payment_method_data: storage_model.payment_method_data,
payment_method_billing_address: storage_model
.payment_method_billing_address,
network_token_payment_method_data: storage_model
.network_token_payment_method_data,
external_vault_token_data: storage_model.external_vault_token_data,
},
)),
key_manager_identifier,
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())?;
let data = EncryptedPaymentMethod::from_encryptable(decrypted_data)
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Invalid batch operation data")?;
let payment_method_billing_address = data
.payment_method_billing_address
.map(|billing| {
billing.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Error while deserializing Address")?;
let payment_method_data = data
.payment_method_data
.map(|payment_method_data| {
payment_method_data
.deserialize_inner_value(|value| value.parse_value("Payment Method Data"))
})
.transpose()
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Error while deserializing Payment Method Data")?;
let network_token_payment_method_data = data
.network_token_payment_method_data
.map(|network_token_payment_method_data| {
network_token_payment_method_data.deserialize_inner_value(|value| {
value.parse_value("Network token Payment Method Data")
})
})
.transpose()
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Error while deserializing Network token Payment Method Data")?;
let external_vault_token_data = data
.external_vault_token_data
.map(|external_vault_token_data| {
external_vault_token_data.deserialize_inner_value(|value| {
value.parse_value("External Vault Token Data")
})
})
.transpose()
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Error while deserializing External Vault Token Data")?;
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
customer_id: storage_model.customer_id,
merchant_id: storage_model.merchant_id,
id: storage_model.id,
created_at: storage_model.created_at,
last_modified: storage_model.last_modified,
payment_method_type: storage_model.payment_method_type_v2,
payment_method_subtype: storage_model.payment_method_subtype,
payment_method_data,
locker_id: storage_model.locker_id.map(VaultId::generate),
last_used_at: storage_model.last_used_at,
connector_mandate_details: storage_model.connector_mandate_details.map(From::from),
customer_acceptance: storage_model.customer_acceptance,
status: storage_model.status,
network_transaction_id: storage_model.network_transaction_id,
client_secret: storage_model.client_secret,
payment_method_billing_address,
updated_by: storage_model.updated_by,
locker_fingerprint_id: storage_model.locker_fingerprint_id,
version: storage_model.version,
network_token_requestor_reference_id: storage_model
.network_token_requestor_reference_id,
network_token_locker_id: storage_model.network_token_locker_id,
network_token_payment_method_data,
external_vault_source: storage_model.external_vault_source,
external_vault_token_data,
})
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting payment method data".to_string(),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(Self::NewDstType {
customer_id: self.customer_id,
merchant_id: self.merchant_id,
id: self.id,
created_at: self.created_at,
last_modified: self.last_modified,
payment_method_type_v2: self.payment_method_type,
payment_method_subtype: self.payment_method_subtype,
payment_method_data: self.payment_method_data.map(|val| val.into()),
locker_id: self.locker_id.map(|id| id.get_string_repr().clone()),
last_used_at: self.last_used_at,
connector_mandate_details: self.connector_mandate_details.map(|cmd| cmd.into()),
customer_acceptance: self.customer_acceptance,
status: self.status,
network_transaction_id: self.network_transaction_id,
client_secret: self.client_secret,
payment_method_billing_address: self
.payment_method_billing_address
.map(|val| val.into()),
updated_by: self.updated_by,
locker_fingerprint_id: self.locker_fingerprint_id,
version: self.version,
network_token_requestor_reference_id: self.network_token_requestor_reference_id,
network_token_locker_id: self.network_token_locker_id,
network_token_payment_method_data: self
.network_token_payment_method_data
.map(|val| val.into()),
external_vault_token_data: self.external_vault_token_data.map(|val| val.into()),
})
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct PaymentMethodSession {
pub id: id_type::GlobalPaymentMethodSessionId,
pub customer_id: id_type::GlobalCustomerId,
#[encrypt(ty = Value)]
pub billing: Option<Encryptable<Address>>,
pub return_url: Option<common_utils::types::Url>,
pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>,
pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,
pub tokenization_data: Option<pii::SecretSerdeValue>,
pub expires_at: PrimitiveDateTime,
pub associated_payment_methods: Option<Vec<String>>,
pub associated_payment: Option<id_type::GlobalPaymentId>,
pub associated_token_id: Option<id_type::GlobalTokenId>,
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl super::behaviour::Conversion for PaymentMethodSession {
type DstType = diesel_models::payment_methods_session::PaymentMethodSession;
type NewDstType = diesel_models::payment_methods_session::PaymentMethodSession;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(Self::DstType {
id: self.id,
customer_id: self.customer_id,
billing: self.billing.map(|val| val.into()),
psp_tokenization: self.psp_tokenization,
network_tokenization: self.network_tokenization,
tokenization_data: self.tokenization_data,
expires_at: self.expires_at,
associated_payment_methods: self.associated_payment_methods,
associated_payment: self.associated_payment,
return_url: self.return_url,
associated_token_id: self.associated_token_id,
})
}
async fn convert_back(
state: &keymanager::KeyManagerState,
storage_model: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
use common_utils::ext_traits::ValueExt;
async {
let decrypted_data = crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::BatchDecrypt(EncryptedPaymentMethodSession::to_encryptable(
EncryptedPaymentMethodSession {
billing: storage_model.billing,
},
)),
key_manager_identifier,
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())?;
let data = EncryptedPaymentMethodSession::from_encryptable(decrypted_data)
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Invalid batch operation data")?;
let billing = data
.billing
.map(|billing| {
billing.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Error while deserializing Address")?;
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
id: storage_model.id,
customer_id: storage_model.customer_id,
billing,
psp_tokenization: storage_model.psp_tokenization,
network_tokenization: storage_model.network_tokenization,
tokenization_data: storage_model.tokenization_data,
expires_at: storage_model.expires_at,
associated_payment_methods: storage_model.associated_payment_methods,
associated_payment: storage_model.associated_payment,
return_url: storage_model.return_url,
associated_token_id: storage_model.associated_token_id,
})
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting payment method data".to_string(),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(Self::NewDstType {
id: self.id,
customer_id: self.customer_id,
billing: self.billing.map(|val| val.into()),
psp_tokenization: self.psp_tokenization,
network_tokenization: self.network_tokenization,
tokenization_data: self.tokenization_data,
expires_at: self.expires_at,
associated_payment_methods: self.associated_payment_methods,
associated_payment: self.associated_payment,
return_url: self.return_url,
associated_token_id: self.associated_token_id,
})
}
}
#[async_trait::async_trait]
pub trait PaymentMethodInterface {
type Error;
#[cfg(feature = "v1")]
async fn find_payment_method(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
payment_method_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentMethod, Self::Error>;
#[cfg(feature = "v2")]
async fn find_payment_method(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
payment_method_id: &id_type::GlobalPaymentMethodId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentMethod, Self::Error>;
#[cfg(feature = "v1")]
async fn find_payment_method_by_locker_id(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
locker_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentMethod, Self::Error>;
#[cfg(feature = "v1")]
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
limit: Option<i64>,
) -> CustomResult<Vec<PaymentMethod>, Self::Error>;
// Need to fix this once we start moving to v2 for payment method
#[cfg(feature = "v2")]
async fn find_payment_method_list_by_global_customer_id(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
id: &id_type::GlobalCustomerId,
limit: Option<i64>,
) -> CustomResult<Vec<PaymentMethod>, Self::Error>;
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
async fn find_payment_method_by_customer_id_merchant_id_status(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
limit: Option<i64>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<PaymentMethod>, Self::Error>;
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
async fn find_payment_method_by_global_customer_id_merchant_id_status(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
customer_id: &id_type::GlobalCustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
limit: Option<i64>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<PaymentMethod>, Self::Error>;
#[cfg(feature = "v1")]
async fn get_payment_method_count_by_customer_id_merchant_id_status(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> CustomResult<i64, Self::Error>;
async fn get_payment_method_count_by_merchant_id_status(
&self,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> CustomResult<i64, Self::Error>;
async fn insert_payment_method(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: PaymentMethod,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentMethod, Self::Error>;
async fn update_payment_method(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: PaymentMethod,
payment_method_update: PaymentMethodUpdate,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentMethod, Self::Error>;
#[cfg(feature = "v2")]
async fn delete_payment_method(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: PaymentMethod,
) -> CustomResult<PaymentMethod, Self::Error>;
#[cfg(feature = "v2")]
async fn find_payment_method_by_fingerprint_id(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
fingerprint_id: &str,
) -> CustomResult<PaymentMethod, Self::Error>;
#[cfg(feature = "v1")]
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
merchant_id: &id_type::MerchantId,
payment_method_id: &str,
) -> CustomResult<PaymentMethod, Self::Error>;
}
#[cfg(feature = "v2")]
pub enum PaymentMethodsSessionUpdateEnum {
GeneralUpdate {
billing: Box<Option<Encryptable<Address>>>,
psp_tokenization: Option<common_types::payment_methods::PspTokenization>,
network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,
tokenization_data: Option<pii::SecretSerdeValue>,
},
UpdateAssociatedPaymentMethods {
associated_payment_methods: Option<Vec<String>>,
},
}
#[cfg(feature = "v2")]
impl From<PaymentMethodsSessionUpdateEnum> for PaymentMethodsSessionUpdateInternal {
fn from(update: PaymentMethodsSessionUpdateEnum) -> Self {
match update {
PaymentMethodsSessionUpdateEnum::GeneralUpdate {
billing,
psp_tokenization,
network_tokenization,
tokenization_data,
} => Self {
billing: *billing,
psp_tokenization,
network_tokenization,
tokenization_data,
associated_payment_methods: None,
},
PaymentMethodsSessionUpdateEnum::UpdateAssociatedPaymentMethods {
associated_payment_methods,
} => Self {
billing: None,
psp_tokenization: None,
network_tokenization: None,
tokenization_data: None,
associated_payment_methods,
},
}
}
}
#[cfg(feature = "v2")]
impl PaymentMethodSession {
pub fn apply_changeset(self, update_session: PaymentMethodsSessionUpdateInternal) -> Self {
let Self {
id,
customer_id,
billing,
psp_tokenization,
network_tokenization,
tokenization_data,
expires_at,
return_url,
associated_payment_methods,
associated_payment,
associated_token_id,
} = self;
Self {
id,
customer_id,
billing: update_session.billing.or(billing),
psp_tokenization: update_session.psp_tokenization.or(psp_tokenization),
network_tokenization: update_session.network_tokenization.or(network_tokenization),
tokenization_data: update_session.tokenization_data.or(tokenization_data),
expires_at,
return_url,
associated_payment_methods: update_session
.associated_payment_methods
.or(associated_payment_methods),
associated_payment,
associated_token_id,
}
}
}
#[cfg(feature = "v2")]
pub struct PaymentMethodsSessionUpdateInternal {
pub billing: Option<Encryptable<Address>>,
pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>,
pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,
pub tokenization_data: Option<pii::SecretSerdeValue>,
pub associated_payment_methods: Option<Vec<String>>,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct ConnectorCustomerDetails {
pub connector_customer_id: String,
pub merchant_connector_id: id_type::MerchantConnectorAccountId,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct PaymentMethodCustomerMigrate {
pub customer: customers::CustomerRequest,
pub connector_customer_details: Option<Vec<ConnectorCustomerDetails>>,
}
#[cfg(feature = "v1")]
impl TryFrom<(payment_methods::PaymentMethodRecord, id_type::MerchantId)>
for PaymentMethodCustomerMigrate
{
type Error = error_stack::Report<ValidationError>;
fn try_from(
value: (payment_methods::PaymentMethodRecord, id_type::MerchantId),
) -> Result<Self, Self::Error> {
let (record, merchant_id) = value;
let connector_customer_details = record
.connector_customer_id
.and_then(|connector_customer_id| {
// Handle single merchant_connector_id
record
.merchant_connector_id
.as_ref()
.map(|merchant_connector_id| {
Ok(vec![ConnectorCustomerDetails {
connector_customer_id: connector_customer_id.clone(),
|
crates/hyperswitch_domain_models/src/payment_methods.rs#chunk0
|
hyperswitch_domain_models
|
chunk
| 8,187
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub fn set_card_details(
self,
card_from_locker: &'a api_models::payment_methods::Card,
optional_card_info: Option<diesel_models::CardInfo>,
card_cvc: Option<Secret<String>>,
) -> NetworkTokenizationBuilder<'a, PmAssigned> {
let card = domain::CardDetail {
card_number: card_from_locker.card_number.clone(),
card_exp_month: card_from_locker.card_exp_month.clone(),
card_exp_year: card_from_locker.card_exp_year.clone(),
bank_code: optional_card_info
.as_ref()
.and_then(|card_info| card_info.bank_code.clone()),
nick_name: card_from_locker
.nick_name
.as_ref()
.map(|nick_name| Secret::new(nick_name.clone())),
card_holder_name: card_from_locker.name_on_card.clone(),
card_issuer: optional_card_info
.as_ref()
.and_then(|card_info| card_info.card_issuer.clone()),
card_network: optional_card_info
.as_ref()
.and_then(|card_info| card_info.card_network.clone()),
card_type: optional_card_info
.as_ref()
.and_then(|card_info| card_info.card_type.clone()),
card_issuing_country: optional_card_info
.as_ref()
.and_then(|card_info| card_info.card_issuing_country.clone()),
co_badged_card_data: None,
};
NetworkTokenizationBuilder {
state: std::marker::PhantomData,
card: Some(card),
card_cvc,
customer: self.customer,
network_token: self.network_token,
stored_card: self.stored_card,
stored_token: self.stored_token,
payment_method_response: self.payment_method_response,
card_tokenized: self.card_tokenized,
error_code: self.error_code,
error_message: self.error_message,
}
}
|
crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
|
router
|
function_signature
| 414
|
rust
| null | null | null | null |
set_card_details
| null | null | null | null | null | null | null |
File: crates/diesel_models/src/query/organization.rs
Public functions: 3
use common_utils::id_type;
use diesel::{associations::HasTable, ExpressionMethods};
#[cfg(feature = "v1")]
use crate::schema::organization::dsl::org_id as dsl_identifier;
#[cfg(feature = "v2")]
use crate::schema_v2::organization::dsl::id as dsl_identifier;
use crate::{organization::*, query::generics, PgPooledConn, StorageResult};
impl OrganizationNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Organization> {
generics::generic_insert(conn, self).await
}
}
impl Organization {
pub async fn find_by_org_id(
conn: &PgPooledConn,
org_id: id_type::OrganizationId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl_identifier.eq(org_id),
)
.await
}
pub async fn update_by_org_id(
conn: &PgPooledConn,
org_id: id_type::OrganizationId,
update: OrganizationUpdate,
) -> StorageResult<Self> {
generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
dsl_identifier.eq(org_id),
OrganizationUpdateInternal::from(update),
)
.await
}
}
|
crates/diesel_models/src/query/organization.rs
|
diesel_models
|
full_file
| 324
| null | null | null | null | null | null | null | null | null | null | null | null | null |
File: crates/router/src/compatibility/stripe/payment_intents.rs
Public functions: 8
pub mod types;
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::payments as payment_types;
#[cfg(feature = "v1")]
use error_stack::report;
#[cfg(feature = "v1")]
use router_env::Tag;
use router_env::{instrument, tracing, Flow};
use crate::{
compatibility::{stripe::errors, wrap},
core::payments,
routes::{self},
services::{api, authentication as auth},
};
#[cfg(feature = "v1")]
use crate::{
core::api_locking::GetLockingInput,
logger,
routes::payments::get_or_generate_payment_id,
types::{api as api_types, domain},
};
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCreate, payment_id))]
pub async fn payment_intents_create(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
) -> HttpResponse {
let payload: types::StripePaymentIntentRequest = match qs_config
.deserialize_bytes(&form_payload)
.map_err(|err| report!(errors::StripeErrorCode::from(err)))
{
Ok(p) => p,
Err(err) => return api::log_and_return_error_response(err),
};
tracing::Span::current().record(
"payment_id",
payload
.id
.as_ref()
.map(|payment_id| payment_id.get_string_repr())
.unwrap_or_default(),
);
logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?payload);
let mut create_payment_req: payment_types::PaymentsRequest = match payload.try_into() {
Ok(req) => req,
Err(err) => return api::log_and_return_error_response(err),
};
if let Err(err) = get_or_generate_payment_id(&mut create_payment_req) {
return api::log_and_return_error_response(err);
}
let flow = Flow::PaymentsCreate;
let locking_action = create_payment_req.get_locking_input(flow.clone());
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripePaymentIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
create_payment_req,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
let eligible_connectors = req.connector.clone();
payments::payments_core::<
api_types::Authorize,
api_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Authorize>,
>(
state,
req_state,
merchant_context,
None,
payments::PaymentCreate,
req,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
eligible_connectors,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieveForceSync))]
pub async fn payment_intents_retrieve(
state: web::Data<routes::AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::PaymentId>,
query_payload: web::Query<types::StripePaymentRetrieveBody>,
) -> HttpResponse {
let payload = payment_types::PaymentsRetrieveRequest {
resource_id: api_types::PaymentIdType::PaymentIntentId(path.into_inner()),
merchant_id: None,
force_sync: true,
connector: None,
param: None,
merchant_connector_details: None,
client_secret: query_payload.client_secret.clone(),
expand_attempts: None,
expand_captures: None,
all_keys_required: None,
};
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
};
let (auth_type, auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
let flow = Flow::PaymentsRetrieveForceSync;
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripePaymentIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth, payload, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::PSync,
api_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::PSync>,
>(
state,
req_state,
merchant_context,
None,
payments::PaymentStatus,
payload,
auth_flow,
payments::CallConnectorAction::Trigger,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&*auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow))]
pub async fn payment_intents_retrieve_with_gateway_creds(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
) -> HttpResponse {
let json_payload: payment_types::PaymentRetrieveBodyWithCredentials = match qs_config
.deserialize_bytes(&form_payload)
.map_err(|err| report!(errors::StripeErrorCode::from(err)))
{
Ok(p) => p,
Err(err) => return api::log_and_return_error_response(err),
};
let payload = payment_types::PaymentsRetrieveRequest {
resource_id: payment_types::PaymentIdType::PaymentIntentId(json_payload.payment_id),
merchant_id: json_payload.merchant_id.clone(),
force_sync: json_payload.force_sync.unwrap_or(false),
merchant_connector_details: json_payload.merchant_connector_details.clone(),
..Default::default()
};
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
};
let (auth_type, _auth_flow) = match auth::get_auth_type_and_flow(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
let flow = match json_payload.force_sync {
Some(true) => Flow::PaymentsRetrieveForceSync,
_ => Flow::PaymentsRetrieve,
};
tracing::Span::current().record("flow", flow.to_string());
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripePaymentIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::PSync,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::PSync>,
>(
state,
req_state,
merchant_context,
None,
payments::PaymentStatus,
req,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&*auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdate))]
pub async fn payment_intents_update(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
path: web::Path<common_utils::id_type::PaymentId>,
) -> HttpResponse {
let payment_id = path.into_inner();
let stripe_payload: types::StripePaymentIntentRequest = match qs_config
.deserialize_bytes(&form_payload)
{
Ok(p) => p,
Err(err) => {
return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err)))
}
};
let mut payload: payment_types::PaymentsRequest = match stripe_payload.try_into() {
Ok(req) => req,
Err(err) => return api::log_and_return_error_response(err),
};
payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(payment_id));
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
};
let (auth_type, auth_flow) = match auth::get_auth_type_and_flow(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
let flow = Flow::PaymentsUpdate;
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripePaymentIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
let eligible_connectors = req.connector.clone();
payments::payments_core::<
api_types::Authorize,
api_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Authorize>,
>(
state,
req_state,
merchant_context,
None,
payments::PaymentUpdate,
req,
auth_flow,
payments::CallConnectorAction::Trigger,
eligible_connectors,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&*auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsConfirm, payment_id))]
pub async fn payment_intents_confirm(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
path: web::Path<common_utils::id_type::PaymentId>,
) -> HttpResponse {
let payment_id = path.into_inner();
let stripe_payload: types::StripePaymentIntentRequest = match qs_config
.deserialize_bytes(&form_payload)
{
Ok(p) => p,
Err(err) => {
return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err)))
}
};
tracing::Span::current().record(
"payment_id",
stripe_payload.id.as_ref().map(|id| id.get_string_repr()),
);
logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?stripe_payload);
let mut payload: payment_types::PaymentsRequest = match stripe_payload.try_into() {
Ok(req) => req,
Err(err) => return api::log_and_return_error_response(err),
};
payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(payment_id));
payload.confirm = Some(true);
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
};
let (auth_type, auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
let flow = Flow::PaymentsConfirm;
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripePaymentIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
let eligible_connectors = req.connector.clone();
payments::payments_core::<
api_types::Authorize,
api_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Authorize>,
>(
state,
req_state,
merchant_context,
None,
payments::PaymentConfirm,
req,
auth_flow,
payments::CallConnectorAction::Trigger,
eligible_connectors,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&*auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCapture, payment_id))]
pub async fn payment_intents_capture(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
path: web::Path<common_utils::id_type::PaymentId>,
) -> HttpResponse {
let stripe_payload: payment_types::PaymentsCaptureRequest = match qs_config
.deserialize_bytes(&form_payload)
{
Ok(p) => p,
Err(err) => {
return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err)))
}
};
tracing::Span::current().record("payment_id", stripe_payload.payment_id.get_string_repr());
logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?stripe_payload);
let payload = payment_types::PaymentsCaptureRequest {
payment_id: path.into_inner(),
..stripe_payload
};
let flow = Flow::PaymentsCapture;
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripePaymentIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth: auth::AuthenticationData, payload, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::Capture,
api_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Capture>,
>(
state,
req_state,
merchant_context,
None,
payments::PaymentCapture,
payload,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCancel, payment_id))]
pub async fn payment_intents_cancel(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
path: web::Path<common_utils::id_type::PaymentId>,
) -> HttpResponse {
let payment_id = path.into_inner();
let stripe_payload: types::StripePaymentCancelRequest = match qs_config
.deserialize_bytes(&form_payload)
{
Ok(p) => p,
Err(err) => {
return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err)))
}
};
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?stripe_payload);
let mut payload: payment_types::PaymentsCancelRequest = stripe_payload.into();
payload.payment_id = payment_id;
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
};
let (auth_type, auth_flow) = match auth::get_auth_type_and_flow(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
let flow = Flow::PaymentsCancel;
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripePaymentIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::Void,
api_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Void>,
>(
state,
req_state,
merchant_context,
None,
payments::PaymentCancel,
req,
auth_flow,
payments::CallConnectorAction::Trigger,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&*auth_type,
locking_action,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]
#[cfg(feature = "olap")]
pub async fn payment_intent_list(
state: web::Data<routes::AppState>,
req: HttpRequest,
payload: web::Query<types::StripePaymentListConstraints>,
) -> HttpResponse {
let payload = match payment_types::PaymentListConstraints::try_from(payload.into_inner()) {
Ok(p) => p,
Err(err) => return api::log_and_return_error_response(err),
};
use crate::core::api_locking;
let flow = Flow::PaymentsList;
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripePaymentIntentListResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::list_payments(state, merchant_context, None, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/compatibility/stripe/payment_intents.rs
|
router
|
full_file
| 4,320
| null | null | null | null | null | null | null | null | null | null | null | null | null |
Documentation: api-reference/v2/merchant-connector-account/connector-account--update.mdx
# Type: Doc File
---
openapi: put /v2/connector-accounts/{id}
---
|
api-reference/v2/merchant-connector-account/connector-account--update.mdx
| null |
doc_file
| 41
|
doc
| null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn get_filters(
pool: &AnalyticsProvider,
req: GetDisputeFilterRequest,
auth: &AuthInfo,
) -> AnalyticsResult<DisputeFiltersResponse> {
let mut res = DisputeFiltersResponse::default();
for dim in req.group_by_names {
let values = match pool {
AnalyticsProvider::Sqlx(pool) => {
get_dispute_filter_for_dimension(dim, auth, &req.time_range, pool)
.await
}
AnalyticsProvider::Clickhouse(pool) => {
get_dispute_filter_for_dimension(dim, auth, &req.time_range, pool)
.await
}
AnalyticsProvider::CombinedCkh(sqlx_pool, ckh_pool) => {
let ckh_result = get_dispute_filter_for_dimension(
dim,
auth,
&req.time_range,
ckh_pool,
)
.await;
let sqlx_result = get_dispute_filter_for_dimension(
dim,
auth,
&req.time_range,
sqlx_pool,
)
.await;
match (&sqlx_result, &ckh_result) {
(Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres disputes analytics filters")
},
_ => {}
};
ckh_result
}
AnalyticsProvider::CombinedSqlx(sqlx_pool, ckh_pool) => {
let ckh_result = get_dispute_filter_for_dimension(
dim,
auth,
&req.time_range,
ckh_pool,
)
.await;
let sqlx_result = get_dispute_filter_for_dimension(
dim,
auth,
&req.time_range,
sqlx_pool,
)
.await;
match (&sqlx_result, &ckh_result) {
(Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres disputes analytics filters")
},
_ => {}
};
sqlx_result
}
}
.change_context(AnalyticsError::UnknownError)?
.into_iter()
.filter_map(|fil: DisputeFilterRow| match dim {
DisputeDimensions::DisputeStage => fil.dispute_stage,
DisputeDimensions::Connector => fil.connector,
DisputeDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()),
})
.collect::<Vec<String>>();
res.query_data.push(DisputeFilterValue {
dimension: dim,
values,
})
}
Ok(res)
}
|
crates/analytics/src/disputes/core.rs
|
analytics
|
function_signature
| 600
|
rust
| null | null | null | null |
get_filters
| null | null | null | null | null | null | null |
pub async fn organization_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<admin::OrganizationCreateRequest>,
) -> HttpResponse {
let flow = Flow::OrganizationCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| create_organization(state, req),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/admin.rs
|
router
|
function_signature
| 113
|
rust
| null | null | null | null |
organization_create
| null | null | null | null | null | null | null |
pub struct CardExpiration {
pub month: CardExpirationMonth,
pub year: CardExpirationYear,
}
|
crates/cards/src/lib.rs
|
cards
|
struct_definition
| 22
|
rust
|
CardExpiration
| null | null | null | null | null | null | null | null | null | null | null |
pub struct Trustpay {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
amount_converter_to_float_major_unit:
&'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
amount_converter_to_string_minor_unit:
&'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
|
crates/hyperswitch_connectors/src/connectors/trustpay.rs
|
hyperswitch_connectors
|
struct_definition
| 79
|
rust
|
Trustpay
| null | null | null | null | null | null | null | null | null | null | null |
pub struct PaymentDetails {
pub amount: i64,
pub currency: Option<storage_enums::Currency>,
pub payment_method: Option<PaymentMethod>,
pub payment_method_type: Option<PaymentMethodType>,
pub refund_transaction_id: Option<String>,
}
|
crates/router/src/core/fraud_check/types.rs
|
router
|
struct_definition
| 57
|
rust
|
PaymentDetails
| null | null | null | null | null | null | null | null | null | null | null |
pub struct PaypalRedirectsWebhooks {
pub purchase_units: Vec<PurchaseUnitItem>,
pub links: Vec<PaypalLinks>,
pub id: String,
pub intent: PaypalPaymentIntent,
}
|
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 44
|
rust
|
PaypalRedirectsWebhooks
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn decide_storage_scheme<T, D>(
store: &KVRouterStore<T>,
storage_scheme: MerchantStorageScheme,
operation: Op<'_>,
) -> MerchantStorageScheme
where
D: de::DeserializeOwned
+ serde::Serialize
+ Debug
+ KvStorePartition
+ UniqueConstraints
+ Sync,
T: crate::database::store::DatabaseStore,
{
if store.soft_kill_mode {
let ops = operation.to_string();
let updated_scheme = match operation {
Op::Insert => MerchantStorageScheme::PostgresOnly,
Op::Find => MerchantStorageScheme::RedisKv,
Op::Update(_, _, Some("postgres_only")) => MerchantStorageScheme::PostgresOnly,
Op::Update(partition_key, field, Some(_updated_by)) => {
match Box::pin(kv_wrapper::<D, _, _>(
store,
KvOperation::<D>::HGet(field),
partition_key,
))
.await
{
Ok(_) => {
metrics::KV_SOFT_KILL_ACTIVE_UPDATE.add(1, &[]);
MerchantStorageScheme::RedisKv
}
Err(_) => MerchantStorageScheme::PostgresOnly,
}
}
Op::Update(_, _, None) => MerchantStorageScheme::PostgresOnly,
};
let type_name = std::any::type_name::<D>();
logger::info!(soft_kill_mode = "decide_storage_scheme", decided_scheme = %updated_scheme, configured_scheme = %storage_scheme,entity = %type_name, operation = %ops);
updated_scheme
} else {
storage_scheme
}
}
|
crates/storage_impl/src/redis/kv_store.rs
|
storage_impl
|
function_signature
| 347
|
rust
| null | null | null | null |
decide_storage_scheme
| null | null | null | null | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.