text
stringlengths 65
57.3k
| file_path
stringlengths 22
92
| module
stringclasses 38
values | type
stringclasses 7
values | struct_name
stringlengths 3
60
⌀ | impl_count
int64 0
60
⌀ | traits
listlengths 0
59
⌀ | tokens
int64 16
8.19k
| function_name
stringlengths 3
85
⌀ | type_name
stringlengths 1
67
⌀ | trait_name
stringclasses 573
values | method_count
int64 0
31
⌀ | public_method_count
int64 0
19
⌀ | submodule_count
int64 0
56
⌀ | export_count
int64 0
9
⌀ |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
// Struct: LocalPrice
// File: crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct LocalPrice
|
crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
LocalPrice
| 0
|
[] | 46
| null | null | null | null | null | null | null |
// File: crates/api_models/src/events/gsm.rs
// Module: api_models
use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::gsm;
impl ApiEventMetric for gsm::GsmCreateRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Gsm)
}
}
impl ApiEventMetric for gsm::GsmUpdateRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Gsm)
}
}
impl ApiEventMetric for gsm::GsmRetrieveRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Gsm)
}
}
impl ApiEventMetric for gsm::GsmDeleteRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Gsm)
}
}
impl ApiEventMetric for gsm::GsmDeleteResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Gsm)
}
}
impl ApiEventMetric for gsm::GsmResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Gsm)
}
}
|
crates/api_models/src/events/gsm.rs
|
api_models
|
full_file
| null | null | null | 289
| null | null | null | null | null | null | null |
// Struct: ApiKeyExpiryWorkflow
// File: crates/router/src/workflows/api_key_expiry.rs
// Module: router
// Implementations: 0
pub struct ApiKeyExpiryWorkflow
|
crates/router/src/workflows/api_key_expiry.rs
|
router
|
struct_definition
|
ApiKeyExpiryWorkflow
| 0
|
[] | 41
| null | null | null | null | null | null | null |
// Function: track_database_call
// File: crates/diesel_models/src/query/generics.rs
// Module: diesel_models
pub fn track_database_call<T, Fut, U>(future: Fut, operation: DatabaseOperation) -> U
where
Fut: std::future::Future<Output = U>,
|
crates/diesel_models/src/query/generics.rs
|
diesel_models
|
function_signature
| null | null | null | 66
|
track_database_call
| null | null | null | null | null | null |
// Function: update_payment_method_status_internal
// File: crates/router/src/core/payment_methods.rs
// Module: router
pub fn update_payment_method_status_internal(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
status: enums::PaymentMethodStatus,
payment_method_id: &id_type::GlobalPaymentMethodId,
) -> RouterResult<domain::PaymentMethod>
|
crates/router/src/core/payment_methods.rs
|
router
|
function_signature
| null | null | null | 94
|
update_payment_method_status_internal
| null | null | null | null | null | null |
db.delete_payment_method_by_merchant_id_payment_method_id(
&(self.state.into()),
self.merchant_context.get_merchant_key_store(),
self.merchant_context.get_merchant_account().get_id(),
pm_id.payment_method_id.as_str(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
if customer.default_payment_method_id.as_ref() == Some(&pm_id.payment_method_id) {
let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod {
default_payment_method_id: Some(None),
};
db.update_customer_by_customer_id_merchant_id(
key_manager_state,
key.customer_id,
key.merchant_id,
customer,
customer_update,
self.merchant_context.get_merchant_key_store(),
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the default payment method id for the customer")?;
};
Ok(services::ApplicationResponse::Json(
api::PaymentMethodDeleteResponse {
payment_method_id: key.payment_method_id.clone(),
deleted: true,
},
))
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn add_payment_method(
&self,
req: &api::PaymentMethodCreate,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
req.validate()?;
let db = &*self.state.store;
let merchant_id = self.merchant_context.get_merchant_account().get_id();
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
let payment_method = req.payment_method.get_required_value("payment_method")?;
let key_manager_state = self.state.into();
let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req
.billing
.clone()
.async_map(|billing| {
create_encrypted_data(
&key_manager_state,
self.merchant_context.get_merchant_key_store(),
billing,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt Payment method billing address")?;
let connector_mandate_details = req
.connector_mandate_details
.clone()
.map(serde_json::to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let response = match payment_method {
#[cfg(feature = "payouts")]
api_enums::PaymentMethod::BankTransfer => match req.bank_transfer.clone() {
Some(bank) => self
.add_bank_to_locker(
req.clone(),
self.merchant_context.get_merchant_key_store(),
&bank,
&customer_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add PaymentMethod Failed"),
_ => Ok(self.store_default_payment_method(req, &customer_id, merchant_id)),
},
api_enums::PaymentMethod::Card => match req.card.clone() {
Some(card) => {
let mut card_details = card;
card_details = helpers::populate_bin_details_for_payment_method_create(
card_details.clone(),
db.get_payment_methods_store(),
)
.await;
helpers::validate_card_expiry(
&card_details.card_exp_month,
&card_details.card_exp_year,
)?;
Box::pin(self.add_card_to_locker(
req.clone(),
&card_details,
&customer_id,
None,
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Card Failed")
}
_ => Ok(self.store_default_payment_method(req, &customer_id, merchant_id)),
},
_ => Ok(self.store_default_payment_method(req, &customer_id, merchant_id)),
};
let (mut resp, duplication_check) = response?;
match duplication_check {
Some(duplication_check) => match duplication_check {
payment_methods::DataDuplicationCheck::Duplicated => {
let existing_pm = self
.get_or_insert_payment_method(
req.clone(),
&mut resp,
&customer_id,
self.merchant_context.get_merchant_key_store(),
)
.await?;
resp.client_secret = existing_pm.client_secret;
}
payment_methods::DataDuplicationCheck::MetaDataChanged => {
if let Some(card) = req.card.clone() {
let existing_pm = self
.get_or_insert_payment_method(
req.clone(),
&mut resp,
&customer_id,
self.merchant_context.get_merchant_key_store(),
)
.await?;
let client_secret = existing_pm.client_secret.clone();
self.delete_card_from_locker(
&customer_id,
merchant_id,
existing_pm
.locker_id
.as_ref()
.unwrap_or(&existing_pm.payment_method_id),
)
.await?;
let add_card_resp = self
.add_card_hs(
req.clone(),
&card,
&customer_id,
api::enums::LockerChoice::HyperswitchCardVault,
Some(
existing_pm
.locker_id
.as_ref()
.unwrap_or(&existing_pm.payment_method_id),
),
)
.await;
if let Err(err) = add_card_resp {
logger::error!(vault_err=?err);
db.delete_payment_method_by_merchant_id_payment_method_id(
&(self.state.into()),
self.merchant_context.get_merchant_key_store(),
merchant_id,
&resp.payment_method_id,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::PaymentMethodNotFound,
)?;
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while updating card metadata changes"))?
};
let existing_pm_data = self
.get_card_details_without_locker_fallback(&existing_pm)
.await?;
let updated_card = Some(api::CardDetailFromLocker {
scheme: existing_pm.scheme.clone(),
last4_digits: Some(card.card_number.get_last4()),
issuer_country: card
.card_issuing_country
.or(existing_pm_data.issuer_country),
card_isin: Some(card.card_number.get_card_isin()),
card_number: Some(card.card_number),
expiry_month: Some(card.card_exp_month),
expiry_year: Some(card.card_exp_year),
card_token: None,
card_fingerprint: None,
card_holder_name: card
.card_holder_name
.or(existing_pm_data.card_holder_name),
nick_name: card.nick_name.or(existing_pm_data.nick_name),
card_network: card.card_network.or(existing_pm_data.card_network),
card_issuer: card.card_issuer.or(existing_pm_data.card_issuer),
card_type: card.card_type.or(existing_pm_data.card_type),
saved_to_locker: true,
});
let updated_pmd = updated_card.as_ref().map(|card| {
PaymentMethodsData::Card(CardDetailsPaymentMethod::from((
card.clone(),
None,
)))
});
let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> =
updated_pmd
.async_map(|updated_pmd| {
create_encrypted_data(
&key_manager_state,
self.merchant_context.get_merchant_key_store(),
updated_pmd,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data: pm_data_encrypted.map(Into::into),
};
db.update_payment_method(
&(self.state.into()),
self.merchant_context.get_merchant_key_store(),
existing_pm,
pm_update,
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
resp.client_secret = client_secret;
}
}
},
None => {
let pm_metadata = resp.metadata.as_ref().map(|data| data.peek());
let locker_id = if resp.payment_method == Some(api_enums::PaymentMethod::Card)
|| resp.payment_method == Some(api_enums::PaymentMethod::BankTransfer)
{
Some(resp.payment_method_id)
} else {
None
};
resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
let pm = self
.insert_payment_method(
&resp,
req,
self.merchant_context.get_merchant_key_store(),
merchant_id,
&customer_id,
pm_metadata.cloned(),
None,
locker_id,
connector_mandate_details,
req.network_transaction_id.clone(),
payment_method_billing_address,
None,
None,
None,
Default::default(), //Currently this method is used for adding payment method via PaymentMethodCreate API which doesn't support external vault. hence Default i.e. InternalVault is passed for vault source and type
)
.await?;
resp.client_secret = pm.client_secret;
}
}
Ok(services::ApplicationResponse::Json(resp))
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn get_client_secret_or_add_payment_method(
state: &routes::SessionState,
req: api::PaymentMethodCreate,
merchant_context: &domain::MerchantContext,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
let merchant_id = merchant_context.get_merchant_account().get_id();
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
let cards = PmCards {
state,
merchant_context,
};
#[cfg(not(feature = "payouts"))]
let condition = req.card.is_some();
#[cfg(feature = "payouts")]
let condition = req.card.is_some() || req.bank_transfer.is_some() || req.wallet.is_some();
let key_manager_state = state.into();
let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req
.billing
.clone()
.async_map(|billing| {
create_encrypted_data(
&key_manager_state,
merchant_context.get_merchant_key_store(),
billing,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt Payment method billing address")?;
let connector_mandate_details = req
.connector_mandate_details
.clone()
.map(serde_json::to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
if condition {
Box::pin(cards.add_payment_method(&req)).await
} else {
let payment_method_id = generate_id(consts::ID_LENGTH, "pm");
let res = cards
.create_payment_method(
&req,
&customer_id,
payment_method_id.as_str(),
None,
merchant_id,
None,
None,
None,
connector_mandate_details,
Some(enums::PaymentMethodStatus::AwaitingData),
None,
payment_method_billing_address,
None,
None,
None,
None,
Default::default(), //Currently this method is used for adding payment method via PaymentMethodCreate API which doesn't support external vault. hence Default i.e. InternalVault is passed for vault type
)
.await?;
if res.status == enums::PaymentMethodStatus::AwaitingData {
add_payment_method_status_update_task(
&*state.store,
&res,
enums::PaymentMethodStatus::AwaitingData,
enums::PaymentMethodStatus::Inactive,
merchant_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to add payment method status update task in process tracker",
)?;
}
Ok(services::api::ApplicationResponse::Json(
api::PaymentMethodResponse::foreign_from((None, res)),
))
}
}
#[instrument(skip_all)]
pub fn authenticate_pm_client_secret_and_check_expiry(
req_client_secret: &String,
payment_method: &domain::PaymentMethod,
) -> errors::CustomResult<bool, errors::ApiErrorResponse> {
let stored_client_secret = payment_method
.client_secret
.clone()
.get_required_value("client_secret")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "client_secret",
})
.attach_printable("client secret not found in db")?;
if req_client_secret != &stored_client_secret {
Err((errors::ApiErrorResponse::ClientSecretInvalid).into())
} else {
let current_timestamp = common_utils::date_time::now();
let session_expiry = payment_method
.created_at
.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY));
let expired = current_timestamp > session_expiry;
Ok(expired)
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn add_payment_method_data(
state: routes::SessionState,
req: api::PaymentMethodCreate,
merchant_context: domain::MerchantContext,
pm_id: String,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
let db = &*state.store;
let cards = PmCards {
state: &state,
merchant_context: &merchant_context,
};
let pmd = req
.payment_method_data
.clone()
.get_required_value("payment_method_data")?;
req.payment_method.get_required_value("payment_method")?;
let client_secret = req
.client_secret
.clone()
.get_required_value("client_secret")?;
let payment_method = db
.find_payment_method(
&((&state).into()),
merchant_context.get_merchant_key_store(),
pm_id.as_str(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Unable to find payment method")?;
if payment_method.status != enums::PaymentMethodStatus::AwaitingData {
return Err((errors::ApiErrorResponse::ClientSecretExpired).into());
}
let customer_id = payment_method.customer_id.clone();
let customer = db
.find_customer_by_customer_id_merchant_id(
&(&state).into(),
&customer_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
let client_secret_expired =
authenticate_pm_client_secret_and_check_expiry(&client_secret, &payment_method)?;
if client_secret_expired {
return Err((errors::ApiErrorResponse::ClientSecretExpired).into());
};
let key_manager_state = (&state).into();
match pmd {
api_models::payment_methods::PaymentMethodCreateData::Card(card) => {
helpers::validate_card_expiry(&card.card_exp_month, &card.card_exp_year)?;
let resp = Box::pin(cards.add_card_to_locker(req.clone(), &card, &customer_id, None))
.await
.change_context(errors::ApiErrorResponse::InternalServerError);
match resp {
Ok((mut pm_resp, duplication_check)) => {
if duplication_check.is_some() {
let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
status: Some(enums::PaymentMethodStatus::Inactive),
};
db.update_payment_method(
&((&state).into()),
merchant_context.get_merchant_key_store(),
payment_method,
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
cards
.get_or_insert_payment_method(
req.clone(),
&mut pm_resp,
&customer_id,
merchant_context.get_merchant_key_store(),
)
.await?;
return Ok(services::ApplicationResponse::Json(pm_resp));
} else {
let locker_id = pm_resp.payment_method_id.clone();
pm_resp.payment_method_id.clone_from(&pm_id);
pm_resp.client_secret = Some(client_secret.clone());
let card_isin = card.card_number.get_card_isin();
let card_info = db
.get_card_info(card_isin.as_str())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get card info")?;
let updated_card = CardDetailsPaymentMethod {
issuer_country: card_info
.as_ref()
.and_then(|ci| ci.card_issuing_country.clone()),
last4_digits: Some(card.card_number.get_last4()),
expiry_month: Some(card.card_exp_month),
expiry_year: Some(card.card_exp_year),
nick_name: card.nick_name,
card_holder_name: card.card_holder_name,
card_network: card_info.as_ref().and_then(|ci| ci.card_network.clone()),
card_isin: Some(card_isin),
card_issuer: card_info.as_ref().and_then(|ci| ci.card_issuer.clone()),
card_type: card_info.as_ref().and_then(|ci| ci.card_type.clone()),
saved_to_locker: true,
co_badged_card_data: None,
};
let pm_data_encrypted: Encryptable<Secret<serde_json::Value>> =
create_encrypted_data(
&key_manager_state,
merchant_context.get_merchant_key_store(),
PaymentMethodsData::Card(updated_card),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
let pm_update = storage::PaymentMethodUpdate::AdditionalDataUpdate {
payment_method_data: Some(pm_data_encrypted.into()),
status: Some(enums::PaymentMethodStatus::Active),
locker_id: Some(locker_id),
network_token_requestor_reference_id: None,
payment_method: req.payment_method,
payment_method_issuer: req.payment_method_issuer,
payment_method_type: req.payment_method_type,
network_token_locker_id: None,
network_token_payment_method_data: None,
};
db.update_payment_method(
&((&state).into()),
merchant_context.get_merchant_key_store(),
payment_method,
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
if customer.default_payment_method_id.is_none() {
let _ = cards
.set_default_payment_method(
merchant_context.get_merchant_account().get_id(),
&customer_id,
pm_id,
)
.await
.map_err(|error| {
logger::error!(
?error,
"Failed to set the payment method as default"
)
});
}
return Ok(services::ApplicationResponse::Json(pm_resp));
}
}
Err(e) => {
let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
status: Some(enums::PaymentMethodStatus::Inactive),
};
db.update_payment_method(
&((&state).into()),
merchant_context.get_merchant_key_store(),
payment_method,
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
return Err(e.attach_printable("Failed to add card to locker"));
}
}
}
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn update_customer_payment_method(
state: routes::SessionState,
merchant_context: domain::MerchantContext,
req: api::PaymentMethodUpdate,
payment_method_id: &str,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
// Currently update is supported only for cards
if let Some(card_update) = req.card.clone() {
let db = state.store.as_ref();
let pm = db
.find_payment_method(
&((&state).into()),
merchant_context.get_merchant_key_store(),
payment_method_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
if let Some(cs) = &req.client_secret {
let is_client_secret_expired = authenticate_pm_client_secret_and_check_expiry(cs, &pm)?;
if is_client_secret_expired {
return Err((errors::ApiErrorResponse::ClientSecretExpired).into());
};
};
if pm.status == enums::PaymentMethodStatus::AwaitingData {
return Err(report!(errors::ApiErrorResponse::NotSupported {
message: "Payment method is awaiting data so it cannot be updated".into()
}));
}
if pm.payment_method_data.is_none() {
return Err(report!(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment_method_data not found".to_string()
}));
}
// Fetch the existing payment method data from db
let existing_card_data =
pm.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.map(
|value| -> Result<
PaymentMethodsData,
error_stack::Report<errors::ApiErrorResponse>,
> {
value
.parse_value::<PaymentMethodsData>("PaymentMethodsData")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize payment methods data")
},
)
.transpose()?
.and_then(|pmd| match pmd {
PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
_ => None,
})
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain decrypted card object from db")?;
let is_card_updation_required =
validate_payment_method_update(card_update.clone(), existing_card_data.clone());
let response = if is_card_updation_required {
// Fetch the existing card data from locker for getting card number
let card_data_from_locker = get_card_from_locker(
&state,
&pm.customer_id,
&pm.merchant_id,
pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting card from locker")?;
if card_update.card_exp_month.is_some() || card_update.card_exp_year.is_some() {
helpers::validate_card_expiry(
card_update
.card_exp_month
.as_ref()
.unwrap_or(&card_data_from_locker.card_exp_month),
card_update
.card_exp_year
.as_ref()
.unwrap_or(&card_data_from_locker.card_exp_year),
)?;
}
let updated_card_details = card_update.apply(card_data_from_locker.clone());
// Construct new payment method object from request
let new_pm = api::PaymentMethodCreate {
payment_method: pm.get_payment_method_type(),
payment_method_type: pm.get_payment_method_subtype(),
payment_method_issuer: pm.payment_method_issuer.clone(),
payment_method_issuer_code: pm.payment_method_issuer_code,
#[cfg(feature = "payouts")]
bank_transfer: None,
card: Some(updated_card_details.clone()),
#[cfg(feature = "payouts")]
wallet: None,
metadata: None,
customer_id: Some(pm.customer_id.clone()),
client_secret: pm.client_secret.clone(),
payment_method_data: None,
card_network: None,
billing: None,
connector_mandate_details: None,
network_transaction_id: None,
};
new_pm.validate()?;
let cards = PmCards {
state: &state,
merchant_context: &merchant_context,
};
// Delete old payment method from locker
cards
.delete_card_from_locker(
&pm.customer_id,
&pm.merchant_id,
pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await?;
// Add the updated payment method data to locker
let (mut add_card_resp, _) = Box::pin(cards.add_card_to_locker(
new_pm.clone(),
&updated_card_details,
&pm.customer_id,
Some(pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id)),
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add updated payment method to locker")?;
// Construct new updated card object. Consider a field if passed in request or else populate it with the existing value from existing_card_data
let updated_card = Some(api::CardDetailFromLocker {
scheme: existing_card_data.scheme,
last4_digits: Some(card_data_from_locker.card_number.get_last4()),
issuer_country: existing_card_data.issuer_country,
card_number: existing_card_data.card_number,
expiry_month: card_update
.card_exp_month
.or(existing_card_data.expiry_month),
expiry_year: card_update.card_exp_year.or(existing_card_data.expiry_year),
card_token: existing_card_data.card_token,
card_fingerprint: existing_card_data.card_fingerprint,
card_holder_name: card_update
.card_holder_name
.or(existing_card_data.card_holder_name),
nick_name: card_update.nick_name.or(existing_card_data.nick_name),
card_network: existing_card_data.card_network,
card_isin: existing_card_data.card_isin,
card_issuer: existing_card_data.card_issuer,
card_type: existing_card_data.card_type,
saved_to_locker: true,
});
let updated_pmd = updated_card.as_ref().map(|card| {
PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None)))
});
let key_manager_state = (&state).into();
let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd
.async_map(|updated_pmd| {
create_encrypted_data(
&key_manager_state,
merchant_context.get_merchant_key_store(),
updated_pmd,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data: pm_data_encrypted.map(Into::into),
};
add_card_resp
.payment_method_id
.clone_from(&pm.payment_method_id);
db.update_payment_method(
&((&state).into()),
merchant_context.get_merchant_key_store(),
pm,
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
add_card_resp
} else {
// Return existing payment method data as response without any changes
api::PaymentMethodResponse {
merchant_id: pm.merchant_id.to_owned(),
customer_id: Some(pm.customer_id.clone()),
payment_method_id: pm.payment_method_id.clone(),
payment_method: pm.get_payment_method_type(),
payment_method_type: pm.get_payment_method_subtype(),
#[cfg(feature = "payouts")]
bank_transfer: None,
card: Some(existing_card_data),
metadata: pm.metadata,
created: Some(pm.created_at),
recurring_enabled: Some(false),
installment_payment_enabled: Some(false),
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()),
client_secret: pm.client_secret.clone(),
}
};
Ok(services::ApplicationResponse::Json(response))
} else {
Err(report!(errors::ApiErrorResponse::NotSupported {
message: "Payment method update for the given payment method is not supported".into()
}))
}
}
#[cfg(feature = "v1")]
pub fn validate_payment_method_update(
card_updation_obj: CardDetailUpdate,
existing_card_data: api::CardDetailFromLocker,
) -> bool {
// Return true If any one of the below condition returns true,
// If a field is not passed in the update request, return false.
// If the field is present, it depends on the existing field data:
// - If existing field data is not present, or if it is present and doesn't match
// the update request data, then return true.
// - Or else return false
card_updation_obj
.card_exp_month
.map(|exp_month| exp_month.expose())
.is_some_and(|new_exp_month| {
existing_card_data
.expiry_month
.map(|exp_month| exp_month.expose())
!= Some(new_exp_month)
})
|| card_updation_obj
.card_exp_year
.map(|exp_year| exp_year.expose())
.is_some_and(|new_exp_year| {
existing_card_data
.expiry_year
.map(|exp_year| exp_year.expose())
!= Some(new_exp_year)
})
|| card_updation_obj
.card_holder_name
.map(|name| name.expose())
.is_some_and(|new_card_holder_name| {
existing_card_data
.card_holder_name
.map(|name| name.expose())
!= Some(new_card_holder_name)
})
|| card_updation_obj
.nick_name
.map(|nick_name| nick_name.expose())
.is_some_and(|new_nick_name| {
existing_card_data
.nick_name
.map(|nick_name| nick_name.expose())
!= Some(new_nick_name)
})
}
#[cfg(feature = "v2")]
pub fn validate_payment_method_update(
_card_updation_obj: CardDetailUpdate,
_existing_card_data: api::CardDetailFromLocker,
) -> bool {
todo!()
}
// Wrapper function to switch lockers
pub async fn get_card_from_locker(
state: &routes::SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &str,
) -> errors::RouterResult<Card> {
metrics::GET_FROM_LOCKER.add(1, &[]);
let get_card_from_rs_locker_resp = common_utils::metrics::utils::record_operation_time(
async {
get_card_from_hs_locker(
state,
customer_id,
merchant_id,
card_reference,
api_enums::LockerChoice::HyperswitchCardVault,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting card from hyperswitch card vault")
.inspect_err(|_| {
metrics::CARD_LOCKER_FAILURES.add(
1,
router_env::metric_attributes!(("locker", "rust"), ("operation", "get")),
);
})
},
&metrics::CARD_GET_TIME,
router_env::metric_attributes!(("locker", "rust")),
)
.await?;
logger::debug!("card retrieved from rust locker");
Ok(get_card_from_rs_locker_resp)
}
#[cfg(feature = "v2")]
pub async fn delete_card_by_locker_id(
state: &routes::SessionState,
id: &id_type::GlobalCustomerId,
merchant_id: &id_type::MerchantId,
) -> errors::RouterResult<payment_methods::DeleteCardResp> {
todo!()
}
#[instrument(skip_all)]
pub async fn decode_and_decrypt_locker_data(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
enc_card_data: String,
) -> errors::CustomResult<Secret<String>, errors::VaultError> {
let key = key_store.key.get_inner().peek();
let decoded_bytes = hex::decode(&enc_card_data)
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to decode hex string into bytes")?;
// Decrypt
domain::types::crypto_operation(
&state.into(),
type_name!(payment_method::PaymentMethod),
domain::types::CryptoOperation::DecryptOptional(Some(Encryption::new(
decoded_bytes.into(),
))),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
.await
.and_then(|val| val.try_into_optionaloperation())
.change_context(errors::VaultError::FetchPaymentMethodFailed)?
.map_or(
Err(report!(errors::VaultError::FetchPaymentMethodFailed)),
|d| Ok(d.into_inner()),
)
}
#[instrument(skip_all)]
pub async fn get_payment_method_from_hs_locker<'a>(
state: &'a routes::SessionState,
key_store: &domain::MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
payment_method_reference: &'a str,
locker_choice: Option<api_enums::LockerChoice>,
) -> errors::CustomResult<Secret<String>, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = state.conf.jwekey.get_inner();
let payment_method_data = if !locker.mock_locker {
let request = payment_methods::mk_get_card_request_hs(
jwekey,
locker,
customer_id,
merchant_id,
payment_method_reference,
locker_choice,
state.tenant.tenant_id.clone(),
state.request_id,
)
.await
.change_context(errors::VaultError::FetchPaymentMethodFailed)
.attach_printable("Making get payment method request failed")?;
let get_card_resp = call_locker_api::<payment_methods::RetrieveCardResp>(
state,
request,
"get_pm_from_locker",
locker_choice,
)
.await
.change_context(errors::VaultError::FetchPaymentMethodFailed)?;
let retrieve_card_resp = get_card_resp
.payload
.get_required_value("RetrieveCardRespPayload")
.change_context(errors::VaultError::FetchPaymentMethodFailed)
.attach_printable("Failed to retrieve field - payload from RetrieveCardResp")?;
let enc_card_data = retrieve_card_resp
.enc_card_data
.get_required_value("enc_card_data")
.change_context(errors::VaultError::FetchPaymentMethodFailed)
.attach_printable(
"Failed to retrieve field - enc_card_data from RetrieveCardRespPayload",
)?;
decode_and_decrypt_locker_data(state, key_store, enc_card_data.peek().to_string()).await?
} else {
mock_get_payment_method(state, key_store, payment_method_reference)
.await?
.payment_method
.payment_method_data
};
Ok(payment_method_data)
}
#[instrument(skip_all)]
pub async fn add_card_to_hs_locker(
state: &routes::SessionState,
payload: &payment_methods::StoreLockerReq,
customer_id: &id_type::CustomerId,
locker_choice: api_enums::LockerChoice,
) -> errors::CustomResult<payment_methods::StoreCardRespPayload, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = state.conf.jwekey.get_inner();
let db = &*state.store;
let stored_card_response = if !locker.mock_locker {
let request = payment_methods::mk_add_locker_request_hs(
jwekey,
locker,
payload,
locker_choice,
state.tenant.tenant_id.clone(),
state.request_id,
)
.await?;
call_locker_api::<payment_methods::StoreCardResp>(
state,
request,
"add_card_to_hs_locker",
Some(locker_choice),
)
.await
.change_context(errors::VaultError::SaveCardFailed)?
} else {
let card_id = generate_id(consts::ID_LENGTH, "card");
mock_call_to_locker_hs(db, &card_id, payload, None, None, Some(customer_id)).await?
};
let stored_card = stored_card_response
.payload
.get_required_value("StoreCardRespPayload")
.change_context(errors::VaultError::SaveCardFailed)?;
Ok(stored_card)
}
#[instrument(skip_all)]
pub async fn call_locker_api<T>(
state: &routes::SessionState,
request: Request,
flow_name: &str,
locker_choice: Option<api_enums::LockerChoice>,
) -> errors::CustomResult<T, errors::VaultError>
where
T: serde::de::DeserializeOwned,
{
let locker = &state.conf.locker;
let jwekey = state.conf.jwekey.get_inner();
let response_type_name = type_name!(T);
let response = services::call_connector_api(state, request, flow_name)
.await
.change_context(errors::VaultError::ApiError)?;
let is_locker_call_succeeded = response.is_ok();
let jwe_body = response
.unwrap_or_else(|err| err)
.response
.parse_struct::<services::JweBody>("JweBody")
|
crates/router/src/core/payment_methods/cards.rs#chunk1
|
router
|
chunk
| null | null | null | 8,183
| null | null | null | null | null | null | null |
// Struct: DummyConnectorRefundRequest
// File: crates/hyperswitch_connectors/src/connectors/dummyconnector/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct DummyConnectorRefundRequest
|
crates/hyperswitch_connectors/src/connectors/dummyconnector/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
DummyConnectorRefundRequest
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Struct: RefundListConstraints
// File: crates/hyperswitch_domain_models/src/refunds.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct RefundListConstraints
|
crates/hyperswitch_domain_models/src/refunds.rs
|
hyperswitch_domain_models
|
struct_definition
|
RefundListConstraints
| 0
|
[] | 44
| null | null | null | null | null | null | null |
// Struct: GigadatCpiRequest
// File: crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct GigadatCpiRequest
|
crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
GigadatCpiRequest
| 0
|
[] | 55
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/ctp_mastercard.rs
// Module: hyperswitch_connectors
// Public structs: 1
use common_utils::errors::CustomResult;
use error_stack::report;
use hyperswitch_domain_models::{
router_data::{AccessToken, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, RefundsResponseData},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors, webhooks,
};
use crate::constants::headers;
#[derive(Clone)]
pub struct CtpMastercard;
impl api::Payment for CtpMastercard {}
impl api::PaymentSession for CtpMastercard {}
impl api::ConnectorAccessToken for CtpMastercard {}
impl api::MandateSetup for CtpMastercard {}
impl api::PaymentAuthorize for CtpMastercard {}
impl api::PaymentSync for CtpMastercard {}
impl api::PaymentCapture for CtpMastercard {}
impl api::PaymentVoid for CtpMastercard {}
impl api::Refund for CtpMastercard {}
impl api::RefundExecute for CtpMastercard {}
impl api::RefundSync for CtpMastercard {}
impl api::PaymentToken for CtpMastercard {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for CtpMastercard
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for CtpMastercard
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for CtpMastercard {
fn id(&self) -> &'static str {
"ctp_mastercard"
}
fn base_url<'a>(&self, _connectors: &'a Connectors) -> &'a str {
""
}
}
impl ConnectorValidation for CtpMastercard {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for CtpMastercard {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for CtpMastercard {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for CtpMastercard
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
for CtpMastercard
{
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for CtpMastercard {}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for CtpMastercard {}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for CtpMastercard {}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for CtpMastercard {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for CtpMastercard {}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for CtpMastercard {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
impl ConnectorSpecifications for CtpMastercard {}
|
crates/hyperswitch_connectors/src/connectors/ctp_mastercard.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 1,046
| null | null | null | null | null | null | null |
// Implementation: impl RetryLimitsConfig
// File: crates/router/src/types/storage/revenue_recovery.rs
// Module: router
// Methods: 1 total (1 public)
impl RetryLimitsConfig
|
crates/router/src/types/storage/revenue_recovery.rs
|
router
|
impl_block
| null | null | null | 40
| null |
RetryLimitsConfig
| null | 1
| 1
| null | null |
// Module Structure
// File: crates/router/src/core/revenue_recovery.rs
// Module: router
// Public submodules:
pub mod api;
pub mod transformers;
pub mod types;
|
crates/router/src/core/revenue_recovery.rs
|
router
|
module_structure
| null | null | null | 38
| null | null | null | null | null | 3
| 0
|
// File: crates/router/src/bin/scheduler.rs
// Module: router
// Public functions: 5
// Public structs: 2
use std::{collections::HashMap, str::FromStr, sync::Arc};
use actix_web::{dev::Server, web, Scope};
use api_models::health_check::SchedulerHealthCheckResponse;
use common_utils::ext_traits::{OptionExt, StringExt};
use diesel_models::process_tracker::{self as storage, business_status};
use error_stack::ResultExt;
use router::{
configs::settings::{CmdLineConf, Settings},
core::{
errors::{self, CustomResult},
health_check::HealthCheckInterface,
},
logger, routes,
services::{self, api},
workflows,
};
use router_env::{
instrument,
tracing::{self, Instrument},
};
use scheduler::{
consumer::workflows::ProcessTrackerWorkflow, errors::ProcessTrackerError,
workflows::ProcessTrackerWorkflows, SchedulerSessionState,
};
use storage_impl::errors::ApplicationError;
use tokio::sync::{mpsc, oneshot};
const SCHEDULER_FLOW: &str = "SCHEDULER_FLOW";
#[tokio::main]
async fn main() -> CustomResult<(), ProcessTrackerError> {
let cmd_line = <CmdLineConf as clap::Parser>::parse();
#[allow(clippy::expect_used)]
let conf = Settings::with_config_path(cmd_line.config_path)
.expect("Unable to construct application configuration");
let api_client = Box::new(
services::ProxyClient::new(&conf.proxy)
.change_context(ProcessTrackerError::ConfigurationError)?,
);
// channel for listening to redis disconnect events
let (redis_shutdown_signal_tx, redis_shutdown_signal_rx) = oneshot::channel();
let state = Box::pin(routes::AppState::new(
conf,
redis_shutdown_signal_tx,
api_client,
))
.await;
// channel to shutdown scheduler gracefully
let (tx, rx) = mpsc::channel(1);
let _task_handle = tokio::spawn(
router::receiver_for_error(redis_shutdown_signal_rx, tx.clone()).in_current_span(),
);
#[allow(clippy::expect_used)]
let scheduler_flow_str =
std::env::var(SCHEDULER_FLOW).expect("SCHEDULER_FLOW environment variable not set");
#[allow(clippy::expect_used)]
let scheduler_flow = scheduler::SchedulerFlow::from_str(&scheduler_flow_str)
.expect("Unable to parse SchedulerFlow from environment variable");
#[allow(clippy::print_stdout)] // The logger has not yet been initialized
#[cfg(feature = "vergen")]
{
println!(
"Starting {scheduler_flow} (Version: {})",
router_env::git_tag!()
);
}
let _guard = router_env::setup(
&state.conf.log,
&scheduler_flow_str,
[router_env::service_name!()],
);
#[allow(clippy::expect_used)]
let web_server = Box::pin(start_web_server(
state.clone(),
scheduler_flow_str.to_string(),
))
.await
.expect("Failed to create the server");
let _task_handle = tokio::spawn(
async move {
let _ = web_server.await;
logger::error!("The health check probe stopped working!");
}
.in_current_span(),
);
logger::debug!(startup_config=?state.conf);
start_scheduler(&state, scheduler_flow, (tx, rx)).await?;
logger::error!("Scheduler shut down");
Ok(())
}
pub async fn start_web_server(
state: routes::AppState,
service: String,
) -> errors::ApplicationResult<Server> {
let server = state
.conf
.scheduler
.as_ref()
.ok_or(ApplicationError::InvalidConfigurationValueError(
"Scheduler server is invalidly configured".into(),
))?
.server
.clone();
let web_server = actix_web::HttpServer::new(move || {
actix_web::App::new().service(Health::server(state.clone(), service.clone()))
})
.bind((server.host.as_str(), server.port))
.change_context(ApplicationError::ConfigurationError)?
.workers(server.workers)
.run();
let _ = web_server.handle();
Ok(web_server)
}
pub struct Health;
impl Health {
pub fn server(state: routes::AppState, service: String) -> Scope {
web::scope("health")
.app_data(web::Data::new(state))
.app_data(web::Data::new(service))
.service(web::resource("").route(web::get().to(health)))
.service(web::resource("/ready").route(web::get().to(deep_health_check)))
}
}
#[instrument(skip_all)]
pub async fn health() -> impl actix_web::Responder {
logger::info!("Scheduler health was called");
actix_web::HttpResponse::Ok().body("Scheduler health is good")
}
#[instrument(skip_all)]
pub async fn deep_health_check(
state: web::Data<routes::AppState>,
service: web::Data<String>,
) -> impl actix_web::Responder {
let mut checks = HashMap::new();
let stores = state.stores.clone();
let app_state = Arc::clone(&state.into_inner());
let service_name = service.into_inner();
for (tenant, _) in stores {
let session_state_res = app_state.clone().get_session_state(&tenant, None, || {
errors::ApiErrorResponse::MissingRequiredField {
field_name: "tenant_id",
}
.into()
});
let session_state = match session_state_res {
Ok(state) => state,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let report = deep_health_check_func(session_state, &service_name).await;
match report {
Ok(response) => {
checks.insert(
tenant,
serde_json::to_string(&response)
.map_err(|err| {
logger::error!(serialization_error=?err);
})
.unwrap_or_default(),
);
}
Err(err) => {
return api::log_and_return_error_response(err);
}
}
}
services::http_response_json(
serde_json::to_string(&checks)
.map_err(|err| {
logger::error!(serialization_error=?err);
})
.unwrap_or_default(),
)
}
#[instrument(skip_all)]
pub async fn deep_health_check_func(
state: routes::SessionState,
service: &str,
) -> errors::RouterResult<SchedulerHealthCheckResponse> {
logger::info!("{} deep health check was called", service);
logger::debug!("Database health check begin");
let db_status = state
.health_check_db()
.await
.map(|_| true)
.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Database",
message,
})
})?;
logger::debug!("Database health check end");
logger::debug!("Redis health check begin");
let redis_status = state
.health_check_redis()
.await
.map(|_| true)
.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Redis",
message,
})
})?;
let outgoing_req_check =
state
.health_check_outgoing()
.await
.map(|_| true)
.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Outgoing Request",
message,
})
})?;
logger::debug!("Redis health check end");
let response = SchedulerHealthCheckResponse {
database: db_status,
redis: redis_status,
outgoing_request: outgoing_req_check,
};
Ok(response)
}
#[derive(Debug, Copy, Clone)]
pub struct WorkflowRunner;
#[async_trait::async_trait]
impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner {
async fn trigger_workflow<'a>(
&'a self,
state: &'a routes::SessionState,
process: storage::ProcessTracker,
) -> CustomResult<(), ProcessTrackerError> {
let runner = process
.runner
.clone()
.get_required_value("runner")
.change_context(ProcessTrackerError::MissingRequiredField)
.attach_printable("Missing runner field in process information")?;
let runner: storage::ProcessTrackerRunner = runner
.parse_enum("ProcessTrackerRunner")
.change_context(ProcessTrackerError::UnexpectedFlow)
.attach_printable("Failed to parse workflow runner name")?;
let get_operation = |runner: storage::ProcessTrackerRunner| -> CustomResult<
Box<dyn ProcessTrackerWorkflow<routes::SessionState>>,
ProcessTrackerError,
> {
match runner {
storage::ProcessTrackerRunner::PaymentsSyncWorkflow => {
Ok(Box::new(workflows::payment_sync::PaymentsSyncWorkflow))
}
storage::ProcessTrackerRunner::RefundWorkflowRouter => {
Ok(Box::new(workflows::refund_router::RefundWorkflowRouter))
}
storage::ProcessTrackerRunner::ProcessDisputeWorkflow => {
Ok(Box::new(workflows::process_dispute::ProcessDisputeWorkflow))
}
storage::ProcessTrackerRunner::DisputeListWorkflow => {
Ok(Box::new(workflows::dispute_list::DisputeListWorkflow))
}
storage::ProcessTrackerRunner::DeleteTokenizeDataWorkflow => Ok(Box::new(
workflows::tokenized_data::DeleteTokenizeDataWorkflow,
)),
storage::ProcessTrackerRunner::ApiKeyExpiryWorkflow => {
#[cfg(feature = "email")]
{
Ok(Box::new(workflows::api_key_expiry::ApiKeyExpiryWorkflow))
}
#[cfg(not(feature = "email"))]
{
Err(error_stack::report!(ProcessTrackerError::UnexpectedFlow))
.attach_printable(
"Cannot run API key expiry workflow when email feature is disabled",
)
}
}
storage::ProcessTrackerRunner::OutgoingWebhookRetryWorkflow => Ok(Box::new(
workflows::outgoing_webhook_retry::OutgoingWebhookRetryWorkflow,
)),
storage::ProcessTrackerRunner::AttachPayoutAccountWorkflow => {
#[cfg(feature = "payouts")]
{
Ok(Box::new(
workflows::attach_payout_account_workflow::AttachPayoutAccountWorkflow,
))
}
#[cfg(not(feature = "payouts"))]
{
Err(
error_stack::report!(ProcessTrackerError::UnexpectedFlow),
)
.attach_printable(
"Cannot run Stripe external account workflow when payouts feature is disabled",
)
}
}
storage::ProcessTrackerRunner::PaymentMethodStatusUpdateWorkflow => Ok(Box::new(
workflows::payment_method_status_update::PaymentMethodStatusUpdateWorkflow,
)),
storage::ProcessTrackerRunner::PassiveRecoveryWorkflow => {
Ok(Box::new(workflows::revenue_recovery::ExecutePcrWorkflow))
}
}
};
let operation = get_operation(runner)?;
let app_state = &state.clone();
let output = operation.execute_workflow(state, process.clone()).await;
match output {
Ok(_) => operation.success_handler(app_state, process).await,
Err(error) => match operation
.error_handler(app_state, process.clone(), error)
.await
{
Ok(_) => (),
Err(error) => {
logger::error!(?error, "Failed while handling error");
let status = state
.get_db()
.as_scheduler()
.finish_process_with_business_status(
process,
business_status::GLOBAL_FAILURE,
)
.await;
if let Err(error) = status {
logger::error!(
?error,
"Failed while performing database operation: {}",
business_status::GLOBAL_FAILURE
);
}
}
},
};
Ok(())
}
}
async fn start_scheduler(
state: &routes::AppState,
scheduler_flow: scheduler::SchedulerFlow,
channel: (mpsc::Sender<()>, mpsc::Receiver<()>),
) -> CustomResult<(), ProcessTrackerError> {
let scheduler_settings = state
.conf
.scheduler
.clone()
.ok_or(ProcessTrackerError::ConfigurationError)?;
scheduler::start_process_tracker(
state,
scheduler_flow,
Arc::new(scheduler_settings),
channel,
WorkflowRunner {},
|state, tenant| {
Arc::new(state.clone())
.get_session_state(tenant, None, || ProcessTrackerError::TenantNotFound.into())
},
)
.await
}
|
crates/router/src/bin/scheduler.rs
|
router
|
full_file
| null | null | null | 2,733
| null | null | null | null | null | null | null |
// Function: relay
// File: crates/router/src/routes/relay.rs
// Module: router
pub fn relay(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Json<api_models::relay::RelayRequest>,
) -> impl Responder
|
crates/router/src/routes/relay.rs
|
router
|
function_signature
| null | null | null | 66
|
relay
| null | null | null | null | null | null |
// Struct: SignifydErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct SignifydErrorResponse
|
crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs
|
hyperswitch_connectors
|
struct_definition
|
SignifydErrorResponse
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Function: server
// File: crates/router/src/routes/app.rs
// Module: router
pub fn server(state: AppState) -> Scope
|
crates/router/src/routes/app.rs
|
router
|
function_signature
| null | null | null | 29
|
server
| null | null | null | null | null | null |
// Struct: BillwerkErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct BillwerkErrorResponse
|
crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
BillwerkErrorResponse
| 0
|
[] | 48
| null | null | null | null | null | null | null |
// Function: get_request_id
// File: crates/hyperswitch_interfaces/src/events/routing_api_logs.rs
// Module: hyperswitch_interfaces
// Documentation: Returns the request ID of the event.
pub fn get_request_id(&self) -> &str
|
crates/hyperswitch_interfaces/src/events/routing_api_logs.rs
|
hyperswitch_interfaces
|
function_signature
| null | null | null | 53
|
get_request_id
| null | null | null | null | null | null |
// Implementation: impl api::PaymentAuthorize for for Adyen
// File: crates/hyperswitch_connectors/src/connectors/adyen.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentAuthorize for for Adyen
|
crates/hyperswitch_connectors/src/connectors/adyen.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Adyen
|
api::PaymentAuthorize for
| 0
| 0
| null | null |
// Implementation: impl ConnectorTransactionId for for Helcim
// File: crates/hyperswitch_connectors/src/connectors/helcim.rs
// Module: hyperswitch_connectors
// Methods: 2 total (0 public)
impl ConnectorTransactionId for for Helcim
|
crates/hyperswitch_connectors/src/connectors/helcim.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Helcim
|
ConnectorTransactionId for
| 2
| 0
| null | null |
// Implementation: impl api::RefundExecute for for Mollie
// File: crates/hyperswitch_connectors/src/connectors/mollie.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundExecute for for Mollie
|
crates/hyperswitch_connectors/src/connectors/mollie.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 62
| null |
Mollie
|
api::RefundExecute for
| 0
| 0
| null | null |
// Implementation: impl api::MandateSetup for for Authipay
// File: crates/hyperswitch_connectors/src/connectors/authipay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::MandateSetup for for Authipay
|
crates/hyperswitch_connectors/src/connectors/authipay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Authipay
|
api::MandateSetup for
| 0
| 0
| null | null |
// Function: get_three_ds_decision_rule_output
// File: crates/router/src/core/three_ds_decision_rule.rs
// Module: router
pub fn get_three_ds_decision_rule_output(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
request: api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteRequest,
) -> errors::RouterResult<common_types::three_ds_decision_rule_engine::ThreeDSDecision>
|
crates/router/src/core/three_ds_decision_rule.rs
|
router
|
function_signature
| null | null | null | 97
|
get_three_ds_decision_rule_output
| null | null | null | null | null | null |
// Trait: Operation
// File: crates/router/src/core/payments/operations.rs
// Module: router
pub trait Operation<F: Clone, T>: Send + std::fmt::Debug
|
crates/router/src/core/payments/operations.rs
|
router
|
trait_definition
| null | null | null | 39
| null | null |
Operation
| null | null | null | null |
// Implementation: impl Responder
// File: crates/router/src/analytics.rs
// Module: router
// Methods: 0 total (0 public)
impl Responder
|
crates/router/src/analytics.rs
|
router
|
impl_block
| null | null | null | 35
| null |
Responder
| null | 0
| 0
| null | null |
// Struct: RSyncSearchData
// File: crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct RSyncSearchData
|
crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
RSyncSearchData
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Implementation: impl RefundMetricAccumulator for for RefundProcessedAmountAccumulator
// File: crates/analytics/src/refunds/accumulator.rs
// Module: analytics
// Methods: 2 total (0 public)
impl RefundMetricAccumulator for for RefundProcessedAmountAccumulator
|
crates/analytics/src/refunds/accumulator.rs
|
analytics
|
impl_block
| null | null | null | 64
| null |
RefundProcessedAmountAccumulator
|
RefundMetricAccumulator for
| 2
| 0
| null | null |
// File: crates/router/src/core/authentication/utils.rs
// Module: router
// Public functions: 5
use common_utils::ext_traits::AsyncExt;
use error_stack::ResultExt;
use hyperswitch_domain_models::router_data_v2::ExternalAuthenticationFlowData;
use masking::ExposeInterface;
use crate::{
consts,
core::{
errors::{self, ConnectorErrorExt, StorageErrorExt},
payments,
},
errors::RouterResult,
routes::SessionState,
services::{self, execute_connector_processing_step},
types::{
api, authentication::AuthenticationResponseData, domain, storage,
transformers::ForeignFrom, RouterData,
},
utils::OptionExt,
};
#[cfg(feature = "v1")]
pub fn get_connector_data_if_separate_authn_supported(
connector_call_type: &api::ConnectorCallType,
) -> Option<api::ConnectorData> {
match connector_call_type {
api::ConnectorCallType::PreDetermined(connector_routing_data) => {
if connector_routing_data
.connector_data
.connector_name
.is_separate_authentication_supported()
{
Some(connector_routing_data.connector_data.clone())
} else {
None
}
}
api::ConnectorCallType::Retryable(connector_routing_data) => connector_routing_data
.first()
.and_then(|connector_routing_data| {
if connector_routing_data
.connector_data
.connector_name
.is_separate_authentication_supported()
{
Some(connector_routing_data.connector_data.clone())
} else {
None
}
}),
api::ConnectorCallType::SessionMultiple(_) => None,
}
}
pub async fn update_trackers<F: Clone, Req>(
state: &SessionState,
router_data: RouterData<F, Req, AuthenticationResponseData>,
authentication: storage::Authentication,
acquirer_details: Option<super::types::AcquirerDetails>,
merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
) -> RouterResult<storage::Authentication> {
let authentication_update = match router_data.response {
Ok(response) => match response {
AuthenticationResponseData::PreAuthNResponse {
threeds_server_transaction_id,
maximum_supported_3ds_version,
connector_authentication_id,
three_ds_method_data,
three_ds_method_url,
message_version,
connector_metadata,
directory_server_id,
} => storage::AuthenticationUpdate::PreAuthenticationUpdate {
threeds_server_transaction_id,
maximum_supported_3ds_version,
connector_authentication_id,
three_ds_method_data,
three_ds_method_url,
message_version,
connector_metadata,
authentication_status: common_enums::AuthenticationStatus::Pending,
acquirer_bin: acquirer_details
.as_ref()
.map(|acquirer_details| acquirer_details.acquirer_bin.clone()),
acquirer_merchant_id: acquirer_details
.as_ref()
.map(|acquirer_details| acquirer_details.acquirer_merchant_id.clone()),
acquirer_country_code: acquirer_details
.and_then(|acquirer_details| acquirer_details.acquirer_country_code),
directory_server_id,
billing_address: None,
shipping_address: None,
browser_info: Box::new(None),
email: None,
},
AuthenticationResponseData::AuthNResponse {
authn_flow_type,
authentication_value,
trans_status,
connector_metadata,
ds_trans_id,
eci,
challenge_code,
challenge_cancel,
challenge_code_reason,
message_extension,
} => {
authentication_value
.async_map(|auth_val| {
crate::core::payment_methods::vault::create_tokenize(
state,
auth_val.expose(),
None,
authentication
.authentication_id
.get_string_repr()
.to_string(),
merchant_key_store.key.get_inner(),
)
})
.await
.transpose()?;
let authentication_status =
common_enums::AuthenticationStatus::foreign_from(trans_status.clone());
storage::AuthenticationUpdate::AuthenticationUpdate {
trans_status,
acs_url: authn_flow_type.get_acs_url(),
challenge_request: authn_flow_type.get_challenge_request(),
challenge_request_key: authn_flow_type.get_challenge_request_key(),
acs_reference_number: authn_flow_type.get_acs_reference_number(),
acs_trans_id: authn_flow_type.get_acs_trans_id(),
acs_signed_content: authn_flow_type.get_acs_signed_content(),
authentication_type: authn_flow_type.get_decoupled_authentication_type(),
authentication_status,
connector_metadata,
ds_trans_id,
eci,
challenge_code,
challenge_cancel,
challenge_code_reason,
message_extension,
}
}
AuthenticationResponseData::PostAuthNResponse {
trans_status,
authentication_value,
eci,
challenge_cancel,
challenge_code_reason,
} => {
authentication_value
.async_map(|auth_val| {
crate::core::payment_methods::vault::create_tokenize(
state,
auth_val.expose(),
None,
authentication
.authentication_id
.get_string_repr()
.to_string(),
merchant_key_store.key.get_inner(),
)
})
.await
.transpose()?;
storage::AuthenticationUpdate::PostAuthenticationUpdate {
authentication_status: common_enums::AuthenticationStatus::foreign_from(
trans_status.clone(),
),
trans_status,
eci,
challenge_cancel,
challenge_code_reason,
}
}
AuthenticationResponseData::PreAuthVersionCallResponse {
maximum_supported_3ds_version,
} => storage::AuthenticationUpdate::PreAuthenticationVersionCallUpdate {
message_version: maximum_supported_3ds_version.clone(),
maximum_supported_3ds_version,
},
AuthenticationResponseData::PreAuthThreeDsMethodCallResponse {
threeds_server_transaction_id,
three_ds_method_data,
three_ds_method_url,
connector_metadata,
} => storage::AuthenticationUpdate::PreAuthenticationThreeDsMethodCall {
threeds_server_transaction_id,
three_ds_method_data,
three_ds_method_url,
connector_metadata,
acquirer_bin: acquirer_details
.as_ref()
.map(|acquirer_details| acquirer_details.acquirer_bin.clone()),
acquirer_merchant_id: acquirer_details
.map(|acquirer_details| acquirer_details.acquirer_merchant_id),
},
},
Err(error) => storage::AuthenticationUpdate::ErrorUpdate {
connector_authentication_id: error.connector_transaction_id,
authentication_status: common_enums::AuthenticationStatus::Failed,
error_message: error
.reason
.map(|reason| format!("message: {}, reason: {}", error.message, reason))
.or(Some(error.message)),
error_code: Some(error.code),
},
};
state
.store
.update_authentication_by_merchant_id_authentication_id(
authentication,
authentication_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while updating authentication")
}
impl ForeignFrom<common_enums::AuthenticationStatus> for common_enums::AttemptStatus {
fn foreign_from(from: common_enums::AuthenticationStatus) -> Self {
match from {
common_enums::AuthenticationStatus::Started
| common_enums::AuthenticationStatus::Pending => Self::AuthenticationPending,
common_enums::AuthenticationStatus::Success => Self::AuthenticationSuccessful,
common_enums::AuthenticationStatus::Failed => Self::AuthenticationFailed,
}
}
}
#[allow(clippy::too_many_arguments)]
pub async fn create_new_authentication(
state: &SessionState,
merchant_id: common_utils::id_type::MerchantId,
authentication_connector: String,
token: String,
profile_id: common_utils::id_type::ProfileId,
payment_id: common_utils::id_type::PaymentId,
merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
organization_id: common_utils::id_type::OrganizationId,
force_3ds_challenge: Option<bool>,
psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
) -> RouterResult<storage::Authentication> {
let authentication_id = common_utils::id_type::AuthenticationId::generate_authentication_id(
consts::AUTHENTICATION_ID_PREFIX,
);
let authentication_client_secret = Some(common_utils::generate_id_with_default_len(&format!(
"{}_secret",
authentication_id.get_string_repr()
)));
let new_authorization = storage::AuthenticationNew {
authentication_id: authentication_id.clone(),
merchant_id,
authentication_connector: Some(authentication_connector),
connector_authentication_id: None,
payment_method_id: format!("eph_{token}"),
authentication_type: None,
authentication_status: common_enums::AuthenticationStatus::Started,
authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus::Unused,
error_message: None,
error_code: None,
connector_metadata: None,
maximum_supported_version: None,
threeds_server_transaction_id: None,
cavv: None,
authentication_flow_type: None,
message_version: None,
eci: None,
trans_status: None,
acquirer_bin: None,
acquirer_merchant_id: None,
three_ds_method_data: None,
three_ds_method_url: None,
acs_url: None,
challenge_request: None,
challenge_request_key: None,
acs_reference_number: None,
acs_trans_id: None,
acs_signed_content: None,
profile_id,
payment_id: Some(payment_id),
merchant_connector_id: Some(merchant_connector_id),
ds_trans_id: None,
directory_server_id: None,
acquirer_country_code: None,
service_details: None,
organization_id,
authentication_client_secret,
force_3ds_challenge,
psd2_sca_exemption_type,
return_url: None,
amount: None,
currency: None,
billing_address: None,
shipping_address: None,
browser_info: None,
email: None,
profile_acquirer_id: None,
challenge_code: None,
challenge_cancel: None,
challenge_code_reason: None,
message_extension: None,
};
state
.store
.insert_authentication(new_authorization)
.await
.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
message: format!(
"Authentication with authentication_id {} already exists",
authentication_id.get_string_repr()
),
})
}
pub async fn do_auth_connector_call<F, Req, Res>(
state: &SessionState,
authentication_connector_name: String,
router_data: RouterData<F, Req, Res>,
) -> RouterResult<RouterData<F, Req, Res>>
where
Req: std::fmt::Debug + Clone + 'static,
Res: std::fmt::Debug + Clone + 'static,
F: std::fmt::Debug + Clone + 'static,
dyn api::Connector + Sync: services::api::ConnectorIntegration<F, Req, Res>,
dyn api::ConnectorV2 + Sync:
services::api::ConnectorIntegrationV2<F, ExternalAuthenticationFlowData, Req, Res>,
{
let connector_data =
api::AuthenticationConnectorData::get_connector_by_name(&authentication_connector_name)?;
let connector_integration: services::BoxedExternalAuthenticationConnectorIntegrationInterface<
F,
Req,
Res,
> = connector_data.connector.get_connector_integration();
let router_data = execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
Ok(router_data)
}
pub async fn get_authentication_connector_data(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
business_profile: &domain::Profile,
authentication_connector: Option<String>,
) -> RouterResult<(
common_enums::AuthenticationConnectors,
payments::helpers::MerchantConnectorAccountType,
)> {
let authentication_connector = if let Some(authentication_connector) = authentication_connector
{
api_models::enums::convert_authentication_connector(&authentication_connector).ok_or(
errors::ApiErrorResponse::UnprocessableEntity {
message: format!(
"Invalid authentication_connector found in request : {authentication_connector}",
),
},
)?
} else {
let authentication_details = business_profile
.authentication_connector_details
.clone()
.get_required_value("authentication_details")
.change_context(errors::ApiErrorResponse::UnprocessableEntity {
message: "authentication_connector_details is not available in business profile"
.into(),
})
.attach_printable("authentication_connector_details not configured by the merchant")?;
authentication_details
.authentication_connectors
.first()
.ok_or(errors::ApiErrorResponse::UnprocessableEntity {
message: format!(
"No authentication_connector found for profile_id {:?}",
business_profile.get_id()
),
})
.attach_printable(
"No authentication_connector found from merchant_account.authentication_details",
)?
.to_owned()
};
let profile_id = business_profile.get_id();
let authentication_connector_mca = payments::helpers::get_merchant_connector_account(
state,
&business_profile.merchant_id,
None,
key_store,
profile_id,
authentication_connector.to_string().as_str(),
None,
)
.await?;
Ok((authentication_connector, authentication_connector_mca))
}
|
crates/router/src/core/authentication/utils.rs
|
router
|
full_file
| null | null | null | 2,885
| null | null | null | null | null | null | null |
// Function: build_and_send_decision_engine_http_request
// File: crates/router/src/core/payments/routing/utils.rs
// Module: router
pub fn build_and_send_decision_engine_http_request<Req, Res, ErrRes>(
state: &SessionState,
http_method: services::Method,
path: &str,
request_body: Option<Req>,
_timeout: Option<u64>,
context_message: &str,
events_wrapper: Option<RoutingEventsWrapper<Req>>,
) -> RoutingResult<RoutingEventsResponse<Res>>
where
Req: Serialize + Send + Sync + 'static + Clone,
Res: Serialize + serde::de::DeserializeOwned + std::fmt::Debug + Clone + 'static,
ErrRes: serde::de::DeserializeOwned + std::fmt::Debug + Clone + DecisionEngineErrorsInterface,
|
crates/router/src/core/payments/routing/utils.rs
|
router
|
function_signature
| null | null | null | 178
|
build_and_send_decision_engine_http_request
| null | null | null | null | null | null |
// Struct: ErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/payone/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ErrorResponse
|
crates/hyperswitch_connectors/src/connectors/payone/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ErrorResponse
| 0
|
[] | 43
| null | null | null | null | null | null | null |
// Function: get_crm_client
// File: crates/external_services/src/crm.rs
// Module: external_services
// Documentation: Retrieves the appropriate Crm client based on the configuration.
pub fn get_crm_client(&self) -> Arc<dyn CrmInterface>
|
crates/external_services/src/crm.rs
|
external_services
|
function_signature
| null | null | null | 56
|
get_crm_client
| null | null | null | null | null | null |
// Function: signal_handler
// File: crates/common_utils/src/signals.rs
// Module: common_utils
pub fn signal_handler(mut sig: signal_hook_tokio::Signals, sender: mpsc::Sender<()
|
crates/common_utils/src/signals.rs
|
common_utils
|
function_signature
| null | null | null | 45
|
signal_handler
| null | null | null | null | null | null |
// File: crates/analytics/src/refunds/accumulator.rs
// Module: analytics
// Public functions: 1
// Public structs: 9
use api_models::analytics::refunds::{
ErrorMessagesResult, ReasonsResult, RefundMetricsBucketValue,
};
use bigdecimal::ToPrimitive;
use diesel_models::enums as storage_enums;
use super::{distribution::RefundDistributionRow, metrics::RefundMetricRow};
#[derive(Debug, Default)]
pub struct RefundMetricsAccumulator {
pub refund_success_rate: SuccessRateAccumulator,
pub refund_count: CountAccumulator,
pub refund_success: CountAccumulator,
pub processed_amount: RefundProcessedAmountAccumulator,
pub refund_reason: RefundReasonAccumulator,
pub refund_reason_distribution: RefundReasonDistributionAccumulator,
pub refund_error_message: RefundReasonAccumulator,
pub refund_error_message_distribution: RefundErrorMessageDistributionAccumulator,
}
#[derive(Debug, Default)]
pub struct RefundReasonDistributionRow {
pub count: i64,
pub total: i64,
pub refund_reason: String,
}
#[derive(Debug, Default)]
pub struct RefundReasonDistributionAccumulator {
pub refund_reason_vec: Vec<RefundReasonDistributionRow>,
}
#[derive(Debug, Default)]
pub struct RefundErrorMessageDistributionRow {
pub count: i64,
pub total: i64,
pub refund_error_message: String,
}
#[derive(Debug, Default)]
pub struct RefundErrorMessageDistributionAccumulator {
pub refund_error_message_vec: Vec<RefundErrorMessageDistributionRow>,
}
#[derive(Debug, Default)]
#[repr(transparent)]
pub struct RefundReasonAccumulator {
pub count: u64,
}
#[derive(Debug, Default)]
pub struct SuccessRateAccumulator {
pub success: u32,
pub total: u32,
}
#[derive(Debug, Default)]
#[repr(transparent)]
pub struct CountAccumulator {
pub count: Option<i64>,
}
#[derive(Debug, Default)]
pub struct RefundProcessedAmountAccumulator {
pub count: Option<i64>,
pub total: Option<i64>,
}
pub trait RefundMetricAccumulator {
type MetricOutput;
fn add_metrics_bucket(&mut self, metrics: &RefundMetricRow);
fn collect(self) -> Self::MetricOutput;
}
pub trait RefundDistributionAccumulator {
type DistributionOutput;
fn add_distribution_bucket(&mut self, distribution: &RefundDistributionRow);
fn collect(self) -> Self::DistributionOutput;
}
impl RefundDistributionAccumulator for RefundReasonDistributionAccumulator {
type DistributionOutput = Option<Vec<ReasonsResult>>;
fn add_distribution_bucket(&mut self, distribution: &RefundDistributionRow) {
self.refund_reason_vec.push(RefundReasonDistributionRow {
count: distribution.count.unwrap_or_default(),
total: distribution
.total
.clone()
.map(|i| i.to_i64().unwrap_or_default())
.unwrap_or_default(),
refund_reason: distribution.refund_reason.clone().unwrap_or_default(),
})
}
fn collect(mut self) -> Self::DistributionOutput {
if self.refund_reason_vec.is_empty() {
None
} else {
self.refund_reason_vec.sort_by(|a, b| b.count.cmp(&a.count));
let mut res: Vec<ReasonsResult> = Vec::new();
for val in self.refund_reason_vec.into_iter() {
let perc = f64::from(u32::try_from(val.count).ok()?) * 100.0
/ f64::from(u32::try_from(val.total).ok()?);
res.push(ReasonsResult {
reason: val.refund_reason,
count: val.count,
percentage: (perc * 100.0).round() / 100.0,
})
}
Some(res)
}
}
}
impl RefundDistributionAccumulator for RefundErrorMessageDistributionAccumulator {
type DistributionOutput = Option<Vec<ErrorMessagesResult>>;
fn add_distribution_bucket(&mut self, distribution: &RefundDistributionRow) {
self.refund_error_message_vec
.push(RefundErrorMessageDistributionRow {
count: distribution.count.unwrap_or_default(),
total: distribution
.total
.clone()
.map(|i| i.to_i64().unwrap_or_default())
.unwrap_or_default(),
refund_error_message: distribution
.refund_error_message
.clone()
.unwrap_or_default(),
})
}
fn collect(mut self) -> Self::DistributionOutput {
if self.refund_error_message_vec.is_empty() {
None
} else {
self.refund_error_message_vec
.sort_by(|a, b| b.count.cmp(&a.count));
let mut res: Vec<ErrorMessagesResult> = Vec::new();
for val in self.refund_error_message_vec.into_iter() {
let perc = f64::from(u32::try_from(val.count).ok()?) * 100.0
/ f64::from(u32::try_from(val.total).ok()?);
res.push(ErrorMessagesResult {
error_message: val.refund_error_message,
count: val.count,
percentage: (perc * 100.0).round() / 100.0,
})
}
Some(res)
}
}
}
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())
}
}
impl RefundMetricAccumulator for RefundProcessedAmountAccumulator {
type MetricOutput = (Option<u64>, Option<u64>, Option<u64>);
#[inline]
fn add_metrics_bucket(&mut self, metrics: &RefundMetricRow) {
self.total = match (
self.total,
metrics.total.as_ref().and_then(ToPrimitive::to_i64),
) {
(None, None) => None,
(None, i @ Some(_)) | (i @ Some(_), None) => i,
(Some(a), Some(b)) => Some(a + b),
};
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 {
let total = u64::try_from(self.total.unwrap_or_default()).ok();
let count = self.count.and_then(|i| u64::try_from(i).ok());
(total, count, Some(0))
}
}
impl RefundMetricAccumulator for SuccessRateAccumulator {
type MetricOutput = (Option<u32>, Option<u32>, Option<f64>);
fn add_metrics_bucket(&mut self, metrics: &RefundMetricRow) {
if let Some(ref refund_status) = metrics.refund_status {
if refund_status.as_ref() == &storage_enums::RefundStatus::Success {
if let Some(success) = metrics
.count
.and_then(|success| u32::try_from(success).ok())
{
self.success += success;
}
}
};
if let Some(total) = metrics.count.and_then(|total| u32::try_from(total).ok()) {
self.total += total;
}
}
fn collect(self) -> Self::MetricOutput {
if self.total == 0 {
(None, None, None)
} else {
let success = Some(self.success);
let total = Some(self.total);
let success_rate = match (success, total) {
(Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
_ => None,
};
(success, total, success_rate)
}
}
}
impl RefundMetricAccumulator for RefundReasonAccumulator {
type MetricOutput = Option<u64>;
fn add_metrics_bucket(&mut self, metrics: &RefundMetricRow) {
if let Some(count) = metrics.count {
if let Ok(count_u64) = u64::try_from(count) {
self.count += count_u64;
}
}
}
fn collect(self) -> Self::MetricOutput {
Some(self.count)
}
}
impl RefundMetricsAccumulator {
pub fn collect(self) -> RefundMetricsBucketValue {
let (successful_refunds, total_refunds, refund_success_rate) =
self.refund_success_rate.collect();
let (refund_processed_amount, refund_processed_count, refund_processed_amount_in_usd) =
self.processed_amount.collect();
RefundMetricsBucketValue {
successful_refunds,
total_refunds,
refund_success_rate,
refund_count: self.refund_count.collect(),
refund_success_count: self.refund_success.collect(),
refund_processed_amount,
refund_processed_amount_in_usd,
refund_processed_count,
refund_reason_distribution: self.refund_reason_distribution.collect(),
refund_error_message_distribution: self.refund_error_message_distribution.collect(),
refund_reason_count: self.refund_reason.collect(),
refund_error_message_count: self.refund_error_message.collect(),
}
}
}
|
crates/analytics/src/refunds/accumulator.rs
|
analytics
|
full_file
| null | null | null | 2,173
| null | null | null | null | null | null | null |
// Function: populate_vault_session_details
// File: crates/router/src/core/payments/vault_session.rs
// Module: router
pub fn populate_vault_session_details<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
req_state: ReqState,
customer: &Option<domain::Customer>,
merchant_context: &domain::MerchantContext,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
profile: &domain::Profile,
payment_data: &mut D,
header_payload: HeaderPayload,
) -> RouterResult<()>
where
F: Send + Clone + Sync,
RouterDReq: Send + Sync,
// To create connector flow specific interface data
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
|
crates/router/src/core/payments/vault_session.rs
|
router
|
function_signature
| null | null | null | 259
|
populate_vault_session_details
| null | null | null | null | null | null |
// File: crates/scheduler/src/consumer.rs
// Module: scheduler
// Public functions: 7
// TODO: Figure out what to log
use std::{
sync::{self, atomic},
time as std_time,
};
pub mod types;
pub mod workflows;
use common_utils::{errors::CustomResult, id_type, signals::get_allowed_signals};
use diesel_models::enums;
pub use diesel_models::{self, process_tracker as storage};
use error_stack::ResultExt;
use futures::future;
use redis_interface::{RedisConnectionPool, RedisEntryId};
use router_env::{
instrument,
tracing::{self, Instrument},
};
use time::PrimitiveDateTime;
use tokio::sync::mpsc;
use uuid::Uuid;
use super::env::logger;
pub use super::workflows::ProcessTrackerWorkflow;
use crate::{
configs::settings::SchedulerSettings, db::process_tracker::ProcessTrackerInterface, errors,
metrics, utils as pt_utils, SchedulerAppState, SchedulerInterface, SchedulerSessionState,
};
// Valid consumer business statuses
pub fn valid_business_statuses() -> Vec<&'static str> {
vec![storage::business_status::PENDING]
}
#[instrument(skip_all)]
pub async fn start_consumer<T: SchedulerAppState + 'static, U: SchedulerSessionState + 'static, F>(
state: &T,
settings: sync::Arc<SchedulerSettings>,
workflow_selector: impl workflows::ProcessTrackerWorkflows<U> + 'static + Copy + std::fmt::Debug,
(tx, mut rx): (mpsc::Sender<()>, mpsc::Receiver<()>),
app_state_to_session_state: F,
) -> CustomResult<(), errors::ProcessTrackerError>
where
F: Fn(&T, &id_type::TenantId) -> CustomResult<U, errors::ProcessTrackerError>,
{
use std::time::Duration;
use rand::distributions::{Distribution, Uniform};
let mut rng = rand::thread_rng();
// TODO: this can be removed once rand-0.9 is released
// reference - https://github.com/rust-random/rand/issues/1326#issuecomment-1635331942
#[allow(unknown_lints)]
#[allow(clippy::unnecessary_fallible_conversions)]
let timeout = Uniform::try_from(0..=settings.loop_interval)
.change_context(errors::ProcessTrackerError::ConfigurationError)?;
tokio::time::sleep(Duration::from_millis(timeout.sample(&mut rng))).await;
let mut interval = tokio::time::interval(Duration::from_millis(settings.loop_interval));
let mut shutdown_interval =
tokio::time::interval(Duration::from_millis(settings.graceful_shutdown_interval));
let consumer_operation_counter = sync::Arc::new(atomic::AtomicU64::new(0));
let signal = get_allowed_signals()
.map_err(|error| {
logger::error!(?error, "Signal Handler Error");
errors::ProcessTrackerError::ConfigurationError
})
.attach_printable("Failed while creating a signals handler")?;
let handle = signal.handle();
let task_handle =
tokio::spawn(common_utils::signals::signal_handler(signal, tx).in_current_span());
'consumer: loop {
match rx.try_recv() {
Err(mpsc::error::TryRecvError::Empty) => {
interval.tick().await;
// A guard from env to disable the consumer
if settings.consumer.disabled {
continue;
}
consumer_operation_counter.fetch_add(1, atomic::Ordering::SeqCst);
let start_time = std_time::Instant::now();
let tenants = state.get_tenants();
for tenant in tenants {
let session_state = app_state_to_session_state(state, &tenant)?;
pt_utils::consumer_operation_handler(
session_state.clone(),
settings.clone(),
|error| {
logger::error!(?error, "Failed to perform consumer operation");
},
workflow_selector,
)
.await;
}
let end_time = std_time::Instant::now();
let duration = end_time.saturating_duration_since(start_time).as_secs_f64();
logger::debug!("Time taken to execute consumer_operation: {}s", duration);
let current_count =
consumer_operation_counter.fetch_sub(1, atomic::Ordering::SeqCst);
logger::info!("Current tasks being executed: {}", current_count);
}
Ok(()) | Err(mpsc::error::TryRecvError::Disconnected) => {
logger::debug!("Awaiting shutdown!");
rx.close();
loop {
shutdown_interval.tick().await;
let active_tasks = consumer_operation_counter.load(atomic::Ordering::Acquire);
logger::info!("Active tasks: {active_tasks}");
match active_tasks {
0 => {
logger::info!("Terminating consumer");
break 'consumer;
}
_ => continue,
}
}
}
}
}
handle.close();
task_handle
.await
.change_context(errors::ProcessTrackerError::UnexpectedFlow)?;
Ok(())
}
#[instrument(skip_all)]
pub async fn consumer_operations<T: SchedulerSessionState + 'static>(
state: &T,
settings: &SchedulerSettings,
workflow_selector: impl workflows::ProcessTrackerWorkflows<T> + 'static + Copy + std::fmt::Debug,
) -> CustomResult<(), errors::ProcessTrackerError> {
let stream_name = settings.stream.clone();
let group_name = settings.consumer.consumer_group.clone();
let consumer_name = format!("consumer_{}", Uuid::new_v4());
let _group_created = &mut state
.get_db()
.consumer_group_create(&stream_name, &group_name, &RedisEntryId::AfterLastID)
.await;
let mut tasks = state
.get_db()
.as_scheduler()
.fetch_consumer_tasks(&stream_name, &group_name, &consumer_name)
.await?;
if !tasks.is_empty() {
logger::info!("{} picked {} tasks", consumer_name, tasks.len());
}
let mut handler = vec![];
for task in tasks.iter_mut() {
let pickup_time = common_utils::date_time::now();
pt_utils::add_histogram_metrics(&pickup_time, task, &stream_name);
metrics::TASK_CONSUMED.add(1, &[]);
handler.push(tokio::task::spawn(start_workflow(
state.clone(),
task.clone(),
pickup_time,
workflow_selector,
)))
}
future::join_all(handler).await;
Ok(())
}
#[instrument(skip(db, redis_conn))]
pub async fn fetch_consumer_tasks(
db: &dyn ProcessTrackerInterface,
redis_conn: &RedisConnectionPool,
stream_name: &str,
group_name: &str,
consumer_name: &str,
) -> CustomResult<Vec<storage::ProcessTracker>, errors::ProcessTrackerError> {
let batches = pt_utils::get_batches(redis_conn, stream_name, group_name, consumer_name).await?;
// Returning early to avoid execution of database queries when `batches` is empty
if batches.is_empty() {
return Ok(Vec::new());
}
let mut tasks = batches.into_iter().fold(Vec::new(), |mut acc, batch| {
acc.extend_from_slice(
batch
.trackers
.into_iter()
.filter(|task| task.is_valid_business_status(&valid_business_statuses()))
.collect::<Vec<_>>()
.as_slice(),
);
acc
});
let task_ids = tasks
.iter()
.map(|task| task.id.to_owned())
.collect::<Vec<_>>();
db.process_tracker_update_process_status_by_ids(
task_ids,
storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::ProcessStarted,
business_status: None,
},
)
.await
.change_context(errors::ProcessTrackerError::ProcessFetchingFailed)?;
tasks
.iter_mut()
.for_each(|x| x.status = enums::ProcessTrackerStatus::ProcessStarted);
Ok(tasks)
}
// Accept flow_options if required
#[instrument(skip(state), fields(workflow_id))]
pub async fn start_workflow<T>(
state: T,
process: storage::ProcessTracker,
_pickup_time: PrimitiveDateTime,
workflow_selector: impl workflows::ProcessTrackerWorkflows<T> + 'static + std::fmt::Debug,
) -> CustomResult<(), errors::ProcessTrackerError>
where
T: SchedulerSessionState,
{
tracing::Span::current().record("workflow_id", Uuid::new_v4().to_string());
logger::info!(pt.name=?process.name, pt.id=%process.id);
let res = workflow_selector
.trigger_workflow(&state.clone(), process.clone())
.await
.inspect_err(|error| {
logger::error!(?error, "Failed to trigger workflow");
});
metrics::TASK_PROCESSED.add(1, &[]);
res
}
#[instrument(skip_all)]
pub async fn consumer_error_handler(
state: &(dyn SchedulerInterface + 'static),
process: storage::ProcessTracker,
error: errors::ProcessTrackerError,
) -> CustomResult<(), errors::ProcessTrackerError> {
logger::error!(pt.name=?process.name, pt.id=%process.id, ?error, "Failed to execute workflow");
state
.process_tracker_update_process_status_by_ids(
vec![process.id],
storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Finish,
business_status: Some(String::from(storage::business_status::GLOBAL_ERROR)),
},
)
.await
.change_context(errors::ProcessTrackerError::ProcessUpdateFailed)?;
Ok(())
}
pub async fn create_task(
db: &dyn ProcessTrackerInterface,
process_tracker_entry: storage::ProcessTrackerNew,
) -> CustomResult<(), storage_impl::errors::StorageError> {
db.insert_process(process_tracker_entry).await?;
Ok(())
}
|
crates/scheduler/src/consumer.rs
|
scheduler
|
full_file
| null | null | null | 2,137
| null | null | null | null | null | null | null |
// Function: get_payments_aggregates
// File: crates/router/src/routes/payments.rs
// Module: router
pub fn get_payments_aggregates(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Query<common_utils::types::TimeRange>,
) -> impl Responder
|
crates/router/src/routes/payments.rs
|
router
|
function_signature
| null | null | null | 73
|
get_payments_aggregates
| null | null | null | null | null | null |
// Implementation: impl api::Refund for for Adyen
// File: crates/hyperswitch_connectors/src/connectors/adyen.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::Refund for for Adyen
|
crates/hyperswitch_connectors/src/connectors/adyen.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Adyen
|
api::Refund for
| 0
| 0
| null | null |
// Struct: RetryMapping
// File: crates/scheduler/src/consumer/types/process_data.rs
// Module: scheduler
// Implementations: 0
pub struct RetryMapping
|
crates/scheduler/src/consumer/types/process_data.rs
|
scheduler
|
struct_definition
|
RetryMapping
| 0
|
[] | 36
| null | null | null | null | null | null | null |
// File: crates/common_utils/src/tokenization.rs
// Module: common_utils
// Public functions: 1
//! Module for tokenization-related functionality
//!
//! This module provides types and functions for handling tokenized payment data,
//! including response structures and token generation utilities.
use crate::consts::TOKEN_LENGTH;
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
/// Generates a new token string
///
/// # Returns
/// A randomly generated token string of length `TOKEN_LENGTH`
pub fn generate_token() -> String {
use nanoid::nanoid;
nanoid!(TOKEN_LENGTH)
}
|
crates/common_utils/src/tokenization.rs
|
common_utils
|
full_file
| null | null | null | 130
| null | null | null | null | null | null | null |
// Struct: RefundData
// File: crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct RefundData
|
crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
RefundData
| 0
|
[] | 48
| null | null | null | null | null | null | null |
// Function: update_role
// File: crates/router/src/routes/user_role.rs
// Module: router
pub fn update_role(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<role_api::UpdateRoleRequest>,
path: web::Path<String>,
) -> HttpResponse
|
crates/router/src/routes/user_role.rs
|
router
|
function_signature
| null | null | null | 67
|
update_role
| null | null | null | null | null | null |
// Implementation: impl Braintree
// File: crates/hyperswitch_connectors/src/connectors/braintree.rs
// Module: hyperswitch_connectors
// Methods: 1 total (0 public)
impl Braintree
|
crates/hyperswitch_connectors/src/connectors/braintree.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 46
| null |
Braintree
| null | 1
| 0
| null | null |
// Struct: EuclidApiClient
// File: crates/router/src/core/payments/routing/utils.rs
// Module: router
// Implementations: 1
// Traits: DecisionEngineApiHandler
pub struct EuclidApiClient
|
crates/router/src/core/payments/routing/utils.rs
|
router
|
struct_definition
|
EuclidApiClient
| 1
|
[
"DecisionEngineApiHandler"
] | 46
| null | null | null | null | null | null | null |
// Implementation: impl CardNetworkTokenizeExecutor
// File: crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
// Module: router
// Methods: 3 total (0 public)
impl CardNetworkTokenizeExecutor
|
crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
|
router
|
impl_block
| null | null | null | 47
| null |
CardNetworkTokenizeExecutor
| null | 3
| 0
| null | null |
// Struct: PartnerReferralRequest
// File: crates/router/src/types/api/connector_onboarding/paypal.rs
// Module: router
// Implementations: 1
pub struct PartnerReferralRequest
|
crates/router/src/types/api/connector_onboarding/paypal.rs
|
router
|
struct_definition
|
PartnerReferralRequest
| 1
|
[] | 42
| null | null | null | null | null | null | null |
// File: crates/masking/src/secret.rs
// Module: masking
// Public functions: 5
// Public structs: 1
//! Structure describing secret.
use std::{fmt, marker::PhantomData};
use crate::{strategy::Strategy, PeekInterface, StrongSecret};
/// Secret thing.
///
/// To get access to value use method `expose()` of trait [`crate::ExposeInterface`].
///
/// ## Masking
/// Use the [`crate::strategy::Strategy`] trait to implement a masking strategy on a zero-variant
/// enum and pass this enum as a second generic parameter to [`Secret`] while defining it.
/// [`Secret`] will take care of applying the masking strategy on the inner secret when being
/// displayed.
///
/// ## Masking Example
///
/// ```
/// use masking::Strategy;
/// use masking::Secret;
/// use std::fmt;
///
/// enum MyStrategy {}
///
/// impl<T> Strategy<T> for MyStrategy
/// where
/// T: fmt::Display
/// {
/// fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// write!(f, "{}", val.to_string().to_ascii_lowercase())
/// }
/// }
///
/// let my_secret: Secret<String, MyStrategy> = Secret::new("HELLO".to_string());
///
/// assert_eq!("hello", &format!("{:?}", my_secret));
/// ```
pub struct Secret<Secret, MaskingStrategy = crate::WithType>
where
MaskingStrategy: Strategy<Secret>,
{
pub(crate) inner_secret: Secret,
pub(crate) masking_strategy: PhantomData<MaskingStrategy>,
}
impl<SecretValue, MaskingStrategy> Secret<SecretValue, MaskingStrategy>
where
MaskingStrategy: Strategy<SecretValue>,
{
/// Take ownership of a secret value
pub fn new(secret: SecretValue) -> Self {
Self {
inner_secret: secret,
masking_strategy: PhantomData,
}
}
/// Zip 2 secrets with the same masking strategy into one
pub fn zip<OtherSecretValue>(
self,
other: Secret<OtherSecretValue, MaskingStrategy>,
) -> Secret<(SecretValue, OtherSecretValue), MaskingStrategy>
where
MaskingStrategy: Strategy<OtherSecretValue> + Strategy<(SecretValue, OtherSecretValue)>,
{
(self.inner_secret, other.inner_secret).into()
}
/// consume self and modify the inner value
pub fn map<OtherSecretValue>(
self,
f: impl FnOnce(SecretValue) -> OtherSecretValue,
) -> Secret<OtherSecretValue, MaskingStrategy>
where
MaskingStrategy: Strategy<OtherSecretValue>,
{
f(self.inner_secret).into()
}
/// Convert to [`StrongSecret`]
pub fn into_strong(self) -> StrongSecret<SecretValue, MaskingStrategy>
where
SecretValue: zeroize::DefaultIsZeroes,
{
StrongSecret::new(self.inner_secret)
}
/// Convert to [`Secret`] with a reference to the inner secret
pub fn as_ref(&self) -> Secret<&SecretValue, MaskingStrategy>
where
MaskingStrategy: for<'a> Strategy<&'a SecretValue>,
{
Secret::new(self.peek())
}
}
impl<SecretValue, MaskingStrategy> PeekInterface<SecretValue>
for Secret<SecretValue, MaskingStrategy>
where
MaskingStrategy: Strategy<SecretValue>,
{
fn peek(&self) -> &SecretValue {
&self.inner_secret
}
fn peek_mut(&mut self) -> &mut SecretValue {
&mut self.inner_secret
}
}
impl<SecretValue, MaskingStrategy> From<SecretValue> for Secret<SecretValue, MaskingStrategy>
where
MaskingStrategy: Strategy<SecretValue>,
{
fn from(secret: SecretValue) -> Self {
Self::new(secret)
}
}
impl<SecretValue, MaskingStrategy> Clone for Secret<SecretValue, MaskingStrategy>
where
SecretValue: Clone,
MaskingStrategy: Strategy<SecretValue>,
{
fn clone(&self) -> Self {
Self {
inner_secret: self.inner_secret.clone(),
masking_strategy: PhantomData,
}
}
}
impl<SecretValue, MaskingStrategy> PartialEq for Secret<SecretValue, MaskingStrategy>
where
Self: PeekInterface<SecretValue>,
SecretValue: PartialEq,
MaskingStrategy: Strategy<SecretValue>,
{
fn eq(&self, other: &Self) -> bool {
self.peek().eq(other.peek())
}
}
impl<SecretValue, MaskingStrategy> Eq for Secret<SecretValue, MaskingStrategy>
where
Self: PeekInterface<SecretValue>,
SecretValue: Eq,
MaskingStrategy: Strategy<SecretValue>,
{
}
impl<SecretValue, MaskingStrategy> fmt::Debug for Secret<SecretValue, MaskingStrategy>
where
MaskingStrategy: Strategy<SecretValue>,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
MaskingStrategy::fmt(&self.inner_secret, f)
}
}
impl<SecretValue, MaskingStrategy> Default for Secret<SecretValue, MaskingStrategy>
where
SecretValue: Default,
MaskingStrategy: Strategy<SecretValue>,
{
fn default() -> Self {
SecretValue::default().into()
}
}
// Required by base64-serde to serialize Secret of Vec<u8> which contains the base64 decoded value
impl AsRef<[u8]> for Secret<Vec<u8>> {
fn as_ref(&self) -> &[u8] {
self.peek().as_slice()
}
}
/// Strategy for masking JSON values
#[cfg(feature = "serde")]
pub enum JsonMaskStrategy {}
#[cfg(feature = "serde")]
impl Strategy<serde_json::Value> for JsonMaskStrategy {
fn fmt(value: &serde_json::Value, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match value {
serde_json::Value::Object(map) => {
write!(f, "{{")?;
let mut first = true;
for (key, val) in map {
if !first {
write!(f, ", ")?;
}
first = false;
write!(f, "\"{key}\":")?;
Self::fmt(val, f)?;
}
write!(f, "}}")
}
serde_json::Value::Array(arr) => {
write!(f, "[")?;
let mut first = true;
for val in arr {
if !first {
write!(f, ", ")?;
}
first = false;
Self::fmt(val, f)?;
}
write!(f, "]")
}
serde_json::Value::String(s) => {
// For strings, we show a masked version that gives a hint about the content
let masked = if s.len() <= 2 {
"**".to_string()
} else if s.len() <= 6 {
format!("{}**", &s[0..1])
} else {
// For longer strings, show first and last character with length in between
format!(
"{}**{}**{}",
&s[0..1],
s.len() - 2,
&s[s.len() - 1..s.len()]
)
};
write!(f, "\"{masked}\"")
}
serde_json::Value::Number(n) => {
// For numbers, we can show the order of magnitude
if n.is_i64() || n.is_u64() {
let num_str = n.to_string();
let masked_num = "*".repeat(num_str.len());
write!(f, "{masked_num}")
} else if n.is_f64() {
// For floats, just use a generic mask
write!(f, "**.**")
} else {
write!(f, "0")
}
}
serde_json::Value::Bool(b) => {
// For booleans, we can show a hint about which one it is
write!(f, "{}", if *b { "**true" } else { "**false" })
}
serde_json::Value::Null => write!(f, "null"),
}
}
}
#[cfg(feature = "proto_tonic")]
impl<T> prost::Message for Secret<T, crate::WithType>
where
T: prost::Message + Default + Clone,
{
fn encode_raw(&self, buf: &mut impl bytes::BufMut) {
self.peek().encode_raw(buf);
}
fn merge_field(
&mut self,
tag: u32,
wire_type: prost::encoding::WireType,
buf: &mut impl bytes::Buf,
ctx: prost::encoding::DecodeContext,
) -> Result<(), prost::DecodeError> {
if tag == 1 {
self.peek_mut().merge_field(tag, wire_type, buf, ctx)
} else {
prost::encoding::skip_field(wire_type, tag, buf, ctx)
}
}
fn encoded_len(&self) -> usize {
self.peek().encoded_len()
}
fn clear(&mut self) {
self.peek_mut().clear();
}
}
#[cfg(test)]
#[cfg(feature = "serde")]
mod tests {
use serde_json::json;
use super::*;
#[test]
#[allow(clippy::expect_used)]
fn test_json_mask_strategy() {
// Create a sample JSON with different types for testing
let original = json!({ "user": { "name": "John Doe", "email": "[email protected]", "age": 35, "verified": true }, "card": { "number": "4242424242424242", "cvv": 123, "amount": 99.99 }, "tags": ["personal", "premium"], "null_value": null, "short": "hi" });
// Apply the JsonMaskStrategy
let secret = Secret::<_, JsonMaskStrategy>::new(original.clone());
let masked_str = format!("{secret:?}");
// Get specific values from original
let original_obj = original.as_object().expect("Original should be an object");
let user_obj = original_obj["user"]
.as_object()
.expect("User should be an object");
let name = user_obj["name"].as_str().expect("Name should be a string");
let email = user_obj["email"]
.as_str()
.expect("Email should be a string");
let age = user_obj["age"].as_i64().expect("Age should be a number");
let verified = user_obj["verified"]
.as_bool()
.expect("Verified should be a boolean");
let card_obj = original_obj["card"]
.as_object()
.expect("Card should be an object");
let card_number = card_obj["number"]
.as_str()
.expect("Card number should be a string");
let cvv = card_obj["cvv"].as_i64().expect("CVV should be a number");
let tags = original_obj["tags"]
.as_array()
.expect("Tags should be an array");
let tag1 = tags
.first()
.and_then(|v| v.as_str())
.expect("First tag should be a string");
// Now explicitly verify the masking patterns for each value type
// 1. String masking - pattern: first char + ** + length - 2 + ** + last char
let expected_name_mask = format!(
"\"{}**{}**{}\"",
&name[0..1],
name.len() - 2,
&name[name.len() - 1..]
);
let expected_email_mask = format!(
"\"{}**{}**{}\"",
&email[0..1],
email.len() - 2,
&email[email.len() - 1..]
);
let expected_card_mask = format!(
"\"{}**{}**{}\"",
&card_number[0..1],
card_number.len() - 2,
&card_number[card_number.len() - 1..]
);
let expected_tag1_mask = if tag1.len() <= 2 {
"\"**\"".to_string()
} else if tag1.len() <= 6 {
format!("\"{}**\"", &tag1[0..1])
} else {
format!(
"\"{}**{}**{}\"",
&tag1[0..1],
tag1.len() - 2,
&tag1[tag1.len() - 1..]
)
};
let expected_short_mask = "\"**\"".to_string(); // For "hi"
// 2. Number masking
let expected_age_mask = "*".repeat(age.to_string().len()); // Repeat * for the number of digits
let expected_cvv_mask = "*".repeat(cvv.to_string().len());
// 3. Boolean masking
let expected_verified_mask = if verified { "**true" } else { "**false" };
// Check that the masked output includes the expected masked patterns
assert!(
masked_str.contains(&expected_name_mask),
"Name not masked correctly. Expected: {expected_name_mask}"
);
assert!(
masked_str.contains(&expected_email_mask),
"Email not masked correctly. Expected: {expected_email_mask}",
);
assert!(
masked_str.contains(&expected_card_mask),
"Card number not masked correctly. Expected: {expected_card_mask}",
);
assert!(
masked_str.contains(&expected_tag1_mask),
"Tag not masked correctly. Expected: {expected_tag1_mask}",
);
assert!(
masked_str.contains(&expected_short_mask),
"Short string not masked correctly. Expected: {expected_short_mask}",
);
assert!(
masked_str.contains(&expected_age_mask),
"Age not masked correctly. Expected: {expected_age_mask}",
);
assert!(
masked_str.contains(&expected_cvv_mask),
"CVV not masked correctly. Expected: {expected_cvv_mask}",
);
assert!(
masked_str.contains(expected_verified_mask),
"Boolean not masked correctly. Expected: {expected_verified_mask}",
);
// Check structure preservation
assert!(
masked_str.contains("\"user\""),
"Structure not preserved - missing user object"
);
assert!(
masked_str.contains("\"card\""),
"Structure not preserved - missing card object"
);
assert!(
masked_str.contains("\"tags\""),
"Structure not preserved - missing tags array"
);
assert!(
masked_str.contains("\"null_value\":null"),
"Null value not preserved correctly"
);
// Additional security checks to ensure no original values are exposed
assert!(
!masked_str.contains(name),
"Original name value exposed in masked output"
);
assert!(
!masked_str.contains(email),
"Original email value exposed in masked output"
);
assert!(
!masked_str.contains(card_number),
"Original card number exposed in masked output"
);
assert!(
!masked_str.contains(&age.to_string()),
"Original age value exposed in masked output"
);
assert!(
!masked_str.contains(&cvv.to_string()),
"Original CVV value exposed in masked output"
);
assert!(
!masked_str.contains(tag1),
"Original tag value exposed in masked output"
);
assert!(
!masked_str.contains("hi"),
"Original short string value exposed in masked output"
);
}
}
|
crates/masking/src/secret.rs
|
masking
|
full_file
| null | null | null | 3,372
| null | null | null | null | null | null | null |
// Implementation: impl ConnectorValidation for for Katapult
// File: crates/hyperswitch_connectors/src/connectors/katapult.rs
// Module: hyperswitch_connectors
// Methods: 2 total (0 public)
impl ConnectorValidation for for Katapult
|
crates/hyperswitch_connectors/src/connectors/katapult.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 54
| null |
Katapult
|
ConnectorValidation for
| 2
| 0
| null | null |
// Struct: PaysafePaymentsResponse
// File: crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaysafePaymentsResponse
|
crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaysafePaymentsResponse
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Struct: ArchipelCard
// File: crates/hyperswitch_connectors/src/connectors/archipel/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ArchipelCard
|
crates/hyperswitch_connectors/src/connectors/archipel/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ArchipelCard
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Implementation: impl ForexMetric for for DisputeMetrics
// File: crates/api_models/src/analytics/disputes.rs
// Module: api_models
// Methods: 1 total (0 public)
impl ForexMetric for for DisputeMetrics
|
crates/api_models/src/analytics/disputes.rs
|
api_models
|
impl_block
| null | null | null | 50
| null |
DisputeMetrics
|
ForexMetric for
| 1
| 0
| null | null |
// Function: get_struct_fields
// File: crates/router_derive/src/macros/helpers.rs
// Module: router_derive
pub fn get_struct_fields(
data: syn::Data,
) -> syn::Result<Punctuated<syn::Field, syn::token::Comma>>
|
crates/router_derive/src/macros/helpers.rs
|
router_derive
|
function_signature
| null | null | null | 60
|
get_struct_fields
| null | null | null | null | null | null |
// Struct: GigadatErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct GigadatErrorResponse
|
crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
GigadatErrorResponse
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Function: toggle_blocklist_guard
// File: crates/router/src/core/blocklist.rs
// Module: router
pub fn toggle_blocklist_guard(
state: SessionState,
merchant_context: domain::MerchantContext,
query: api_blocklist::ToggleBlocklistQuery,
) -> RouterResponse<api_blocklist::ToggleBlocklistResponse>
|
crates/router/src/core/blocklist.rs
|
router
|
function_signature
| null | null | null | 72
|
toggle_blocklist_guard
| null | null | null | null | null | null |
// Implementation: impl api::ConnectorAccessToken for for Opayo
// File: crates/hyperswitch_connectors/src/connectors/opayo.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::ConnectorAccessToken for for Opayo
|
crates/hyperswitch_connectors/src/connectors/opayo.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Opayo
|
api::ConnectorAccessToken for
| 0
| 0
| null | null |
// Struct: ConnectorDetailsCore
// File: crates/router/src/core/fraud_check/types.rs
// Module: router
// Implementations: 0
pub struct ConnectorDetailsCore
|
crates/router/src/core/fraud_check/types.rs
|
router
|
struct_definition
|
ConnectorDetailsCore
| 0
|
[] | 37
| null | null | null | null | null | null | null |
// Function: api_key_update
// File: crates/openapi/src/routes/api_keys.rs
// Module: openapi
pub fn api_key_update()
|
crates/openapi/src/routes/api_keys.rs
|
openapi
|
function_signature
| null | null | null | 31
|
api_key_update
| null | null | null | null | null | null |
// Implementation: impl api::Refund for for Shift4
// File: crates/hyperswitch_connectors/src/connectors/shift4.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::Refund for for Shift4
|
crates/hyperswitch_connectors/src/connectors/shift4.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Shift4
|
api::Refund for
| 0
| 0
| null | null |
// Struct: FailedTransactionData
// File: crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct FailedTransactionData
|
crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs
|
hyperswitch_connectors
|
struct_definition
|
FailedTransactionData
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentVoid for for Paytm
// File: crates/hyperswitch_connectors/src/connectors/paytm.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Paytm
|
crates/hyperswitch_connectors/src/connectors/paytm.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Paytm
|
api::PaymentVoid for
| 0
| 0
| null | null |
// Module Structure
// File: crates/hyperswitch_connectors/src/connectors/paytm.rs
// Module: hyperswitch_connectors
// Public submodules:
pub mod transformers;
|
crates/hyperswitch_connectors/src/connectors/paytm.rs
|
hyperswitch_connectors
|
module_structure
| null | null | null | 38
| null | null | null | null | null | 1
| 0
|
// Struct: RoutingAlgorithmHelpers
// File: crates/router/src/core/routing/helpers.rs
// Module: router
// Implementations: 1
pub struct RoutingAlgorithmHelpers<'h>
|
crates/router/src/core/routing/helpers.rs
|
router
|
struct_definition
|
RoutingAlgorithmHelpers
| 1
|
[] | 39
| null | null | null | null | null | null | null |
// Struct: PaypalLiabilityResponse
// File: crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaypalLiabilityResponse
|
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaypalLiabilityResponse
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Struct: DeviceData
// File: crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct DeviceData
|
crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
DeviceData
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Function: get_api_event_dimensions
// File: crates/analytics/src/utils.rs
// Module: analytics
pub fn get_api_event_dimensions() -> Vec<NameDescription>
|
crates/analytics/src/utils.rs
|
analytics
|
function_signature
| null | null | null | 36
|
get_api_event_dimensions
| null | null | null | null | null | null |
// Function: refunds_retrieve
// File: crates/router/src/routes/refunds.rs
// Module: router
pub fn refunds_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::GlobalRefundId>,
query_params: web::Query<api_models::refunds::RefundsRetrieveBody>,
) -> HttpResponse
|
crates/router/src/routes/refunds.rs
|
router
|
function_signature
| null | null | null | 83
|
refunds_retrieve
| null | null | null | null | null | null |
// Struct: TempLockerCardSupport
// File: crates/router/src/core/payment_methods/cards.rs
// Module: router
// Implementations: 1
pub struct TempLockerCardSupport
|
crates/router/src/core/payment_methods/cards.rs
|
router
|
struct_definition
|
TempLockerCardSupport
| 1
|
[] | 38
| null | null | null | null | null | null | null |
// Function: get_method
// File: crates/router/src/core/proxy/utils.rs
// Module: router
pub fn get_method(&self) -> common_utils::request::Method
|
crates/router/src/core/proxy/utils.rs
|
router
|
function_signature
| null | null | null | 37
|
get_method
| null | null | null | null | null | null |
// Implementation: impl api::PaymentsCompleteAuthorize for for Nmi
// File: crates/hyperswitch_connectors/src/connectors/nmi.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentsCompleteAuthorize for for Nmi
|
crates/hyperswitch_connectors/src/connectors/nmi.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Nmi
|
api::PaymentsCompleteAuthorize for
| 0
| 0
| null | null |
// Struct: Nuvei
// File: crates/hyperswitch_connectors/src/connectors/nuvei.rs
// Module: hyperswitch_connectors
// Implementations: 24
// Traits: ConnectorCommon, ConnectorValidation, api::Payment, api::PaymentToken, api::MandateSetup, api::PaymentVoid, api::PaymentSync, api::PaymentCapture, api::PaymentSession, api::PaymentAuthorize, api::PaymentAuthorizeSessionToken, api::Refund, api::RefundExecute, api::RefundSync, api::PaymentsCompleteAuthorize, api::ConnectorAccessToken, api::PaymentsPreProcessing, api::PaymentPostCaptureVoid, api::Payouts, api::PayoutFulfill, IncomingWebhook, ConnectorRedirectResponse, ConnectorSpecifications
pub struct Nuvei
|
crates/hyperswitch_connectors/src/connectors/nuvei.rs
|
hyperswitch_connectors
|
struct_definition
|
Nuvei
| 24
|
[
"ConnectorCommon",
"ConnectorValidation",
"api::Payment",
"api::PaymentToken",
"api::MandateSetup",
"api::PaymentVoid",
"api::PaymentSync",
"api::PaymentCapture",
"api::PaymentSession",
"api::PaymentAuthorize",
"api::PaymentAuthorizeSessionToken",
"api::Refund",
"api::RefundExecute",
"api::RefundSync",
"api::PaymentsCompleteAuthorize",
"api::ConnectorAccessToken",
"api::PaymentsPreProcessing",
"api::PaymentPostCaptureVoid",
"api::Payouts",
"api::PayoutFulfill",
"IncomingWebhook",
"ConnectorRedirectResponse",
"ConnectorSpecifications"
] | 169
| null | null | null | null | null | null | null |
// Struct: OpenSearchClient
// File: crates/analytics/src/opensearch.rs
// Module: analytics
// Implementations: 2
// Traits: HealthCheck
pub struct OpenSearchClient
|
crates/analytics/src/opensearch.rs
|
analytics
|
struct_definition
|
OpenSearchClient
| 2
|
[
"HealthCheck"
] | 42
| null | null | null | null | null | null | null |
// Struct: GooglePayTransactionInfo
// File: crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct GooglePayTransactionInfo
|
crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
GooglePayTransactionInfo
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Function: payment_method_session_list_payment_methods
// File: crates/openapi/src/routes/payment_method.rs
// Module: openapi
pub fn payment_method_session_list_payment_methods()
|
crates/openapi/src/routes/payment_method.rs
|
openapi
|
function_signature
| null | null | null | 37
|
payment_method_session_list_payment_methods
| null | null | null | null | null | null |
// Function: get_merchant_account
// File: crates/router/src/core/admin.rs
// Module: router
pub fn get_merchant_account(
state: SessionState,
req: api::MerchantId,
_profile_id: Option<id_type::ProfileId>,
) -> RouterResponse<api::MerchantAccountResponse>
|
crates/router/src/core/admin.rs
|
router
|
function_signature
| null | null | null | 68
|
get_merchant_account
| null | null | null | null | null | null |
// Implementation: impl Default for for ConnectorAuthentication
// File: crates/test_utils/src/connector_auth.rs
// Module: test_utils
// Methods: 1 total (0 public)
impl Default for for ConnectorAuthentication
|
crates/test_utils/src/connector_auth.rs
|
test_utils
|
impl_block
| null | null | null | 44
| null |
ConnectorAuthentication
|
Default for
| 1
| 0
| null | null |
// Trait: GetPaymentMethodDetails
// File: crates/router/src/routes/dummy_connector/types.rs
// Module: router
pub trait GetPaymentMethodDetails
|
crates/router/src/routes/dummy_connector/types.rs
|
router
|
trait_definition
| null | null | null | 32
| null | null |
GetPaymentMethodDetails
| null | null | null | null |
// File: crates/diesel_models/src/query/dispute.rs
// Module: diesel_models
// Public functions: 5
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table};
use super::generics;
use crate::{
dispute::{Dispute, DisputeNew, DisputeUpdate, DisputeUpdateInternal},
errors,
schema::dispute::dsl,
PgPooledConn, StorageResult,
};
impl DisputeNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Dispute> {
generics::generic_insert(conn, self).await
}
}
impl Dispute {
pub async fn find_by_merchant_id_payment_id_connector_dispute_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
connector_dispute_id: &str,
) -> StorageResult<Option<Self>> {
generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::payment_id.eq(payment_id.to_owned()))
.and(dsl::connector_dispute_id.eq(connector_dispute_id.to_owned())),
)
.await
}
pub async fn find_by_merchant_id_dispute_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
dispute_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::dispute_id.eq(dispute_id.to_owned())),
)
.await
}
pub async fn find_by_merchant_id_payment_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
_,
<<Self as HasTable>::Table as Table>::PrimaryKey,
_,
>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::payment_id.eq(payment_id.to_owned())),
None,
None,
None,
)
.await
}
pub async fn update(self, conn: &PgPooledConn, dispute: DisputeUpdate) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
dsl::dispute_id.eq(self.dispute_id.to_owned()),
DisputeUpdateInternal::from(dispute),
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
result => result,
}
}
}
|
crates/diesel_models/src/query/dispute.rs
|
diesel_models
|
full_file
| null | null | null | 686
| null | null | null | null | null | null | null |
// Struct: AdjustedBy
// File: crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct AdjustedBy
|
crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
AdjustedBy
| 0
|
[] | 46
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/thunes.rs
// Module: hyperswitch_connectors
// Public functions: 1
// Public structs: 1
pub mod transformers;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{ExposeInterface, Mask};
use transformers as thunes;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Thunes {
amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Thunes {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
}
impl api::Payment for Thunes {}
impl api::PaymentSession for Thunes {}
impl api::ConnectorAccessToken for Thunes {}
impl api::MandateSetup for Thunes {}
impl api::PaymentAuthorize for Thunes {}
impl api::PaymentSync for Thunes {}
impl api::PaymentCapture for Thunes {}
impl api::PaymentVoid for Thunes {}
impl api::Refund for Thunes {}
impl api::RefundExecute for Thunes {}
impl api::RefundSync for Thunes {}
impl api::PaymentToken for Thunes {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Thunes
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Thunes
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Thunes {
fn id(&self) -> &'static str {
"thunes"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
// TODO! Check connector documentation, on which unit they are processing the currency.
// If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,
// if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.thunes.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = thunes::ThunesAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.expose().into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: thunes::ThunesErrorResponse = res
.response
.parse_struct("ThunesErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code,
message: response.message,
reason: response.reason,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Thunes {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Thunes {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Thunes {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Thunes {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Thunes {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = thunes::ThunesRouterData::from((amount, req));
let connector_req = thunes::ThunesPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: thunes::ThunesPaymentsResponse = res
.response
.parse_struct("Thunes PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Thunes {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: thunes::ThunesPaymentsResponse = res
.response
.parse_struct("thunes PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Thunes {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: thunes::ThunesPaymentsResponse = res
.response
.parse_struct("Thunes PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Thunes {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Thunes {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = thunes::ThunesRouterData::from((refund_amount, req));
let connector_req = thunes::ThunesRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: thunes::RefundResponse =
res.response
.parse_struct("thunes RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Thunes {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: thunes::RefundResponse = res
.response
.parse_struct("thunes RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Thunes {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static THUNES_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Thunes",
description: "Thunes Payouts is a global payment solution that enables businesses to send instant, secure, and cost-effective cross-border payments to bank accounts, mobile wallets, and cards in over 130 countries using a single API",
connector_type: common_enums::HyperswitchConnectorCategory::PayoutProcessor,
integration_status: common_enums::ConnectorIntegrationStatus::Sandbox,
};
impl ConnectorSpecifications for Thunes {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&THUNES_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
None
}
fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> {
None
}
}
|
crates/hyperswitch_connectors/src/connectors/thunes.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 4,518
| null | null | null | null | null | null | null |
// Implementation: impl super::refunds::metrics::RefundMetricAnalytics for for ClickhouseClient
// File: crates/analytics/src/clickhouse.rs
// Module: analytics
// Methods: 0 total (0 public)
impl super::refunds::metrics::RefundMetricAnalytics for for ClickhouseClient
|
crates/analytics/src/clickhouse.rs
|
analytics
|
impl_block
| null | null | null | 65
| null |
ClickhouseClient
|
super::refunds::metrics::RefundMetricAnalytics for
| 0
| 0
| null | null |
// Implementation: impl webhooks::IncomingWebhook for for Loonio
// File: crates/hyperswitch_connectors/src/connectors/loonio.rs
// Module: hyperswitch_connectors
// Methods: 3 total (0 public)
impl webhooks::IncomingWebhook for for Loonio
|
crates/hyperswitch_connectors/src/connectors/loonio.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 62
| null |
Loonio
|
webhooks::IncomingWebhook for
| 3
| 0
| null | null |
// Implementation: impl HashedApiKey
// File: crates/diesel_models/src/api_keys.rs
// Module: diesel_models
// Methods: 1 total (1 public)
impl HashedApiKey
|
crates/diesel_models/src/api_keys.rs
|
diesel_models
|
impl_block
| null | null | null | 40
| null |
HashedApiKey
| null | 1
| 1
| null | null |
// Struct: Placetopay
// File: crates/hyperswitch_connectors/src/connectors/placetopay.rs
// Module: hyperswitch_connectors
// Implementations: 17
// Traits: api::Payment, api::PaymentSession, api::ConnectorAccessToken, api::MandateSetup, api::PaymentAuthorize, api::PaymentSync, api::PaymentCapture, api::PaymentVoid, api::Refund, api::RefundExecute, api::RefundSync, api::PaymentToken, ConnectorCommon, ConnectorValidation, IncomingWebhook, ConnectorSpecifications
pub struct Placetopay
|
crates/hyperswitch_connectors/src/connectors/placetopay.rs
|
hyperswitch_connectors
|
struct_definition
|
Placetopay
| 17
|
[
"api::Payment",
"api::PaymentSession",
"api::ConnectorAccessToken",
"api::MandateSetup",
"api::PaymentAuthorize",
"api::PaymentSync",
"api::PaymentCapture",
"api::PaymentVoid",
"api::Refund",
"api::RefundExecute",
"api::RefundSync",
"api::PaymentToken",
"ConnectorCommon",
"ConnectorValidation",
"IncomingWebhook",
"ConnectorSpecifications"
] | 128
| null | null | null | null | null | null | null |
// Struct: ClientProcessorInformation
// File: crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ClientProcessorInformation
|
crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ClientProcessorInformation
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Struct: Klarna
// File: crates/hyperswitch_connectors/src/connectors/klarna.rs
// Module: hyperswitch_connectors
// Implementations: 17
// Traits: ConnectorCommon, ConnectorValidation, api::Payment, api::PaymentAuthorize, api::PaymentSync, api::PaymentVoid, api::PaymentCapture, api::PaymentSession, api::ConnectorAccessToken, api::PaymentToken, api::MandateSetup, api::Refund, api::RefundExecute, api::RefundSync, IncomingWebhook, ConnectorSpecifications
pub struct Klarna
|
crates/hyperswitch_connectors/src/connectors/klarna.rs
|
hyperswitch_connectors
|
struct_definition
|
Klarna
| 17
|
[
"ConnectorCommon",
"ConnectorValidation",
"api::Payment",
"api::PaymentAuthorize",
"api::PaymentSync",
"api::PaymentVoid",
"api::PaymentCapture",
"api::PaymentSession",
"api::ConnectorAccessToken",
"api::PaymentToken",
"api::MandateSetup",
"api::Refund",
"api::RefundExecute",
"api::RefundSync",
"IncomingWebhook",
"ConnectorSpecifications"
] | 123
| null | null | null | null | null | null | null |
// Implementation: impl AsSchedulerInterface for for T
// File: crates/scheduler/src/scheduler.rs
// Module: scheduler
// Methods: 1 total (0 public)
impl AsSchedulerInterface for for T
|
crates/scheduler/src/scheduler.rs
|
scheduler
|
impl_block
| null | null | null | 44
| null |
T
|
AsSchedulerInterface for
| 1
| 0
| null | null |
// Implementation: impl Default for for AnalyticsProvider
// File: crates/analytics/src/lib.rs
// Module: analytics
// Methods: 1 total (0 public)
impl Default for for AnalyticsProvider
|
crates/analytics/src/lib.rs
|
analytics
|
impl_block
| null | null | null | 41
| null |
AnalyticsProvider
|
Default for
| 1
| 0
| null | null |
// Struct: PaymentsPostSessionTokensData
// File: crates/hyperswitch_domain_models/src/router_request_types.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct PaymentsPostSessionTokensData
|
crates/hyperswitch_domain_models/src/router_request_types.rs
|
hyperswitch_domain_models
|
struct_definition
|
PaymentsPostSessionTokensData
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Implementation: impl webhooks::IncomingWebhook for for Bluecode
// File: crates/hyperswitch_connectors/src/connectors/bluecode.rs
// Module: hyperswitch_connectors
// Methods: 6 total (0 public)
impl webhooks::IncomingWebhook for for Bluecode
|
crates/hyperswitch_connectors/src/connectors/bluecode.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Bluecode
|
webhooks::IncomingWebhook for
| 6
| 0
| null | null |
// Function: update
// File: crates/diesel_models/src/query/dispute.rs
// Module: diesel_models
pub fn update(self, conn: &PgPooledConn, dispute: DisputeUpdate) -> StorageResult<Self>
|
crates/diesel_models/src/query/dispute.rs
|
diesel_models
|
function_signature
| null | null | null | 48
|
update
| null | null | null | null | null | null |
// Implementation: impl api::RefundExecute for for Nomupay
// File: crates/hyperswitch_connectors/src/connectors/nomupay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundExecute for for Nomupay
|
crates/hyperswitch_connectors/src/connectors/nomupay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 63
| null |
Nomupay
|
api::RefundExecute for
| 0
| 0
| null | null |
// File: crates/openapi/src/routes/refunds.rs
// Module: openapi
// Public functions: 11
/// Refunds - Create
///
/// Creates a refund against an already processed payment. In case of some processors, you can even opt to refund only a partial amount multiple times until the original charge amount has been refunded
#[utoipa::path(
post,
path = "/refunds",
request_body(
content = RefundRequest,
examples(
(
"Create an instant refund to refund the whole amount" = (
value = json!({
"payment_id": "{{payment_id}}",
"refund_type": "instant"
})
)
),
(
"Create an instant refund to refund partial amount" = (
value = json!({
"payment_id": "{{payment_id}}",
"refund_type": "instant",
"amount": 654
})
)
),
(
"Create an instant refund with reason" = (
value = json!({
"payment_id": "{{payment_id}}",
"refund_type": "instant",
"amount": 6540,
"reason": "Customer returned product"
})
)
),
)
),
responses(
(status = 200, description = "Refund created", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Refunds",
operation_id = "Create a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn refunds_create() {}
/// Refunds - Retrieve
///
/// Retrieves a Refund. This may be used to get the status of a previously initiated refund
#[utoipa::path(
get,
path = "/refunds/{refund_id}",
params(
("refund_id" = String, Path, description = "The identifier for refund")
),
responses(
(status = 200, description = "Refund retrieved", body = RefundResponse),
(status = 404, description = "Refund does not exist in our records")
),
tag = "Refunds",
operation_id = "Retrieve a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn refunds_retrieve() {}
/// Refunds - Retrieve (POST)
///
/// To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment
#[utoipa::path(
get,
path = "/refunds/sync",
responses(
(status = 200, description = "Refund retrieved", body = RefundResponse),
(status = 404, description = "Refund does not exist in our records")
),
tag = "Refunds",
operation_id = "Retrieve a Refund",
security(("api_key" = []))
)]
pub async fn refunds_retrieve_with_body() {}
/// Refunds - Update
///
/// Updates the properties of a Refund object. This API can be used to attach a reason for the refund or metadata fields
#[utoipa::path(
post,
path = "/refunds/{refund_id}",
params(
("refund_id" = String, Path, description = "The identifier for refund")
),
request_body(
content = RefundUpdateRequest,
examples(
(
"Update refund reason" = (
value = json!({
"reason": "Paid by mistake"
})
)
),
)
),
responses(
(status = 200, description = "Refund updated", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Refunds",
operation_id = "Update a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn refunds_update() {}
/// Refunds - List
///
/// Lists all the refunds associated with the merchant, or for a specific payment if payment_id is provided
#[utoipa::path(
post,
path = "/refunds/list",
request_body=RefundListRequest,
responses(
(status = 200, description = "List of refunds", body = RefundListResponse),
),
tag = "Refunds",
operation_id = "List all Refunds",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub fn refunds_list() {}
/// Refunds - List For the Given profiles
///
/// Lists all the refunds associated with the merchant or a payment_id if payment_id is not provided
#[utoipa::path(
post,
path = "/refunds/profile/list",
request_body=RefundListRequest,
responses(
(status = 200, description = "List of refunds", body = RefundListResponse),
),
tag = "Refunds",
operation_id = "List all Refunds for the given Profiles",
security(("api_key" = []))
)]
pub fn refunds_list_profile() {}
/// Refunds - Filter
///
/// To list the refunds filters associated with list of connectors, currencies and payment statuses
#[utoipa::path(
post,
path = "/refunds/filter",
request_body=TimeRange,
responses(
(status = 200, description = "List of filters", body = RefundListMetaData),
),
tag = "Refunds",
operation_id = "List all filters for Refunds",
security(("api_key" = []))
)]
pub async fn refunds_filter_list() {}
/// Refunds - Create
///
/// Creates a refund against an already processed payment. In case of some processors, you can even opt to refund only a partial amount multiple times until the original charge amount has been refunded
#[utoipa::path(
post,
path = "/v2/refunds",
request_body(
content = RefundsCreateRequest,
examples(
(
"Create an instant refund to refund the whole amount" = (
value = json!({
"payment_id": "{{payment_id}}",
"merchant_reference_id": "ref_123",
"refund_type": "instant"
})
)
),
(
"Create an instant refund to refund partial amount" = (
value = json!({
"payment_id": "{{payment_id}}",
"merchant_reference_id": "ref_123",
"refund_type": "instant",
"amount": 654
})
)
),
(
"Create an instant refund with reason" = (
value = json!({
"payment_id": "{{payment_id}}",
"merchant_reference_id": "ref_123",
"refund_type": "instant",
"amount": 6540,
"reason": "Customer returned product"
})
)
),
)
),
responses(
(status = 200, description = "Refund created", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Refunds",
operation_id = "Create a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn refunds_create() {}
/// Refunds - Metadata Update
///
/// Updates the properties of a Refund object. This API can be used to attach a reason for the refund or metadata fields
#[utoipa::path(
put,
path = "/v2/refunds/{id}/update-metadata",
params(
("id" = String, Path, description = "The identifier for refund")
),
request_body(
content = RefundMetadataUpdateRequest,
examples(
(
"Update refund reason" = (
value = json!({
"reason": "Paid by mistake"
})
)
)
)
),
responses(
(status = 200, description = "Refund updated", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Refunds",
operation_id = "Update Refund Metadata and Reason",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn refunds_metadata_update() {}
/// Refunds - Retrieve
///
/// Retrieves a Refund. This may be used to get the status of a previously initiated refund
#[utoipa::path(
get,
path = "/v2/refunds/{id}",
params(
("id" = String, Path, description = "The identifier for refund")
),
responses(
(status = 200, description = "Refund retrieved", body = RefundResponse),
(status = 404, description = "Refund does not exist in our records")
),
tag = "Refunds",
operation_id = "Retrieve a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn refunds_retrieve() {}
/// Refunds - List
///
/// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided
#[utoipa::path(
post,
path = "/v2/refunds/list",
request_body=RefundListRequest,
responses(
(status = 200, description = "List of refunds", body = RefundListResponse),
),
tag = "Refunds",
operation_id = "List all Refunds",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub fn refunds_list() {}
|
crates/openapi/src/routes/refunds.rs
|
openapi
|
full_file
| null | null | null | 2,123
| null | null | null | null | null | null | null |
// Struct: DwollaPaymentSyncResponse
// File: crates/hyperswitch_connectors/src/connectors/dwolla/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct DwollaPaymentSyncResponse
|
crates/hyperswitch_connectors/src/connectors/dwolla/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
DwollaPaymentSyncResponse
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Implementation: impl ConstraintGraphBuilder
// File: crates/hyperswitch_constraint_graph/src/builder.rs
// Module: hyperswitch_constraint_graph
// Methods: 11 total (8 public)
impl ConstraintGraphBuilder
|
crates/hyperswitch_constraint_graph/src/builder.rs
|
hyperswitch_constraint_graph
|
impl_block
| null | null | null | 46
| null |
ConstraintGraphBuilder
| null | 11
| 8
| null | null |
// Implementation: impl api::PaymentVoid for for Peachpayments
// File: crates/hyperswitch_connectors/src/connectors/peachpayments.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Peachpayments
|
crates/hyperswitch_connectors/src/connectors/peachpayments.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Peachpayments
|
api::PaymentVoid for
| 0
| 0
| null | null |
// File: crates/hyperswitch_connectors/src/connectors/paytm/transformers.rs
// Module: hyperswitch_connectors
// Public structs: 8
use common_enums::enums;
use common_utils::types::StringMinorUnit;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::types::{RefundsResponseRouterData, ResponseRouterData};
//TODO: Fill the struct with respective fields
pub struct PaytmRouterData<T> {
pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(StringMinorUnit, T)> for PaytmRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
//Todo : use utils to convert the amount to the type of amount that a connector accepts
Self {
amount,
router_data: item,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct PaytmPaymentsRequest {
amount: StringMinorUnit,
card: PaytmCard,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct PaytmCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&PaytmRouterData<&PaymentsAuthorizeRouterData>> for PaytmPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaytmRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented(
"Card payment method not implemented".to_string(),
)
.into()),
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
//TODO: Fill the struct with respective fields
// Auth Struct
pub struct PaytmAuthType {
pub merchant_id: Secret<String>,
pub merchant_key: Secret<String>,
pub website: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PaytmAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
merchant_id: key1.to_owned(), // merchant_id
merchant_key: api_key.to_owned(), // signing key
website: api_secret.to_owned(), // website name
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
//TODO: Append the remaining status flags
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum PaytmPaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<PaytmPaymentStatus> for common_enums::AttemptStatus {
fn from(item: PaytmPaymentStatus) -> Self {
match item {
PaytmPaymentStatus::Succeeded => Self::Charged,
PaytmPaymentStatus::Failed => Self::Failure,
PaytmPaymentStatus::Processing => Self::Authorizing,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PaytmPaymentsResponse {
status: PaytmPaymentStatus,
id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, PaytmPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaytmPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct PaytmRefundRequest {
pub amount: StringMinorUnit,
}
impl<F> TryFrom<&PaytmRouterData<&RefundsRouterData<F>>> for PaytmRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaytmRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct PaytmErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
pub reason: Option<String>,
pub network_advice_code: Option<String>,
pub network_decline_code: Option<String>,
pub network_error_message: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/paytm/transformers.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 1,717
| null | null | null | null | null | null | null |
// File: crates/common_utils/src/access_token.rs
// Module: common_utils
// Public functions: 1
//! Commonly used utilities for access token
use std::fmt::Display;
use crate::id_type;
/// Create a key for fetching the access token from redis
pub fn create_access_token_key(
merchant_id: &id_type::MerchantId,
merchant_connector_id_or_connector_name: impl Display,
) -> String {
merchant_id.get_access_token_key(merchant_connector_id_or_connector_name)
}
|
crates/common_utils/src/access_token.rs
|
common_utils
|
full_file
| null | null | null | 107
| null | null | null | null | null | null | null |
// Function: to_storage_model
// File: crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
// Module: hyperswitch_domain_models
pub fn to_storage_model(self) -> diesel_models::PaymentAttemptUpdate
|
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 46
|
to_storage_model
| null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs
// Module: hyperswitch_connectors
// Public structs: 14
use cards::CardNumber;
use common_enums::{enums, AttemptStatus, CaptureMethod, Currency, PaymentMethod};
use common_utils::{errors::ParsingError, ext_traits::Encode};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::Execute,
router_request_types::ResponseId,
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{api::CurrencyUnit, errors::ConnectorError};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
get_amount_as_string, get_unimplemented_payment_method_error_message, to_connector_meta,
CardData, CardIssuer, RouterData as _,
},
};
#[derive(Debug, Serialize)]
pub struct PayeezyRouterData<T> {
pub amount: String,
pub router_data: T,
}
impl<T> TryFrom<(&CurrencyUnit, Currency, i64, T)> for PayeezyRouterData<T> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
(currency_unit, currency, amount, router_data): (&CurrencyUnit, Currency, i64, T),
) -> Result<Self, Self::Error> {
let amount = get_amount_as_string(currency_unit, amount, currency)?;
Ok(Self {
amount,
router_data,
})
}
}
#[derive(Serialize, Debug)]
pub struct PayeezyCard {
#[serde(rename = "type")]
pub card_type: PayeezyCardType,
pub cardholder_name: Secret<String>,
pub card_number: CardNumber,
pub exp_date: Secret<String>,
pub cvv: Secret<String>,
}
#[derive(Serialize, Debug)]
pub enum PayeezyCardType {
#[serde(rename = "American Express")]
AmericanExpress,
Visa,
Mastercard,
Discover,
}
impl TryFrom<CardIssuer> for PayeezyCardType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(issuer: CardIssuer) -> Result<Self, Self::Error> {
match issuer {
CardIssuer::AmericanExpress => Ok(Self::AmericanExpress),
CardIssuer::Master => Ok(Self::Mastercard),
CardIssuer::Discover => Ok(Self::Discover),
CardIssuer::Visa => Ok(Self::Visa),
CardIssuer::Maestro
| CardIssuer::DinersClub
| CardIssuer::JCB
| CardIssuer::CarteBlanche
| CardIssuer::UnionPay
| CardIssuer::CartesBancaires => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Payeezy"),
))?,
}
}
}
#[derive(Serialize, Debug)]
#[serde(untagged)]
pub enum PayeezyPaymentMethod {
PayeezyCard(PayeezyCard),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PayeezyPaymentMethodType {
CreditCard,
}
#[derive(Serialize, Debug)]
pub struct PayeezyPaymentsRequest {
pub merchant_ref: String,
pub transaction_type: PayeezyTransactionType,
pub method: PayeezyPaymentMethodType,
pub amount: String,
pub currency_code: String,
pub credit_card: PayeezyPaymentMethod,
pub stored_credentials: Option<StoredCredentials>,
pub reference: String,
}
#[derive(Serialize, Debug)]
pub struct StoredCredentials {
pub sequence: Sequence,
pub initiator: Initiator,
pub is_scheduled: bool,
pub cardbrand_original_transaction_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Sequence {
First,
Subsequent,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Initiator {
Merchant,
CardHolder,
}
impl TryFrom<&PayeezyRouterData<&PaymentsAuthorizeRouterData>> for PayeezyPaymentsRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &PayeezyRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.payment_method {
PaymentMethod::Card => get_card_specific_payment_data(item),
PaymentMethod::CardRedirect
| PaymentMethod::PayLater
| PaymentMethod::Wallet
| PaymentMethod::BankRedirect
| PaymentMethod::BankTransfer
| PaymentMethod::Crypto
| PaymentMethod::BankDebit
| PaymentMethod::Reward
| PaymentMethod::RealTimePayment
| PaymentMethod::MobilePayment
| PaymentMethod::Upi
| PaymentMethod::Voucher
| PaymentMethod::OpenBanking
| PaymentMethod::GiftCard => {
Err(ConnectorError::NotImplemented("Payment methods".to_string()).into())
}
}
}
}
fn get_card_specific_payment_data(
item: &PayeezyRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<PayeezyPaymentsRequest, error_stack::Report<ConnectorError>> {
let merchant_ref = item.router_data.attempt_id.to_string();
let method = PayeezyPaymentMethodType::CreditCard;
let amount = item.amount.clone();
let currency_code = item.router_data.request.currency.to_string();
let credit_card = get_payment_method_data(item)?;
let (transaction_type, stored_credentials) =
get_transaction_type_and_stored_creds(item.router_data)?;
Ok(PayeezyPaymentsRequest {
merchant_ref,
transaction_type,
method,
amount,
currency_code,
credit_card,
stored_credentials,
reference: item.router_data.connector_request_reference_id.clone(),
})
}
fn get_transaction_type_and_stored_creds(
item: &PaymentsAuthorizeRouterData,
) -> Result<(PayeezyTransactionType, Option<StoredCredentials>), error_stack::Report<ConnectorError>>
{
let connector_mandate_id = item.request.mandate_id.as_ref().and_then(|mandate_ids| {
match mandate_ids.mandate_reference_id.clone() {
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
connector_mandate_ids,
)) => connector_mandate_ids.get_connector_mandate_id(),
_ => None,
}
});
let (transaction_type, stored_credentials) =
if is_mandate_payment(item, connector_mandate_id.as_ref()) {
// Mandate payment
(
PayeezyTransactionType::Recurring,
Some(StoredCredentials {
// connector_mandate_id is not present then it is a First payment, else it is a Subsequent mandate payment
sequence: match connector_mandate_id.is_some() {
true => Sequence::Subsequent,
false => Sequence::First,
},
// off_session true denotes the customer not present during the checkout process. In other cases customer present at the checkout.
initiator: match item.request.off_session {
Some(true) => Initiator::Merchant,
_ => Initiator::CardHolder,
},
is_scheduled: true,
// In case of first mandate payment connector_mandate_id would be None, otherwise holds some value
cardbrand_original_transaction_id: connector_mandate_id.map(Secret::new),
}),
)
} else {
match item.request.capture_method {
Some(CaptureMethod::Manual) => Ok((PayeezyTransactionType::Authorize, None)),
Some(CaptureMethod::SequentialAutomatic) | Some(CaptureMethod::Automatic) => {
Ok((PayeezyTransactionType::Purchase, None))
}
Some(CaptureMethod::ManualMultiple) | Some(CaptureMethod::Scheduled) | None => {
Err(ConnectorError::FlowNotSupported {
flow: item.request.capture_method.unwrap_or_default().to_string(),
connector: "Payeezy".to_string(),
})
}
}?
};
Ok((transaction_type, stored_credentials))
}
fn is_mandate_payment(
item: &PaymentsAuthorizeRouterData,
connector_mandate_id: Option<&String>,
) -> bool {
item.request.setup_mandate_details.is_some() || connector_mandate_id.is_some()
}
fn get_payment_method_data(
item: &PayeezyRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<PayeezyPaymentMethod, error_stack::Report<ConnectorError>> {
match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref card) => {
let card_type = PayeezyCardType::try_from(card.get_card_issuer()?)?;
let payeezy_card = PayeezyCard {
card_type,
cardholder_name: item
.router_data
.get_optional_billing_full_name()
.unwrap_or(Secret::new("".to_string())),
card_number: card.card_number.clone(),
exp_date: card.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?,
cvv: card.card_cvc.clone(),
};
Ok(PayeezyPaymentMethod::PayeezyCard(payeezy_card))
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Payeezy"),
))?
}
}
}
// Auth Struct
pub struct PayeezyAuthType {
pub(super) api_key: Secret<String>,
pub(super) api_secret: Secret<String>,
pub(super) merchant_token: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PayeezyAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} = item
{
Ok(Self {
api_key: api_key.to_owned(),
api_secret: api_secret.to_owned(),
merchant_token: key1.to_owned(),
})
} else {
Err(ConnectorError::FailedToObtainAuthType.into())
}
}
}
// PaymentsResponse
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum PayeezyPaymentStatus {
Approved,
Declined,
#[default]
#[serde(rename = "Not Processed")]
NotProcessed,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PayeezyPaymentsResponse {
pub correlation_id: String,
pub transaction_status: PayeezyPaymentStatus,
pub validation_status: String,
pub transaction_type: PayeezyTransactionType,
pub transaction_id: String,
pub transaction_tag: Option<String>,
pub method: Option<String>,
pub amount: String,
pub currency: String,
pub bank_resp_code: String,
pub bank_message: String,
pub gateway_resp_code: String,
pub gateway_message: String,
pub stored_credentials: Option<PaymentsStoredCredentials>,
pub reference: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaymentsStoredCredentials {
cardbrand_original_transaction_id: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct PayeezyCaptureOrVoidRequest {
transaction_tag: String,
transaction_type: PayeezyTransactionType,
amount: String,
currency_code: String,
}
impl TryFrom<&PayeezyRouterData<&PaymentsCaptureRouterData>> for PayeezyCaptureOrVoidRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &PayeezyRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let metadata: PayeezyPaymentsMetadata =
to_connector_meta(item.router_data.request.connector_meta.clone())
.change_context(ConnectorError::RequestEncodingFailed)?;
Ok(Self {
transaction_type: PayeezyTransactionType::Capture,
amount: item.amount.clone(),
currency_code: item.router_data.request.currency.to_string(),
transaction_tag: metadata.transaction_tag,
})
}
}
impl TryFrom<&PaymentsCancelRouterData> for PayeezyCaptureOrVoidRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let metadata: PayeezyPaymentsMetadata =
to_connector_meta(item.request.connector_meta.clone())
.change_context(ConnectorError::RequestEncodingFailed)?;
Ok(Self {
transaction_type: PayeezyTransactionType::Void,
amount: item
.request
.amount
.ok_or(ConnectorError::RequestEncodingFailed)?
.to_string(),
currency_code: item.request.currency.unwrap_or_default().to_string(),
transaction_tag: metadata.transaction_tag,
})
}
}
#[derive(Debug, Deserialize, Serialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum PayeezyTransactionType {
Authorize,
Capture,
Purchase,
Recurring,
Void,
Refund,
#[default]
Pending,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PayeezyPaymentsMetadata {
transaction_tag: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, PayeezyPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PayeezyPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let metadata = item
.response
.transaction_tag
.map(|txn_tag| construct_payeezy_payments_metadata(txn_tag).encode_to_value())
.transpose()
.change_context(ConnectorError::ResponseHandlingFailed)?;
let mandate_reference = item
.response
.stored_credentials
.map(|credentials| credentials.cardbrand_original_transaction_id)
.map(|id| MandateReference {
connector_mandate_id: Some(id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
let status = get_status(
item.response.transaction_status,
item.response.transaction_type,
);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: metadata,
network_txn_id: None,
connector_response_reference_id: Some(
item.response
.reference
.unwrap_or(item.response.transaction_id),
),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
fn get_status(status: PayeezyPaymentStatus, method: PayeezyTransactionType) -> AttemptStatus {
match status {
PayeezyPaymentStatus::Approved => match method {
PayeezyTransactionType::Authorize => AttemptStatus::Authorized,
PayeezyTransactionType::Capture
| PayeezyTransactionType::Purchase
| PayeezyTransactionType::Recurring => AttemptStatus::Charged,
PayeezyTransactionType::Void => AttemptStatus::Voided,
PayeezyTransactionType::Refund | PayeezyTransactionType::Pending => {
AttemptStatus::Pending
}
},
PayeezyPaymentStatus::Declined | PayeezyPaymentStatus::NotProcessed => match method {
PayeezyTransactionType::Capture => AttemptStatus::CaptureFailed,
PayeezyTransactionType::Authorize
| PayeezyTransactionType::Purchase
| PayeezyTransactionType::Recurring => AttemptStatus::AuthorizationFailed,
PayeezyTransactionType::Void => AttemptStatus::VoidFailed,
PayeezyTransactionType::Refund | PayeezyTransactionType::Pending => {
AttemptStatus::Pending
}
},
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
pub struct PayeezyRefundRequest {
transaction_tag: String,
transaction_type: PayeezyTransactionType,
amount: String,
currency_code: String,
}
impl<F> TryFrom<&PayeezyRouterData<&RefundsRouterData<F>>> for PayeezyRefundRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &PayeezyRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let metadata: PayeezyPaymentsMetadata =
to_connector_meta(item.router_data.request.connector_metadata.clone())
.change_context(ConnectorError::RequestEncodingFailed)?;
Ok(Self {
transaction_type: PayeezyTransactionType::Refund,
amount: item.amount.clone(),
currency_code: item.router_data.request.currency.to_string(),
transaction_tag: metadata.transaction_tag,
})
}
}
// Type definition for Refund Response
#[derive(Debug, Deserialize, Default, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum RefundStatus {
Approved,
Declined,
#[default]
#[serde(rename = "Not Processed")]
NotProcessed,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Approved => Self::Success,
RefundStatus::Declined => Self::Failure,
RefundStatus::NotProcessed => Self::Pending,
}
}
}
#[derive(Deserialize, Debug, Serialize)]
pub struct RefundResponse {
pub correlation_id: String,
pub transaction_status: RefundStatus,
pub validation_status: String,
pub transaction_type: String,
pub transaction_id: String,
pub transaction_tag: Option<String>,
pub method: Option<String>,
pub amount: String,
pub currency: String,
pub bank_resp_code: String,
pub bank_message: String,
pub gateway_resp_code: String,
pub gateway_message: String,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<ParsingError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.transaction_status),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Message {
pub code: String,
pub description: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PayeezyError {
pub messages: Vec<Message>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PayeezyErrorResponse {
pub transaction_status: String,
#[serde(rename = "Error")]
pub error: PayeezyError,
}
fn construct_payeezy_payments_metadata(transaction_tag: String) -> PayeezyPaymentsMetadata {
PayeezyPaymentsMetadata { transaction_tag }
}
|
crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 4,386
| null | null | null | null | null | null | null |
// Function: call_database
// File: crates/storage_impl/src/lib.rs
// Module: storage_impl
pub fn call_database<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
execute_query: R,
) -> error_stack::Result<D, StorageError>
where
D: Debug + Sync + Conversion,
R: futures::Future<Output = error_stack::Result<M, diesel_models::errors::DatabaseError>>
+ Send,
M: ReverseConversion<D>,
|
crates/storage_impl/src/lib.rs
|
storage_impl
|
function_signature
| null | null | null | 117
|
call_database
| null | null | null | null | null | null |
// Implementation: impl ConnectorSpecifications for for Nordea
// File: crates/hyperswitch_connectors/src/connectors/nordea.rs
// Module: hyperswitch_connectors
// Methods: 4 total (0 public)
impl ConnectorSpecifications for for Nordea
|
crates/hyperswitch_connectors/src/connectors/nordea.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 54
| null |
Nordea
|
ConnectorSpecifications for
| 4
| 0
| null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.