AdityaNarayan/GLM-4.5-Air-CPT-LoRA-v4-HyperSwitch
Text Generation
β’
Updated
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 FraudHighRiskResponse {
pub score: f32,
pub reason: Vec<String>,
}
|
crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
|
hyperswitch_connectors
|
struct_definition
| 23
|
rust
|
FraudHighRiskResponse
| null | null | null | null | null | null | null | null | null | null | null |
impl Handler {
pub fn from_conf(
conf: DrainerSettings,
stores: HashMap<id_type::TenantId, Arc<Store>>,
) -> Self {
let shutdown_interval = Duration::from_millis(conf.shutdown_interval.into());
let loop_interval = Duration::from_millis(conf.loop_interval.into());
let active_tasks = Arc::new(atomic::AtomicU64::new(0));
let running = Arc::new(atomic::AtomicBool::new(true));
let handler = HandlerInner {
shutdown_interval,
loop_interval,
active_tasks,
conf,
stores,
running,
};
Self {
inner: Arc::new(handler),
}
}
pub fn close(&self) {
self.running.store(false, atomic::Ordering::SeqCst);
}
pub async fn spawn(&self) -> errors::DrainerResult<()> {
let mut stream_index: u8 = 0;
let jobs_picked = Arc::new(atomic::AtomicU8::new(0));
while self.running.load(atomic::Ordering::SeqCst) {
metrics::DRAINER_HEALTH.add(1, &[]);
for store in self.stores.values() {
if store.is_stream_available(stream_index).await {
let _task_handle = tokio::spawn(
drainer_handler(
store.clone(),
stream_index,
self.conf.max_read_count,
self.active_tasks.clone(),
jobs_picked.clone(),
)
.in_current_span(),
);
}
}
stream_index = utils::increment_stream_index(
(stream_index, jobs_picked.clone()),
self.conf.num_partitions,
)
.await;
time::sleep(self.loop_interval).await;
}
Ok(())
}
pub(crate) async fn shutdown_listener(&self, mut rx: mpsc::Receiver<()>) {
while let Some(_c) = rx.recv().await {
logger::info!("Awaiting shutdown!");
metrics::SHUTDOWN_SIGNAL_RECEIVED.add(1, &[]);
let shutdown_started = time::Instant::now();
rx.close();
//Check until the active tasks are zero. This does not include the tasks in the stream.
while self.active_tasks.load(atomic::Ordering::SeqCst) != 0 {
time::sleep(self.shutdown_interval).await;
}
logger::info!("Terminating drainer");
metrics::SUCCESSFUL_SHUTDOWN.add(1, &[]);
let shutdown_ended = shutdown_started.elapsed().as_secs_f64() * 1000f64;
metrics::CLEANUP_TIME.record(shutdown_ended, &[]);
self.close();
}
logger::info!(
tasks_remaining = self.active_tasks.load(atomic::Ordering::SeqCst),
"Drainer shutdown successfully"
)
}
pub fn spawn_error_handlers(&self, tx: mpsc::Sender<()>) -> errors::DrainerResult<()> {
let (redis_error_tx, redis_error_rx) = oneshot::channel();
let redis_conn_clone = self
.stores
.values()
.next()
.map(|store| store.redis_conn.clone());
match redis_conn_clone {
None => {
logger::error!("No redis connection found");
Err(
errors::DrainerError::UnexpectedError("No redis connection found".to_string())
.into(),
)
}
Some(redis_conn_clone) => {
// Spawn a task to monitor if redis is down or not
let _task_handle = tokio::spawn(
async move { redis_conn_clone.on_error(redis_error_tx).await }
.in_current_span(),
);
//Spawns a task to send shutdown signal if redis goes down
let _task_handle =
tokio::spawn(redis_error_receiver(redis_error_rx, tx).in_current_span());
Ok(())
}
}
}
}
|
crates/drainer/src/handler.rs
|
drainer
|
impl_block
| 833
|
rust
| null |
Handler
| null |
impl Handler
| null | null | null | null | null | null | null | null |
impl api::Payment for Zsl {}
|
crates/hyperswitch_connectors/src/connectors/zsl.rs
|
hyperswitch_connectors
|
impl_block
| 8
|
rust
| null |
Zsl
|
api::Payment for
|
impl api::Payment for for Zsl
| null | null | null | null | null | null | null | null |
pub async fn validate_request_and_fetch_optional_customer(
&self,
) -> RouterResult<Option<api::CustomerDetails>> {
// Validate card's expiry
migration::validate_card_expiry(&self.data.card_expiry_month, &self.data.card_expiry_year)?;
// Validate customer ID
let customer_id = self
.customer
.customer_id
.as_ref()
.get_required_value("customer_id")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "customer.customer_id",
})?;
// Fetch customer details if present
let db = &*self.state.store;
let key_manager_state: &KeyManagerState = &self.state.into();
db.find_customer_optional_by_customer_id_merchant_id(
key_manager_state,
customer_id,
self.merchant_account.get_id(),
self.key_store,
self.merchant_account.storage_scheme,
)
.await
.inspect_err(|err| logger::info!("Error fetching customer: {:?}", err))
.change_context(errors::ApiErrorResponse::InternalServerError)
.map_or(
// Validate if customer creation is feasible
if self.customer.name.is_some()
|| self.customer.email.is_some()
|| self.customer.phone.is_some()
{
Ok(None)
} else {
Err(report!(errors::ApiErrorResponse::MissingRequiredFields {
field_names: vec!["customer.name", "customer.email", "customer.phone"],
}))
},
// If found, send back CustomerDetails from DB
|optional_customer| {
Ok(optional_customer.map(|customer| api::CustomerDetails {
id: customer.customer_id.clone(),
name: customer.name.clone().map(|name| name.into_inner()),
email: customer.email.clone().map(Email::from),
phone: customer.phone.clone().map(|phone| phone.into_inner()),
phone_country_code: customer.phone_country_code.clone(),
tax_registration_id: customer
.tax_registration_id
.clone()
.map(|tax_registration_id| tax_registration_id.into_inner()),
}))
},
)
}
|
crates/router/src/core/payment_methods/tokenize/card_executor.rs
|
router
|
function_signature
| 441
|
rust
| null | null | null | null |
validate_request_and_fetch_optional_customer
| null | null | null | null | null | null | null |
pub struct CardRequestStruct {
billing_address: Option<Address>,
expiry: Option<Secret<String>>,
name: Option<Secret<String>>,
number: Option<cards::CardNumber>,
security_code: Option<Secret<String>>,
attributes: Option<CardRequestAttributes>,
}
|
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 57
|
rust
|
CardRequestStruct
| null | null | null | null | null | null | null | null | null | null | null |
pub struct OpayoPaymentsRequest {
amount: MinorUnit,
card: OpayoCard,
}
|
crates/hyperswitch_connectors/src/connectors/opayo/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 21
|
rust
|
OpayoPaymentsRequest
| null | null | null | null | null | null | null | null | null | null | null |
pub struct RelayResponse {
/// The unique identifier for the Relay
#[schema(example = "relay_mbabizu24mvu3mela5njyhpit4", value_type = String)]
pub id: common_utils::id_type::RelayId,
/// The status of the relay request
#[schema(value_type = RelayStatus)]
pub status: api_enums::RelayStatus,
/// The identifier that is associated to a resource at the connector reference to which the relay request is being made
#[schema(example = "pi_3MKEivSFNglxLpam0ZaL98q9")]
pub connector_resource_id: String,
/// The error details if the relay request failed
pub error: Option<RelayError>,
/// The identifier that is associated to a resource at the connector to which the relay request is being made
#[schema(example = "re_3QY4TnEOqOywnAIx1Mm1p7GQ")]
pub connector_reference_id: Option<String>,
/// Identifier of the connector ( merchant connector account ) which was chosen to make the payment
#[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)]
pub connector_id: common_utils::id_type::MerchantConnectorAccountId,
/// The business profile that is associated with this relay request.
#[schema(example = "pro_abcdefghijklmnopqrstuvwxyz", value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
/// The type of relay request
#[serde(rename = "type")]
#[schema(value_type = RelayType)]
pub relay_type: api_enums::RelayType,
/// The data that is associated with the relay request
pub data: Option<RelayData>,
}
|
crates/api_models/src/relay.rs
|
api_models
|
struct_definition
| 396
|
rust
|
RelayResponse
| null | null | null | null | null | null | null | null | null | null | null |
/// Get the decrypted Apple Pay payment data if it exists
pub fn get_decrypted_apple_pay_payment_data_optional(&self) -> Option<&ApplePayPredecryptData> {
match self {
Self::Encrypted(_) => None,
Self::Decrypted(decrypted_data) => Some(decrypted_data),
}
}
|
crates/common_types/src/payments.rs
|
common_types
|
function_signature
| 69
|
rust
| null | null | null | null |
get_decrypted_apple_pay_payment_data_optional
| null | null | null | null | null | null | null |
File: crates/analytics/src/payments/distribution.rs
Public structs: 1
use api_models::analytics::{
payments::{
PaymentDimensions, PaymentDistributions, PaymentFilters, PaymentMetricsBucketIdentifier,
},
Granularity, PaymentDistributionBody, TimeRange,
};
use diesel_models::enums as storage_enums;
use time::PrimitiveDateTime;
use crate::{
enums::AuthInfo,
query::{Aggregate, GroupByClause, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult},
};
mod payment_error_message;
use payment_error_message::PaymentErrorMessage;
#[derive(Debug, PartialEq, Eq, serde::Deserialize)]
pub struct PaymentDistributionRow {
pub currency: Option<DBEnumWrapper<storage_enums::Currency>>,
pub status: Option<DBEnumWrapper<storage_enums::AttemptStatus>>,
pub connector: Option<String>,
pub authentication_type: Option<DBEnumWrapper<storage_enums::AuthenticationType>>,
pub payment_method: Option<String>,
pub payment_method_type: Option<String>,
pub client_source: Option<String>,
pub client_version: Option<String>,
pub profile_id: 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 first_attempt: Option<bool>,
pub total: Option<bigdecimal::BigDecimal>,
pub count: Option<i64>,
pub error_message: Option<String>,
pub routing_approach: Option<DBEnumWrapper<storage_enums::RoutingApproach>>,
pub signature_network: Option<String>,
pub is_issuer_regulated: Option<bool>,
pub is_debit_routed: Option<bool>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub start_bucket: Option<PrimitiveDateTime>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub end_bucket: Option<PrimitiveDateTime>,
}
pub trait PaymentDistributionAnalytics: LoadRow<PaymentDistributionRow> {}
#[async_trait::async_trait]
pub trait PaymentDistribution<T>
where
T: AnalyticsDataSource + PaymentDistributionAnalytics,
{
#[allow(clippy::too_many_arguments)]
async fn load_distribution(
&self,
distribution: &PaymentDistributionBody,
dimensions: &[PaymentDimensions],
auth: &AuthInfo,
filters: &PaymentFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentDistributionRow)>>;
}
#[async_trait::async_trait]
impl<T> PaymentDistribution<T> for PaymentDistributions
where
T: AnalyticsDataSource + PaymentDistributionAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_distribution(
&self,
distribution: &PaymentDistributionBody,
dimensions: &[PaymentDimensions],
auth: &AuthInfo,
filters: &PaymentFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentDistributionRow)>> {
match self {
Self::PaymentErrorMessage => {
PaymentErrorMessage
.load_distribution(
distribution,
dimensions,
auth,
filters,
granularity,
time_range,
pool,
)
.await
}
}
}
}
|
crates/analytics/src/payments/distribution.rs
|
analytics
|
full_file
| 779
| null | null | null | null | null | null | null | null | null | null | null | null | null |
File: crates/router/src/core/unified_authentication_service/types.rs
Public structs: 2
use api_models::payments;
use hyperswitch_domain_models::{
errors::api_error_response::{self as errors, NotImplementedMessage},
router_request_types::{
authentication::MessageCategory,
unified_authentication_service::{
UasAuthenticationRequestData, UasPostAuthenticationRequestData,
UasPreAuthenticationRequestData,
},
BrowserInformation,
},
};
use crate::{
core::{errors::RouterResult, payments::helpers::MerchantConnectorAccountType},
db::domain,
routes::SessionState,
};
pub const CTP_MASTERCARD: &str = "ctp_mastercard";
pub const UNIFIED_AUTHENTICATION_SERVICE: &str = "unified_authentication_service";
pub const IRRELEVANT_ATTEMPT_ID_IN_AUTHENTICATION_FLOW: &str =
"irrelevant_attempt_id_in_AUTHENTICATION_flow";
pub const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_AUTHENTICATION_FLOW: &str =
"irrelevant_connector_request_reference_id_in_AUTHENTICATION_flow";
pub struct ClickToPay;
pub struct ExternalAuthentication;
#[async_trait::async_trait]
pub trait UnifiedAuthenticationService {
#[allow(clippy::too_many_arguments)]
fn get_pre_authentication_request_data(
_payment_method_data: Option<&domain::PaymentMethodData>,
_service_details: Option<payments::CtpServiceDetails>,
_amount: common_utils::types::MinorUnit,
_currency: Option<common_enums::Currency>,
_merchant_details: Option<&hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails>,
_billing_address: Option<&hyperswitch_domain_models::address::Address>,
_acquirer_bin: Option<String>,
_acquirer_merchant_id: Option<String>,
) -> RouterResult<UasPreAuthenticationRequestData> {
Err(errors::ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason(
"get_pre_authentication_request_data".to_string(),
),
}
.into())
}
#[allow(clippy::too_many_arguments)]
async fn pre_authentication(
_state: &SessionState,
_merchant_id: &common_utils::id_type::MerchantId,
_payment_id: Option<&common_utils::id_type::PaymentId>,
_payment_method_data: Option<&domain::PaymentMethodData>,
_merchant_connector_account: &MerchantConnectorAccountType,
_connector_name: &str,
_authentication_id: &common_utils::id_type::AuthenticationId,
_payment_method: common_enums::PaymentMethod,
_amount: common_utils::types::MinorUnit,
_currency: Option<common_enums::Currency>,
_service_details: Option<payments::CtpServiceDetails>,
_merchant_details: Option<&hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails>,
_billing_address: Option<&hyperswitch_domain_models::address::Address>,
_acquirer_bin: Option<String>,
_acquirer_merchant_id: Option<String>,
) -> RouterResult<hyperswitch_domain_models::types::UasPreAuthenticationRouterData> {
Err(errors::ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("pre_authentication".to_string()),
}
.into())
}
#[allow(clippy::too_many_arguments)]
fn get_authentication_request_data(
_browser_details: Option<BrowserInformation>,
_amount: Option<common_utils::types::MinorUnit>,
_currency: Option<common_enums::Currency>,
_message_category: MessageCategory,
_device_channel: payments::DeviceChannel,
_authentication: diesel_models::authentication::Authentication,
_return_url: Option<String>,
_sdk_information: Option<payments::SdkInformation>,
_threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
_email: Option<common_utils::pii::Email>,
_webhook_url: String,
) -> RouterResult<UasAuthenticationRequestData> {
Err(errors::ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason(
"get_pre_authentication_request_data".to_string(),
),
}
.into())
}
#[allow(clippy::too_many_arguments)]
async fn authentication(
_state: &SessionState,
_business_profile: &domain::Profile,
_payment_method: &common_enums::PaymentMethod,
_browser_details: Option<BrowserInformation>,
_amount: Option<common_utils::types::MinorUnit>,
_currency: Option<common_enums::Currency>,
_message_category: MessageCategory,
_device_channel: payments::DeviceChannel,
_authentication_data: diesel_models::authentication::Authentication,
_return_url: Option<String>,
_sdk_information: Option<payments::SdkInformation>,
_threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
_email: Option<common_utils::pii::Email>,
_webhook_url: String,
_merchant_connector_account: &MerchantConnectorAccountType,
_connector_name: &str,
_payment_id: Option<common_utils::id_type::PaymentId>,
) -> RouterResult<hyperswitch_domain_models::types::UasAuthenticationRouterData> {
Err(errors::ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("authentication".to_string()),
}
.into())
}
fn get_post_authentication_request_data(
_authentication: Option<diesel_models::authentication::Authentication>,
) -> RouterResult<UasPostAuthenticationRequestData> {
Err(errors::ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("post_authentication".to_string()),
}
.into())
}
#[allow(clippy::too_many_arguments)]
async fn post_authentication(
_state: &SessionState,
_business_profile: &domain::Profile,
_payment_id: Option<&common_utils::id_type::PaymentId>,
_merchant_connector_account: &MerchantConnectorAccountType,
_connector_name: &str,
_authentication_id: &common_utils::id_type::AuthenticationId,
_payment_method: common_enums::PaymentMethod,
_merchant_id: &common_utils::id_type::MerchantId,
_authentication: Option<&diesel_models::authentication::Authentication>,
) -> RouterResult<hyperswitch_domain_models::types::UasPostAuthenticationRouterData> {
Err(errors::ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("post_authentication".to_string()),
}
.into())
}
#[allow(clippy::too_many_arguments)]
async fn confirmation(
_state: &SessionState,
_authentication_id: Option<&common_utils::id_type::AuthenticationId>,
_currency: Option<common_enums::Currency>,
_status: common_enums::AttemptStatus,
_service_details: Option<payments::CtpServiceDetails>,
_merchant_connector_account: &MerchantConnectorAccountType,
_connector_name: &str,
_payment_method: common_enums::PaymentMethod,
_net_amount: common_utils::types::MinorUnit,
_payment_id: Option<&common_utils::id_type::PaymentId>,
_merchant_id: &common_utils::id_type::MerchantId,
) -> RouterResult<()> {
Err(errors::ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("confirmation".to_string()),
}
.into())
}
}
|
crates/router/src/core/unified_authentication_service/types.rs
|
router
|
full_file
| 1,586
| null | null | null | null | null | null | null | null | null | null | null | null | null |
File: crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs
Public structs: 12
#[cfg(feature = "payouts")]
use api_models::enums::Currency;
#[cfg(feature = "payouts")]
use api_models::payouts::{Bank, PayoutMethodData};
#[cfg(feature = "payouts")]
use common_enums::{PayoutStatus, PayoutType};
#[cfg(feature = "payouts")]
use common_utils::pii::Email;
use common_utils::types::FloatMajorUnit;
use hyperswitch_domain_models::router_data::ConnectorAuthType;
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::router_flow_types::PoCreate;
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::types::{PayoutsResponseData, PayoutsRouterData};
use hyperswitch_interfaces::errors::ConnectorError;
#[cfg(feature = "payouts")]
use masking::ExposeInterface;
use masking::Secret;
use serde::{Deserialize, Serialize};
#[cfg(feature = "payouts")]
use crate::types::PayoutsResponseRouterData;
#[cfg(feature = "payouts")]
use crate::utils::{
AddressDetailsData as _, CustomerDetails as _, PayoutsData as _, RouterData as _,
};
pub struct EbanxRouterData<T> {
pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for EbanxRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Clone)]
pub struct EbanxPayoutCreateRequest {
integration_key: Secret<String>,
external_reference: String,
country: String,
amount: FloatMajorUnit,
currency: Currency,
target: EbanxPayoutType,
target_account: Secret<String>,
payee: EbanxPayoutDetails,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Clone)]
pub enum EbanxPayoutType {
BankAccount,
Mercadopago,
EwalletNequi,
PixKey,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Clone)]
pub struct EbanxPayoutDetails {
name: Secret<String>,
email: Option<Email>,
document: Option<Secret<String>>,
document_type: Option<EbanxDocumentType>,
bank_info: EbanxBankDetails,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Clone)]
pub enum EbanxDocumentType {
#[serde(rename = "CPF")]
NaturalPersonsRegister,
#[serde(rename = "CNPJ")]
NationalRegistryOfLegalEntities,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Clone)]
pub struct EbanxBankDetails {
bank_name: Option<String>,
bank_branch: Option<String>,
bank_account: Option<Secret<String>>,
account_type: Option<EbanxBankAccountType>,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Clone)]
pub enum EbanxBankAccountType {
#[serde(rename = "C")]
CheckingAccount,
}
#[cfg(feature = "payouts")]
impl TryFrom<&EbanxRouterData<&PayoutsRouterData<PoCreate>>> for EbanxPayoutCreateRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &EbanxRouterData<&PayoutsRouterData<PoCreate>>) -> Result<Self, Self::Error> {
let ebanx_auth_type = EbanxAuthType::try_from(&item.router_data.connector_auth_type)?;
match item.router_data.get_payout_method_data()? {
PayoutMethodData::Bank(Bank::Pix(pix_data)) => {
let bank_info = EbanxBankDetails {
bank_account: Some(pix_data.bank_account_number),
bank_branch: pix_data.bank_branch,
bank_name: pix_data.bank_name,
account_type: Some(EbanxBankAccountType::CheckingAccount),
};
let billing_address = item.router_data.get_billing_address()?;
let customer_details = item.router_data.request.get_customer_details()?;
let document_type = pix_data.tax_id.clone().map(|tax_id| {
if tax_id.clone().expose().len() == 11 {
EbanxDocumentType::NaturalPersonsRegister
} else {
EbanxDocumentType::NationalRegistryOfLegalEntities
}
});
let payee = EbanxPayoutDetails {
name: billing_address.get_full_name()?,
email: customer_details.email.clone(),
bank_info,
document_type,
document: pix_data.tax_id.to_owned(),
};
Ok(Self {
amount: item.amount,
integration_key: ebanx_auth_type.integration_key,
country: customer_details.get_customer_phone_country_code()?,
currency: item.router_data.request.source_currency,
external_reference: item.router_data.connector_request_reference_id.to_owned(),
target: EbanxPayoutType::PixKey,
target_account: pix_data.pix_key,
payee,
})
}
PayoutMethodData::Card(_) | PayoutMethodData::Bank(_) | PayoutMethodData::Wallet(_) => {
Err(ConnectorError::NotSupported {
message: "Payment Method Not Supported".to_string(),
connector: "Ebanx",
})?
}
}
}
}
pub struct EbanxAuthType {
pub integration_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for EbanxAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
integration_key: api_key.to_owned(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EbanxPayoutStatus {
#[serde(rename = "PA")]
Succeeded,
#[serde(rename = "CA")]
Cancelled,
#[serde(rename = "PE")]
Processing,
#[serde(rename = "OP")]
RequiresFulfillment,
}
#[cfg(feature = "payouts")]
impl From<EbanxPayoutStatus> for PayoutStatus {
fn from(item: EbanxPayoutStatus) -> Self {
match item {
EbanxPayoutStatus::Succeeded => Self::Success,
EbanxPayoutStatus::Cancelled => Self::Cancelled,
EbanxPayoutStatus::Processing => Self::Pending,
EbanxPayoutStatus::RequiresFulfillment => Self::RequiresFulfillment,
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EbanxPayoutResponse {
payout: EbanxPayoutResponseDetails,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EbanxPayoutResponseDetails {
uid: String,
status: EbanxPayoutStatus,
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, EbanxPayoutResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, EbanxPayoutResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::from(item.response.payout.status)),
connector_payout_id: Some(item.response.payout.uid),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
}),
..item.data
})
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EbanxPayoutFulfillRequest {
integration_key: Secret<String>,
uid: String,
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<&EbanxRouterData<&PayoutsRouterData<F>>> for EbanxPayoutFulfillRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &EbanxRouterData<&PayoutsRouterData<F>>) -> Result<Self, Self::Error> {
let request = item.router_data.request.to_owned();
let ebanx_auth_type = EbanxAuthType::try_from(&item.router_data.connector_auth_type)?;
let payout_type = request.get_payout_type()?;
match payout_type {
PayoutType::Bank => Ok(Self {
integration_key: ebanx_auth_type.integration_key,
uid: request
.connector_payout_id
.to_owned()
.ok_or(ConnectorError::MissingRequiredField { field_name: "uid" })?,
}),
PayoutType::Card | PayoutType::Wallet => Err(ConnectorError::NotSupported {
message: "Payout Method Not Supported".to_string(),
connector: "Ebanx",
})?,
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EbanxFulfillResponse {
#[serde(rename = "type")]
status: EbanxFulfillStatus,
message: String,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EbanxFulfillStatus {
Success,
ApiError,
AuthenticationError,
InvalidRequestError,
RequestError,
}
#[cfg(feature = "payouts")]
impl From<EbanxFulfillStatus> for PayoutStatus {
fn from(item: EbanxFulfillStatus) -> Self {
match item {
EbanxFulfillStatus::Success => Self::Success,
EbanxFulfillStatus::ApiError
| EbanxFulfillStatus::AuthenticationError
| EbanxFulfillStatus::InvalidRequestError
| EbanxFulfillStatus::RequestError => Self::Failed,
}
}
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, EbanxFulfillResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, EbanxFulfillResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::from(item.response.status)),
connector_payout_id: Some(item.data.request.get_transfer_id()?),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct EbanxErrorResponse {
pub code: String,
pub status_code: String,
pub message: Option<String>,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EbanxPayoutCancelRequest {
integration_key: Secret<String>,
uid: String,
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<&PayoutsRouterData<F>> for EbanxPayoutCancelRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let request = item.request.to_owned();
let ebanx_auth_type = EbanxAuthType::try_from(&item.connector_auth_type)?;
let payout_type = request.get_payout_type()?;
match payout_type {
PayoutType::Bank => Ok(Self {
integration_key: ebanx_auth_type.integration_key,
uid: request
.connector_payout_id
.to_owned()
.ok_or(ConnectorError::MissingRequiredField { field_name: "uid" })?,
}),
PayoutType::Card | PayoutType::Wallet => Err(ConnectorError::NotSupported {
message: "Payout Method Not Supported".to_string(),
connector: "Ebanx",
})?,
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EbanxCancelResponse {
#[serde(rename = "type")]
status: EbanxCancelStatus,
message: String,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EbanxCancelStatus {
Success,
ApiError,
AuthenticationError,
InvalidRequestError,
RequestError,
}
#[cfg(feature = "payouts")]
impl From<EbanxCancelStatus> for PayoutStatus {
fn from(item: EbanxCancelStatus) -> Self {
match item {
EbanxCancelStatus::Success => Self::Cancelled,
EbanxCancelStatus::ApiError
| EbanxCancelStatus::AuthenticationError
| EbanxCancelStatus::InvalidRequestError
| EbanxCancelStatus::RequestError => Self::Failed,
}
}
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, EbanxCancelResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, EbanxCancelResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::from(item.response.status)),
connector_payout_id: item.data.request.connector_payout_id.clone(),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
}),
..item.data
})
}
}
|
crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs
|
hyperswitch_connectors
|
full_file
| 3,134
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub fn generate_digest(&self, payload: &[u8]) -> String {
let payload_digest = digest::digest(&digest::SHA256, payload);
consts::BASE64_ENGINE.encode(payload_digest)
}
|
crates/hyperswitch_connectors/src/connectors/wellsfargo.rs
|
hyperswitch_connectors
|
function_signature
| 47
|
rust
| null | null | null | null |
generate_digest
| null | null | null | null | null | null | null |
pub struct RequiredFields(pub HashMap<enums::PaymentMethod, PaymentMethodType>);
|
crates/payment_methods/src/configs/settings.rs
|
payment_methods
|
struct_definition
| 17
|
rust
|
RequiredFields
| null | null | null | null | null | null | null | null | null | null | null |
pub struct Capture {
pub capture_id: String,
pub payment_id: common_utils::id_type::PaymentId,
pub merchant_id: common_utils::id_type::MerchantId,
pub status: storage_enums::CaptureStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
pub connector: String,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub error_reason: Option<String>,
pub tax_amount: Option<MinorUnit>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub authorized_attempt_id: String,
pub connector_capture_id: Option<ConnectorTransactionId>,
pub capture_sequence: i16,
// reference to the capture at connector side
pub connector_response_reference_id: Option<String>,
/// INFO: This field is deprecated and replaced by processor_capture_data
pub connector_capture_data: Option<String>,
pub processor_capture_data: Option<String>,
}
|
crates/diesel_models/src/capture.rs
|
diesel_models
|
struct_definition
| 246
|
rust
|
Capture
| null | null | null | null | null | null | null | null | null | null | null |
pub struct DeleteNetworkTokenResponse {
pub status: DeleteNetworkTokenStatus,
}
|
crates/router/src/types/payment_methods.rs
|
router
|
struct_definition
| 17
|
rust
|
DeleteNetworkTokenResponse
| null | null | null | null | null | null | null | null | null | null | null |
impl api::Payment for Bamboraapac {}
|
crates/hyperswitch_connectors/src/connectors/bamboraapac.rs
|
hyperswitch_connectors
|
impl_block
| 11
|
rust
| null |
Bamboraapac
|
api::Payment for
|
impl api::Payment for for Bamboraapac
| null | null | null | null | null | null | null | null |
pub struct Transactions {
transaction_id: String,
gateway_status_code: String,
payment_method: PaymentMethod,
amount: i64,
currency: Currency,
gateway: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs
|
hyperswitch_connectors
|
struct_definition
| 43
|
rust
|
Transactions
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/router/tests/connectors/nmi.rs
use std::{str::FromStr, time::Duration};
use router::types::{self, domain, storage::enums};
use crate::{
connector_auth,
utils::{self, ConnectorActions},
};
struct NmiTest;
impl ConnectorActions for NmiTest {}
impl utils::Connector for NmiTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Nmi;
utils::construct_connector_data_old(
Box::new(Nmi::new()),
types::Connector::Nmi,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.nmi
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"nmi".to_string()
}
}
static CONNECTOR: NmiTest = NmiTest {};
fn get_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),
..utils::CCardType::default().0
}),
amount: 2023,
..utils::PaymentAuthorizeType::default().0
})
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_authorize_data(), None)
.await
.expect("Authorize payment response");
let transaction_id = utils::get_connector_transaction_id(response.response).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
// Assert the sync response, it will be authorized in case of manual capture, for automatic it will be Completed Success
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorizing);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
let capture_response = CONNECTOR
.capture_payment(transaction_id.clone(), None, None)
.await
.unwrap();
assert_eq!(
capture_response.status,
enums::AttemptStatus::CaptureInitiated
);
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorizing);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
let capture_response = CONNECTOR
.capture_payment(
transaction_id.clone(),
Some(types::PaymentsCaptureData {
amount_to_capture: 1000,
..utils::PaymentCaptureType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
capture_response.status,
enums::AttemptStatus::CaptureInitiated
);
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorizing);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
let void_response = CONNECTOR
.void_payment(
transaction_id.clone(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("user_cancel".to_string()),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(void_response.status, enums::AttemptStatus::VoidInitiated);
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Voided,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorizing);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
let capture_response = CONNECTOR
.capture_payment(transaction_id.clone(), None, None)
.await
.unwrap();
assert_eq!(
capture_response.status,
enums::AttemptStatus::CaptureInitiated
);
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
let refund_response = CONNECTOR
.refund_payment(transaction_id.clone(), None, None)
.await
.unwrap();
assert_eq!(refund_response.status, enums::AttemptStatus::Pending);
let sync_response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Pending,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
sync_response.response.unwrap().refund_status,
enums::RefundStatus::Pending
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorizing);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
let capture_response = CONNECTOR
.capture_payment(
transaction_id.clone(),
Some(types::PaymentsCaptureData {
amount_to_capture: 2023,
..utils::PaymentCaptureType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
capture_response.status,
enums::AttemptStatus::CaptureInitiated
);
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
let refund_response = CONNECTOR
.refund_payment(
transaction_id.clone(),
Some(types::RefundsData {
refund_amount: 1023,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(refund_response.status, enums::AttemptStatus::Pending);
let sync_response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Pending,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
sync_response.response.unwrap().refund_status,
enums::RefundStatus::Pending
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let response = CONNECTOR
.make_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
let refund_response = CONNECTOR
.refund_payment(transaction_id.clone(), None, None)
.await
.unwrap();
assert_eq!(refund_response.status, enums::AttemptStatus::Pending);
let sync_response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Pending,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
sync_response.response.unwrap().refund_status,
enums::RefundStatus::Pending
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let response = CONNECTOR
.make_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
let refund_response = CONNECTOR
.refund_payment(
transaction_id.clone(),
Some(types::RefundsData {
refund_amount: 1000,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(refund_response.status, enums::AttemptStatus::Pending);
let sync_response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Pending,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
sync_response.response.unwrap().refund_status,
enums::RefundStatus::Pending
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
let response = CONNECTOR
.make_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
//try refund for previous payment
let transaction_id = utils::get_connector_transaction_id(response.response).unwrap();
for _x in 0..2 {
tokio::time::sleep(Duration::from_secs(5)).await; // to avoid 404 error
let refund_response = CONNECTOR
.refund_payment(
transaction_id.clone(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
let sync_response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Pending,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
sync_response.response.unwrap().refund_status,
enums::RefundStatus::Pending,
);
}
}
// Creates a payment with incorrect CVC.
#[ignore = "Connector returns SUCCESS status in case of invalid CVC"]
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {}
// Creates a payment with incorrect expiry month.
#[ignore = "Connector returns SUCCESS status in case of expired month."]
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {}
// Creates a payment with incorrect expiry year.
#[ignore = "Connector returns SUCCESS status in case of expired year."]
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let response = CONNECTOR
.make_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
let void_response = CONNECTOR
.void_payment(transaction_id.clone(), None, None)
.await
.unwrap();
assert_eq!(void_response.status, enums::AttemptStatus::VoidFailed);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorizing);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
let capture_response = CONNECTOR
.capture_payment("9123456789".to_string(), None, None)
.await
.unwrap();
assert_eq!(capture_response.status, enums::AttemptStatus::CaptureFailed);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
let refund_response = CONNECTOR
.refund_payment(
transaction_id,
Some(types::RefundsData {
refund_amount: 3024,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Failure
);
}
|
crates/router/tests/connectors/nmi.rs
|
router
|
full_file
| 4,885
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl ConnectorSpecifications for Shift4 {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&SHIFT4_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*SHIFT4_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&SHIFT4_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates/hyperswitch_connectors/src/connectors/shift4.rs
|
hyperswitch_connectors
|
impl_block
| 105
|
rust
| null |
Shift4
|
ConnectorSpecifications for
|
impl ConnectorSpecifications for for Shift4
| null | null | null | null | null | null | null | null |
pub struct PayuOrderResponseProperty {
name: String,
value: String,
}
|
crates/hyperswitch_connectors/src/connectors/payu/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 19
|
rust
|
PayuOrderResponseProperty
| null | null | null | null | null | null | null | null | null | null | null |
/// Panics if `json_payload` array does not contain one `GetAuthEventMetricRequest` element.
pub async fn get_merchant_auth_event_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetAuthEventMetricRequest; 1]>,
) -> impl Responder {
// safety: This shouldn't panic owing to the data type
#[allow(clippy::expect_used)]
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetAuthEventMetricRequest");
let flow = AnalyticsFlow::GetAuthMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let auth: AuthInfo = AuthInfo::MerchantLevel {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
};
analytics::auth_events::get_metrics(&state.pool, &auth, req)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/analytics.rs
|
router
|
function_signature
| 308
|
rust
| null | null | null | null |
get_merchant_auth_event_metrics
| null | null | null | null | null | null | null |
impl api::Payment for Datatrans {}
|
crates/hyperswitch_connectors/src/connectors/datatrans.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Datatrans
|
api::Payment for
|
impl api::Payment for for Datatrans
| null | null | null | null | null | null | null | null |
File: crates/router/src/types/storage/dispute.rs
use async_bb8_diesel::AsyncRunQueryDsl;
use common_utils::errors::CustomResult;
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, QueryDsl};
pub use diesel_models::dispute::{Dispute, DisputeNew, DisputeUpdate};
use diesel_models::{errors, query::generics::db_metrics, schema::dispute::dsl};
use error_stack::ResultExt;
use hyperswitch_domain_models::disputes;
use crate::{connection::PgPooledConn, logger};
#[async_trait::async_trait]
pub trait DisputeDbExt: Sized {
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
dispute_list_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
async fn get_dispute_status_with_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::enums::DisputeStatus, i64)>, errors::DatabaseError>;
}
#[async_trait::async_trait]
impl DisputeDbExt for Dispute {
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
dispute_list_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.order(dsl::modified_at.desc())
.into_boxed();
let mut search_by_payment_or_dispute_id = false;
if let (Some(payment_id), Some(dispute_id)) = (
&dispute_list_constraints.payment_id,
&dispute_list_constraints.dispute_id,
) {
search_by_payment_or_dispute_id = true;
filter = filter.filter(
dsl::payment_id
.eq(payment_id.to_owned())
.or(dsl::dispute_id.eq(dispute_id.to_owned())),
);
};
if !search_by_payment_or_dispute_id {
if let Some(payment_id) = &dispute_list_constraints.payment_id {
filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned()));
};
}
if !search_by_payment_or_dispute_id {
if let Some(dispute_id) = &dispute_list_constraints.dispute_id {
filter = filter.filter(dsl::dispute_id.eq(dispute_id.clone()));
};
}
if let Some(time_range) = dispute_list_constraints.time_range {
filter = filter.filter(dsl::created_at.ge(time_range.start_time));
if let Some(end_time) = time_range.end_time {
filter = filter.filter(dsl::created_at.le(end_time));
}
}
if let Some(profile_id) = &dispute_list_constraints.profile_id {
filter = filter.filter(dsl::profile_id.eq_any(profile_id.clone()));
}
if let Some(connector_list) = &dispute_list_constraints.connector {
filter = filter.filter(dsl::connector.eq_any(connector_list.clone()));
}
if let Some(reason) = &dispute_list_constraints.reason {
filter = filter.filter(dsl::connector_reason.eq(reason.clone()));
}
if let Some(dispute_stage) = &dispute_list_constraints.dispute_stage {
filter = filter.filter(dsl::dispute_stage.eq_any(dispute_stage.clone()));
}
if let Some(dispute_status) = &dispute_list_constraints.dispute_status {
filter = filter.filter(dsl::dispute_status.eq_any(dispute_status.clone()));
}
if let Some(currency_list) = &dispute_list_constraints.currency {
filter = filter.filter(dsl::dispute_currency.eq_any(currency_list.clone()));
}
if let Some(merchant_connector_id) = &dispute_list_constraints.merchant_connector_id {
filter = filter.filter(dsl::merchant_connector_id.eq(merchant_connector_id.clone()))
}
if let Some(limit) = dispute_list_constraints.limit {
filter = filter.limit(limit.into());
}
if let Some(offset) = dispute_list_constraints.offset {
filter = filter.offset(offset.into());
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
filter.get_results_async(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering records by predicate")
}
async fn get_dispute_status_with_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::DatabaseError> {
let mut query = <Self as HasTable>::table()
.group_by(dsl::dispute_status)
.select((dsl::dispute_status, diesel::dsl::count_star()))
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.into_boxed();
if let Some(profile_id) = profile_id_list {
query = query.filter(dsl::profile_id.eq_any(profile_id));
}
query = query.filter(dsl::created_at.ge(time_range.start_time));
query = match time_range.end_time {
Some(ending_at) => query.filter(dsl::created_at.le(ending_at)),
None => query,
};
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
query.get_results_async::<(common_enums::DisputeStatus, i64)>(conn),
db_metrics::DatabaseOperation::Count,
)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering records by predicate")
}
}
|
crates/router/src/types/storage/dispute.rs
|
router
|
full_file
| 1,396
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn user_from_email(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_api::UserFromEmailRequest>,
) -> HttpResponse {
let flow = Flow::UserFromEmail;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, _: (), req_body, _| user_core::user_from_email(state, req_body),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/user.rs
|
router
|
function_signature
| 124
|
rust
| null | null | null | null |
user_from_email
| null | null | null | null | null | null | null |
File: crates/common_types/src/primitive_wrappers.rs
Public functions: 1
Public structs: 5
pub use bool_wrappers::*;
pub use u32_wrappers::*;
mod bool_wrappers {
use std::ops::Deref;
use serde::{Deserialize, Serialize};
/// Bool that represents if Extended Authorization is Applied or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct ExtendedAuthorizationAppliedBool(bool);
impl Deref for ExtendedAuthorizationAppliedBool {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<bool> for ExtendedAuthorizationAppliedBool {
fn from(value: bool) -> Self {
Self(value)
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for ExtendedAuthorizationAppliedBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for ExtendedAuthorizationAppliedBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Extended Authorization is Requested or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct RequestExtendedAuthorizationBool(bool);
impl Deref for RequestExtendedAuthorizationBool {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<bool> for RequestExtendedAuthorizationBool {
fn from(value: bool) -> Self {
Self(value)
}
}
impl RequestExtendedAuthorizationBool {
/// returns the inner bool value
pub fn is_true(&self) -> bool {
self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for RequestExtendedAuthorizationBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for RequestExtendedAuthorizationBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Extended Authorization is always Requested or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct AlwaysRequestExtendedAuthorization(bool);
impl Deref for AlwaysRequestExtendedAuthorization {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB>
for AlwaysRequestExtendedAuthorization
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for AlwaysRequestExtendedAuthorization
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Cvv should be collected during payment or not. Default is true
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct ShouldCollectCvvDuringPayment(bool);
impl Deref for ShouldCollectCvvDuringPayment {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for ShouldCollectCvvDuringPayment
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for ShouldCollectCvvDuringPayment
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
impl Default for ShouldCollectCvvDuringPayment {
/// Default for `ShouldCollectCvvDuringPayment` is `true`
fn default() -> Self {
Self(true)
}
}
}
mod u32_wrappers {
use std::ops::Deref;
use serde::{de::Error, Deserialize, Serialize};
use crate::consts::{
DEFAULT_DISPUTE_POLLING_INTERVAL_IN_HOURS, MAX_DISPUTE_POLLING_INTERVAL_IN_HOURS,
};
/// Time interval in hours for polling disputes
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, diesel::expression::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Integer)]
pub struct DisputePollingIntervalInHours(i32);
impl Deref for DisputePollingIntervalInHours {
type Target = i32;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'de> Deserialize<'de> for DisputePollingIntervalInHours {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let val = i32::deserialize(deserializer)?;
if val < 0 {
Err(D::Error::custom(
"DisputePollingIntervalInHours cannot be negative",
))
} else if val > MAX_DISPUTE_POLLING_INTERVAL_IN_HOURS {
Err(D::Error::custom(
"DisputePollingIntervalInHours exceeds the maximum allowed value of 24",
))
} else {
Ok(Self(val))
}
}
}
impl diesel::deserialize::FromSql<diesel::sql_types::Integer, diesel::pg::Pg>
for DisputePollingIntervalInHours
{
fn from_sql(value: diesel::pg::PgValue<'_>) -> diesel::deserialize::Result<Self> {
i32::from_sql(value).map(Self)
}
}
impl diesel::serialize::ToSql<diesel::sql_types::Integer, diesel::pg::Pg>
for DisputePollingIntervalInHours
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>,
) -> diesel::serialize::Result {
<i32 as diesel::serialize::ToSql<diesel::sql_types::Integer, diesel::pg::Pg>>::to_sql(
&self.0, out,
)
}
}
impl Default for DisputePollingIntervalInHours {
/// Default for `ShouldCollectCvvDuringPayment` is `true`
fn default() -> Self {
Self(DEFAULT_DISPUTE_POLLING_INTERVAL_IN_HOURS)
}
}
}
|
crates/common_types/src/primitive_wrappers.rs
|
common_types
|
full_file
| 2,012
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct BluesnapWebhookObjectResource {
reference_number: String,
transaction_type: BluesnapWebhookEvents,
reversal_ref_num: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 34
|
rust
|
BluesnapWebhookObjectResource
| null | null | null | null | null | null | null | null | null | null | null |
pub struct WebhookResponseData {
pub statuses: Statuses,
pub descriptor: String,
pub notifications: NotificationContainer,
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "transaction-id")]
pub transaction_id: String,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "transaction-state")]
pub transaction_state: GetnetPaymentStatus,
#[serde(rename = "completion-time-stamp")]
pub completion_time_stamp: u64,
#[serde(rename = "requested-amount")]
pub requested_amount: Amount,
#[serde(rename = "parent-transaction-id")]
#[serde(skip_serializing_if = "Option::is_none")]
pub parent_transaction_id: Option<String>,
#[serde(rename = "account-holder")]
pub account_holder: Option<AccountHolder>,
#[serde(rename = "card-token")]
pub card_token: CardToken,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
#[serde(rename = "payment-methods")]
pub payment_methods: PaymentMethodContainer,
#[serde(rename = "parent-transaction-amount")]
#[serde(skip_serializing_if = "Option::is_none")]
pub parent_transaction_amount: Option<Amount>,
#[serde(rename = "authorization-code")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorization_code: Option<String>,
#[serde(rename = "api-id")]
pub api_id: String,
#[serde(rename = "provider-account-id")]
#[serde(skip_serializing_if = "Option::is_none")]
pub provider_account_id: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 381
|
rust
|
WebhookResponseData
| null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.SepaBankTransfer
{
"type": "object",
"required": [
"iban",
"bic"
],
"properties": {
"bank_name": {
"type": "string",
"description": "Bank name",
"example": "Deutsche Bank",
"nullable": true
},
"bank_country_code": {
"allOf": [
{
"$ref": "#/components/schemas/CountryAlpha2"
}
],
"nullable": true
},
"bank_city": {
"type": "string",
"description": "Bank city",
"example": "California",
"nullable": true
},
"iban": {
"type": "string",
"description": "International Bank Account Number (iban) - used in many countries for identifying a bank along with it's customer.",
"example": "DE89370400440532013000"
},
"bic": {
"type": "string",
"description": "[8 / 11 digits] Bank Identifier Code (bic) / Swift Code - used in many countries for identifying a bank and it's branches",
"example": "HSBCGB2LXXX"
}
}
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 289
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"SepaBankTransfer"
] | null | null | null | null |
pub struct SubmitSingleCaptureResponse {
submit_single_capture_result: SubmitSingleCaptureResult,
}
|
crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 19
|
rust
|
SubmitSingleCaptureResponse
| null | null | null | null | null | null | null | null | null | null | null |
impl VaultingInterface for GetVaultFingerprint {
fn get_vaulting_request_url() -> &'static str {
consts::VAULT_FINGERPRINT_REQUEST_URL
}
fn get_vaulting_flow_name() -> &'static str {
consts::VAULT_GET_FINGERPRINT_FLOW_TYPE
}
}
|
crates/router/src/types/payment_methods.rs
|
router
|
impl_block
| 66
|
rust
| null |
GetVaultFingerprint
|
VaultingInterface for
|
impl VaultingInterface for for GetVaultFingerprint
| null | null | null | null | null | null | null | null |
pub struct PaypalPaymentsSyncResponse {
id: String,
status: PaypalPaymentStatus,
amount: OrderAmount,
invoice_id: Option<String>,
supplementary_data: PaypalSupplementaryData,
}
|
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 42
|
rust
|
PaypalPaymentsSyncResponse
| null | null | null | null | null | null | null | null | null | null | null |
impl api::RefundExecute for Nexinets {}
|
crates/hyperswitch_connectors/src/connectors/nexinets.rs
|
hyperswitch_connectors
|
impl_block
| 11
|
rust
| null |
Nexinets
|
api::RefundExecute for
|
impl api::RefundExecute for for Nexinets
| null | null | null | null | null | null | null | null |
Documentation: api-reference/v1/routing/routing--activate-config.mdx
# Type: Doc File
---
openapi: post /routing/{routing_algorithm_id}/activate
---
|
api-reference/v1/routing/routing--activate-config.mdx
| null |
doc_file
| 37
|
doc
| null | null | null | null | null | null | null | null | null | null | null | null |
pub fn from_storage(refund: &'a Refund) -> Self {
Self {
internal_reference_id: &refund.internal_reference_id,
refund_id: &refund.refund_id,
payment_id: &refund.payment_id,
merchant_id: &refund.merchant_id,
connector_transaction_id: refund.get_connector_transaction_id(),
connector: &refund.connector,
connector_refund_id: refund.get_optional_connector_refund_id(),
external_reference_id: refund.external_reference_id.as_ref(),
refund_type: &refund.refund_type,
total_amount: &refund.total_amount,
currency: &refund.currency,
refund_amount: &refund.refund_amount,
refund_status: &refund.refund_status,
sent_to_gateway: &refund.sent_to_gateway,
refund_error_message: refund.refund_error_message.as_ref(),
refund_arn: refund.refund_arn.as_ref(),
created_at: refund.created_at.assume_utc(),
modified_at: refund.modified_at.assume_utc(),
description: refund.description.as_ref(),
attempt_id: &refund.attempt_id,
refund_reason: refund.refund_reason.as_ref(),
refund_error_code: refund.refund_error_code.as_ref(),
profile_id: refund.profile_id.as_ref(),
organization_id: &refund.organization_id,
}
}
|
crates/router/src/services/kafka/refund_event.rs
|
router
|
function_signature
| 272
|
rust
| null | null | null | null |
from_storage
| null | null | null | null | null | null | null |
OpenAPI Block Path: paths."/payment_methods/{method_id}/update"
{
"post": {
"tags": [
"Payment Methods"
],
"summary": "Payment Method - Update",
"description": "Update an existing payment method of a customer.\nThis API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments.",
"operationId": "Update a Payment method",
"parameters": [
{
"name": "method_id",
"in": "path",
"description": "The unique identifier for the Payment Method",
"required": true,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PaymentMethodUpdate"
}
}
},
"required": true
},
"responses": {
"200": {
"description": "Payment Method updated",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PaymentMethodResponse"
}
}
}
},
"404": {
"description": "Payment Method does not exist in records"
}
},
"security": [
{
"api_key": []
},
{
"publishable_key": []
}
]
}
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 316
|
.json
| null | null | null | null | null |
openapi_spec
|
paths
|
[
"/payment_methods/{method_id}/update"
] | null | null | null | null |
/// For backwards compatibility, whenever new business labels are passed in
/// primary_business_details, create a profile
pub async fn create_profile_from_business_labels(
state: &SessionState,
db: &dyn StorageInterface,
key_store: &domain::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
new_business_details: Vec<admin_types::PrimaryBusinessDetails>,
) -> RouterResult<()> {
let key_manager_state = &state.into();
let merchant_account = db
.find_merchant_account_by_merchant_id(key_manager_state, merchant_id, key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let old_business_details = merchant_account
.primary_business_details
.clone()
.parse_value::<Vec<admin_types::PrimaryBusinessDetails>>("PrimaryBusinessDetails")
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "routing_algorithm",
})
.attach_printable("Invalid routing algorithm given")?;
// find the diff between two vectors
let business_profiles_to_create = new_business_details
.into_iter()
.filter(|business_details| !old_business_details.contains(business_details))
.collect::<Vec<_>>();
for business_profile in business_profiles_to_create {
let profile_name = format!("{}_{}", business_profile.country, business_profile.business);
let profile_create_request = admin_types::ProfileCreate {
profile_name: Some(profile_name),
..Default::default()
};
let profile_create_result = create_and_insert_business_profile(
state,
profile_create_request,
merchant_account.clone(),
key_store,
)
.await
.map_err(|profile_insert_error| {
// If there is any duplicate error, we need not take any action
logger::warn!("Profile already exists {profile_insert_error:?}");
});
// If a profile is created, then unset the default profile
if profile_create_result.is_ok() && merchant_account.default_profile.is_some() {
let unset_default_profile = domain::MerchantAccountUpdate::UnsetDefaultProfile;
db.update_merchant(
key_manager_state,
merchant_account.clone(),
unset_default_profile,
key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
}
}
Ok(())
}
|
crates/router/src/core/admin.rs
|
router
|
function_signature
| 498
|
rust
| null | null | null | null |
create_profile_from_business_labels
| null | null | null | null | null | null | null |
pub struct ExternalVaultProxy;
|
crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
|
hyperswitch_domain_models
|
struct_definition
| 6
|
rust
|
ExternalVaultProxy
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/router/tests/connectors/wellsfargo.rs
use masking::Secret;
use router::types::{self, api, domain, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct WellsfargoTest;
impl ConnectorActions for WellsfargoTest {}
impl utils::Connector for WellsfargoTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Wellsfargo;
utils::construct_connector_data_old(
Box::new(Wellsfargo::new()),
types::Connector::Wellsfargo,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.wellsfargo
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"wellsfargo".to_string()
}
}
static CONNECTOR: WellsfargoTest = WellsfargoTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (βΉ1.50) is greater than charge amount (βΉ1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
|
crates/router/tests/connectors/wellsfargo.rs
|
router
|
full_file
| 2,939
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl<O> VirInterpreterBackend<O>
where
O: Clone,
{
#[inline]
fn eval_comparison(comp: &vir::ValuedComparison, ctx: &types::Context) -> bool {
match &comp.logic {
vir::ValuedComparisonLogic::PositiveDisjunction => {
comp.values.iter().any(|v| ctx.check_presence(v))
}
vir::ValuedComparisonLogic::NegativeConjunction => {
comp.values.iter().all(|v| !ctx.check_presence(v))
}
}
}
#[inline]
fn eval_condition(cond: &vir::ValuedIfCondition, ctx: &types::Context) -> bool {
cond.iter().all(|comp| Self::eval_comparison(comp, ctx))
}
fn eval_statement(stmt: &vir::ValuedIfStatement, ctx: &types::Context) -> bool {
if Self::eval_condition(&stmt.condition, ctx) {
{
stmt.nested.as_ref().map_or(true, |nested_stmts| {
nested_stmts.iter().any(|s| Self::eval_statement(s, ctx))
})
}
} else {
false
}
}
fn eval_rule(rule: &vir::ValuedRule<O>, ctx: &types::Context) -> bool {
rule.statements
.iter()
.any(|stmt| Self::eval_statement(stmt, ctx))
}
fn eval_program(
program: &vir::ValuedProgram<O>,
ctx: &types::Context,
) -> backend::BackendOutput<O> {
program
.rules
.iter()
.find(|rule| Self::eval_rule(rule, ctx))
.map_or_else(
|| backend::BackendOutput {
connector_selection: program.default_selection.clone(),
rule_name: None,
},
|rule| backend::BackendOutput {
connector_selection: rule.connector_selection.clone(),
rule_name: Some(rule.name.clone()),
},
)
}
}
|
crates/euclid/src/backend/vir_interpreter.rs
|
euclid
|
impl_block
| 419
|
rust
| null |
VirInterpreterBackend
| null |
impl VirInterpreterBackend
| null | null | null | null | null | null | null | null |
impl api::PaymentVoid for Coingate {}
|
crates/hyperswitch_connectors/src/connectors/coingate.rs
|
hyperswitch_connectors
|
impl_block
| 10
|
rust
| null |
Coingate
|
api::PaymentVoid for
|
impl api::PaymentVoid for for Coingate
| null | null | null | null | null | null | null | null |
pub struct CybersourceConsumerAuthInformation {
ucaf_collection_indicator: Option<String>,
cavv: Option<Secret<String>>,
ucaf_authentication_data: Option<Secret<String>>,
xid: Option<String>,
directory_server_transaction_id: Option<Secret<String>>,
specification_version: Option<SemanticVersion>,
/// This field specifies the 3ds version
pa_specification_version: Option<SemanticVersion>,
/// Verification response enrollment status.
///
/// This field is supported only on Asia, Middle East, and Africa Gateway.
///
/// For external authentication, this field will always be "Y"
veres_enrolled: Option<String>,
/// Raw electronic commerce indicator (ECI)
eci_raw: Option<String>,
/// This field is supported only on Asia, Middle East, and Africa Gateway
/// Also needed for Credit Mutuel-CIC in France and Mastercard Identity Check transactions
/// This field is only applicable for Mastercard and Visa Transactions
pares_status: Option<CybersourceParesStatus>,
//This field is used to send the authentication date in yyyyMMDDHHMMSS format
authentication_date: Option<String>,
/// This field indicates the 3D Secure transaction flow. It is only supported for secure transactions in France.
/// The possible values are - CH (Challenge), FD (Frictionless with delegation), FR (Frictionless)
effective_authentication_type: Option<EffectiveAuthenticationType>,
/// This field indicates the authentication type or challenge presented to the cardholder at checkout.
challenge_code: Option<String>,
/// This field indicates the reason for payer authentication response status. It is only supported for secure transactions in France.
signed_pares_status_reason: Option<String>,
/// This field indicates the reason why strong authentication was cancelled. It is only supported for secure transactions in France.
challenge_cancel_code: Option<String>,
/// This field indicates the score calculated by the 3D Securing platform. It is only supported for secure transactions in France.
network_score: Option<u32>,
/// This is the transaction ID generated by the access control server. This field is supported only for secure transactions in France.
acs_transaction_id: Option<String>,
/// This is the algorithm for generating a cardholder authentication verification value (CAVV) or universal cardholder authentication field (UCAF) data.
cavv_algorithm: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 506
|
rust
|
CybersourceConsumerAuthInformation
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn generate_merchant_authentication_report(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<ReportRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GenerateAuthenticationReport;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {
let user = UserInterface::find_user_by_id(&*state.global_store, &user_id)
.await
.change_context(AnalyticsError::UnknownError)?;
let user_email = UserEmail::from_pii_email(user.email)
.change_context(AnalyticsError::UnknownError)?
.get_secret();
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let lambda_req = GenerateReportRequest {
request: payload,
merchant_id: Some(merchant_id.clone()),
auth: AuthInfo::MerchantLevel {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
},
email: user_email,
};
let json_bytes =
serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;
invoke_lambda(
&state.conf.report_download_config.authentication_function,
&state.conf.report_download_config.region,
&json_bytes,
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantReportRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/analytics.rs
|
router
|
function_signature
| 365
|
rust
| null | null | null | null |
generate_merchant_authentication_report
| null | null | null | null | null | null | null |
pub struct CardInfoFetch;
|
crates/router/src/core/cards_info.rs
|
router
|
struct_definition
| 6
|
rust
|
CardInfoFetch
| null | null | null | null | null | null | null | null | null | null | null |
impl PaymentAddress {
pub fn new(
shipping: Option<Address>,
billing: Option<Address>,
payment_method_billing: Option<Address>,
should_unify_address: Option<bool>,
) -> Self {
// billing -> .billing, this is the billing details passed in the root of payments request
// payment_method_billing -> .payment_method_data.billing
let unified_payment_method_billing = if should_unify_address.unwrap_or(true) {
// Merge the billing details field from both `payment.billing` and `payment.payment_method_data.billing`
// The unified payment_method_billing will be used as billing address and passed to the connector module
// This unification is required in order to provide backwards compatibility
// so that if `payment.billing` is passed it should be sent to the connector module
// Unify the billing details with `payment_method_data.billing`
payment_method_billing
.as_ref()
.map(|payment_method_billing| {
payment_method_billing
.clone()
.unify_address(billing.as_ref())
})
.or(billing.clone())
} else {
payment_method_billing.clone()
};
Self {
shipping,
billing,
unified_payment_method_billing,
payment_method_billing,
}
}
pub fn get_shipping(&self) -> Option<&Address> {
self.shipping.as_ref()
}
pub fn get_payment_method_billing(&self) -> Option<&Address> {
self.unified_payment_method_billing.as_ref()
}
/// Unify the billing details from `payment_method_data.[payment_method_data].billing details`.
/// Here the fields passed in payment_method_data_billing takes precedence
pub fn unify_with_payment_method_data_billing(
self,
payment_method_data_billing: Option<Address>,
) -> Self {
// Unify the billing details with `payment_method_data.billing_details`
let unified_payment_method_billing = payment_method_data_billing
.map(|payment_method_data_billing| {
payment_method_data_billing.unify_address(self.get_payment_method_billing())
})
.or(self.get_payment_method_billing().cloned());
Self {
shipping: self.shipping,
billing: self.billing,
unified_payment_method_billing,
payment_method_billing: self.payment_method_billing,
}
}
/// Unify the billing details from `payment_method_data.[payment_method_data].billing details`.
/// Here the `self` takes precedence
pub fn unify_with_payment_data_billing(
self,
other_payment_method_billing: Option<Address>,
) -> Self {
let unified_payment_method_billing = self
.get_payment_method_billing()
.map(|payment_method_billing| {
payment_method_billing
.clone()
.unify_address(other_payment_method_billing.as_ref())
})
.or(other_payment_method_billing);
Self {
shipping: self.shipping,
billing: self.billing,
unified_payment_method_billing,
payment_method_billing: self.payment_method_billing,
}
}
pub fn get_request_payment_method_billing(&self) -> Option<&Address> {
self.payment_method_billing.as_ref()
}
pub fn get_payment_billing(&self) -> Option<&Address> {
self.billing.as_ref()
}
}
|
crates/hyperswitch_domain_models/src/payment_address.rs
|
hyperswitch_domain_models
|
impl_block
| 685
|
rust
| null |
PaymentAddress
| null |
impl PaymentAddress
| null | null | null | null | null | null | null | null |
/// Generate a new GlobalAttemptId from a cell id
pub fn generate(cell_id: &super::CellId) -> Self {
let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Attempt);
Self(global_id)
}
|
crates/common_utils/src/id_type/global_id/payment.rs
|
common_utils
|
function_signature
| 56
|
rust
| null | null | null | null |
generate
| null | null | null | null | null | null | null |
File: crates/api_models/src/events/locker_migration.rs
use common_utils::events::ApiEventMetric;
use crate::locker_migration::MigrateCardResponse;
impl ApiEventMetric for MigrateCardResponse {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::RustLocker)
}
}
|
crates/api_models/src/events/locker_migration.rs
|
api_models
|
full_file
| 83
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl api::PaymentVoid for Novalnet {}
|
crates/hyperswitch_connectors/src/connectors/novalnet.rs
|
hyperswitch_connectors
|
impl_block
| 10
|
rust
| null |
Novalnet
|
api::PaymentVoid for
|
impl api::PaymentVoid for for Novalnet
| null | null | null | null | null | null | null | null |
File: crates/router/src/core/cache.rs
Public functions: 1
use common_utils::errors::CustomResult;
use error_stack::{report, ResultExt};
use storage_impl::redis::cache::{redact_from_redis_and_publish, CacheKind};
use super::errors;
use crate::{routes::SessionState, services};
pub async fn invalidate(
state: SessionState,
key: &str,
) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ApiErrorResponse> {
let store = state.store.as_ref();
let result = redact_from_redis_and_publish(
store.get_cache_store().as_ref(),
[CacheKind::All(key.into())],
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
// If the message was published to atleast one channel
// then return status Ok
if result > 0 {
Ok(services::api::ApplicationResponse::StatusOk)
} else {
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate cache"))
}
}
|
crates/router/src/core/cache.rs
|
router
|
full_file
| 230
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl Opayo {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
|
crates/hyperswitch_connectors/src/connectors/opayo.rs
|
hyperswitch_connectors
|
impl_block
| 33
|
rust
| null |
Opayo
| null |
impl Opayo
| null | null | null | null | null | null | null | null |
impl Noon {
pub const fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
|
crates/hyperswitch_connectors/src/connectors/noon.rs
|
hyperswitch_connectors
|
impl_block
| 34
|
rust
| null |
Noon
| null |
impl Noon
| null | null | null | null | null | null | null | null |
OpenAPI Block Path: paths."/refunds/{refund_id}"
{
"get": {
"tags": [
"Refunds"
],
"summary": "Refunds - Retrieve",
"description": "Retrieves a Refund. This may be used to get the status of a previously initiated refund",
"operationId": "Retrieve a Refund",
"parameters": [
{
"name": "refund_id",
"in": "path",
"description": "The identifier for refund",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Refund retrieved",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/RefundResponse"
}
}
}
},
"404": {
"description": "Refund does not exist in our records"
}
},
"security": [
{
"api_key": []
}
]
},
"post": {
"tags": [
"Refunds"
],
"summary": "Refunds - Update",
"description": "Updates the properties of a Refund object. This API can be used to attach a reason for the refund or metadata fields",
"operationId": "Update a Refund",
"parameters": [
{
"name": "refund_id",
"in": "path",
"description": "The identifier for refund",
"required": true,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/RefundUpdateRequest"
},
"examples": {
"Update refund reason": {
"value": {
"reason": "Paid by mistake"
}
}
}
}
},
"required": true
},
"responses": {
"200": {
"description": "Refund updated",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/RefundResponse"
}
}
}
},
"400": {
"description": "Missing Mandatory fields",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/GenericErrorResponseOpenApi"
}
}
}
}
},
"security": [
{
"api_key": []
}
]
}
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 580
|
.json
| null | null | null | null | null |
openapi_spec
|
paths
|
[
"/refunds/{refund_id}"
] | null | null | null | null |
pub async fn api_key_list(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<api_types::ListApiKeyConstraints>,
) -> impl Responder {
let flow = Flow::ApiKeyList;
let payload = query.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state,
auth::AuthenticationDataWithoutProfile {
merchant_account, ..
},
payload,
_| async move {
let merchant_id = merchant_account.get_id().to_owned();
api_keys::list_api_keys(state, merchant_id, payload.limit, payload.skip).await
},
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantApiKeyRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/api_keys.rs
|
router
|
function_signature
| 208
|
rust
| null | null | null | null |
api_key_list
| null | null | null | null | null | null | null |
shipping_address_id: storage_model.shipping_address_id,
billing_address_id: storage_model.billing_address_id,
statement_descriptor_name: storage_model.statement_descriptor_name,
statement_descriptor_suffix: storage_model.statement_descriptor_suffix,
created_at: storage_model.created_at,
modified_at: storage_model.modified_at,
last_synced: storage_model.last_synced,
setup_future_usage: storage_model.setup_future_usage,
off_session: storage_model.off_session,
client_secret: storage_model.client_secret,
active_attempt: RemoteStorageObject::ForeignID(storage_model.active_attempt_id),
business_country: storage_model.business_country,
business_label: storage_model.business_label,
order_details: storage_model.order_details,
allowed_payment_method_types: storage_model.allowed_payment_method_types,
connector_metadata: storage_model.connector_metadata,
feature_metadata: storage_model.feature_metadata,
attempt_count: storage_model.attempt_count,
profile_id: storage_model.profile_id,
merchant_decision: storage_model.merchant_decision,
payment_link_id: storage_model.payment_link_id,
payment_confirm_source: storage_model.payment_confirm_source,
updated_by: storage_model.updated_by,
surcharge_applicable: storage_model.surcharge_applicable,
request_incremental_authorization: storage_model.request_incremental_authorization,
incremental_authorization_allowed: storage_model.incremental_authorization_allowed,
authorization_count: storage_model.authorization_count,
fingerprint_id: storage_model.fingerprint_id,
session_expiry: storage_model.session_expiry,
request_external_three_ds_authentication: storage_model
.request_external_three_ds_authentication,
split_payments: storage_model.split_payments,
frm_metadata: storage_model.frm_metadata,
shipping_cost: storage_model.shipping_cost,
tax_details: storage_model.tax_details,
customer_details: data.customer_details,
billing_details: data.billing_details,
merchant_order_reference_id: storage_model.merchant_order_reference_id,
shipping_details: data.shipping_details,
is_payment_processor_token_flow: storage_model.is_payment_processor_token_flow,
organization_id: storage_model.organization_id,
skip_external_tax_calculation: storage_model.skip_external_tax_calculation,
request_extended_authorization: storage_model.request_extended_authorization,
psd2_sca_exemption_type: storage_model.psd2_sca_exemption_type,
processor_merchant_id: storage_model
.processor_merchant_id
.unwrap_or(storage_model.merchant_id),
created_by: storage_model
.created_by
.and_then(|created_by| created_by.parse::<CreatedBy>().ok()),
force_3ds_challenge: storage_model.force_3ds_challenge,
force_3ds_challenge_trigger: storage_model.force_3ds_challenge_trigger,
is_iframe_redirection_enabled: storage_model.is_iframe_redirection_enabled,
is_payment_id_from_merchant: storage_model.is_payment_id_from_merchant,
payment_channel: storage_model.payment_channel,
tax_status: storage_model.tax_status,
discount_amount: storage_model.discount_amount,
shipping_amount_tax: storage_model.shipping_amount_tax,
duty_amount: storage_model.duty_amount,
order_date: storage_model.order_date,
enable_partial_authorization: storage_model.enable_partial_authorization,
})
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting payment intent".to_string(),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(DieselPaymentIntentNew {
payment_id: self.payment_id,
merchant_id: self.merchant_id,
status: self.status,
amount: self.amount,
currency: self.currency,
amount_captured: self.amount_captured,
customer_id: self.customer_id,
description: self.description,
return_url: None, // deprecated
metadata: self.metadata,
connector_id: self.connector_id,
shipping_address_id: self.shipping_address_id,
billing_address_id: self.billing_address_id,
statement_descriptor_name: self.statement_descriptor_name,
statement_descriptor_suffix: self.statement_descriptor_suffix,
created_at: self.created_at,
modified_at: self.modified_at,
last_synced: self.last_synced,
setup_future_usage: self.setup_future_usage,
off_session: self.off_session,
client_secret: self.client_secret,
active_attempt_id: self.active_attempt.get_id(),
business_country: self.business_country,
business_label: self.business_label,
order_details: self.order_details,
allowed_payment_method_types: self.allowed_payment_method_types,
connector_metadata: self.connector_metadata,
feature_metadata: self.feature_metadata,
attempt_count: self.attempt_count,
profile_id: self.profile_id,
merchant_decision: self.merchant_decision,
payment_link_id: self.payment_link_id,
payment_confirm_source: self.payment_confirm_source,
updated_by: self.updated_by,
surcharge_applicable: self.surcharge_applicable,
request_incremental_authorization: self.request_incremental_authorization,
incremental_authorization_allowed: self.incremental_authorization_allowed,
authorization_count: self.authorization_count,
fingerprint_id: self.fingerprint_id,
session_expiry: self.session_expiry,
request_external_three_ds_authentication: self.request_external_three_ds_authentication,
charges: None,
split_payments: self.split_payments,
frm_metadata: self.frm_metadata,
customer_details: self.customer_details.map(Encryption::from),
billing_details: self.billing_details.map(Encryption::from),
merchant_order_reference_id: self.merchant_order_reference_id,
shipping_details: self.shipping_details.map(Encryption::from),
is_payment_processor_token_flow: self.is_payment_processor_token_flow,
organization_id: self.organization_id,
shipping_cost: self.shipping_cost,
tax_details: self.tax_details,
skip_external_tax_calculation: self.skip_external_tax_calculation,
request_extended_authorization: self.request_extended_authorization,
psd2_sca_exemption_type: self.psd2_sca_exemption_type,
platform_merchant_id: None,
processor_merchant_id: Some(self.processor_merchant_id),
created_by: self.created_by.map(|cb| cb.to_string()),
force_3ds_challenge: self.force_3ds_challenge,
force_3ds_challenge_trigger: self.force_3ds_challenge_trigger,
is_iframe_redirection_enabled: self.is_iframe_redirection_enabled,
extended_return_url: self.return_url,
is_payment_id_from_merchant: self.is_payment_id_from_merchant,
payment_channel: self.payment_channel,
tax_status: self.tax_status,
discount_amount: self.discount_amount,
order_date: self.order_date,
shipping_amount_tax: self.shipping_amount_tax,
duty_amount: self.duty_amount,
enable_partial_authorization: self.enable_partial_authorization,
})
}
}
|
crates/hyperswitch_domain_models/src/payments/payment_intent.rs#chunk2
|
hyperswitch_domain_models
|
chunk
| 1,447
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct TokenizedCardData {
card_data: ArchipelTokenizedCard,
wallet_information: ArchipelWalletInformation,
}
|
crates/hyperswitch_connectors/src/connectors/archipel/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 27
|
rust
|
TokenizedCardData
| null | null | null | null | null | null | null | null | null | null | null |
pub struct NordeaOAuthExchangeRequest {
/// authorization_code flow
#[serde(skip_serializing_if = "Option::is_none")]
pub code: Option<Secret<String>>,
pub grant_type: GrantType,
#[serde(skip_serializing_if = "Option::is_none")]
pub redirect_uri: Option<String>,
/// refresh_token flow
#[serde(skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<Secret<String>>,
}
|
crates/hyperswitch_connectors/src/connectors/nordea/requests.rs
|
hyperswitch_connectors
|
struct_definition
| 98
|
rust
|
NordeaOAuthExchangeRequest
| null | null | null | null | null | null | null | null | null | null | null |
impl api::Payment for Rapyd {}
|
crates/hyperswitch_connectors/src/connectors/rapyd.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Rapyd
|
api::Payment for
|
impl api::Payment for for Rapyd
| null | null | null | null | null | null | null | null |
#[proc_macro]
pub fn knowledge(ts: TokenStream) -> TokenStream {
match inner::knowledge_inner(ts.into()) {
Ok(ts) => ts.into(),
Err(e) => e.into_compile_error().into(),
}
}
|
crates/euclid_macros/src/lib.rs
|
euclid_macros
|
macro
| 50
|
rust
| null | null | null | null | null | null | null | null |
proc_function_like
| null | null | null |
pub fn get_all_captures(&self) -> Vec<&storage::Capture> {
self.all_captures
.iter()
.map(|key_value| key_value.1)
.collect()
}
|
crates/router/src/core/payments/types.rs
|
router
|
function_signature
| 47
|
rust
| null | null | null | null |
get_all_captures
| null | null | null | null | null | null | null |
pub trait DecryptedDataConversion<T: Clone, S: Strategy<T> + Send>: Sized {
fn convert(
value: &DecryptedData,
encryption: Encryption,
) -> CustomResult<Self, errors::CryptoError>;
}
|
crates/common_utils/src/types/keymanager.rs
|
common_utils
|
trait_definition
| 50
|
rust
| null | null |
DecryptedDataConversion
| null | null | null | null | null | null | null | null | null |
impl RefundMetricAccumulator for CountAccumulator {
type MetricOutput = Option<u64>;
#[inline]
fn add_metrics_bucket(&mut self, metrics: &RefundMetricRow) {
self.count = match (self.count, metrics.count) {
(None, None) => None,
(None, i @ Some(_)) | (i @ Some(_), None) => i,
(Some(a), Some(b)) => Some(a + b),
}
}
#[inline]
fn collect(self) -> Self::MetricOutput {
self.count.and_then(|i| u64::try_from(i).ok())
}
}
|
crates/analytics/src/refunds/accumulator.rs
|
analytics
|
impl_block
| 142
|
rust
| null |
CountAccumulator
|
RefundMetricAccumulator for
|
impl RefundMetricAccumulator for for CountAccumulator
| null | null | null | null | null | null | null | null |
pub async fn get_filters_for_payments(
state: SessionState,
merchant_context: domain::MerchantContext,
time_range: common_utils::types::TimeRange,
) -> RouterResponse<api::PaymentListFilters> {
let db = state.store.as_ref();
let pi = db
.filter_payment_intents_by_time_range_constraints(
&(&state).into(),
merchant_context.get_merchant_account().get_id(),
&time_range,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let filters = db
.get_filters_for_payments(
pi.as_slice(),
merchant_context.get_merchant_account().get_id(),
// since OLAP doesn't have KV. Force to get the data from PSQL.
storage_enums::MerchantStorageScheme::PostgresOnly,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
Ok(services::ApplicationResponse::Json(
api::PaymentListFilters {
connector: filters.connector,
currency: filters.currency,
status: filters.status,
payment_method: filters.payment_method,
payment_method_type: filters.payment_method_type,
authentication_type: filters.authentication_type,
},
))
}
|
crates/router/src/core/payments.rs
|
router
|
function_signature
| 283
|
rust
| null | null | null | null |
get_filters_for_payments
| null | null | null | null | null | null | null |
pub async fn verify_email_request(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::SendVerifyEmailRequest>,
query: web::Query<user_api::AuthIdAndThemeIdQueryParam>,
) -> HttpResponse {
let flow = Flow::VerifyEmailRequest;
let query_params = query.into_inner();
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
json_payload.into_inner(),
|state, _: (), req_body, _| {
user_core::send_verification_mail(
state,
req_body,
query_params.auth_id.clone(),
query_params.theme_id.clone(),
)
},
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/user.rs
|
router
|
function_signature
| 175
|
rust
| null | null | null | null |
verify_email_request
| null | null | null | null | null | null | null |
pub struct SignifydErrorResponse {
pub messages: Vec<String>,
pub errors: serde_json::Value,
}
|
crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs
|
hyperswitch_connectors
|
struct_definition
| 24
|
rust
|
SignifydErrorResponse
| null | null | null | null | null | null | null | null | null | null | null |
impl api::Refund for Zen {}
|
crates/hyperswitch_connectors/src/connectors/zen.rs
|
hyperswitch_connectors
|
impl_block
| 8
|
rust
| null |
Zen
|
api::Refund for
|
impl api::Refund for for Zen
| null | null | null | null | null | null | null | null |
File: crates/hyperswitch_domain_models/src/gsm.rs
Public structs: 2
use common_utils::{errors::ValidationError, ext_traits::StringExt};
use serde::{self, Deserialize, Serialize};
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct GatewayStatusMap {
pub connector: String,
pub flow: String,
pub sub_flow: String,
pub code: String,
pub message: String,
pub status: String,
pub router_error: Option<String>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub error_category: Option<common_enums::ErrorCategory>,
pub feature_data: common_types::domain::GsmFeatureData,
pub feature: common_enums::GsmFeature,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GatewayStatusMappingUpdate {
pub status: Option<String>,
pub router_error: Option<Option<String>>,
pub decision: Option<common_enums::GsmDecision>,
pub step_up_possible: Option<bool>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub error_category: Option<common_enums::ErrorCategory>,
pub clear_pan_possible: Option<bool>,
pub feature_data: Option<common_types::domain::GsmFeatureData>,
pub feature: Option<common_enums::GsmFeature>,
}
impl TryFrom<GatewayStatusMap> for diesel_models::gsm::GatewayStatusMappingNew {
type Error = error_stack::Report<ValidationError>;
fn try_from(value: GatewayStatusMap) -> Result<Self, Self::Error> {
Ok(Self {
connector: value.connector.to_string(),
flow: value.flow,
sub_flow: value.sub_flow,
code: value.code,
message: value.message,
status: value.status.clone(),
router_error: value.router_error,
decision: value.feature_data.get_decision().to_string(),
step_up_possible: value
.feature_data
.get_retry_feature_data()
.map(|retry_feature_data| retry_feature_data.is_step_up_possible())
.unwrap_or(false),
unified_code: value.unified_code,
unified_message: value.unified_message,
error_category: value.error_category,
clear_pan_possible: value
.feature_data
.get_retry_feature_data()
.map(|retry_feature_data| retry_feature_data.is_clear_pan_possible())
.unwrap_or(false),
feature_data: Some(value.feature_data),
feature: Some(value.feature),
})
}
}
impl TryFrom<GatewayStatusMappingUpdate> for diesel_models::gsm::GatewayStatusMappingUpdate {
type Error = error_stack::Report<ValidationError>;
fn try_from(value: GatewayStatusMappingUpdate) -> Result<Self, Self::Error> {
Ok(Self {
status: value.status,
router_error: value.router_error,
decision: value.decision.map(|gsm_decision| gsm_decision.to_string()),
step_up_possible: value.step_up_possible,
unified_code: value.unified_code,
unified_message: value.unified_message,
error_category: value.error_category,
clear_pan_possible: value.clear_pan_possible,
feature_data: value.feature_data,
feature: value.feature,
})
}
}
impl TryFrom<diesel_models::gsm::GatewayStatusMap> for GatewayStatusMap {
type Error = ValidationError;
fn try_from(item: diesel_models::gsm::GatewayStatusMap) -> Result<Self, Self::Error> {
let decision =
StringExt::<common_enums::GsmDecision>::parse_enum(item.decision, "GsmDecision")
.map_err(|_| ValidationError::InvalidValue {
message: "Failed to parse GsmDecision".to_string(),
})?;
let db_feature_data = item.feature_data;
// The only case where `FeatureData` can be null is for legacy records
// (i.e., records created before `FeatureData` and related features were introduced).
// At that time, the only supported feature was `Retry`, so it's safe to default to it.
let feature_data = match db_feature_data {
Some(common_types::domain::GsmFeatureData::Retry(data)) => {
common_types::domain::GsmFeatureData::Retry(data)
}
None => common_types::domain::GsmFeatureData::Retry(
common_types::domain::RetryFeatureData {
step_up_possible: item.step_up_possible,
clear_pan_possible: item.clear_pan_possible,
alternate_network_possible: false,
decision,
},
),
};
let feature = item.feature.unwrap_or(common_enums::GsmFeature::Retry);
Ok(Self {
connector: item.connector,
flow: item.flow,
sub_flow: item.sub_flow,
code: item.code,
message: item.message,
status: item.status,
router_error: item.router_error,
unified_code: item.unified_code,
unified_message: item.unified_message,
error_category: item.error_category,
feature_data,
feature,
})
}
}
|
crates/hyperswitch_domain_models/src/gsm.rs
|
hyperswitch_domain_models
|
full_file
| 1,075
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct PayloadRefundResponse {
pub amount: f64,
#[serde(rename = "id")]
pub transaction_id: String,
pub ledger: Vec<RefundsLedger>,
#[serde(rename = "payment_method_id")]
pub connector_payment_method_id: Option<Secret<String>>,
pub processing_id: Option<Secret<String>>,
pub ref_number: Option<String>,
pub status: RefundStatus,
pub status_code: Option<String>,
pub status_message: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/payload/responses.rs
|
hyperswitch_connectors
|
struct_definition
| 106
|
rust
|
PayloadRefundResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub fn generate_signature(
&self,
auth: bankofamerica::BankOfAmericaAuthType,
host: String,
resource: &str,
payload: &String,
date: OffsetDateTime,
http_method: Method,
) -> CustomResult<String, errors::ConnectorError> {
let bankofamerica::BankOfAmericaAuthType {
api_key,
merchant_account,
api_secret,
} = auth;
let is_post_method = matches!(http_method, Method::Post);
let digest_str = if is_post_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 {
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/bankofamerica.rs
|
hyperswitch_connectors
|
function_signature
| 389
|
rust
| null | null | null | null |
generate_signature
| null | null | null | null | null | null | null |
pub fn get_connector_payment_id(&self) -> Option<&str> {
self.connector_payment_id.as_deref()
}
|
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
|
hyperswitch_domain_models
|
function_signature
| 26
|
rust
| null | null | null | null |
get_connector_payment_id
| null | null | null | null | null | null | null |
Documentation: api-reference/v1/payments/payments--session-token.mdx
# Type: Doc File
---
openapi: post /payments/session_tokens
---
|
api-reference/v1/payments/payments--session-token.mdx
| null |
doc_file
| 33
|
doc
| null | null | null | null | null | null | null | null | null | null | null | null |
pub struct PayuPaymentsResponse {
pub status: PayuPaymentStatusData,
pub redirect_uri: String,
pub iframe_allowed: Option<bool>,
pub three_ds_protocol_version: Option<String>,
pub order_id: String,
pub ext_order_id: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/payu/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 59
|
rust
|
PayuPaymentsResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn update_connector_mandate_id(
db: &dyn StorageInterface,
merchant_id: &id_type::MerchantId,
mandate_ids_opt: Option<String>,
payment_method_id: Option<String>,
resp: Result<types::PaymentsResponseData, types::ErrorResponse>,
storage_scheme: MerchantStorageScheme,
) -> RouterResponse<mandates::MandateResponse> {
let mandate_details = Option::foreign_from(resp);
let connector_mandate_id = mandate_details
.clone()
.map(|md| {
md.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.map(masking::Secret::new)
})
.transpose()?;
//Ignore updation if the payment_attempt mandate_id or connector_mandate_id is not present
if let Some((mandate_id, connector_id)) = mandate_ids_opt.zip(connector_mandate_id) {
let mandate = db
.find_mandate_by_merchant_id_mandate_id(merchant_id, &mandate_id, storage_scheme)
.await
.change_context(errors::ApiErrorResponse::MandateNotFound)?;
let update_mandate_details = match payment_method_id {
Some(pmd_id) => storage::MandateUpdate::ConnectorMandateIdUpdate {
connector_mandate_id: mandate_details
.and_then(|mandate_reference| mandate_reference.connector_mandate_id),
connector_mandate_ids: Some(connector_id),
payment_method_id: pmd_id,
original_payment_id: None,
},
None => storage::MandateUpdate::ConnectorReferenceUpdate {
connector_mandate_ids: Some(connector_id),
},
};
// only update the connector_mandate_id if existing is none
if mandate.connector_mandate_id.is_none() {
db.update_mandate_by_merchant_id_mandate_id(
merchant_id,
&mandate_id,
update_mandate_details,
mandate,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::MandateUpdateFailed)?;
}
}
Ok(services::ApplicationResponse::StatusOk)
}
|
crates/router/src/core/mandate.rs
|
router
|
function_signature
| 469
|
rust
| null | null | null | null |
update_connector_mandate_id
| null | null | null | null | null | null | null |
pub struct EbanxPayoutDetails {
name: Secret<String>,
email: Option<Email>,
document: Option<Secret<String>>,
document_type: Option<EbanxDocumentType>,
bank_info: EbanxBankDetails,
}
|
crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 52
|
rust
|
EbanxPayoutDetails
| null | null | null | null | null | null | null | null | null | null | null |
pub struct GooglePayPaymentMethodInfo {
/// The name of the card network
pub card_network: String,
/// The details of the card
pub card_details: String,
//assurance_details of the card
pub assurance_details: Option<GooglePayAssuranceDetails>,
}
|
crates/hyperswitch_domain_models/src/payment_method_data.rs
|
hyperswitch_domain_models
|
struct_definition
| 61
|
rust
|
GooglePayPaymentMethodInfo
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn delete_gsm_rule(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<gsm_api_types::GsmDeleteRequest>,
) -> impl Responder {
let payload = json_payload.into_inner();
let flow = Flow::GsmRuleDelete;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, payload, _| gsm::delete_gsm_rule(state, payload),
&ADMIN_API_AUTH,
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/gsm.rs
|
router
|
function_signature
| 131
|
rust
| null | null | null | null |
delete_gsm_rule
| null | null | null | null | null | null | null |
File: crates/common_utils/src/ext_traits.rs
//! This module holds traits for extending functionalities for existing datatypes
//! & inbuilt datatypes.
use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface, Secret, Strategy};
use quick_xml::de;
#[cfg(all(feature = "logs", feature = "async_ext"))]
use router_env::logger;
use serde::{Deserialize, Serialize};
use crate::{
crypto,
errors::{self, CustomResult},
fp_utils::when,
};
/// Encode interface
/// An interface for performing type conversions and serialization
pub trait Encode<'e>
where
Self: 'e + std::fmt::Debug,
{
// If needed get type information/custom error implementation.
///
/// Converting `Self` into an intermediate representation `<P>`
/// and then performing encoding operation using the `Serialize` trait from `serde`
/// Specifically to convert into json, by using `serde_json`
fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize;
/// Converting `Self` into an intermediate representation `<P>`
/// and then performing encoding operation using the `Serialize` trait from `serde`
/// Specifically, to convert into urlencoded, by using `serde_urlencoded`
fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize;
/// Functionality, for specifically encoding `Self` into `String`
/// after serialization by using `serde::Serialize`
fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize;
/// Functionality, for specifically encoding `Self` into `String`
/// after serialization by using `serde::Serialize`
/// specifically, to convert into JSON `String`.
fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize;
/// Functionality, for specifically encoding `Self` into `String`
/// after serialization by using `serde::Serialize`
/// specifically, to convert into XML `String`.
fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize;
/// Functionality, for specifically encoding `Self` into `serde_json::Value`
/// after serialization by using `serde::Serialize`
fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError>
where
Self: Serialize;
/// Functionality, for specifically encoding `Self` into `Vec<u8>`
/// after serialization by using `serde::Serialize`
fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError>
where
Self: Serialize;
}
impl<'e, A> Encode<'e> for A
where
Self: 'e + std::fmt::Debug,
{
fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize,
{
serde_json::to_string(
&P::try_from(self).change_context(errors::ParsingError::UnknownError)?,
)
.change_context(errors::ParsingError::EncodeError("string"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize,
{
serde_urlencoded::to_string(
&P::try_from(self).change_context(errors::ParsingError::UnknownError)?,
)
.change_context(errors::ParsingError::EncodeError("url-encoded"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
// Check without two functions can we combine this
fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize,
{
serde_urlencoded::to_string(self)
.change_context(errors::ParsingError::EncodeError("url-encoded"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize,
{
serde_json::to_string(self)
.change_context(errors::ParsingError::EncodeError("json"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize,
{
quick_xml::se::to_string(self)
.change_context(errors::ParsingError::EncodeError("xml"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError>
where
Self: Serialize,
{
serde_json::to_value(self)
.change_context(errors::ParsingError::EncodeError("json-value"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a value"))
}
fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError>
where
Self: Serialize,
{
serde_json::to_vec(self)
.change_context(errors::ParsingError::EncodeError("byte-vec"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a value"))
}
}
/// Extending functionalities of `bytes::Bytes`
pub trait BytesExt {
/// Convert `bytes::Bytes` into type `<T>` using `serde::Deserialize`
fn parse_struct<'de, T>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>;
}
impl BytesExt for bytes::Bytes {
fn parse_struct<'de, T>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>,
{
use bytes::Buf;
serde_json::from_slice::<T>(self.chunk())
.change_context(errors::ParsingError::StructParseFailure(type_name))
.attach_printable_lazy(|| {
let variable_type = std::any::type_name::<T>();
format!("Unable to parse {variable_type} from bytes {self:?}")
})
}
}
/// Extending functionalities of `[u8]` for performing parsing
pub trait ByteSliceExt {
/// Convert `[u8]` into type `<T>` by using `serde::Deserialize`
fn parse_struct<'de, T>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>;
}
impl ByteSliceExt for [u8] {
#[track_caller]
fn parse_struct<'de, T>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>,
{
serde_json::from_slice(self)
.change_context(errors::ParsingError::StructParseFailure(type_name))
.attach_printable_lazy(|| format!("Unable to parse {type_name} from &[u8] {:?}", &self))
}
}
/// Extending functionalities of `serde_json::Value` for performing parsing
pub trait ValueExt {
/// Convert `serde_json::Value` into type `<T>` by using `serde::Deserialize`
fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: serde::de::DeserializeOwned;
}
impl ValueExt for serde_json::Value {
fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: serde::de::DeserializeOwned,
{
let debug = format!(
"Unable to parse {type_name} from serde_json::Value: {:?}",
&self
);
serde_json::from_value::<T>(self)
.change_context(errors::ParsingError::StructParseFailure(type_name))
.attach_printable_lazy(|| debug)
}
}
impl<MaskingStrategy> ValueExt for Secret<serde_json::Value, MaskingStrategy>
where
MaskingStrategy: Strategy<serde_json::Value>,
{
fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: serde::de::DeserializeOwned,
{
self.expose().parse_value(type_name)
}
}
impl<E: ValueExt + Clone> ValueExt for crypto::Encryptable<E> {
fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: serde::de::DeserializeOwned,
{
self.into_inner().parse_value(type_name)
}
}
/// Extending functionalities of `String` for performing parsing
pub trait StringExt<T> {
/// Convert `String` into type `<T>` (which being an `enum`)
fn parse_enum(self, enum_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: std::str::FromStr,
// Requirement for converting the `Err` variant of `FromStr` to `Report<Err>`
<T as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static;
/// Convert `serde_json::Value` into type `<T>` by using `serde::Deserialize`
fn parse_struct<'de>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>;
}
impl<T> StringExt<T> for String {
fn parse_enum(self, enum_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: std::str::FromStr,
<T as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static,
{
T::from_str(&self)
.change_context(errors::ParsingError::EnumParseFailure(enum_name))
.attach_printable_lazy(|| format!("Invalid enum variant {self:?} for enum {enum_name}"))
}
fn parse_struct<'de>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>,
{
serde_json::from_str::<T>(self)
.change_context(errors::ParsingError::StructParseFailure(type_name))
.attach_printable_lazy(|| {
format!("Unable to parse {type_name} from string {:?}", &self)
})
}
}
/// Extending functionalities of Wrapper types for idiomatic
#[cfg(feature = "async_ext")]
#[cfg_attr(feature = "async_ext", async_trait::async_trait)]
pub trait AsyncExt<A> {
/// Output type of the map function
type WrappedSelf<T>;
/// Extending map by allowing functions which are async
async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = B> + Send;
/// Extending the `and_then` by allowing functions which are async
async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send;
/// Extending `unwrap_or_else` to allow async fallback
async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = A> + Send;
}
#[cfg(feature = "async_ext")]
#[cfg_attr(feature = "async_ext", async_trait::async_trait)]
impl<A: Send, E: Send + std::fmt::Debug> AsyncExt<A> for Result<A, E> {
type WrappedSelf<T> = Result<T, E>;
async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send,
{
match self {
Ok(a) => func(a).await,
Err(err) => Err(err),
}
}
async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = B> + Send,
{
match self {
Ok(a) => Ok(func(a).await),
Err(err) => Err(err),
}
}
async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = A> + Send,
{
match self {
Ok(a) => a,
Err(_err) => {
#[cfg(feature = "logs")]
logger::error!("Error: {:?}", _err);
func().await
}
}
}
}
#[cfg(feature = "async_ext")]
#[cfg_attr(feature = "async_ext", async_trait::async_trait)]
impl<A: Send> AsyncExt<A> for Option<A> {
type WrappedSelf<T> = Option<T>;
async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send,
{
match self {
Some(a) => func(a).await,
None => None,
}
}
async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = B> + Send,
{
match self {
Some(a) => Some(func(a).await),
None => None,
}
}
async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = A> + Send,
{
match self {
Some(a) => a,
None => func().await,
}
}
}
/// Extension trait for validating application configuration. This trait provides utilities to
/// check whether the value is either the default value or is empty.
pub trait ConfigExt {
/// Returns whether the value of `self` is the default value for `Self`.
fn is_default(&self) -> bool
where
Self: Default + PartialEq<Self>,
{
*self == Self::default()
}
/// Returns whether the value of `self` is empty after trimming whitespace on both left and
/// right ends.
fn is_empty_after_trim(&self) -> bool;
/// Returns whether the value of `self` is the default value for `Self` or empty after trimming
/// whitespace on both left and right ends.
fn is_default_or_empty(&self) -> bool
where
Self: Default + PartialEq<Self>,
{
self.is_default() || self.is_empty_after_trim()
}
}
impl ConfigExt for u32 {
fn is_empty_after_trim(&self) -> bool {
false
}
}
impl ConfigExt for String {
fn is_empty_after_trim(&self) -> bool {
self.trim().is_empty()
}
}
impl<T, U> ConfigExt for Secret<T, U>
where
T: ConfigExt + Default + PartialEq<T>,
U: Strategy<T>,
{
fn is_default(&self) -> bool
where
T: Default + PartialEq<T>,
{
*self.peek() == T::default()
}
fn is_empty_after_trim(&self) -> bool {
self.peek().is_empty_after_trim()
}
fn is_default_or_empty(&self) -> bool
where
T: Default + PartialEq<T>,
{
self.peek().is_default() || self.peek().is_empty_after_trim()
}
}
/// Extension trait for deserializing XML strings using `quick-xml` crate
pub trait XmlExt {
/// Deserialize an XML string into the specified type `<T>`.
fn parse_xml<T>(self) -> Result<T, de::DeError>
where
T: serde::de::DeserializeOwned;
}
impl XmlExt for &str {
fn parse_xml<T>(self) -> Result<T, de::DeError>
where
T: serde::de::DeserializeOwned,
{
de::from_str(self)
}
}
/// Extension trait for Option to validate missing fields
pub trait OptionExt<T> {
/// check if the current option is Some
fn check_value_present(
&self,
field_name: &'static str,
) -> CustomResult<(), errors::ValidationError>;
/// Throw missing required field error when the value is None
fn get_required_value(
self,
field_name: &'static str,
) -> CustomResult<T, errors::ValidationError>;
/// Try parsing the option as Enum
fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError>
where
T: AsRef<str>,
E: std::str::FromStr,
// Requirement for converting the `Err` variant of `FromStr` to `Report<Err>`
<E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static;
/// Try parsing the option as Type
fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError>
where
T: ValueExt,
U: serde::de::DeserializeOwned;
/// update option value
fn update_value(&mut self, value: Option<T>);
}
impl<T> OptionExt<T> for Option<T>
where
T: std::fmt::Debug,
{
#[track_caller]
fn check_value_present(
&self,
field_name: &'static str,
) -> CustomResult<(), errors::ValidationError> {
when(self.is_none(), || {
Err(errors::ValidationError::MissingRequiredField {
field_name: field_name.to_string(),
})
.attach_printable(format!("Missing required field {field_name} in {self:?}"))
})
}
// This will allow the error message that was generated in this function to point to the call site
#[track_caller]
fn get_required_value(
self,
field_name: &'static str,
) -> CustomResult<T, errors::ValidationError> {
match self {
Some(v) => Ok(v),
None => Err(errors::ValidationError::MissingRequiredField {
field_name: field_name.to_string(),
})
.attach_printable(format!("Missing required field {field_name} in {self:?}")),
}
}
#[track_caller]
fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError>
where
T: AsRef<str>,
E: std::str::FromStr,
<E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static,
{
let value = self
.get_required_value(enum_name)
.change_context(errors::ParsingError::UnknownError)?;
E::from_str(value.as_ref())
.change_context(errors::ParsingError::UnknownError)
.attach_printable_lazy(|| format!("Invalid {{ {enum_name}: {value:?} }} "))
}
#[track_caller]
fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError>
where
T: ValueExt,
U: serde::de::DeserializeOwned,
{
let value = self
.get_required_value(type_name)
.change_context(errors::ParsingError::UnknownError)?;
value.parse_value(type_name)
}
fn update_value(&mut self, value: Self) {
if let Some(a) = value {
*self = Some(a)
}
}
}
|
crates/common_utils/src/ext_traits.rs
|
common_utils
|
full_file
| 4,745
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct PmTokenStored;
|
crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
|
router
|
struct_definition
| 7
|
rust
|
PmTokenStored
| null | null | null | null | null | null | null | null | null | null | null |
impl api::PaymentCapture for Fiuu {}
|
crates/hyperswitch_connectors/src/connectors/fiuu.rs
|
hyperswitch_connectors
|
impl_block
| 10
|
rust
| null |
Fiuu
|
api::PaymentCapture for
|
impl api::PaymentCapture for for Fiuu
| null | null | null | null | null | null | null | null |
pub struct PaymentInput {
pub amount: common_utils::types::MinorUnit,
pub currency: enums::Currency,
pub authentication_type: Option<enums::AuthenticationType>,
pub card_bin: Option<String>,
pub capture_method: Option<enums::CaptureMethod>,
pub business_country: Option<enums::Country>,
pub billing_country: Option<enums::Country>,
pub business_label: Option<String>,
pub setup_future_usage: Option<enums::SetupFutureUsage>,
}
|
crates/euclid/src/backend/inputs.rs
|
euclid
|
struct_definition
| 102
|
rust
|
PaymentInput
| null | null | null | null | null | null | null | null | null | null | null |
A comprehensive dataset extracted from the Hyperswitch open-source payment processing platform, containing 16,731 code samples across 37 modules with 6.99M tokens for training Rust code understanding and generation models.
This dataset provides both file-level and granular code samples from Hyperswitch, a modern payment switch written in Rust. It's designed for training code models to understand payment processing patterns, Rust idioms, and large-scale system architecture.
"total_samples": 16990,
"file_level_samples": 3143,
"granular_samples": 13847,
"commit_samples": 0,
"total_tokens": 8899898,
"sample_types": {
"impl_block": 4103,
"function_signature": 3993,
"struct_definition": 5484,
"full_file": 1623,
"doc_chunk": 69,
"openapi_block": 709,
"trait_definition": 221,
"web_doc_file": 72,
"doc_file": 238,
"chunk": 432,
"macro": 44,
"impl_block_chunk": 2
}
@dataset{HyperSwitch-Repo-CPT-Dataset-v2,
title={HyperSwitch-Repo-CPT-Dataset-v2},
author={Aditya Narayan},
year={2024},
publisher={Hugging Face},
url={https://huggingface.co/datasets/AdityaNarayan/HyperSwitch-Repo-CPT-Dataset-v2},
note={Extracted from https://github.com/juspay/hyperswitch}
}
This dataset is part of ongoing research into domain-specific code model training for financial technology applications.