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: RedsysCardData
// File: crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct RedsysCardData
|
crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
RedsysCardData
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Trait: Message
// File: crates/events/src/lib.rs
// Module: events
// Documentation: A message that can be sent.
pub trait Message
|
crates/events/src/lib.rs
|
events
|
trait_definition
| null | null | null | 32
| null | null |
Message
| null | null | null | null |
// Implementation: impl super::frm::filters::FrmFilterAnalytics for for ClickhouseClient
// File: crates/analytics/src/clickhouse.rs
// Module: analytics
// Methods: 0 total (0 public)
impl super::frm::filters::FrmFilterAnalytics for for ClickhouseClient
|
crates/analytics/src/clickhouse.rs
|
analytics
|
impl_block
| null | null | null | 63
| null |
ClickhouseClient
|
super::frm::filters::FrmFilterAnalytics for
| 0
| 0
| null | null |
// Implementation: impl NuveiAuthorizePreprocessingCommon for for PaymentsPreProcessingData
// File: crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
// Module: hyperswitch_connectors
// Methods: 16 total (0 public)
impl NuveiAuthorizePreprocessingCommon for for PaymentsPreProcessingData
|
crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 73
| null |
PaymentsPreProcessingData
|
NuveiAuthorizePreprocessingCommon for
| 16
| 0
| null | null |
// Struct: PaymeRefundRequest
// File: crates/hyperswitch_connectors/src/connectors/payme/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaymeRefundRequest
|
crates/hyperswitch_connectors/src/connectors/payme/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaymeRefundRequest
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentVoid for for Placetopay
// File: crates/hyperswitch_connectors/src/connectors/placetopay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Placetopay
|
crates/hyperswitch_connectors/src/connectors/placetopay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 63
| null |
Placetopay
|
api::PaymentVoid for
| 0
| 0
| null | null |
// Function: merchant_account_update
// File: crates/router/src/core/admin.rs
// Module: router
pub fn merchant_account_update(
state: SessionState,
merchant_id: &id_type::MerchantId,
_profile_id: Option<id_type::ProfileId>,
req: api::MerchantAccountUpdate,
) -> RouterResponse<api::MerchantAccountResponse>
|
crates/router/src/core/admin.rs
|
router
|
function_signature
| null | null | null | 78
|
merchant_account_update
| null | null | null | null | null | null |
// Struct: Shift4PaymentsRequest
// File: crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct Shift4PaymentsRequest
|
crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
Shift4PaymentsRequest
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// File: crates/router/src/core/payment_methods/transformers.rs
// Module: router
// Public functions: 26
// Public structs: 16
pub use ::payment_methods::controller::{DataDuplicationCheck, DeleteCardResp};
#[cfg(feature = "v2")]
use api_models::payment_methods::PaymentMethodResponseItem;
use api_models::{enums as api_enums, payment_methods::Card};
use common_utils::{
ext_traits::{Encode, StringExt},
id_type,
pii::Email,
request::RequestContent,
};
use error_stack::ResultExt;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payment_method_data;
use josekit::jwe;
use router_env::tracing_actix_web::RequestId;
use serde::{Deserialize, Serialize};
#[cfg(feature = "v2")]
use crate::types::{payment_methods as pm_types, transformers};
use crate::{
configs::settings,
core::errors::{self, CustomResult},
headers,
pii::{prelude::*, Secret},
services::{api as services, encryption, EncryptionAlgorithm},
types::{api, domain},
utils::OptionExt,
};
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum StoreLockerReq {
LockerCard(StoreCardReq),
LockerGeneric(StoreGenericReq),
}
impl StoreLockerReq {
pub fn update_requestor_card_reference(&mut self, card_reference: Option<String>) {
match self {
Self::LockerCard(c) => c.requestor_card_reference = card_reference,
Self::LockerGeneric(_) => (),
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StoreCardReq {
pub merchant_id: id_type::MerchantId,
pub merchant_customer_id: id_type::CustomerId,
#[serde(skip_serializing_if = "Option::is_none")]
pub requestor_card_reference: Option<String>,
pub card: Card,
pub ttl: i64,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StoreGenericReq {
pub merchant_id: id_type::MerchantId,
pub merchant_customer_id: id_type::CustomerId,
#[serde(rename = "enc_card_data")]
pub enc_data: String,
pub ttl: i64,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StoreCardResp {
pub status: String,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub payload: Option<StoreCardRespPayload>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StoreCardRespPayload {
pub card_reference: String,
pub duplication_check: Option<DataDuplicationCheck>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CardReqBody {
pub merchant_id: id_type::MerchantId,
pub merchant_customer_id: id_type::CustomerId,
pub card_reference: String,
}
#[cfg(feature = "v2")]
#[derive(Debug, Deserialize, Serialize)]
pub struct CardReqBodyV2 {
pub merchant_id: id_type::MerchantId,
pub merchant_customer_id: String, // Not changing this as it might lead to api contract failure
pub card_reference: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct RetrieveCardResp {
pub status: String,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub payload: Option<RetrieveCardRespPayload>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct RetrieveCardRespPayload {
pub card: Option<Card>,
pub enc_card_data: Option<Secret<String>>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddCardRequest {
pub card_number: cards::CardNumber,
pub customer_id: id_type::CustomerId,
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
pub merchant_id: id_type::MerchantId,
pub email_address: Option<Email>,
pub name_on_card: Option<Secret<String>>,
pub nickname: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddCardResponse {
pub card_id: String,
pub external_id: String,
pub card_fingerprint: Secret<String>,
pub card_global_fingerprint: Secret<String>,
#[serde(rename = "merchant_id")]
pub merchant_id: Option<id_type::MerchantId>,
pub card_number: Option<cards::CardNumber>,
pub card_exp_year: Option<Secret<String>>,
pub card_exp_month: Option<Secret<String>>,
pub name_on_card: Option<Secret<String>>,
pub nickname: Option<String>,
pub customer_id: Option<id_type::CustomerId>,
pub duplicate: Option<bool>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddPaymentMethodResponse {
pub payment_method_id: String,
pub external_id: String,
#[serde(rename = "merchant_id")]
pub merchant_id: Option<id_type::MerchantId>,
pub nickname: Option<String>,
pub customer_id: Option<id_type::CustomerId>,
pub duplicate: Option<bool>,
pub payment_method_data: Secret<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct GetPaymentMethodResponse {
pub payment_method: AddPaymentMethodResponse,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct GetCardResponse {
pub card: AddCardResponse,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetCard<'a> {
merchant_id: &'a str,
card_id: &'a str,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DeleteCardResponse {
pub card_id: Option<String>,
pub external_id: Option<String>,
pub card_isin: Option<Secret<String>>,
pub status: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(transparent)]
pub struct PaymentMethodMetadata {
pub payment_method_tokenization: std::collections::HashMap<String, String>,
}
pub fn get_dotted_jwe(jwe: encryption::JweBody) -> String {
let header = jwe.header;
let encryption_key = jwe.encrypted_key;
let iv = jwe.iv;
let encryption_payload = jwe.encrypted_payload;
let tag = jwe.tag;
format!("{header}.{encryption_key}.{iv}.{encryption_payload}.{tag}")
}
pub fn get_dotted_jws(jws: encryption::JwsBody) -> String {
let header = jws.header;
let payload = jws.payload;
let signature = jws.signature;
format!("{header}.{payload}.{signature}")
}
pub async fn get_decrypted_response_payload(
jwekey: &settings::Jwekey,
jwe_body: encryption::JweBody,
locker_choice: Option<api_enums::LockerChoice>,
decryption_scheme: settings::DecryptionScheme,
) -> CustomResult<String, errors::VaultError> {
let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::HyperswitchCardVault);
let public_key = match target_locker {
api_enums::LockerChoice::HyperswitchCardVault => {
jwekey.vault_encryption_key.peek().as_bytes()
}
};
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jwt = get_dotted_jwe(jwe_body);
let alg = match decryption_scheme {
settings::DecryptionScheme::RsaOaep => jwe::RSA_OAEP,
settings::DecryptionScheme::RsaOaep256 => jwe::RSA_OAEP_256,
};
let jwe_decrypted = encryption::decrypt_jwe(
&jwt,
encryption::KeyIdCheck::SkipKeyIdCheck,
private_key,
alg,
)
.await
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Jwe Decryption failed for JweBody for vault")?;
let jws = jwe_decrypted
.parse_struct("JwsBody")
.change_context(errors::VaultError::ResponseDeserializationFailed)?;
let jws_body = get_dotted_jws(jws);
encryption::verify_sign(jws_body, public_key)
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Jws Decryption failed for JwsBody for vault")
}
pub async fn get_decrypted_vault_response_payload(
jwekey: &settings::Jwekey,
jwe_body: encryption::JweBody,
decryption_scheme: settings::DecryptionScheme,
) -> CustomResult<String, errors::VaultError> {
let public_key = jwekey.vault_encryption_key.peek().as_bytes();
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jwt = get_dotted_jwe(jwe_body);
let alg = match decryption_scheme {
settings::DecryptionScheme::RsaOaep => jwe::RSA_OAEP,
settings::DecryptionScheme::RsaOaep256 => jwe::RSA_OAEP_256,
};
let jwe_decrypted = encryption::decrypt_jwe(
&jwt,
encryption::KeyIdCheck::SkipKeyIdCheck,
private_key,
alg,
)
.await
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Jwe Decryption failed for JweBody for vault")?;
let jws = jwe_decrypted
.parse_struct("JwsBody")
.change_context(errors::VaultError::ResponseDeserializationFailed)?;
let jws_body = get_dotted_jws(jws);
encryption::verify_sign(jws_body, public_key)
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Jws Decryption failed for JwsBody for vault")
}
#[cfg(feature = "v2")]
pub async fn create_jwe_body_for_vault(
jwekey: &settings::Jwekey,
jws: &str,
) -> CustomResult<encryption::JweBody, errors::VaultError> {
let jws_payload: Vec<&str> = jws.split('.').collect();
let generate_jws_body = |payload: Vec<&str>| -> Option<encryption::JwsBody> {
Some(encryption::JwsBody {
header: payload.first()?.to_string(),
payload: payload.get(1)?.to_string(),
signature: payload.get(2)?.to_string(),
})
};
let jws_body =
generate_jws_body(jws_payload).ok_or(errors::VaultError::RequestEncryptionFailed)?;
let payload = jws_body
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
let public_key = jwekey.vault_encryption_key.peek().as_bytes();
let jwe_encrypted =
encryption::encrypt_jwe(&payload, public_key, EncryptionAlgorithm::A256GCM, None)
.await
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Error on jwe encrypt")?;
let jwe_payload: Vec<&str> = jwe_encrypted.split('.').collect();
let generate_jwe_body = |payload: Vec<&str>| -> Option<encryption::JweBody> {
Some(encryption::JweBody {
header: payload.first()?.to_string(),
iv: payload.get(2)?.to_string(),
encrypted_payload: payload.get(3)?.to_string(),
tag: payload.get(4)?.to_string(),
encrypted_key: payload.get(1)?.to_string(),
})
};
let jwe_body =
generate_jwe_body(jwe_payload).ok_or(errors::VaultError::RequestEncodingFailed)?;
Ok(jwe_body)
}
pub async fn mk_basilisk_req(
jwekey: &settings::Jwekey,
jws: &str,
locker_choice: api_enums::LockerChoice,
) -> CustomResult<encryption::JweBody, errors::VaultError> {
let jws_payload: Vec<&str> = jws.split('.').collect();
let generate_jws_body = |payload: Vec<&str>| -> Option<encryption::JwsBody> {
Some(encryption::JwsBody {
header: payload.first()?.to_string(),
payload: payload.get(1)?.to_string(),
signature: payload.get(2)?.to_string(),
})
};
let jws_body = generate_jws_body(jws_payload).ok_or(errors::VaultError::SaveCardFailed)?;
let payload = jws_body
.encode_to_vec()
.change_context(errors::VaultError::SaveCardFailed)?;
let public_key = match locker_choice {
api_enums::LockerChoice::HyperswitchCardVault => {
jwekey.vault_encryption_key.peek().as_bytes()
}
};
let jwe_encrypted =
encryption::encrypt_jwe(&payload, public_key, EncryptionAlgorithm::A256GCM, None)
.await
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Error on jwe encrypt")?;
let jwe_payload: Vec<&str> = jwe_encrypted.split('.').collect();
let generate_jwe_body = |payload: Vec<&str>| -> Option<encryption::JweBody> {
Some(encryption::JweBody {
header: payload.first()?.to_string(),
iv: payload.get(2)?.to_string(),
encrypted_payload: payload.get(3)?.to_string(),
tag: payload.get(4)?.to_string(),
encrypted_key: payload.get(1)?.to_string(),
})
};
let jwe_body = generate_jwe_body(jwe_payload).ok_or(errors::VaultError::SaveCardFailed)?;
Ok(jwe_body)
}
pub async fn mk_add_locker_request_hs(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
payload: &StoreLockerReq,
locker_choice: api_enums::LockerChoice,
tenant_id: id_type::TenantId,
request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let payload = payload
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key)
.await
.change_context(errors::VaultError::RequestEncodingFailed)?;
let jwe_payload = mk_basilisk_req(jwekey, &jws, locker_choice).await?;
let mut url = match locker_choice {
api_enums::LockerChoice::HyperswitchCardVault => locker.host.to_owned(),
};
url.push_str("/cards/add");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::X_TENANT_ID,
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
request.add_header(
headers::X_REQUEST_ID,
req_id.as_hyphenated().to_string().into(),
);
}
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
#[cfg(all(feature = "v1", feature = "payouts"))]
pub fn mk_add_bank_response_hs(
bank: api::BankPayout,
bank_reference: String,
req: api::PaymentMethodCreate,
merchant_id: &id_type::MerchantId,
) -> api::PaymentMethodResponse {
api::PaymentMethodResponse {
merchant_id: merchant_id.to_owned(),
customer_id: req.customer_id,
payment_method_id: bank_reference,
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
bank_transfer: Some(bank),
card: None,
metadata: req.metadata,
created: Some(common_utils::date_time::now()),
recurring_enabled: Some(false), // [#256]
installment_payment_enabled: Some(false), // #[#256]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()),
client_secret: None,
}
}
#[cfg(all(feature = "v2", feature = "payouts"))]
pub fn mk_add_bank_response_hs(
_bank: api::BankPayout,
_bank_reference: String,
_req: api::PaymentMethodCreate,
_merchant_id: &id_type::MerchantId,
) -> api::PaymentMethodResponse {
todo!()
}
#[cfg(feature = "v1")]
pub fn mk_add_card_response_hs(
card: api::CardDetail,
card_reference: String,
req: api::PaymentMethodCreate,
merchant_id: &id_type::MerchantId,
) -> api::PaymentMethodResponse {
let card_number = card.card_number.clone();
let last4_digits = card_number.get_last4();
let card_isin = card_number.get_card_isin();
let card = api::CardDetailFromLocker {
scheme: card
.card_network
.clone()
.map(|card_network| card_network.to_string()),
last4_digits: Some(last4_digits),
issuer_country: card.card_issuing_country,
card_number: Some(card.card_number.clone()),
expiry_month: Some(card.card_exp_month.clone()),
expiry_year: Some(card.card_exp_year.clone()),
card_token: None,
card_fingerprint: None,
card_holder_name: card.card_holder_name.clone(),
nick_name: card.nick_name.clone(),
card_isin: Some(card_isin),
card_issuer: card.card_issuer,
card_network: card.card_network,
card_type: card.card_type,
saved_to_locker: true,
};
api::PaymentMethodResponse {
merchant_id: merchant_id.to_owned(),
customer_id: req.customer_id,
payment_method_id: card_reference,
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
#[cfg(feature = "payouts")]
bank_transfer: None,
card: Some(card),
metadata: req.metadata,
created: Some(common_utils::date_time::now()),
recurring_enabled: Some(false), // [#256]
installment_payment_enabled: Some(false), // #[#256]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()), // [#256]
client_secret: req.client_secret,
}
}
#[cfg(feature = "v2")]
pub fn mk_add_card_response_hs(
card: api::CardDetail,
card_reference: String,
req: api::PaymentMethodCreate,
merchant_id: &id_type::MerchantId,
) -> api::PaymentMethodResponse {
todo!()
}
#[cfg(feature = "v2")]
pub fn generate_pm_vaulting_req_from_update_request(
pm_create: domain::PaymentMethodVaultingData,
pm_update: api::PaymentMethodUpdateData,
) -> domain::PaymentMethodVaultingData {
match (pm_create, pm_update) {
(
domain::PaymentMethodVaultingData::Card(card_create),
api::PaymentMethodUpdateData::Card(update_card),
) => domain::PaymentMethodVaultingData::Card(api::CardDetail {
card_number: card_create.card_number,
card_exp_month: card_create.card_exp_month,
card_exp_year: card_create.card_exp_year,
card_issuing_country: card_create.card_issuing_country,
card_network: card_create.card_network,
card_issuer: card_create.card_issuer,
card_type: card_create.card_type,
card_holder_name: update_card
.card_holder_name
.or(card_create.card_holder_name),
nick_name: update_card.nick_name.or(card_create.nick_name),
card_cvc: None,
}),
_ => todo!(), //todo! - since support for network tokenization is not added PaymentMethodUpdateData. should be handled later.
}
}
#[cfg(feature = "v2")]
pub fn generate_payment_method_response(
payment_method: &domain::PaymentMethod,
single_use_token: &Option<payment_method_data::SingleUsePaymentMethodToken>,
) -> errors::RouterResult<api::PaymentMethodResponse> {
let pmd = payment_method
.payment_method_data
.clone()
.map(|data| data.into_inner())
.and_then(|data| match data {
api::PaymentMethodsData::Card(card) => {
Some(api::PaymentMethodResponseData::Card(card.into()))
}
_ => None,
});
let mut connector_tokens = payment_method
.connector_mandate_details
.as_ref()
.and_then(|connector_token_details| connector_token_details.payments.clone())
.map(|payment_token_details| payment_token_details.0)
.map(|payment_token_details| {
payment_token_details
.into_iter()
.map(transformers::ForeignFrom::foreign_from)
.collect::<Vec<_>>()
})
.unwrap_or_default();
if let Some(token) = single_use_token {
let connector_token_single_use = transformers::ForeignFrom::foreign_from(token);
connector_tokens.push(connector_token_single_use);
}
let connector_tokens = if connector_tokens.is_empty() {
None
} else {
Some(connector_tokens)
};
let network_token_pmd = payment_method
.network_token_payment_method_data
.clone()
.map(|data| data.into_inner())
.and_then(|data| match data {
domain::PaymentMethodsData::NetworkToken(token) => {
Some(api::NetworkTokenDetailsPaymentMethod::from(token))
}
_ => None,
});
let network_token = network_token_pmd.map(|pmd| api::NetworkTokenResponse {
payment_method_data: pmd,
});
let resp = api::PaymentMethodResponse {
merchant_id: payment_method.merchant_id.to_owned(),
customer_id: payment_method.customer_id.to_owned(),
id: payment_method.id.to_owned(),
payment_method_type: payment_method.get_payment_method_type(),
payment_method_subtype: payment_method.get_payment_method_subtype(),
created: Some(payment_method.created_at),
recurring_enabled: Some(false),
last_used_at: Some(payment_method.last_used_at),
payment_method_data: pmd,
connector_tokens,
network_token,
};
Ok(resp)
}
#[allow(clippy::too_many_arguments)]
pub async fn mk_get_card_request_hs(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &str,
locker_choice: Option<api_enums::LockerChoice>,
tenant_id: id_type::TenantId,
request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let merchant_customer_id = customer_id.to_owned();
let card_req_body = CardReqBody {
merchant_id: merchant_id.to_owned(),
merchant_customer_id,
card_reference: card_reference.to_owned(),
};
let payload = card_req_body
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key)
.await
.change_context(errors::VaultError::RequestEncodingFailed)?;
let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::HyperswitchCardVault);
let jwe_payload = mk_basilisk_req(jwekey, &jws, target_locker).await?;
let mut url = match target_locker {
api_enums::LockerChoice::HyperswitchCardVault => locker.host.to_owned(),
};
url.push_str("/cards/retrieve");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::X_TENANT_ID,
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
request.add_header(
headers::X_REQUEST_ID,
req_id.as_hyphenated().to_string().into(),
);
}
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
pub fn mk_get_card_request(
locker: &settings::Locker,
locker_id: &'static str,
card_id: &'static str,
) -> CustomResult<services::Request, errors::VaultError> {
let get_card_req = GetCard {
merchant_id: locker_id,
card_id,
};
let mut url = locker.host.to_owned();
url.push_str("/card/getCard");
let mut request = services::Request::new(services::Method::Post, &url);
request.set_body(RequestContent::FormUrlEncoded(Box::new(get_card_req)));
Ok(request)
}
pub fn mk_get_card_response(card: GetCardResponse) -> errors::RouterResult<Card> {
Ok(Card {
card_number: card.card.card_number.get_required_value("card_number")?,
name_on_card: card.card.name_on_card,
card_exp_month: card
.card
.card_exp_month
.get_required_value("card_exp_month")?,
card_exp_year: card
.card
.card_exp_year
.get_required_value("card_exp_year")?,
card_brand: None,
card_isin: None,
nick_name: card.card.nickname,
})
}
pub async fn mk_delete_card_request_hs(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &str,
tenant_id: id_type::TenantId,
request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let merchant_customer_id = customer_id.to_owned();
let card_req_body = CardReqBody {
merchant_id: merchant_id.to_owned(),
merchant_customer_id,
card_reference: card_reference.to_owned(),
};
let payload = card_req_body
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key)
.await
.change_context(errors::VaultError::RequestEncodingFailed)?;
let jwe_payload =
mk_basilisk_req(jwekey, &jws, api_enums::LockerChoice::HyperswitchCardVault).await?;
let mut url = locker.host.to_owned();
url.push_str("/cards/delete");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::X_TENANT_ID,
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
request.add_header(
headers::X_REQUEST_ID,
req_id.as_hyphenated().to_string().into(),
);
}
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
// Need to fix this once we start moving to v2 completion
#[cfg(feature = "v2")]
pub async fn mk_delete_card_request_hs_by_id(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
id: &String,
merchant_id: &id_type::MerchantId,
card_reference: &str,
tenant_id: id_type::TenantId,
request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let merchant_customer_id = id.to_owned();
let card_req_body = CardReqBodyV2 {
merchant_id: merchant_id.to_owned(),
merchant_customer_id,
card_reference: card_reference.to_owned(),
};
let payload = card_req_body
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key)
.await
.change_context(errors::VaultError::RequestEncodingFailed)?;
let jwe_payload =
mk_basilisk_req(jwekey, &jws, api_enums::LockerChoice::HyperswitchCardVault).await?;
let mut url = locker.host.to_owned();
url.push_str("/cards/delete");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::X_TENANT_ID,
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
request.add_header(
headers::X_REQUEST_ID,
req_id.as_hyphenated().to_string().into(),
);
}
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
pub fn mk_delete_card_response(
response: DeleteCardResponse,
) -> errors::RouterResult<DeleteCardResp> {
Ok(DeleteCardResp {
status: response.status,
error_message: None,
error_code: None,
})
}
#[cfg(feature = "v1")]
pub fn get_card_detail(
pm: &domain::PaymentMethod,
response: Card,
) -> CustomResult<api::CardDetailFromLocker, errors::VaultError> {
let card_number = response.card_number;
let last4_digits = card_number.clone().get_last4();
//fetch form card bin
let card_detail = api::CardDetailFromLocker {
scheme: pm.scheme.to_owned(),
issuer_country: pm.issuer_country.clone(),
last4_digits: Some(last4_digits),
card_number: Some(card_number),
expiry_month: Some(response.card_exp_month),
expiry_year: Some(response.card_exp_year),
card_token: None,
card_fingerprint: None,
card_holder_name: response.name_on_card,
nick_name: response.nick_name.map(Secret::new),
card_isin: None,
card_issuer: None,
card_network: None,
card_type: None,
saved_to_locker: true,
};
Ok(card_detail)
}
#[cfg(feature = "v2")]
pub fn get_card_detail(
_pm: &domain::PaymentMethod,
response: Card,
) -> CustomResult<api::CardDetailFromLocker, errors::VaultError> {
let card_number = response.card_number;
let last4_digits = card_number.clone().get_last4();
//fetch form card bin
let card_detail = api::CardDetailFromLocker {
issuer_country: None,
last4_digits: Some(last4_digits),
card_number: Some(card_number),
expiry_month: Some(response.card_exp_month),
expiry_year: Some(response.card_exp_year),
card_fingerprint: None,
card_holder_name: response.name_on_card,
nick_name: response.nick_name.map(Secret::new),
card_isin: None,
card_issuer: None,
card_network: None,
card_type: None,
saved_to_locker: true,
};
Ok(card_detail)
}
//------------------------------------------------TokenizeService------------------------------------------------
pub fn mk_crud_locker_request(
locker: &settings::Locker,
path: &str,
req: api::TokenizePayloadEncrypted,
tenant_id: id_type::TenantId,
request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let mut url = locker.basilisk_host.to_owned();
url.push_str(path);
let mut request = services::Request::new(services::Method::Post, &url);
request.add_default_headers();
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::X_TENANT_ID,
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
request.add_header(
headers::X_REQUEST_ID,
req_id.as_hyphenated().to_string().into(),
);
}
request.set_body(RequestContent::Json(Box::new(req)));
Ok(request)
}
pub fn mk_card_value1(
card_number: cards::CardNumber,
exp_year: String,
exp_month: String,
name_on_card: Option<String>,
nickname: Option<String>,
card_last_four: Option<String>,
card_token: Option<String>,
) -> CustomResult<String, errors::VaultError> {
let value1 = api::TokenizedCardValue1 {
card_number: card_number.peek().clone(),
exp_year,
exp_month,
name_on_card,
nickname,
card_last_four,
card_token,
};
let value1_req = value1
.encode_to_string_of_json()
.change_context(errors::VaultError::FetchCardFailed)?;
Ok(value1_req)
}
pub fn mk_card_value2(
card_security_code: Option<String>,
card_fingerprint: Option<String>,
external_id: Option<String>,
customer_id: Option<id_type::CustomerId>,
payment_method_id: Option<String>,
) -> CustomResult<String, errors::VaultError> {
let value2 = api::TokenizedCardValue2 {
card_security_code,
card_fingerprint,
external_id,
customer_id,
payment_method_id,
};
let value2_req = value2
.encode_to_string_of_json()
.change_context(errors::VaultError::FetchCardFailed)?;
Ok(value2_req)
}
#[cfg(feature = "v2")]
impl transformers::ForeignTryFrom<(domain::PaymentMethod, String)>
for api::CustomerPaymentMethodResponseItem
{
type Error = error_stack::Report<errors::ValidationError>;
fn foreign_try_from(
(item, payment_token): (domain::PaymentMethod, String),
) -> Result<Self, Self::Error> {
// For payment methods that are active we should always have the payment method subtype
let payment_method_subtype =
item.payment_method_subtype
.ok_or(errors::ValidationError::MissingRequiredField {
field_name: "payment_method_subtype".to_string(),
})?;
// For payment methods that are active we should always have the payment method type
let payment_method_type =
item.payment_method_type
.ok_or(errors::ValidationError::MissingRequiredField {
field_name: "payment_method_type".to_string(),
})?;
let payment_method_data = item
.payment_method_data
.map(|payment_method_data| payment_method_data.into_inner())
.map(|payment_method_data| match payment_method_data {
api_models::payment_methods::PaymentMethodsData::Card(
card_details_payment_method,
) => {
let card_details = api::CardDetailFromLocker::from(card_details_payment_method);
api_models::payment_methods::PaymentMethodListData::Card(card_details)
}
api_models::payment_methods::PaymentMethodsData::BankDetails(..) => todo!(),
api_models::payment_methods::PaymentMethodsData::WalletDetails(..) => {
todo!()
}
});
let payment_method_billing = item
.payment_method_billing_address
.clone()
.map(|billing| billing.into_inner())
.map(From::from);
// TODO: check how we can get this field
let recurring_enabled = true;
Ok(Self {
id: item.id,
customer_id: item.customer_id,
payment_method_type,
payment_method_subtype,
created: item.created_at,
last_used_at: item.last_used_at,
recurring_enabled,
payment_method_data,
bank: None,
requires_cvv: true,
is_default: false,
billing: payment_method_billing,
payment_token,
})
}
}
#[cfg(feature = "v2")]
impl transformers::ForeignTryFrom<domain::PaymentMethod> for PaymentMethodResponseItem {
type Error = error_stack::Report<errors::ValidationError>;
fn foreign_try_from(item: domain::PaymentMethod) -> Result<Self, Self::Error> {
// For payment methods that are active we should always have the payment method subtype
let payment_method_subtype =
item.payment_method_subtype
.ok_or(errors::ValidationError::MissingRequiredField {
field_name: "payment_method_subtype".to_string(),
})?;
// For payment methods that are active we should always have the payment method type
let payment_method_type =
item.payment_method_type
.ok_or(errors::ValidationError::MissingRequiredField {
|
crates/router/src/core/payment_methods/transformers.rs#chunk0
|
router
|
chunk
| null | null | null | 8,190
| null | null | null | null | null | null | null |
// Function: to_redis_field_value_pairs
// File: crates/scheduler/src/consumer/types/batch.rs
// Module: scheduler
pub fn to_redis_field_value_pairs(
&self,
) -> CustomResult<Vec<(&str, String)>, errors::ProcessTrackerError>
|
crates/scheduler/src/consumer/types/batch.rs
|
scheduler
|
function_signature
| null | null | null | 59
|
to_redis_field_value_pairs
| null | null | null | null | null | null |
// Struct: StripebillingRefundRequest
// File: crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct StripebillingRefundRequest
|
crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
StripebillingRefundRequest
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Struct: MerchantRefundReq
// File: crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct MerchantRefundReq
|
crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
MerchantRefundReq
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Implementation: impl PaymentIntentMetricAccumulator for for PaymentsDistributionAccumulator
// File: crates/analytics/src/payment_intents/accumulator.rs
// Module: analytics
// Methods: 2 total (0 public)
impl PaymentIntentMetricAccumulator for for PaymentsDistributionAccumulator
|
crates/analytics/src/payment_intents/accumulator.rs
|
analytics
|
impl_block
| null | null | null | 61
| null |
PaymentsDistributionAccumulator
|
PaymentIntentMetricAccumulator for
| 2
| 0
| null | null |
// Struct: FulfilmentData
// File: crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct FulfilmentData
|
crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs
|
hyperswitch_connectors
|
struct_definition
|
FulfilmentData
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Implementation: impl HealthCheckClient
// File: crates/external_services/src/grpc_client/health_check_client.rs
// Module: external_services
// Methods: 3 total (0 public)
impl HealthCheckClient
|
crates/external_services/src/grpc_client/health_check_client.rs
|
external_services
|
impl_block
| null | null | null | 44
| null |
HealthCheckClient
| null | 3
| 0
| null | null |
// Implementation: impl ConnectorCommon for for Moneris
// File: crates/hyperswitch_connectors/src/connectors/moneris.rs
// Module: hyperswitch_connectors
// Methods: 6 total (0 public)
impl ConnectorCommon for for Moneris
|
crates/hyperswitch_connectors/src/connectors/moneris.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Moneris
|
ConnectorCommon for
| 6
| 0
| null | null |
assert_eq!(
algorithm
.decode_message(&secret, encoded_message.into())
.expect("Decode Failed"),
message
);
}
#[test]
fn test_gcm_aes_256_decode_message() {
// Inputs taken from AES GCM test vectors provided by NIST
// https://github.com/briansmith/ring/blob/95948b3977013aed16db92ae32e6b8384496a740/tests/aead_aes_256_gcm_tests.txt#L447-L452
let right_secret =
hex::decode("feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308")
.expect("Secret decoding");
let wrong_secret =
hex::decode("feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308309")
.expect("Secret decoding");
let message =
// The three parts of the message are the nonce, ciphertext and tag from the test vector
hex::decode(
"cafebabefacedbaddecaf888\
522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662898015ad\
b094dac5d93471bdec1a502270e3cc6c"
).expect("Message decoding");
let algorithm = super::GcmAes256;
let decoded = algorithm
.decode_message(&right_secret, message.clone().into())
.expect("Decoded message");
assert_eq!(
decoded,
hex::decode("d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255")
.expect("Decoded plaintext message")
);
let err_decoded = algorithm.decode_message(&wrong_secret, message.into());
assert!(err_decoded.is_err());
}
#[test]
fn test_md5_digest() {
let message = "abcdefghijklmnopqrstuvwxyz".as_bytes();
assert_eq!(
format!(
"{}",
hex::encode(super::Md5.generate_digest(message).expect("Digest"))
),
"c3fcd3d76192e4007dfb496cca67e13b"
);
}
#[test]
fn test_md5_verify_signature() {
let right_signature =
hex::decode("c3fcd3d76192e4007dfb496cca67e13b").expect("signature decoding");
let wrong_signature =
hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823f")
.expect("Wrong signature decoding");
let secret = "".as_bytes();
let data = "abcdefghijklmnopqrstuvwxyz".as_bytes();
let right_verified = super::Md5
.verify_signature(secret, &right_signature, data)
.expect("Right signature verification result");
assert!(right_verified);
let wrong_verified = super::Md5
.verify_signature(secret, &wrong_signature, data)
.expect("Wrong signature verification result");
assert!(!wrong_verified);
}
use ring::signature::{UnparsedPublicKey, RSA_PSS_2048_8192_SHA256};
#[test]
fn test_rsa_pss_sha256_verify_signature() {
let signer = crate::crypto::RsaPssSha256;
let message = b"abcdefghijklmnopqrstuvwxyz";
let private_key_pem_bytes =
std::fs::read("../../private_key.pem").expect("Failed to read private key");
let parsed_pem = pem::parse(&private_key_pem_bytes).expect("Failed to parse PEM");
let private_key_der = parsed_pem.contents();
let signature = signer
.sign_message(&private_key_pem_bytes, message)
.expect("Signing failed");
let key_pair = crate::crypto::RsaKeyPair::from_pkcs8(private_key_der)
.expect("Failed to parse DER key");
let public_key_der = key_pair.public().as_ref().to_vec();
let public_key = UnparsedPublicKey::new(&RSA_PSS_2048_8192_SHA256, &public_key_der);
assert!(
public_key.verify(message, &signature).is_ok(),
"Right signature should verify"
);
let mut wrong_signature = signature.clone();
if let Some(byte) = wrong_signature.first_mut() {
*byte ^= 0xFF;
}
assert!(
public_key.verify(message, &wrong_signature).is_err(),
"Wrong signature should not verify"
);
}
#[test]
fn test_rsasha256_verify_signature() {
use base64::Engine;
use rand::rngs::OsRng;
use rsa::{
pkcs8::EncodePublicKey,
signature::{RandomizedSigner, SignatureEncoding},
};
use crate::consts::BASE64_ENGINE;
let mut rng = OsRng;
let bits = 2048;
let private_key = rsa::RsaPrivateKey::new(&mut rng, bits).expect("keygen failed");
let signing_key = rsa::pkcs1v15::SigningKey::<rsa::sha2::Sha256>::new(private_key.clone());
let message = "{ This is a test message :) }".as_bytes();
let signature = signing_key.sign_with_rng(&mut rng, message);
let encoded_signature = BASE64_ENGINE.encode(signature.to_bytes());
let rsa_public_key = private_key.to_public_key();
let pem_format_public_key = rsa_public_key
.to_public_key_pem(rsa::pkcs8::LineEnding::LF)
.expect("transformation failed");
let encoded_pub_key = BASE64_ENGINE.encode(&pem_format_public_key[..]);
let right_verified = super::RsaSha256
.verify_signature(
encoded_pub_key.as_bytes(),
encoded_signature.as_bytes(),
message,
)
.expect("Right signature verification result");
assert!(right_verified);
}
}
|
crates/common_utils/src/crypto.rs#chunk1
|
common_utils
|
chunk
| null | null | null | 1,677
| null | null | null | null | null | null | null |
// Function: construct_connector_invoke_hidden_frame
// File: crates/router/src/core/payments/transformers.rs
// Module: router
pub fn construct_connector_invoke_hidden_frame(
connector_three_ds_invoke_data: api_models::payments::PaymentsConnectorThreeDsInvokeData,
) -> RouterResult<api_models::payments::NextActionData>
|
crates/router/src/core/payments/transformers.rs
|
router
|
function_signature
| null | null | null | 69
|
construct_connector_invoke_hidden_frame
| null | null | null | null | null | null |
#[strum(serialize = "24")]
Lija,
#[strum(serialize = "25")]
Luqa,
#[strum(serialize = "26")]
Marsa,
#[strum(serialize = "27")]
Marsaskala,
#[strum(serialize = "28")]
Marsaxlokk,
#[strum(serialize = "29")]
Mdina,
#[strum(serialize = "30")]
Mellieħa,
#[strum(serialize = "31")]
Mġarr,
#[strum(serialize = "32")]
Mosta,
#[strum(serialize = "33")]
Mqabba,
#[strum(serialize = "34")]
Msida,
#[strum(serialize = "35")]
Mtarfa,
#[strum(serialize = "36")]
Munxar,
#[strum(serialize = "37")]
Nadur,
#[strum(serialize = "38")]
Naxxar,
#[strum(serialize = "39")]
Paola,
#[strum(serialize = "40")]
Pembroke,
#[strum(serialize = "41")]
Pietà,
#[strum(serialize = "42")]
Qala,
#[strum(serialize = "43")]
Qormi,
#[strum(serialize = "44")]
Qrendi,
#[strum(serialize = "45")]
Victoria,
#[strum(serialize = "46")]
Rabat,
#[strum(serialize = "48")]
StJulians,
#[strum(serialize = "49")]
SanĠwann,
#[strum(serialize = "50")]
SaintLawrence,
#[strum(serialize = "51")]
StPaulsBay,
#[strum(serialize = "52")]
Sannat,
#[strum(serialize = "53")]
SantaLuċija,
#[strum(serialize = "54")]
SantaVenera,
#[strum(serialize = "55")]
Siġġiewi,
#[strum(serialize = "56")]
Sliema,
#[strum(serialize = "57")]
Swieqi,
#[strum(serialize = "58")]
TaXbiex,
#[strum(serialize = "59")]
Tarxien,
#[strum(serialize = "60")]
Valletta,
#[strum(serialize = "61")]
Xagħra,
#[strum(serialize = "62")]
Xewkija,
#[strum(serialize = "63")]
Xgħajra,
#[strum(serialize = "64")]
Żabbar,
#[strum(serialize = "65")]
ŻebbuġGozo,
#[strum(serialize = "66")]
ŻebbuġMalta,
#[strum(serialize = "67")]
Żejtun,
#[strum(serialize = "68")]
Żurrieq,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum MoldovaStatesAbbreviation {
#[strum(serialize = "AN")]
AneniiNoiDistrict,
#[strum(serialize = "BS")]
BasarabeascaDistrict,
#[strum(serialize = "BD")]
BenderMunicipality,
#[strum(serialize = "BR")]
BriceniDistrict,
#[strum(serialize = "BA")]
BălțiMunicipality,
#[strum(serialize = "CA")]
CahulDistrict,
#[strum(serialize = "CT")]
CantemirDistrict,
#[strum(serialize = "CU")]
ChișinăuMunicipality,
#[strum(serialize = "CM")]
CimișliaDistrict,
#[strum(serialize = "CR")]
CriuleniDistrict,
#[strum(serialize = "CL")]
CălărașiDistrict,
#[strum(serialize = "CS")]
CăușeniDistrict,
#[strum(serialize = "DO")]
DondușeniDistrict,
#[strum(serialize = "DR")]
DrochiaDistrict,
#[strum(serialize = "DU")]
DubăsariDistrict,
#[strum(serialize = "ED")]
EdinețDistrict,
#[strum(serialize = "FL")]
FloreștiDistrict,
#[strum(serialize = "FA")]
FăleștiDistrict,
#[strum(serialize = "GA")]
Găgăuzia,
#[strum(serialize = "GL")]
GlodeniDistrict,
#[strum(serialize = "HI")]
HînceștiDistrict,
#[strum(serialize = "IA")]
IaloveniDistrict,
#[strum(serialize = "NI")]
NisporeniDistrict,
#[strum(serialize = "OC")]
OcnițaDistrict,
#[strum(serialize = "OR")]
OrheiDistrict,
#[strum(serialize = "RE")]
RezinaDistrict,
#[strum(serialize = "RI")]
RîșcaniDistrict,
#[strum(serialize = "SO")]
SorocaDistrict,
#[strum(serialize = "ST")]
StrășeniDistrict,
#[strum(serialize = "SI")]
SîngereiDistrict,
#[strum(serialize = "TA")]
TaracliaDistrict,
#[strum(serialize = "TE")]
TeleneștiDistrict,
#[strum(serialize = "SN")]
TransnistriaAutonomousTerritorialUnit,
#[strum(serialize = "UN")]
UngheniDistrict,
#[strum(serialize = "SD")]
ȘoldăneștiDistrict,
#[strum(serialize = "SV")]
ȘtefanVodăDistrict,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum MonacoStatesAbbreviation {
Monaco,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum MontenegroStatesAbbreviation {
#[strum(serialize = "01")]
AndrijevicaMunicipality,
#[strum(serialize = "02")]
BarMunicipality,
#[strum(serialize = "03")]
BeraneMunicipality,
#[strum(serialize = "04")]
BijeloPoljeMunicipality,
#[strum(serialize = "05")]
BudvaMunicipality,
#[strum(serialize = "07")]
DanilovgradMunicipality,
#[strum(serialize = "22")]
GusinjeMunicipality,
#[strum(serialize = "09")]
KolasinMunicipality,
#[strum(serialize = "10")]
KotorMunicipality,
#[strum(serialize = "11")]
MojkovacMunicipality,
#[strum(serialize = "12")]
NiksicMunicipality,
#[strum(serialize = "06")]
OldRoyalCapitalCetinje,
#[strum(serialize = "23")]
PetnjicaMunicipality,
#[strum(serialize = "13")]
PlavMunicipality,
#[strum(serialize = "14")]
PljevljaMunicipality,
#[strum(serialize = "15")]
PlužineMunicipality,
#[strum(serialize = "16")]
PodgoricaMunicipality,
#[strum(serialize = "17")]
RožajeMunicipality,
#[strum(serialize = "19")]
TivatMunicipality,
#[strum(serialize = "20")]
UlcinjMunicipality,
#[strum(serialize = "18")]
SavnikMunicipality,
#[strum(serialize = "21")]
ŽabljakMunicipality,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum NetherlandsStatesAbbreviation {
#[strum(serialize = "BQ1")]
Bonaire,
#[strum(serialize = "DR")]
Drenthe,
#[strum(serialize = "FL")]
Flevoland,
#[strum(serialize = "FR")]
Friesland,
#[strum(serialize = "GE")]
Gelderland,
#[strum(serialize = "GR")]
Groningen,
#[strum(serialize = "LI")]
Limburg,
#[strum(serialize = "NB")]
NorthBrabant,
#[strum(serialize = "NH")]
NorthHolland,
#[strum(serialize = "OV")]
Overijssel,
#[strum(serialize = "BQ2")]
Saba,
#[strum(serialize = "BQ3")]
SintEustatius,
#[strum(serialize = "ZH")]
SouthHolland,
#[strum(serialize = "UT")]
Utrecht,
#[strum(serialize = "ZE")]
Zeeland,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum NorthMacedoniaStatesAbbreviation {
#[strum(serialize = "01")]
AerodromMunicipality,
#[strum(serialize = "02")]
AracinovoMunicipality,
#[strum(serialize = "03")]
BerovoMunicipality,
#[strum(serialize = "04")]
BitolaMunicipality,
#[strum(serialize = "05")]
BogdanciMunicipality,
#[strum(serialize = "06")]
BogovinjeMunicipality,
#[strum(serialize = "07")]
BosilovoMunicipality,
#[strum(serialize = "08")]
BrvenicaMunicipality,
#[strum(serialize = "09")]
ButelMunicipality,
#[strum(serialize = "77")]
CentarMunicipality,
#[strum(serialize = "78")]
CentarZupaMunicipality,
#[strum(serialize = "22")]
DebarcaMunicipality,
#[strum(serialize = "23")]
DelcevoMunicipality,
#[strum(serialize = "25")]
DemirHisarMunicipality,
#[strum(serialize = "24")]
DemirKapijaMunicipality,
#[strum(serialize = "26")]
DojranMunicipality,
#[strum(serialize = "27")]
DolneniMunicipality,
#[strum(serialize = "28")]
DrugovoMunicipality,
#[strum(serialize = "17")]
GaziBabaMunicipality,
#[strum(serialize = "18")]
GevgelijaMunicipality,
#[strum(serialize = "29")]
GjorcePetrovMunicipality,
#[strum(serialize = "19")]
GostivarMunicipality,
#[strum(serialize = "20")]
GradskoMunicipality,
#[strum(serialize = "85")]
GreaterSkopje,
#[strum(serialize = "34")]
IlindenMunicipality,
#[strum(serialize = "35")]
JegunovceMunicipality,
#[strum(serialize = "37")]
Karbinci,
#[strum(serialize = "38")]
KarposMunicipality,
#[strum(serialize = "36")]
KavadarciMunicipality,
#[strum(serialize = "39")]
KiselaVodaMunicipality,
#[strum(serialize = "40")]
KicevoMunicipality,
#[strum(serialize = "41")]
KonceMunicipality,
#[strum(serialize = "42")]
KocaniMunicipality,
#[strum(serialize = "43")]
KratovoMunicipality,
#[strum(serialize = "44")]
KrivaPalankaMunicipality,
#[strum(serialize = "45")]
KrivogastaniMunicipality,
#[strum(serialize = "46")]
KrusevoMunicipality,
#[strum(serialize = "47")]
KumanovoMunicipality,
#[strum(serialize = "48")]
LipkovoMunicipality,
#[strum(serialize = "49")]
LozovoMunicipality,
#[strum(serialize = "51")]
MakedonskaKamenicaMunicipality,
#[strum(serialize = "52")]
MakedonskiBrodMunicipality,
#[strum(serialize = "50")]
MavrovoAndRostusaMunicipality,
#[strum(serialize = "53")]
MogilaMunicipality,
#[strum(serialize = "54")]
NegotinoMunicipality,
#[strum(serialize = "55")]
NovaciMunicipality,
#[strum(serialize = "56")]
NovoSeloMunicipality,
#[strum(serialize = "58")]
OhridMunicipality,
#[strum(serialize = "57")]
OslomejMunicipality,
#[strum(serialize = "60")]
PehcevoMunicipality,
#[strum(serialize = "59")]
PetrovecMunicipality,
#[strum(serialize = "61")]
PlasnicaMunicipality,
#[strum(serialize = "62")]
PrilepMunicipality,
#[strum(serialize = "63")]
ProbishtipMunicipality,
#[strum(serialize = "64")]
RadovisMunicipality,
#[strum(serialize = "65")]
RankovceMunicipality,
#[strum(serialize = "66")]
ResenMunicipality,
#[strum(serialize = "67")]
RosomanMunicipality,
#[strum(serialize = "68")]
SarajMunicipality,
#[strum(serialize = "70")]
SopisteMunicipality,
#[strum(serialize = "71")]
StaroNagoricaneMunicipality,
#[strum(serialize = "72")]
StrugaMunicipality,
#[strum(serialize = "73")]
StrumicaMunicipality,
#[strum(serialize = "74")]
StudenicaniMunicipality,
#[strum(serialize = "69")]
SvetiNikoleMunicipality,
#[strum(serialize = "75")]
TearceMunicipality,
#[strum(serialize = "76")]
TetovoMunicipality,
#[strum(serialize = "10")]
ValandovoMunicipality,
#[strum(serialize = "11")]
VasilevoMunicipality,
#[strum(serialize = "13")]
VelesMunicipality,
#[strum(serialize = "12")]
VevcaniMunicipality,
#[strum(serialize = "14")]
VinicaMunicipality,
#[strum(serialize = "15")]
VranesticaMunicipality,
#[strum(serialize = "16")]
VrapcisteMunicipality,
#[strum(serialize = "31")]
ZajasMunicipality,
#[strum(serialize = "32")]
ZelenikovoMunicipality,
#[strum(serialize = "33")]
ZrnovciMunicipality,
#[strum(serialize = "79")]
CairMunicipality,
#[strum(serialize = "80")]
CaskaMunicipality,
#[strum(serialize = "81")]
CesinovoOblesevoMunicipality,
#[strum(serialize = "82")]
CucerSandevoMunicipality,
#[strum(serialize = "83")]
StipMunicipality,
#[strum(serialize = "84")]
ShutoOrizariMunicipality,
#[strum(serialize = "30")]
ZelinoMunicipality,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum NorwayStatesAbbreviation {
#[strum(serialize = "02")]
Akershus,
#[strum(serialize = "06")]
Buskerud,
#[strum(serialize = "20")]
Finnmark,
#[strum(serialize = "04")]
Hedmark,
#[strum(serialize = "12")]
Hordaland,
#[strum(serialize = "22")]
JanMayen,
#[strum(serialize = "15")]
MoreOgRomsdal,
#[strum(serialize = "17")]
NordTrondelag,
#[strum(serialize = "18")]
Nordland,
#[strum(serialize = "05")]
Oppland,
#[strum(serialize = "03")]
Oslo,
#[strum(serialize = "11")]
Rogaland,
#[strum(serialize = "14")]
SognOgFjordane,
#[strum(serialize = "21")]
Svalbard,
#[strum(serialize = "16")]
SorTrondelag,
#[strum(serialize = "08")]
Telemark,
#[strum(serialize = "19")]
Troms,
#[strum(serialize = "50")]
Trondelag,
#[strum(serialize = "10")]
VestAgder,
#[strum(serialize = "07")]
Vestfold,
#[strum(serialize = "01")]
Ostfold,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum PolandStatesAbbreviation {
#[strum(serialize = "30")]
GreaterPoland,
#[strum(serialize = "26")]
HolyCross,
#[strum(serialize = "04")]
KuyaviaPomerania,
#[strum(serialize = "12")]
LesserPoland,
#[strum(serialize = "02")]
LowerSilesia,
#[strum(serialize = "06")]
Lublin,
#[strum(serialize = "08")]
Lubusz,
#[strum(serialize = "10")]
Łódź,
#[strum(serialize = "14")]
Mazovia,
#[strum(serialize = "20")]
Podlaskie,
#[strum(serialize = "22")]
Pomerania,
#[strum(serialize = "24")]
Silesia,
#[strum(serialize = "18")]
Subcarpathia,
#[strum(serialize = "16")]
UpperSilesia,
#[strum(serialize = "28")]
WarmiaMasuria,
#[strum(serialize = "32")]
WestPomerania,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum PortugalStatesAbbreviation {
#[strum(serialize = "01")]
AveiroDistrict,
#[strum(serialize = "20")]
Azores,
#[strum(serialize = "02")]
BejaDistrict,
#[strum(serialize = "03")]
BragaDistrict,
#[strum(serialize = "04")]
BragancaDistrict,
#[strum(serialize = "05")]
CasteloBrancoDistrict,
#[strum(serialize = "06")]
CoimbraDistrict,
#[strum(serialize = "08")]
FaroDistrict,
#[strum(serialize = "09")]
GuardaDistrict,
#[strum(serialize = "10")]
LeiriaDistrict,
#[strum(serialize = "11")]
LisbonDistrict,
#[strum(serialize = "30")]
Madeira,
#[strum(serialize = "12")]
PortalegreDistrict,
#[strum(serialize = "13")]
PortoDistrict,
#[strum(serialize = "14")]
SantaremDistrict,
#[strum(serialize = "15")]
SetubalDistrict,
#[strum(serialize = "16")]
VianaDoCasteloDistrict,
#[strum(serialize = "17")]
VilaRealDistrict,
#[strum(serialize = "18")]
ViseuDistrict,
#[strum(serialize = "07")]
EvoraDistrict,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum SpainStatesAbbreviation {
#[strum(serialize = "C")]
ACorunaProvince,
#[strum(serialize = "AB")]
AlbaceteProvince,
#[strum(serialize = "A")]
AlicanteProvince,
#[strum(serialize = "AL")]
AlmeriaProvince,
#[strum(serialize = "AN")]
Andalusia,
#[strum(serialize = "VI")]
ArabaAlava,
#[strum(serialize = "AR")]
Aragon,
#[strum(serialize = "BA")]
BadajozProvince,
#[strum(serialize = "PM")]
BalearicIslands,
#[strum(serialize = "B")]
BarcelonaProvince,
#[strum(serialize = "PV")]
BasqueCountry,
#[strum(serialize = "BI")]
Biscay,
#[strum(serialize = "BU")]
BurgosProvince,
#[strum(serialize = "CN")]
CanaryIslands,
#[strum(serialize = "S")]
Cantabria,
#[strum(serialize = "CS")]
CastellonProvince,
#[strum(serialize = "CL")]
CastileAndLeon,
#[strum(serialize = "CM")]
CastileLaMancha,
#[strum(serialize = "CT")]
Catalonia,
#[strum(serialize = "CE")]
Ceuta,
#[strum(serialize = "CR")]
CiudadRealProvince,
#[strum(serialize = "MD")]
CommunityOfMadrid,
#[strum(serialize = "CU")]
CuencaProvince,
#[strum(serialize = "CC")]
CaceresProvince,
#[strum(serialize = "CA")]
CadizProvince,
#[strum(serialize = "CO")]
CordobaProvince,
#[strum(serialize = "EX")]
Extremadura,
#[strum(serialize = "GA")]
Galicia,
#[strum(serialize = "SS")]
Gipuzkoa,
#[strum(serialize = "GI")]
GironaProvince,
#[strum(serialize = "GR")]
GranadaProvince,
#[strum(serialize = "GU")]
GuadalajaraProvince,
#[strum(serialize = "H")]
HuelvaProvince,
#[strum(serialize = "HU")]
HuescaProvince,
#[strum(serialize = "J")]
JaenProvince,
#[strum(serialize = "RI")]
LaRioja,
#[strum(serialize = "GC")]
LasPalmasProvince,
#[strum(serialize = "LE")]
LeonProvince,
#[strum(serialize = "L")]
LleidaProvince,
#[strum(serialize = "LU")]
LugoProvince,
#[strum(serialize = "M")]
MadridProvince,
#[strum(serialize = "ML")]
Melilla,
#[strum(serialize = "MU")]
MurciaProvince,
#[strum(serialize = "MA")]
MalagaProvince,
#[strum(serialize = "NC")]
Navarre,
#[strum(serialize = "OR")]
OurenseProvince,
#[strum(serialize = "P")]
PalenciaProvince,
#[strum(serialize = "PO")]
PontevedraProvince,
#[strum(serialize = "O")]
ProvinceOfAsturias,
#[strum(serialize = "AV")]
ProvinceOfAvila,
#[strum(serialize = "MC")]
RegionOfMurcia,
#[strum(serialize = "SA")]
SalamancaProvince,
#[strum(serialize = "TF")]
SantaCruzDeTenerifeProvince,
#[strum(serialize = "SG")]
SegoviaProvince,
#[strum(serialize = "SE")]
SevilleProvince,
#[strum(serialize = "SO")]
SoriaProvince,
#[strum(serialize = "T")]
TarragonaProvince,
#[strum(serialize = "TE")]
TeruelProvince,
#[strum(serialize = "TO")]
ToledoProvince,
#[strum(serialize = "V")]
ValenciaProvince,
#[strum(serialize = "VC")]
ValencianCommunity,
#[strum(serialize = "VA")]
ValladolidProvince,
#[strum(serialize = "ZA")]
ZamoraProvince,
#[strum(serialize = "Z")]
ZaragozaProvince,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum SwitzerlandStatesAbbreviation {
#[strum(serialize = "AG")]
Aargau,
#[strum(serialize = "AR")]
AppenzellAusserrhoden,
#[strum(serialize = "AI")]
AppenzellInnerrhoden,
#[strum(serialize = "BL")]
BaselLandschaft,
#[strum(serialize = "FR")]
CantonOfFribourg,
#[strum(serialize = "GE")]
CantonOfGeneva,
#[strum(serialize = "JU")]
CantonOfJura,
#[strum(serialize = "LU")]
CantonOfLucerne,
#[strum(serialize = "NE")]
CantonOfNeuchatel,
#[strum(serialize = "SH")]
CantonOfSchaffhausen,
#[strum(serialize = "SO")]
CantonOfSolothurn,
#[strum(serialize = "SG")]
CantonOfStGallen,
#[strum(serialize = "VS")]
CantonOfValais,
#[strum(serialize = "VD")]
CantonOfVaud,
#[strum(serialize = "ZG")]
CantonOfZug,
#[strum(serialize = "GL")]
Glarus,
#[strum(serialize = "GR")]
Graubunden,
#[strum(serialize = "NW")]
Nidwalden,
#[strum(serialize = "OW")]
Obwalden,
#[strum(serialize = "SZ")]
Schwyz,
#[strum(serialize = "TG")]
Thurgau,
#[strum(serialize = "TI")]
Ticino,
#[strum(serialize = "UR")]
Uri,
#[strum(serialize = "BE")]
CantonOfBern,
#[strum(serialize = "ZH")]
CantonOfZurich,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum UnitedKingdomStatesAbbreviation {
#[strum(serialize = "ABE")]
Aberdeen,
#[strum(serialize = "ABD")]
Aberdeenshire,
#[strum(serialize = "ANS")]
Angus,
#[strum(serialize = "ANT")]
Antrim,
#[strum(serialize = "ANN")]
AntrimAndNewtownabbey,
#[strum(serialize = "ARD")]
Ards,
#[strum(serialize = "AND")]
ArdsAndNorthDown,
#[strum(serialize = "AGB")]
ArgyllAndBute,
#[strum(serialize = "ARM")]
ArmaghCityAndDistrictCouncil,
#[strum(serialize = "ABC")]
ArmaghBanbridgeAndCraigavon,
#[strum(serialize = "SH-AC")]
AscensionIsland,
#[strum(serialize = "BLA")]
BallymenaBorough,
#[strum(serialize = "BLY")]
Ballymoney,
#[strum(serialize = "BNB")]
Banbridge,
#[strum(serialize = "BNS")]
Barnsley,
#[strum(serialize = "BAS")]
BathAndNorthEastSomerset,
#[strum(serialize = "BDF")]
Bedford,
#[strum(serialize = "BFS")]
BelfastDistrict,
#[strum(serialize = "BIR")]
Birmingham,
#[strum(serialize = "BBD")]
BlackburnWithDarwen,
#[strum(serialize = "BPL")]
Blackpool,
#[strum(serialize = "BGW")]
BlaenauGwentCountyBorough,
#[strum(serialize = "BOL")]
Bolton,
#[strum(serialize = "BMH")]
Bournemouth,
#[strum(serialize = "BRC")]
BracknellForest,
#[strum(serialize = "BRD")]
Bradford,
#[strum(serialize = "BGE")]
BridgendCountyBorough,
#[strum(serialize = "BNH")]
BrightonAndHove,
#[strum(serialize = "BKM")]
Buckinghamshire,
#[strum(serialize = "BUR")]
Bury,
#[strum(serialize = "CAY")]
CaerphillyCountyBorough,
#[strum(serialize = "CLD")]
Calderdale,
#[strum(serialize = "CAM")]
Cambridgeshire,
#[strum(serialize = "CMN")]
Carmarthenshire,
#[strum(serialize = "CKF")]
CarrickfergusBoroughCouncil,
#[strum(serialize = "CSR")]
Castlereagh,
#[strum(serialize = "CCG")]
CausewayCoastAndGlens,
#[strum(serialize = "CBF")]
CentralBedfordshire,
#[strum(serialize = "CGN")]
Ceredigion,
#[strum(serialize = "CHE")]
CheshireEast,
#[strum(serialize = "CHW")]
CheshireWestAndChester,
#[strum(serialize = "CRF")]
CityAndCountyOfCardiff,
#[strum(serialize = "SWA")]
CityAndCountyOfSwansea,
#[strum(serialize = "BST")]
CityOfBristol,
#[strum(serialize = "DER")]
CityOfDerby,
#[strum(serialize = "KHL")]
CityOfKingstonUponHull,
#[strum(serialize = "LCE")]
CityOfLeicester,
#[strum(serialize = "LND")]
CityOfLondon,
#[strum(serialize = "NGM")]
CityOfNottingham,
#[strum(serialize = "PTE")]
CityOfPeterborough,
#[strum(serialize = "PLY")]
CityOfPlymouth,
#[strum(serialize = "POR")]
CityOfPortsmouth,
#[strum(serialize = "STH")]
CityOfSouthampton,
#[strum(serialize = "STE")]
CityOfStokeOnTrent,
#[strum(serialize = "SND")]
CityOfSunderland,
#[strum(serialize = "WSM")]
CityOfWestminster,
#[strum(serialize = "WLV")]
CityOfWolverhampton,
#[strum(serialize = "YOR")]
CityOfYork,
#[strum(serialize = "CLK")]
Clackmannanshire,
#[strum(serialize = "CLR")]
ColeraineBoroughCouncil,
#[strum(serialize = "CWY")]
ConwyCountyBorough,
#[strum(serialize = "CKT")]
CookstownDistrictCouncil,
#[strum(serialize = "CON")]
Cornwall,
#[strum(serialize = "DUR")]
CountyDurham,
#[strum(serialize = "COV")]
Coventry,
#[strum(serialize = "CGV")]
CraigavonBoroughCouncil,
#[strum(serialize = "CMA")]
Cumbria,
#[strum(serialize = "DAL")]
Darlington,
#[strum(serialize = "DEN")]
Denbighshire,
#[strum(serialize = "DBY")]
Derbyshire,
#[strum(serialize = "DRS")]
DerryCityAndStrabane,
#[strum(serialize = "DRY")]
DerryCityCouncil,
#[strum(serialize = "DEV")]
Devon,
#[strum(serialize = "DNC")]
Doncaster,
#[strum(serialize = "DOR")]
Dorset,
#[strum(serialize = "DOW")]
DownDistrictCouncil,
#[strum(serialize = "DUD")]
Dudley,
#[strum(serialize = "DGY")]
DumfriesAndGalloway,
#[strum(serialize = "DND")]
Dundee,
#[strum(serialize = "DGN")]
DungannonAndSouthTyroneBoroughCouncil,
#[strum(serialize = "EAY")]
EastAyrshire,
#[strum(serialize = "EDU")]
EastDunbartonshire,
#[strum(serialize = "ELN")]
EastLothian,
#[strum(serialize = "ERW")]
EastRenfrewshire,
#[strum(serialize = "ERY")]
EastRidingOfYorkshire,
#[strum(serialize = "ESX")]
EastSussex,
#[strum(serialize = "EDH")]
Edinburgh,
#[strum(serialize = "ENG")]
England,
#[strum(serialize = "ESS")]
Essex,
#[strum(serialize = "FAL")]
Falkirk,
#[strum(serialize = "FMO")]
FermanaghAndOmagh,
#[strum(serialize = "FER")]
FermanaghDistrictCouncil,
#[strum(serialize = "FIF")]
Fife,
#[strum(serialize = "FLN")]
Flintshire,
#[strum(serialize = "GAT")]
Gateshead,
#[strum(serialize = "GLG")]
Glasgow,
#[strum(serialize = "GLS")]
Gloucestershire,
#[strum(serialize = "GWN")]
Gwynedd,
#[strum(serialize = "HAL")]
Halton,
#[strum(serialize = "HAM")]
Hampshire,
#[strum(serialize = "HPL")]
Hartlepool,
#[strum(serialize = "HEF")]
Herefordshire,
#[strum(serialize = "HRT")]
Hertfordshire,
#[strum(serialize = "HLD")]
Highland,
#[strum(serialize = "IVC")]
Inverclyde,
#[strum(serialize = "IOW")]
IsleOfWight,
#[strum(serialize = "IOS")]
IslesOfScilly,
#[strum(serialize = "KEN")]
Kent,
#[strum(serialize = "KIR")]
Kirklees,
#[strum(serialize = "KWL")]
Knowsley,
#[strum(serialize = "LAN")]
Lancashire,
#[strum(serialize = "LRN")]
|
crates/common_enums/src/enums.rs#chunk5
|
common_enums
|
chunk
| null | null | null | 8,187
| null | null | null | null | null | null | null |
// Function: validate_email_domain_auth_type_using_db
// File: crates/router/src/utils/user.rs
// Module: router
pub fn validate_email_domain_auth_type_using_db(
state: &SessionState,
email: &domain::UserEmail,
required_auth_type: UserAuthType,
) -> UserResult<()>
|
crates/router/src/utils/user.rs
|
router
|
function_signature
| null | null | null | 66
|
validate_email_domain_auth_type_using_db
| null | null | null | null | null | null |
// File: crates/storage_impl/src/lookup.rs
// Module: storage_impl
use common_utils::errors::CustomResult;
use diesel_models::{
enums as storage_enums, kv,
reverse_lookup::{
ReverseLookup as DieselReverseLookup, ReverseLookupNew as DieselReverseLookupNew,
},
};
use error_stack::ResultExt;
use redis_interface::SetnxReply;
use crate::{
diesel_error_to_data_error,
errors::{self, RedisErrorExt},
kv_router_store::KVRouterStore,
redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey},
utils::{self, try_redis_get_else_try_database_get},
DatabaseStore, RouterStore,
};
#[async_trait::async_trait]
pub trait ReverseLookupInterface {
async fn insert_reverse_lookup(
&self,
_new: DieselReverseLookupNew,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<DieselReverseLookup, errors::StorageError>;
async fn get_lookup_by_lookup_id(
&self,
_id: &str,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<DieselReverseLookup, errors::StorageError>;
}
#[async_trait::async_trait]
impl<T: DatabaseStore> ReverseLookupInterface for RouterStore<T> {
async fn insert_reverse_lookup(
&self,
new: DieselReverseLookupNew,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<DieselReverseLookup, errors::StorageError> {
let conn = self
.get_master_pool()
.get()
.await
.change_context(errors::StorageError::DatabaseConnectionError)?;
new.insert(&conn).await.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
}
async fn get_lookup_by_lookup_id(
&self,
id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<DieselReverseLookup, errors::StorageError> {
let conn = utils::pg_connection_read(self).await?;
DieselReverseLookup::find_by_lookup_id(id, &conn)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
}
}
#[async_trait::async_trait]
impl<T: DatabaseStore> ReverseLookupInterface for KVRouterStore<T> {
async fn insert_reverse_lookup(
&self,
new: DieselReverseLookupNew,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<DieselReverseLookup, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselReverseLookup>(
self,
storage_scheme,
Op::Insert,
))
.await;
match storage_scheme {
storage_enums::MerchantStorageScheme::PostgresOnly => {
self.router_store
.insert_reverse_lookup(new, storage_scheme)
.await
}
storage_enums::MerchantStorageScheme::RedisKv => {
let created_rev_lookup = DieselReverseLookup {
lookup_id: new.lookup_id.clone(),
sk_id: new.sk_id.clone(),
pk_id: new.pk_id.clone(),
source: new.source.clone(),
updated_by: storage_scheme.to_string(),
};
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
insertable: Box::new(kv::Insertable::ReverseLookUp(new)),
},
};
match Box::pin(kv_wrapper::<DieselReverseLookup, _, _>(
self,
KvOperation::SetNx(&created_rev_lookup, redis_entry),
PartitionKey::CombinationKey {
combination: &format!("reverse_lookup_{}", &created_rev_lookup.lookup_id),
},
))
.await
.map_err(|err| err.to_redis_failed_response(&created_rev_lookup.lookup_id))?
.try_into_setnx()
{
Ok(SetnxReply::KeySet) => Ok(created_rev_lookup),
Ok(SetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue {
entity: "reverse_lookup",
key: Some(created_rev_lookup.lookup_id.clone()),
}
.into()),
Err(er) => Err(er).change_context(errors::StorageError::KVError),
}
}
}
}
async fn get_lookup_by_lookup_id(
&self,
id: &str,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<DieselReverseLookup, errors::StorageError> {
let database_call = || async {
self.router_store
.get_lookup_by_lookup_id(id, storage_scheme)
.await
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselReverseLookup>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
storage_enums::MerchantStorageScheme::PostgresOnly => database_call().await,
storage_enums::MerchantStorageScheme::RedisKv => {
let redis_fut = async {
Box::pin(kv_wrapper(
self,
KvOperation::<DieselReverseLookup>::Get,
PartitionKey::CombinationKey {
combination: &format!("reverse_lookup_{id}"),
},
))
.await?
.try_into_get()
};
Box::pin(try_redis_get_else_try_database_get(
redis_fut,
database_call,
))
.await
}
}
}
}
|
crates/storage_impl/src/lookup.rs
|
storage_impl
|
full_file
| null | null | null | 1,200
| null | null | null | null | null | null | null |
// Struct: PaymentMethodCollectLink
// File: crates/diesel_models/src/generic_link.rs
// Module: diesel_models
// Implementations: 0
pub struct PaymentMethodCollectLink
|
crates/diesel_models/src/generic_link.rs
|
diesel_models
|
struct_definition
|
PaymentMethodCollectLink
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Function: find_by_merchant_id
// File: crates/diesel_models/src/query/merchant_key_store.rs
// Module: diesel_models
pub fn find_by_merchant_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self>
|
crates/diesel_models/src/query/merchant_key_store.rs
|
diesel_models
|
function_signature
| null | null | null | 68
|
find_by_merchant_id
| null | null | null | null | null | null |
// Function: accept_invitations_v2
// File: crates/router/src/routes/user_role.rs
// Module: router
pub fn accept_invitations_v2(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_role_api::AcceptInvitationsV2Request>,
) -> HttpResponse
|
crates/router/src/routes/user_role.rs
|
router
|
function_signature
| null | null | null | 69
|
accept_invitations_v2
| null | null | null | null | null | null |
// Struct: Parameters
// File: crates/hyperswitch_connectors/src/connectors/aci/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct Parameters
|
crates/hyperswitch_connectors/src/connectors/aci/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
Parameters
| 0
|
[] | 43
| null | null | null | null | null | null | null |
// File: crates/router/tests/connectors/katapult.rs
// Module: router
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData};
use masking::Secret;
use router::types::{self, api, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct KatapultTest;
impl ConnectorActions for KatapultTest {}
impl utils::Connector for KatapultTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Katapult;
utils::construct_connector_data_old(
Box::new(Katapult::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.katapult
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"katapult".to_string()
}
}
static CONNECTOR: KatapultTest = KatapultTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
|
crates/router/tests/connectors/katapult.rs
|
router
|
full_file
| null | null | null | 2,932
| null | null | null | null | null | null | null |
// Function: new
// File: crates/api_models/src/analytics/frm.rs
// Module: api_models
pub fn new(
frm_status: Option<String>,
frm_name: Option<String>,
frm_transaction_type: Option<String>,
normalized_time_range: TimeRange,
) -> Self
|
crates/api_models/src/analytics/frm.rs
|
api_models
|
function_signature
| null | null | null | 62
|
new
| null | null | null | null | null | null |
// Struct: BlackhawknetworkErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/blackhawknetwork/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct BlackhawknetworkErrorResponse
|
crates/hyperswitch_connectors/src/connectors/blackhawknetwork/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
BlackhawknetworkErrorResponse
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Function: get_payment_methods_data
// File: crates/hyperswitch_domain_models/src/vault.rs
// Module: hyperswitch_domain_models
pub fn get_payment_methods_data(&self) -> payment_method_data::PaymentMethodsData
|
crates/hyperswitch_domain_models/src/vault.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 48
|
get_payment_methods_data
| null | null | null | null | null | null |
// File: crates/router/tests/connectors/trustpayments.rs
// Module: router
use std::str::FromStr;
use masking::Secret;
use router::types::{self, api, domain, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct TrustpaymentsTest;
impl ConnectorActions for TrustpaymentsTest {}
impl utils::Connector for TrustpaymentsTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Trustpayments;
utils::construct_connector_data_old(
Box::new(Trustpayments::new()),
types::Connector::Trustpayments,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.trustpayments
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"trustpayments".to_string()
}
}
static CONNECTOR: TrustpaymentsTest = TrustpaymentsTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
Some(utils::PaymentInfo {
address: Some(types::PaymentAddress::new(
None,
None,
Some(hyperswitch_domain_models::address::Address {
address: Some(hyperswitch_domain_models::address::AddressDetails {
country: Some(common_enums::CountryAlpha2::US),
city: Some("New York".to_string()),
zip: Some(Secret::new("10001".to_string())),
line1: Some(Secret::new("123 Main St".to_string())),
line2: None,
line3: None,
state: Some(Secret::new("NY".to_string())),
first_name: Some(Secret::new("John".to_string())),
last_name: Some(Secret::new("Doe".to_string())),
origin_zip: None,
}),
phone: Some(hyperswitch_domain_models::address::PhoneDetails {
number: Some(Secret::new("1234567890".to_string())),
country_code: Some("+1".to_string()),
}),
email: None,
}),
None,
)),
..Default::default()
})
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),
card_exp_month: Secret::new("12".to_string()),
card_exp_year: Secret::new("2025".to_string()),
card_cvc: Secret::new("123".to_string()),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: None,
card_holder_name: Some(Secret::new("John Doe".to_string())),
co_badged_card_data: None,
}),
confirm: true,
amount: 100,
minor_amount: common_utils::types::MinorUnit::new(100),
currency: enums::Currency::USD,
capture_method: Some(enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
})
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
|
crates/router/tests/connectors/trustpayments.rs
|
router
|
full_file
| null | null | null | 3,422
| null | null | null | null | null | null | null |
// File: crates/common_utils/src/metrics.rs
// Module: common_utils
//! Utilities for metrics
pub mod utils;
|
crates/common_utils/src/metrics.rs
|
common_utils
|
full_file
| null | null | null | 26
| null | null | null | null | null | null | null |
// Implementation: impl Responder
// File: crates/router/src/routes/authentication.rs
// Module: router
// Methods: 0 total (0 public)
impl Responder
|
crates/router/src/routes/authentication.rs
|
router
|
impl_block
| null | null | null | 35
| null |
Responder
| null | 0
| 0
| null | null |
// File: crates/hyperswitch_domain_models/src/router_data.rs
// Module: hyperswitch_domain_models
// Public functions: 8
// Public structs: 20
use std::{collections::HashMap, marker::PhantomData};
use common_types::{payments as common_payment_types, primitive_wrappers};
use common_utils::{
errors::IntegrityCheckError,
ext_traits::{OptionExt, ValueExt},
id_type,
types::MinorUnit,
};
use error_stack::ResultExt;
use masking::{ExposeInterface, Secret};
use crate::{
network_tokenization::NetworkTokenNumber, payment_address::PaymentAddress, payment_method_data,
payments,
};
#[cfg(feature = "v2")]
use crate::{
payments::{
payment_attempt::{ErrorDetails, PaymentAttemptUpdate},
payment_intent::PaymentIntentUpdate,
},
router_flow_types, router_request_types, router_response_types,
};
#[derive(Debug, Clone)]
pub struct RouterData<Flow, Request, Response> {
pub flow: PhantomData<Flow>,
pub merchant_id: id_type::MerchantId,
pub customer_id: Option<id_type::CustomerId>,
pub connector_customer: Option<String>,
pub connector: String,
// TODO: This should be a PaymentId type.
// Make this change after all the connector dependency has been removed from connectors
pub payment_id: String,
pub attempt_id: String,
pub tenant_id: id_type::TenantId,
pub status: common_enums::enums::AttemptStatus,
pub payment_method: common_enums::enums::PaymentMethod,
pub connector_auth_type: ConnectorAuthType,
pub description: Option<String>,
pub address: PaymentAddress,
pub auth_type: common_enums::enums::AuthenticationType,
pub connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
pub connector_wallets_details: Option<common_utils::pii::SecretSerdeValue>,
pub amount_captured: Option<i64>,
pub access_token: Option<AccessToken>,
pub session_token: Option<String>,
pub reference_id: Option<String>,
pub payment_method_token: Option<PaymentMethodToken>,
pub recurring_mandate_payment_data: Option<RecurringMandatePaymentData>,
pub preprocessing_id: Option<String>,
/// This is the balance amount for gift cards or voucher
pub payment_method_balance: Option<PaymentMethodBalance>,
///for switching between two different versions of the same connector
pub connector_api_version: Option<String>,
/// Contains flow-specific data required to construct a request and send it to the connector.
pub request: Request,
/// Contains flow-specific data that the connector responds with.
pub response: Result<Response, ErrorResponse>,
/// Contains a reference ID that should be sent in the connector request
pub connector_request_reference_id: String,
#[cfg(feature = "payouts")]
/// Contains payout method data
pub payout_method_data: Option<api_models::payouts::PayoutMethodData>,
#[cfg(feature = "payouts")]
/// Contains payout's quote ID
pub quote_id: Option<String>,
pub test_mode: Option<bool>,
pub connector_http_status_code: Option<u16>,
pub external_latency: Option<u128>,
/// Contains apple pay flow type simplified or manual
pub apple_pay_flow: Option<payment_method_data::ApplePayFlow>,
pub frm_metadata: Option<common_utils::pii::SecretSerdeValue>,
pub dispute_id: Option<String>,
pub refund_id: Option<String>,
/// This field is used to store various data regarding the response from connector
pub connector_response: Option<ConnectorResponseData>,
pub payment_method_status: Option<common_enums::PaymentMethodStatus>,
// minor amount for amount framework
pub minor_amount_captured: Option<MinorUnit>,
pub minor_amount_capturable: Option<MinorUnit>,
pub integrity_check: Result<(), IntegrityCheckError>,
pub additional_merchant_data: Option<api_models::admin::AdditionalMerchantData>,
pub header_payload: Option<payments::HeaderPayload>,
pub connector_mandate_request_reference_id: Option<String>,
pub l2_l3_data: Option<L2L3Data>,
pub authentication_id: Option<id_type::AuthenticationId>,
/// Contains the type of sca exemption required for the transaction
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
/// Contains stringified connector raw response body
pub raw_connector_response: Option<Secret<String>>,
/// Indicates whether the payment ID was provided by the merchant (true),
/// or generated internally by Hyperswitch (false)
pub is_payment_id_from_merchant: Option<bool>,
}
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct L2L3Data {
pub order_date: Option<time::PrimitiveDateTime>,
pub tax_status: Option<common_enums::TaxStatus>,
pub customer_tax_registration_id: Option<Secret<String>>,
pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
pub discount_amount: Option<MinorUnit>,
pub shipping_cost: Option<MinorUnit>,
pub shipping_amount_tax: Option<MinorUnit>,
pub duty_amount: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
pub merchant_order_reference_id: Option<String>,
pub customer_id: Option<id_type::CustomerId>,
pub shipping_origin_zip: Option<Secret<String>>,
pub shipping_state: Option<Secret<String>>,
pub shipping_country: Option<common_enums::CountryAlpha2>,
pub shipping_destination_zip: Option<Secret<String>>,
pub billing_address_city: Option<String>,
pub merchant_tax_registration_id: Option<Secret<String>>,
}
// Different patterns of authentication.
#[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(tag = "auth_type")]
pub enum ConnectorAuthType {
TemporaryAuth,
HeaderKey {
api_key: Secret<String>,
},
BodyKey {
api_key: Secret<String>,
key1: Secret<String>,
},
SignatureKey {
api_key: Secret<String>,
key1: Secret<String>,
api_secret: Secret<String>,
},
MultiAuthKey {
api_key: Secret<String>,
key1: Secret<String>,
api_secret: Secret<String>,
key2: Secret<String>,
},
CurrencyAuthKey {
auth_key_map: HashMap<common_enums::enums::Currency, common_utils::pii::SecretSerdeValue>,
},
CertificateAuth {
certificate: Secret<String>,
private_key: Secret<String>,
},
#[default]
NoKey,
}
impl ConnectorAuthType {
pub fn from_option_secret_value(
value: Option<common_utils::pii::SecretSerdeValue>,
) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> {
value
.parse_value::<Self>("ConnectorAuthType")
.change_context(common_utils::errors::ParsingError::StructParseFailure(
"ConnectorAuthType",
))
}
pub fn from_secret_value(
value: common_utils::pii::SecretSerdeValue,
) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> {
value
.parse_value::<Self>("ConnectorAuthType")
.change_context(common_utils::errors::ParsingError::StructParseFailure(
"ConnectorAuthType",
))
}
// show only first and last two digits of the key and mask others with *
// mask the entire key if it's length is less than or equal to 4
fn mask_key(&self, key: String) -> Secret<String> {
let key_len = key.len();
let masked_key = if key_len <= 4 {
"*".repeat(key_len)
} else {
// Show the first two and last two characters, mask the rest with '*'
let mut masked_key = String::new();
let key_len = key.len();
// Iterate through characters by their index
for (index, character) in key.chars().enumerate() {
if index < 2 || index >= key_len - 2 {
masked_key.push(character); // Keep the first two and last two characters
} else {
masked_key.push('*'); // Mask the middle characters
}
}
masked_key
};
Secret::new(masked_key)
}
// Mask the keys in the auth_type
pub fn get_masked_keys(&self) -> Self {
match self {
Self::TemporaryAuth => Self::TemporaryAuth,
Self::NoKey => Self::NoKey,
Self::HeaderKey { api_key } => Self::HeaderKey {
api_key: self.mask_key(api_key.clone().expose()),
},
Self::BodyKey { api_key, key1 } => Self::BodyKey {
api_key: self.mask_key(api_key.clone().expose()),
key1: self.mask_key(key1.clone().expose()),
},
Self::SignatureKey {
api_key,
key1,
api_secret,
} => Self::SignatureKey {
api_key: self.mask_key(api_key.clone().expose()),
key1: self.mask_key(key1.clone().expose()),
api_secret: self.mask_key(api_secret.clone().expose()),
},
Self::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Self::MultiAuthKey {
api_key: self.mask_key(api_key.clone().expose()),
key1: self.mask_key(key1.clone().expose()),
api_secret: self.mask_key(api_secret.clone().expose()),
key2: self.mask_key(key2.clone().expose()),
},
Self::CurrencyAuthKey { auth_key_map } => Self::CurrencyAuthKey {
auth_key_map: auth_key_map.clone(),
},
Self::CertificateAuth {
certificate,
private_key,
} => Self::CertificateAuth {
certificate: self.mask_key(certificate.clone().expose()),
private_key: self.mask_key(private_key.clone().expose()),
},
}
}
}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct AccessTokenAuthenticationResponse {
pub code: Secret<String>,
pub expires: i64,
}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct AccessToken {
pub token: Secret<String>,
pub expires: i64,
}
#[derive(Debug, Clone, serde::Deserialize)]
pub enum PaymentMethodToken {
Token(Secret<String>),
ApplePayDecrypt(Box<common_payment_types::ApplePayPredecryptData>),
GooglePayDecrypt(Box<common_payment_types::GPayPredecryptData>),
PazeDecrypt(Box<PazeDecryptedData>),
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayPredecryptDataInternal {
pub application_primary_account_number: cards::CardNumber,
pub application_expiration_date: String,
pub currency_code: String,
pub transaction_amount: i64,
pub device_manufacturer_identifier: Secret<String>,
pub payment_data_type: Secret<String>,
pub payment_data: ApplePayCryptogramDataInternal,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayCryptogramDataInternal {
pub online_payment_cryptogram: Secret<String>,
pub eci_indicator: Option<String>,
}
impl TryFrom<ApplePayPredecryptDataInternal> for common_payment_types::ApplePayPredecryptData {
type Error = common_utils::errors::ValidationError;
fn try_from(data: ApplePayPredecryptDataInternal) -> Result<Self, Self::Error> {
let application_expiration_month = data.clone().get_expiry_month()?;
let application_expiration_year = data.clone().get_four_digit_expiry_year()?;
Ok(Self {
application_primary_account_number: data.application_primary_account_number.clone(),
application_expiration_month,
application_expiration_year,
payment_data: data.payment_data.into(),
})
}
}
impl From<GooglePayPredecryptDataInternal> for common_payment_types::GPayPredecryptData {
fn from(data: GooglePayPredecryptDataInternal) -> Self {
Self {
card_exp_month: Secret::new(data.payment_method_details.expiration_month.two_digits()),
card_exp_year: Secret::new(data.payment_method_details.expiration_year.four_digits()),
application_primary_account_number: data.payment_method_details.pan.clone(),
cryptogram: data.payment_method_details.cryptogram.clone(),
eci_indicator: data.payment_method_details.eci_indicator.clone(),
}
}
}
impl From<ApplePayCryptogramDataInternal> for common_payment_types::ApplePayCryptogramData {
fn from(payment_data: ApplePayCryptogramDataInternal) -> Self {
Self {
online_payment_cryptogram: payment_data.online_payment_cryptogram,
eci_indicator: payment_data.eci_indicator,
}
}
}
impl ApplePayPredecryptDataInternal {
/// This logic being applied as apple pay provides application_expiration_date in the YYMMDD format
fn get_four_digit_expiry_year(
&self,
) -> Result<Secret<String>, common_utils::errors::ValidationError> {
Ok(Secret::new(format!(
"20{}",
self.application_expiration_date.get(0..2).ok_or(
common_utils::errors::ValidationError::InvalidValue {
message: "Invalid two-digit year".to_string(),
}
)?
)))
}
fn get_expiry_month(&self) -> Result<Secret<String>, common_utils::errors::ValidationError> {
Ok(Secret::new(
self.application_expiration_date
.get(2..4)
.ok_or(common_utils::errors::ValidationError::InvalidValue {
message: "Invalid two-digit month".to_string(),
})?
.to_owned(),
))
}
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayPredecryptDataInternal {
pub message_expiration: String,
pub message_id: String,
#[serde(rename = "paymentMethod")]
pub payment_method_type: String,
pub payment_method_details: GooglePayPaymentMethodDetails,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayPaymentMethodDetails {
pub auth_method: common_enums::enums::GooglePayAuthMethod,
pub expiration_month: cards::CardExpirationMonth,
pub expiration_year: cards::CardExpirationYear,
pub pan: cards::CardNumber,
pub cryptogram: Option<Secret<String>>,
pub eci_indicator: Option<String>,
pub card_network: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeDecryptedData {
pub client_id: Secret<String>,
pub profile_id: String,
pub token: PazeToken,
pub payment_card_network: common_enums::enums::CardNetwork,
pub dynamic_data: Vec<PazeDynamicData>,
pub billing_address: PazeAddress,
pub consumer: PazeConsumer,
pub eci: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeToken {
pub payment_token: NetworkTokenNumber,
pub token_expiration_month: Secret<String>,
pub token_expiration_year: Secret<String>,
pub payment_account_reference: Secret<String>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeDynamicData {
pub dynamic_data_value: Option<Secret<String>>,
pub dynamic_data_type: Option<String>,
pub dynamic_data_expiration: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeAddress {
pub name: Option<Secret<String>>,
pub line1: Option<Secret<String>>,
pub line2: Option<Secret<String>>,
pub line3: Option<Secret<String>>,
pub city: Option<Secret<String>>,
pub state: Option<Secret<String>>,
pub zip: Option<Secret<String>>,
pub country_code: Option<common_enums::enums::CountryAlpha2>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeConsumer {
// This is consumer data not customer data.
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
pub full_name: Secret<String>,
pub email_address: common_utils::pii::Email,
pub mobile_number: Option<PazePhoneNumber>,
pub country_code: Option<common_enums::enums::CountryAlpha2>,
pub language_code: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PazePhoneNumber {
pub country_code: Secret<String>,
pub phone_number: Secret<String>,
}
#[derive(Debug, Default, Clone)]
pub struct RecurringMandatePaymentData {
pub payment_method_type: Option<common_enums::enums::PaymentMethodType>, //required for making recurring payment using saved payment method through stripe
pub original_payment_authorized_amount: Option<i64>,
pub original_payment_authorized_currency: Option<common_enums::enums::Currency>,
pub mandate_metadata: Option<common_utils::pii::SecretSerdeValue>,
}
#[derive(Debug, Clone)]
pub struct PaymentMethodBalance {
pub amount: MinorUnit,
pub currency: common_enums::enums::Currency,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ConnectorResponseData {
pub additional_payment_method_data: Option<AdditionalPaymentMethodConnectorResponse>,
extended_authorization_response_data: Option<ExtendedAuthorizationResponseData>,
is_overcapture_enabled: Option<primitive_wrappers::OvercaptureEnabledBool>,
}
impl ConnectorResponseData {
pub fn with_additional_payment_method_data(
additional_payment_method_data: AdditionalPaymentMethodConnectorResponse,
) -> Self {
Self {
additional_payment_method_data: Some(additional_payment_method_data),
extended_authorization_response_data: None,
is_overcapture_enabled: None,
}
}
pub fn new(
additional_payment_method_data: Option<AdditionalPaymentMethodConnectorResponse>,
is_overcapture_enabled: Option<primitive_wrappers::OvercaptureEnabledBool>,
extended_authorization_response_data: Option<ExtendedAuthorizationResponseData>,
) -> Self {
Self {
additional_payment_method_data,
extended_authorization_response_data,
is_overcapture_enabled,
}
}
pub fn get_extended_authorization_response_data(
&self,
) -> Option<&ExtendedAuthorizationResponseData> {
self.extended_authorization_response_data.as_ref()
}
pub fn is_overcapture_enabled(&self) -> Option<primitive_wrappers::OvercaptureEnabledBool> {
self.is_overcapture_enabled
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum AdditionalPaymentMethodConnectorResponse {
Card {
/// Details regarding the authentication details of the connector, if this is a 3ds payment.
authentication_data: Option<serde_json::Value>,
/// Various payment checks that are done for a payment
payment_checks: Option<serde_json::Value>,
/// Card Network returned by the processor
card_network: Option<String>,
/// Domestic(Co-Branded) Card network returned by the processor
domestic_network: Option<String>,
},
PayLater {
klarna_sdk: Option<KlarnaSdkResponse>,
},
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExtendedAuthorizationResponseData {
pub extended_authentication_applied:
Option<primitive_wrappers::ExtendedAuthorizationAppliedBool>,
pub capture_before: Option<time::PrimitiveDateTime>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct KlarnaSdkResponse {
pub payment_type: Option<String>,
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct ErrorResponse {
pub code: String,
pub message: String,
pub reason: Option<String>,
pub status_code: u16,
pub attempt_status: Option<common_enums::enums::AttemptStatus>,
pub connector_transaction_id: Option<String>,
pub network_decline_code: Option<String>,
pub network_advice_code: Option<String>,
pub network_error_message: Option<String>,
pub connector_metadata: Option<Secret<serde_json::Value>>,
}
impl Default for ErrorResponse {
fn default() -> Self {
Self {
code: "HE_00".to_string(),
message: "Something went wrong".to_string(),
reason: None,
status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}
}
}
impl ErrorResponse {
pub fn get_not_implemented() -> Self {
Self {
code: "IR_00".to_string(),
message: "This API is under development and will be made available soon.".to_string(),
reason: None,
status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}
}
}
/// Get updatable trakcer objects of payment intent and payment attempt
#[cfg(feature = "v2")]
pub trait TrackerPostUpdateObjects<Flow, FlowRequest, D> {
fn get_payment_intent_update(
&self,
payment_data: &D,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentIntentUpdate;
fn get_payment_attempt_update(
&self,
payment_data: &D,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentAttemptUpdate;
/// Get the amount that can be captured for the payment
fn get_amount_capturable(&self, payment_data: &D) -> Option<MinorUnit>;
/// Get the amount that has been captured for the payment
fn get_captured_amount(&self, payment_data: &D) -> Option<MinorUnit>;
/// Get the attempt status based on parameters like captured amount and amount capturable
fn get_attempt_status_for_db_update(
&self,
payment_data: &D,
) -> common_enums::enums::AttemptStatus;
}
#[cfg(feature = "v2")]
impl
TrackerPostUpdateObjects<
router_flow_types::Authorize,
router_request_types::PaymentsAuthorizeData,
payments::PaymentConfirmData<router_flow_types::Authorize>,
>
for RouterData<
router_flow_types::Authorize,
router_request_types::PaymentsAuthorizeData,
router_response_types::PaymentsResponseData,
>
{
fn get_payment_intent_update(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentIntentUpdate {
let amount_captured = self.get_captured_amount(payment_data);
let updated_feature_metadata =
payment_data
.payment_intent
.feature_metadata
.clone()
.map(|mut feature_metadata| {
if let Some(ref mut payment_revenue_recovery_metadata) =
feature_metadata.payment_revenue_recovery_metadata
{
payment_revenue_recovery_metadata.payment_connector_transmission = if self
.response
.is_ok()
{
common_enums::PaymentConnectorTransmission::ConnectorCallSucceeded
} else {
common_enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful
};
}
Box::new(feature_metadata)
});
match self.response {
Ok(ref _response) => PaymentIntentUpdate::ConfirmIntentPostUpdate {
status: common_enums::IntentStatus::from(
self.get_attempt_status_for_db_update(payment_data),
),
amount_captured,
updated_by: storage_scheme.to_string(),
feature_metadata: updated_feature_metadata,
},
Err(ref error) => PaymentIntentUpdate::ConfirmIntentPostUpdate {
status: {
let attempt_status = match error.attempt_status {
// Use the status sent by connector in error_response if it's present
Some(status) => status,
None => match error.status_code {
500..=511 => common_enums::enums::AttemptStatus::Pending,
_ => common_enums::enums::AttemptStatus::Failure,
},
};
common_enums::IntentStatus::from(attempt_status)
},
amount_captured,
updated_by: storage_scheme.to_string(),
feature_metadata: updated_feature_metadata,
},
}
}
fn get_payment_attempt_update(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentAttemptUpdate {
let amount_capturable = self.get_amount_capturable(payment_data);
match self.response {
Ok(ref response_router_data) => match response_router_data {
router_response_types::PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data,
connector_metadata,
connector_response_reference_id,
..
} => {
let attempt_status = self.get_attempt_status_for_db_update(payment_data);
let connector_payment_id = match resource_id {
router_request_types::ResponseId::NoResponseId => None,
router_request_types::ResponseId::ConnectorTransactionId(id)
| router_request_types::ResponseId::EncodedData(id) => Some(id.to_owned()),
};
PaymentAttemptUpdate::ConfirmIntentResponse(Box::new(
payments::payment_attempt::ConfirmIntentResponseUpdate {
status: attempt_status,
connector_payment_id,
updated_by: storage_scheme.to_string(),
redirection_data: *redirection_data.clone(),
amount_capturable,
connector_metadata: connector_metadata.clone().map(Secret::new),
connector_token_details: response_router_data
.get_updated_connector_token_details(
payment_data
.payment_attempt
.connector_token_details
.as_ref()
.and_then(|token_details| {
token_details.get_connector_token_request_reference_id()
}),
),
connector_response_reference_id: connector_response_reference_id
.clone(),
},
))
}
router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => {
todo!()
}
router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(),
router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(),
router_response_types::PaymentsResponseData::TransactionUnresolvedResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(),
router_response_types::PaymentsResponseData::ConnectorCustomerResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => {
todo!()
}
router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => {
todo!()
}
router_response_types::PaymentsResponseData::PaymentResourceUpdateResponse {
..
} => {
todo!()
}
router_response_types::PaymentsResponseData::PaymentsCreateOrderResponse {
..
} => todo!(),
},
Err(ref error_response) => {
let ErrorResponse {
code,
message,
reason,
status_code: _,
attempt_status: _,
connector_transaction_id,
network_decline_code,
network_advice_code,
network_error_message,
connector_metadata,
} = error_response.clone();
let attempt_status = match error_response.attempt_status {
// Use the status sent by connector in error_response if it's present
Some(status) => status,
None => match error_response.status_code {
500..=511 => common_enums::enums::AttemptStatus::Pending,
_ => common_enums::enums::AttemptStatus::Failure,
},
};
let error_details = ErrorDetails {
code,
message,
reason,
unified_code: None,
unified_message: None,
network_advice_code,
network_decline_code,
network_error_message,
};
PaymentAttemptUpdate::ErrorUpdate {
status: attempt_status,
error: error_details,
amount_capturable,
connector_payment_id: connector_transaction_id,
updated_by: storage_scheme.to_string(),
}
}
}
}
fn get_attempt_status_for_db_update(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>,
) -> common_enums::AttemptStatus {
match self.status {
common_enums::AttemptStatus::Charged => {
let amount_captured = self
.get_captured_amount(payment_data)
.unwrap_or(MinorUnit::zero());
let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();
if amount_captured == total_amount {
common_enums::AttemptStatus::Charged
} else {
common_enums::AttemptStatus::PartialCharged
}
}
_ => self.status,
}
}
fn get_amount_capturable(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>,
) -> Option<MinorUnit> {
// Based on the status of the response, we can determine the amount capturable
let intent_status = common_enums::IntentStatus::from(self.status);
let amount_capturable_from_intent_status = match intent_status {
// If the status is already succeeded / failed we cannot capture any more amount
// So set the amount capturable to zero
common_enums::IntentStatus::Succeeded
| common_enums::IntentStatus::Failed
| common_enums::IntentStatus::Cancelled
| common_enums::IntentStatus::CancelledPostCapture
| common_enums::IntentStatus::Conflicted
| common_enums::IntentStatus::Expired => Some(MinorUnit::zero()),
// For these statuses, update the capturable amount when it reaches terminal / capturable state
common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::Processing => None,
// Invalid states for this flow
common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::RequiresConfirmation
| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => None,
// If status is requires capture, get the total amount that can be captured
// This is in cases where the capture method will be `manual` or `manual_multiple`
// We do not need to handle the case where amount_to_capture is provided here as it cannot be passed in authroize flow
common_enums::IntentStatus::RequiresCapture => {
let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();
Some(total_amount)
}
// Invalid statues for this flow, after doing authorization this state is invalid
common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,
};
self.minor_amount_capturable
.or(amount_capturable_from_intent_status)
.or(Some(payment_data.payment_attempt.get_total_amount()))
}
fn get_captured_amount(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>,
) -> Option<MinorUnit> {
// Based on the status of the response, we can determine the amount that was captured
let intent_status = common_enums::IntentStatus::from(self.status);
let amount_captured_from_intent_status = match intent_status {
// If the status is succeeded then we have captured the whole amount
// we need not check for `amount_to_capture` here because passing `amount_to_capture` when authorizing is not supported
common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => {
let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();
Some(total_amount)
}
// No amount is captured
common_enums::IntentStatus::Cancelled
| common_enums::IntentStatus::CancelledPostCapture
| common_enums::IntentStatus::Failed
| common_enums::IntentStatus::Expired => Some(MinorUnit::zero()),
// For these statuses, update the amount captured when it reaches terminal state
common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::Processing => None,
// Invalid states for this flow
common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::RequiresConfirmation => None,
// No amount has been captured yet
common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => {
Some(MinorUnit::zero())
}
// Invalid statues for this flow
common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,
};
self.minor_amount_captured
.or(amount_captured_from_intent_status)
.or(Some(payment_data.payment_attempt.get_total_amount()))
}
}
#[cfg(feature = "v2")]
impl
TrackerPostUpdateObjects<
router_flow_types::Capture,
router_request_types::PaymentsCaptureData,
payments::PaymentCaptureData<router_flow_types::Capture>,
>
for RouterData<
router_flow_types::Capture,
router_request_types::PaymentsCaptureData,
router_response_types::PaymentsResponseData,
>
{
fn get_payment_intent_update(
&self,
payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentIntentUpdate {
let amount_captured = self.get_captured_amount(payment_data);
match self.response {
Ok(ref _response) => PaymentIntentUpdate::CaptureUpdate {
status: common_enums::IntentStatus::from(
self.get_attempt_status_for_db_update(payment_data),
),
amount_captured,
updated_by: storage_scheme.to_string(),
},
Err(ref error) => PaymentIntentUpdate::CaptureUpdate {
status: error
.attempt_status
.map(common_enums::IntentStatus::from)
.unwrap_or(common_enums::IntentStatus::Failed),
amount_captured,
updated_by: storage_scheme.to_string(),
},
}
}
fn get_payment_attempt_update(
&self,
payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentAttemptUpdate {
let amount_capturable = self.get_amount_capturable(payment_data);
match self.response {
Ok(ref response_router_data) => match response_router_data {
router_response_types::PaymentsResponseData::TransactionResponse { .. } => {
let attempt_status = self.status;
PaymentAttemptUpdate::CaptureUpdate {
status: attempt_status,
amount_capturable,
updated_by: storage_scheme.to_string(),
}
}
router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => {
todo!()
}
router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(),
router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(),
router_response_types::PaymentsResponseData::TransactionUnresolvedResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(),
router_response_types::PaymentsResponseData::ConnectorCustomerResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => {
todo!()
}
router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse {
..
} => todo!(),
router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => {
todo!()
}
router_response_types::PaymentsResponseData::PaymentResourceUpdateResponse {
..
} => {
todo!()
}
router_response_types::PaymentsResponseData::PaymentsCreateOrderResponse {
..
} => todo!(),
},
Err(ref error_response) => {
let ErrorResponse {
code,
message,
reason,
status_code: _,
attempt_status,
connector_transaction_id,
network_advice_code,
network_decline_code,
network_error_message,
connector_metadata: _,
} = error_response.clone();
let attempt_status = attempt_status.unwrap_or(self.status);
let error_details = ErrorDetails {
code,
message,
reason,
unified_code: None,
unified_message: None,
network_advice_code,
network_decline_code,
network_error_message,
};
PaymentAttemptUpdate::ErrorUpdate {
status: attempt_status,
error: error_details,
amount_capturable,
connector_payment_id: connector_transaction_id,
updated_by: storage_scheme.to_string(),
}
}
|
crates/hyperswitch_domain_models/src/router_data.rs#chunk0
|
hyperswitch_domain_models
|
chunk
| null | null | null | 8,191
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentSync for for Billwerk
// File: crates/hyperswitch_connectors/src/connectors/billwerk.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSync for for Billwerk
|
crates/hyperswitch_connectors/src/connectors/billwerk.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Billwerk
|
api::PaymentSync for
| 0
| 0
| null | null |
// Struct: AddVault
// File: crates/router/src/types/payment_methods.rs
// Module: router
// Implementations: 1
// Traits: VaultingInterface
pub struct AddVault
|
crates/router/src/types/payment_methods.rs
|
router
|
struct_definition
|
AddVault
| 1
|
[
"VaultingInterface"
] | 40
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentSession for for CtpMastercard
// File: crates/hyperswitch_connectors/src/connectors/ctp_mastercard.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSession for for CtpMastercard
|
crates/hyperswitch_connectors/src/connectors/ctp_mastercard.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 63
| null |
CtpMastercard
|
api::PaymentSession for
| 0
| 0
| null | null |
// Struct: RetryLimitsConfig
// File: crates/router/src/types/storage/revenue_recovery.rs
// Module: router
// Implementations: 1
pub struct RetryLimitsConfig
|
crates/router/src/types/storage/revenue_recovery.rs
|
router
|
struct_definition
|
RetryLimitsConfig
| 1
|
[] | 37
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentSync for for HyperswitchVault
// File: crates/hyperswitch_connectors/src/connectors/hyperswitch_vault.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSync for for HyperswitchVault
|
crates/hyperswitch_connectors/src/connectors/hyperswitch_vault.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 65
| null |
HyperswitchVault
|
api::PaymentSync for
| 0
| 0
| null | null |
// Function: insert
// File: crates/diesel_models/src/query/events.rs
// Module: diesel_models
pub fn insert(self, conn: &PgPooledConn) -> StorageResult<Event>
|
crates/diesel_models/src/query/events.rs
|
diesel_models
|
function_signature
| null | null | null | 41
|
insert
| null | null | null | null | null | null |
// Function: get_tokens_with_retry_metadata
// File: crates/router/src/types/storage/revenue_recovery_redis_operation.rs
// Module: router
// Documentation: Get all payment processor tokens with retry information and wait times.
pub fn get_tokens_with_retry_metadata(
state: &SessionState,
payment_processor_token_info_map: &HashMap<String, PaymentProcessorTokenStatus>,
) -> HashMap<String, PaymentProcessorTokenWithRetryInfo>
|
crates/router/src/types/storage/revenue_recovery_redis_operation.rs
|
router
|
function_signature
| null | null | null | 88
|
get_tokens_with_retry_metadata
| null | null | null | null | null | null |
// Struct: BraintreeRefundTransactionBody
// File: crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct BraintreeRefundTransactionBody
|
crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
BraintreeRefundTransactionBody
| 0
|
[] | 54
| null | null | null | null | null | null | null |
// Struct: Card
// File: crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct Card
|
crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
Card
| 0
|
[] | 43
| null | null | null | null | null | null | null |
// Struct: SupportedMsgExt
// File: crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct SupportedMsgExt
|
crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
SupportedMsgExt
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Struct: TokenCreation
// File: crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct TokenCreation
|
crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs
|
hyperswitch_connectors
|
struct_definition
|
TokenCreation
| 0
|
[] | 44
| null | null | null | null | null | null | null |
Some(api::MandateTransactionType::NewMandateTransaction) => {
validate_new_mandate_request(req, is_confirm_operation)?;
Ok(Some(api::MandateTransactionType::NewMandateTransaction))
}
Some(api::MandateTransactionType::RecurringMandateTransaction) => {
validate_recurring_mandate(req)?;
Ok(Some(
api::MandateTransactionType::RecurringMandateTransaction,
))
}
None => Ok(None),
}
}
pub fn validate_recurring_details_and_token(
recurring_details: &Option<RecurringDetails>,
payment_token: &Option<String>,
mandate_id: &Option<String>,
) -> CustomResult<(), errors::ApiErrorResponse> {
utils::when(
recurring_details.is_some() && payment_token.is_some(),
|| {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "Expected one out of recurring_details and payment_token but got both"
.into()
}))
},
)?;
utils::when(recurring_details.is_some() && mandate_id.is_some(), || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "Expected one out of recurring_details and mandate_id but got both".into()
}))
})?;
Ok(())
}
pub fn validate_overcapture_request(
enable_overcapture: &Option<common_types::primitive_wrappers::EnableOvercaptureBool>,
capture_method: &Option<common_enums::CaptureMethod>,
) -> CustomResult<(), errors::ApiErrorResponse> {
if let Some(overcapture) = enable_overcapture {
utils::when(
*overcapture.deref()
&& !matches!(*capture_method, Some(common_enums::CaptureMethod::Manual)),
|| {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid overcapture request: supported only with manual capture"
.into()
}))
},
)?;
}
Ok(())
}
fn validate_new_mandate_request(
req: api::MandateValidationFields,
is_confirm_operation: bool,
) -> RouterResult<()> {
// We need not check for customer_id in the confirm request if it is already passed
// in create request
fp_utils::when(!is_confirm_operation && req.customer_id.is_none(), || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`customer_id` is mandatory for mandates".into()
}))
})?;
let mandate_data = req
.mandate_data
.clone()
.get_required_value("mandate_data")?;
// Only use this validation if the customer_acceptance is present
if mandate_data
.customer_acceptance
.map(|inner| inner.acceptance_type == api::AcceptanceType::Online && inner.online.is_none())
.unwrap_or(false)
{
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`mandate_data.customer_acceptance.online` is required when \
`mandate_data.customer_acceptance.acceptance_type` is `online`"
.into()
}))?
}
let mandate_details = match mandate_data.mandate_type {
Some(api_models::payments::MandateType::SingleUse(details)) => Some(details),
Some(api_models::payments::MandateType::MultiUse(details)) => details,
_ => None,
};
mandate_details.and_then(|md| md.start_date.zip(md.end_date)).map(|(start_date, end_date)|
utils::when (start_date >= end_date, || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`mandate_data.mandate_type.{multi_use|single_use}.start_date` should be greater than \
`mandate_data.mandate_type.{multi_use|single_use}.end_date`"
.into()
}))
})).transpose()?;
Ok(())
}
pub fn validate_customer_id_mandatory_cases(
has_setup_future_usage: bool,
customer_id: Option<&id_type::CustomerId>,
) -> RouterResult<()> {
match (has_setup_future_usage, customer_id) {
(true, None) => Err(errors::ApiErrorResponse::PreconditionFailed {
message: "customer_id is mandatory when setup_future_usage is given".to_string(),
}
.into()),
_ => Ok(()),
}
}
#[cfg(feature = "v1")]
pub fn create_startpay_url(
base_url: &str,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
) -> String {
format!(
"{}/payments/redirect/{}/{}/{}",
base_url,
payment_intent.get_id().get_string_repr(),
payment_intent.merchant_id.get_string_repr(),
payment_attempt.attempt_id
)
}
pub fn create_redirect_url(
router_base_url: &String,
payment_attempt: &PaymentAttempt,
connector_name: impl std::fmt::Display,
creds_identifier: Option<&str>,
) -> String {
let creds_identifier_path = creds_identifier.map_or_else(String::new, |cd| format!("/{cd}"));
format!(
"{}/payments/{}/{}/redirect/response/{}",
router_base_url,
payment_attempt.payment_id.get_string_repr(),
payment_attempt.merchant_id.get_string_repr(),
connector_name,
) + creds_identifier_path.as_ref()
}
pub fn create_authentication_url(
router_base_url: &str,
payment_attempt: &PaymentAttempt,
) -> String {
format!(
"{router_base_url}/payments/{}/3ds/authentication",
payment_attempt.payment_id.get_string_repr()
)
}
pub fn create_authorize_url(
router_base_url: &str,
payment_attempt: &PaymentAttempt,
connector_name: impl std::fmt::Display,
) -> String {
format!(
"{}/payments/{}/{}/authorize/{}",
router_base_url,
payment_attempt.payment_id.get_string_repr(),
payment_attempt.merchant_id.get_string_repr(),
connector_name
)
}
pub fn create_webhook_url(
router_base_url: &str,
merchant_id: &id_type::MerchantId,
merchant_connector_id_or_connector_name: &str,
) -> String {
format!(
"{}/webhooks/{}/{}",
router_base_url,
merchant_id.get_string_repr(),
merchant_connector_id_or_connector_name,
)
}
pub fn create_complete_authorize_url(
router_base_url: &String,
payment_attempt: &PaymentAttempt,
connector_name: impl std::fmt::Display,
creds_identifier: Option<&str>,
) -> String {
let creds_identifier = creds_identifier.map_or_else(String::new, |creds_identifier| {
format!("/{creds_identifier}")
});
format!(
"{}/payments/{}/{}/redirect/complete/{}{}",
router_base_url,
payment_attempt.payment_id.get_string_repr(),
payment_attempt.merchant_id.get_string_repr(),
connector_name,
creds_identifier
)
}
fn validate_recurring_mandate(req: api::MandateValidationFields) -> RouterResult<()> {
let recurring_details = req
.recurring_details
.get_required_value("recurring_details")?;
match recurring_details {
RecurringDetails::ProcessorPaymentToken(_)
| RecurringDetails::NetworkTransactionIdAndCardDetails(_) => Ok(()),
_ => {
req.customer_id.check_value_present("customer_id")?;
let confirm = req.confirm.get_required_value("confirm")?;
if !confirm {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`confirm` must be `true` for mandates".into()
}))?
}
let off_session = req.off_session.get_required_value("off_session")?;
if !off_session {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`off_session` should be `true` for mandates".into()
}))?
}
Ok(())
}
}
}
pub fn verify_mandate_details(
request_amount: MinorUnit,
request_currency: api_enums::Currency,
mandate: storage::Mandate,
) -> RouterResult<()> {
match mandate.mandate_type {
storage_enums::MandateType::SingleUse => utils::when(
mandate
.mandate_amount
.map(|mandate_amount| request_amount.get_amount_as_i64() > mandate_amount)
.unwrap_or(true),
|| {
Err(report!(errors::ApiErrorResponse::MandateValidationFailed {
reason: "request amount is greater than mandate amount".into()
}))
},
),
storage::enums::MandateType::MultiUse => utils::when(
mandate
.mandate_amount
.map(|mandate_amount| {
(mandate.amount_captured.unwrap_or(0) + request_amount.get_amount_as_i64())
> mandate_amount
})
.unwrap_or(false),
|| {
Err(report!(errors::ApiErrorResponse::MandateValidationFailed {
reason: "request amount is greater than mandate amount".into()
}))
},
),
}?;
utils::when(
mandate
.mandate_currency
.map(|mandate_currency| mandate_currency != request_currency)
.unwrap_or(false),
|| {
Err(report!(errors::ApiErrorResponse::MandateValidationFailed {
reason: "cross currency mandates not supported".into()
}))
},
)
}
pub fn verify_mandate_details_for_recurring_payments(
mandate_merchant_id: &id_type::MerchantId,
merchant_id: &id_type::MerchantId,
mandate_customer_id: &id_type::CustomerId,
customer_id: &id_type::CustomerId,
) -> RouterResult<()> {
if mandate_merchant_id != merchant_id {
Err(report!(errors::ApiErrorResponse::MandateNotFound))?
}
if mandate_customer_id != customer_id {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "customer_id must match mandate customer_id".into()
}))?
}
Ok(())
}
#[instrument(skip_all)]
pub fn payment_attempt_status_fsm(
payment_method_data: Option<&api::payments::PaymentMethodData>,
confirm: Option<bool>,
) -> storage_enums::AttemptStatus {
match payment_method_data {
Some(_) => match confirm {
Some(true) => storage_enums::AttemptStatus::PaymentMethodAwaited,
_ => storage_enums::AttemptStatus::ConfirmationAwaited,
},
None => storage_enums::AttemptStatus::PaymentMethodAwaited,
}
}
pub fn payment_intent_status_fsm(
payment_method_data: Option<&api::PaymentMethodData>,
confirm: Option<bool>,
) -> storage_enums::IntentStatus {
match payment_method_data {
Some(_) => match confirm {
Some(true) => storage_enums::IntentStatus::RequiresPaymentMethod,
_ => storage_enums::IntentStatus::RequiresConfirmation,
},
None => storage_enums::IntentStatus::RequiresPaymentMethod,
}
}
#[cfg(feature = "v1")]
pub async fn add_domain_task_to_pt<Op>(
operation: &Op,
state: &SessionState,
payment_attempt: &PaymentAttempt,
requeue: bool,
schedule_time: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse>
where
Op: std::fmt::Debug,
{
if check_if_operation_confirm(operation) {
match schedule_time {
Some(stime) => {
if !requeue {
// Here, increment the count of added tasks every time a payment has been confirmed or PSync has been called
metrics::TASKS_ADDED_COUNT.add(
1,
router_env::metric_attributes!(("flow", format!("{:#?}", operation))),
);
super::add_process_sync_task(&*state.store, payment_attempt, stime)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while adding task to process tracker")
} else {
// When the requeue is true, we reset the tasks count as we reset the task every time it is requeued
metrics::TASKS_RESET_COUNT.add(
1,
router_env::metric_attributes!(("flow", format!("{:#?}", operation))),
);
super::reset_process_sync_task(&*state.store, payment_attempt, stime)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while updating task in process tracker")
}
}
None => Ok(()),
}
} else {
Ok(())
}
}
pub fn response_operation<'a, F, R, D>() -> BoxedOperation<'a, F, R, D>
where
F: Send + Clone,
PaymentResponse: Operation<F, R, Data = D>,
{
Box::new(PaymentResponse)
}
pub fn validate_max_amount(
amount: api_models::payments::Amount,
) -> CustomResult<(), errors::ApiErrorResponse> {
match amount {
api_models::payments::Amount::Value(value) => {
utils::when(value.get() > consts::MAX_ALLOWED_AMOUNT, || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"amount should not be more than {}",
consts::MAX_ALLOWED_AMOUNT
)
}))
})
}
api_models::payments::Amount::Zero => Ok(()),
}
}
#[cfg(feature = "v1")]
/// Check whether the customer information that is sent in the root of payments request
/// and in the customer object are same, if the values mismatch return an error
pub fn validate_customer_information(
request: &api_models::payments::PaymentsRequest,
) -> RouterResult<()> {
if let Some(mismatched_fields) = request.validate_customer_details_in_request() {
let mismatched_fields = mismatched_fields.join(", ");
Err(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"The field names `{mismatched_fields}` sent in both places is ambiguous"
),
})?
} else {
Ok(())
}
}
pub async fn validate_card_ip_blocking_for_business_profile(
state: &SessionState,
ip: IpAddr,
fingerprnt: masking::Secret<String>,
card_testing_guard_config: &diesel_models::business_profile::CardTestingGuardConfig,
) -> RouterResult<String> {
let cache_key = format!(
"{}_{}_{}",
consts::CARD_IP_BLOCKING_CACHE_KEY_PREFIX,
fingerprnt.peek(),
ip
);
let unsuccessful_payment_threshold = card_testing_guard_config.card_ip_blocking_threshold;
validate_blocking_threshold(state, unsuccessful_payment_threshold, cache_key).await
}
pub async fn validate_guest_user_card_blocking_for_business_profile(
state: &SessionState,
fingerprnt: masking::Secret<String>,
customer_id: Option<id_type::CustomerId>,
card_testing_guard_config: &diesel_models::business_profile::CardTestingGuardConfig,
) -> RouterResult<String> {
let cache_key = format!(
"{}_{}",
consts::GUEST_USER_CARD_BLOCKING_CACHE_KEY_PREFIX,
fingerprnt.peek()
);
let unsuccessful_payment_threshold =
card_testing_guard_config.guest_user_card_blocking_threshold;
if customer_id.is_none() {
Ok(validate_blocking_threshold(state, unsuccessful_payment_threshold, cache_key).await?)
} else {
Ok(cache_key)
}
}
pub async fn validate_customer_id_blocking_for_business_profile(
state: &SessionState,
customer_id: id_type::CustomerId,
profile_id: &id_type::ProfileId,
card_testing_guard_config: &diesel_models::business_profile::CardTestingGuardConfig,
) -> RouterResult<String> {
let cache_key = format!(
"{}_{}_{}",
consts::CUSTOMER_ID_BLOCKING_PREFIX,
profile_id.get_string_repr(),
customer_id.get_string_repr(),
);
let unsuccessful_payment_threshold = card_testing_guard_config.customer_id_blocking_threshold;
validate_blocking_threshold(state, unsuccessful_payment_threshold, cache_key).await
}
pub async fn validate_blocking_threshold(
state: &SessionState,
unsuccessful_payment_threshold: i32,
cache_key: String,
) -> RouterResult<String> {
match services::card_testing_guard::get_blocked_count_from_cache(state, &cache_key).await {
Ok(Some(unsuccessful_payment_count)) => {
if unsuccessful_payment_count >= unsuccessful_payment_threshold {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Blocked due to suspicious activity".to_string(),
})?
} else {
Ok(cache_key)
}
}
Ok(None) => Ok(cache_key),
Err(error) => Err(errors::ApiErrorResponse::InternalServerError).attach_printable(error)?,
}
}
#[cfg(feature = "v1")]
/// Get the customer details from customer field if present
/// or from the individual fields in `PaymentsRequest`
#[instrument(skip_all)]
pub fn get_customer_details_from_request(
request: &api_models::payments::PaymentsRequest,
) -> CustomerDetails {
let customer_id = request.get_customer_id().map(ToOwned::to_owned);
let customer_name = request
.customer
.as_ref()
.and_then(|customer_details| customer_details.name.clone())
.or(request.name.clone());
let customer_email = request
.customer
.as_ref()
.and_then(|customer_details| customer_details.email.clone())
.or(request.email.clone());
let customer_phone = request
.customer
.as_ref()
.and_then(|customer_details| customer_details.phone.clone())
.or(request.phone.clone());
let customer_phone_code = request
.customer
.as_ref()
.and_then(|customer_details| customer_details.phone_country_code.clone())
.or(request.phone_country_code.clone());
let tax_registration_id = request
.customer
.as_ref()
.and_then(|customer_details| customer_details.tax_registration_id.clone());
CustomerDetails {
customer_id,
name: customer_name,
email: customer_email,
phone: customer_phone,
phone_country_code: customer_phone_code,
tax_registration_id,
}
}
pub async fn get_connector_default(
_state: &SessionState,
request_connector: Option<serde_json::Value>,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
Ok(request_connector.map_or(
api::ConnectorChoice::Decide,
api::ConnectorChoice::StraightThrough,
))
}
#[cfg(feature = "v2")]
pub async fn get_connector_data_from_request(
state: &SessionState,
req: Option<common_types::domain::MerchantConnectorAuthDetails>,
) -> CustomResult<api::ConnectorData, errors::ApiErrorResponse> {
let connector = req
.as_ref()
.map(|connector_details| connector_details.connector_name.to_string())
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "merchant_connector_details",
})?;
let connector_data: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector,
api::GetToken::Connector,
None,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
Ok(connector_data)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
#[allow(clippy::type_complexity)]
pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
_state: &SessionState,
_operation: BoxedOperation<'a, F, R, D>,
_payment_data: &mut PaymentData<F>,
_req: Option<CustomerDetails>,
_merchant_id: &id_type::MerchantId,
_key_store: &domain::MerchantKeyStore,
_storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
#[allow(clippy::type_complexity)]
pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
state: &SessionState,
operation: BoxedOperation<'a, F, R, D>,
payment_data: &mut PaymentData<F>,
req: Option<CustomerDetails>,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError> {
let request_customer_details = req
.get_required_value("customer")
.change_context(errors::StorageError::ValueNotFound("customer".to_owned()))?;
let temp_customer_data = if request_customer_details.name.is_some()
|| request_customer_details.email.is_some()
|| request_customer_details.phone.is_some()
|| request_customer_details.phone_country_code.is_some()
|| request_customer_details.tax_registration_id.is_some()
{
Some(CustomerData {
name: request_customer_details.name.clone(),
email: request_customer_details.email.clone(),
phone: request_customer_details.phone.clone(),
phone_country_code: request_customer_details.phone_country_code.clone(),
tax_registration_id: request_customer_details.tax_registration_id.clone(),
})
} else {
None
};
// Updation of Customer Details for the cases where both customer_id and specific customer
// details are provided in Payment Update Request
let raw_customer_details = payment_data
.payment_intent
.customer_details
.clone()
.map(|customer_details_encrypted| {
customer_details_encrypted
.into_inner()
.expose()
.parse_value::<CustomerData>("CustomerData")
})
.transpose()
.change_context(errors::StorageError::DeserializationFailed)
.attach_printable("Failed to parse customer data from payment intent")?
.map(|parsed_customer_data| CustomerData {
name: request_customer_details
.name
.clone()
.or(parsed_customer_data.name.clone()),
email: request_customer_details
.email
.clone()
.or(parsed_customer_data.email.clone()),
phone: request_customer_details
.phone
.clone()
.or(parsed_customer_data.phone.clone()),
phone_country_code: request_customer_details
.phone_country_code
.clone()
.or(parsed_customer_data.phone_country_code.clone()),
tax_registration_id: request_customer_details
.tax_registration_id
.clone()
.or(parsed_customer_data.tax_registration_id.clone()),
})
.or(temp_customer_data);
let key_manager_state = state.into();
payment_data.payment_intent.customer_details = raw_customer_details
.clone()
.async_map(|customer_details| {
create_encrypted_data(&key_manager_state, key_store, customer_details)
})
.await
.transpose()
.change_context(errors::StorageError::EncryptionError)
.attach_printable("Unable to encrypt customer details")?;
let customer_id = request_customer_details
.customer_id
.or(payment_data.payment_intent.customer_id.clone());
let db = &*state.store;
let key_manager_state = &state.into();
let optional_customer = match customer_id {
Some(customer_id) => {
let customer_data = db
.find_customer_optional_by_customer_id_merchant_id(
key_manager_state,
&customer_id,
merchant_id,
key_store,
storage_scheme,
)
.await?;
let key = key_store.key.get_inner().peek();
let encrypted_data = types::crypto_operation(
key_manager_state,
type_name!(domain::Customer),
types::CryptoOperation::BatchEncrypt(
domain::FromRequestEncryptableCustomer::to_encryptable(
domain::FromRequestEncryptableCustomer {
name: request_customer_details.name.clone(),
email: request_customer_details
.email
.as_ref()
.map(|e| e.clone().expose().switch_strategy()),
phone: request_customer_details.phone.clone(),
tax_registration_id: None,
},
),
),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::StorageError::SerializationFailed)
.attach_printable("Failed while encrypting Customer while Update")?;
let encryptable_customer =
domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
.change_context(errors::StorageError::SerializationFailed)
.attach_printable("Failed while encrypting Customer while Update")?;
Some(match customer_data {
Some(c) => {
// Update the customer data if new data is passed in the request
if request_customer_details.email.is_some()
| request_customer_details.name.is_some()
| request_customer_details.phone.is_some()
| request_customer_details.phone_country_code.is_some()
| request_customer_details.tax_registration_id.is_some()
{
let customer_update = Update {
name: encryptable_customer.name,
email: encryptable_customer.email.map(|email| {
let encryptable: Encryptable<
masking::Secret<String, pii::EmailStrategy>,
> = Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
phone: Box::new(encryptable_customer.phone),
phone_country_code: request_customer_details.phone_country_code,
description: None,
connector_customer: Box::new(None),
metadata: Box::new(None),
address_id: None,
tax_registration_id: encryptable_customer.tax_registration_id,
};
db.update_customer_by_customer_id_merchant_id(
key_manager_state,
customer_id,
merchant_id.to_owned(),
c,
customer_update,
key_store,
storage_scheme,
)
.await
} else {
Ok(c)
}
}
None => {
let new_customer = domain::Customer {
customer_id,
merchant_id: merchant_id.to_owned(),
name: encryptable_customer.name,
email: encryptable_customer.email.map(|email| {
let encryptable: Encryptable<
masking::Secret<String, pii::EmailStrategy>,
> = Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
phone: encryptable_customer.phone,
phone_country_code: request_customer_details.phone_country_code.clone(),
description: None,
created_at: common_utils::date_time::now(),
metadata: None,
modified_at: common_utils::date_time::now(),
connector_customer: None,
address_id: None,
default_payment_method_id: None,
updated_by: None,
version: common_types::consts::API_VERSION,
tax_registration_id: encryptable_customer.tax_registration_id,
};
metrics::CUSTOMER_CREATED.add(1, &[]);
db.insert_customer(new_customer, key_manager_state, key_store, storage_scheme)
.await
}
})
}
None => match &payment_data.payment_intent.customer_id {
None => None,
Some(customer_id) => db
.find_customer_optional_by_customer_id_merchant_id(
key_manager_state,
customer_id,
merchant_id,
key_store,
storage_scheme,
)
.await?
.map(Ok),
},
};
Ok((
operation,
match optional_customer {
Some(customer) => {
let customer = customer?;
payment_data.payment_intent.customer_id = Some(customer.customer_id.clone());
payment_data.email = payment_data.email.clone().or_else(|| {
customer
.email
.clone()
.map(|encrypted_value| encrypted_value.into())
});
Some(customer)
}
None => None,
},
))
}
#[cfg(feature = "v1")]
pub async fn retrieve_payment_method_with_temporary_token(
state: &SessionState,
token: &str,
payment_intent: &PaymentIntent,
payment_attempt: &PaymentAttempt,
merchant_key_store: &domain::MerchantKeyStore,
card_token_data: Option<&domain::CardToken>,
) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> {
let (pm, supplementary_data) =
vault::Vault::get_payment_method_data_from_locker(state, token, merchant_key_store)
.await
.attach_printable(
"Payment method for given token not found or there was a problem fetching it",
)?;
utils::when(
supplementary_data
.customer_id
.ne(&payment_intent.customer_id),
|| {
Err(errors::ApiErrorResponse::PreconditionFailed { message: "customer associated with payment method and customer passed in payment are not same".into() })
},
)?;
Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(match pm {
Some(domain::PaymentMethodData::Card(card)) => {
let mut updated_card = card.clone();
let mut is_card_updated = false;
// The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked
// from payment_method_data.card_token object
let name_on_card =
card_token_data.and_then(|token_data| token_data.card_holder_name.clone());
if let Some(name) = name_on_card.clone() {
if !name.peek().is_empty() {
is_card_updated = true;
updated_card.nick_name = name_on_card;
}
}
if let Some(token_data) = card_token_data {
if let Some(cvc) = token_data.card_cvc.clone() {
is_card_updated = true;
updated_card.card_cvc = cvc;
}
}
// populate additional card details from payment_attempt.payment_method_data (additional_payment_data) if not present in the locker
if updated_card.card_issuer.is_none()
|| updated_card.card_network.is_none()
|| updated_card.card_type.is_none()
|| updated_card.card_issuing_country.is_none()
{
let additional_payment_method_data: Option<
api_models::payments::AdditionalPaymentData,
> = payment_attempt
.payment_method_data
.clone()
.and_then(|data| match data {
serde_json::Value::Null => None, // This is to handle the case when the payment_method_data is null
_ => Some(data.parse_value("AdditionalPaymentData")),
})
.transpose()
.map_err(|err| logger::error!("Failed to parse AdditionalPaymentData {err:?}"))
.ok()
.flatten();
if let Some(api_models::payments::AdditionalPaymentData::Card(card)) =
additional_payment_method_data
{
is_card_updated = true;
updated_card.card_issuer = updated_card.card_issuer.or(card.card_issuer);
updated_card.card_network = updated_card.card_network.or(card.card_network);
updated_card.card_type = updated_card.card_type.or(card.card_type);
updated_card.card_issuing_country = updated_card
.card_issuing_country
.or(card.card_issuing_country);
};
};
if is_card_updated {
let updated_pm = domain::PaymentMethodData::Card(updated_card);
vault::Vault::store_payment_method_data_in_locker(
state,
Some(token.to_owned()),
&updated_pm,
payment_intent.customer_id.to_owned(),
enums::PaymentMethod::Card,
merchant_key_store,
)
.await?;
Some((updated_pm, enums::PaymentMethod::Card))
} else {
Some((
domain::PaymentMethodData::Card(card),
enums::PaymentMethod::Card,
))
}
}
Some(the_pm @ domain::PaymentMethodData::Wallet(_)) => {
Some((the_pm, enums::PaymentMethod::Wallet))
}
Some(the_pm @ domain::PaymentMethodData::BankTransfer(_)) => {
Some((the_pm, enums::PaymentMethod::BankTransfer))
}
Some(the_pm @ domain::PaymentMethodData::BankRedirect(_)) => {
Some((the_pm, enums::PaymentMethod::BankRedirect))
}
Some(the_pm @ domain::PaymentMethodData::BankDebit(_)) => {
Some((the_pm, enums::PaymentMethod::BankDebit))
}
Some(_) => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Payment method received from locker is unsupported by locker")?,
None => None,
})
}
#[cfg(feature = "v2")]
pub async fn retrieve_card_with_permanent_token(
state: &SessionState,
locker_id: &str,
_payment_method_id: &id_type::GlobalPaymentMethodId,
payment_intent: &PaymentIntent,
card_token_data: Option<&domain::CardToken>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<domain::PaymentMethodData> {
todo!()
}
pub enum VaultFetchAction {
FetchCardDetailsFromLocker,
FetchCardDetailsForNetworkTransactionIdFlowFromLocker,
FetchNetworkTokenDataFromTokenizationService(String),
FetchNetworkTokenDetailsFromLocker(api_models::payments::NetworkTokenWithNTIRef),
NoFetchAction,
}
pub fn decide_payment_method_retrieval_action(
is_network_tokenization_enabled: bool,
mandate_id: Option<api_models::payments::MandateIds>,
connector: Option<api_enums::Connector>,
network_tokenization_supported_connectors: &HashSet<api_enums::Connector>,
should_retry_with_pan: bool,
network_token_requestor_ref_id: Option<String>,
) -> VaultFetchAction {
let standard_flow = || {
determine_standard_vault_action(
is_network_tokenization_enabled,
mandate_id,
connector,
network_tokenization_supported_connectors,
network_token_requestor_ref_id,
)
};
if should_retry_with_pan {
VaultFetchAction::FetchCardDetailsFromLocker
} else {
standard_flow()
}
}
pub async fn is_ucs_enabled(state: &SessionState, config_key: &str) -> bool {
let db = state.store.as_ref();
db.find_config_by_key_unwrap_or(config_key, Some("false".to_string()))
.await
.inspect_err(|error| {
logger::error!(
?error,
"Failed to fetch `{config_key}` UCS enabled config from DB"
);
})
.ok()
.and_then(|config| {
config
.config
.parse::<bool>()
.inspect_err(|error| {
logger::error!(?error, "Failed to parse `{config_key}` UCS enabled config");
})
.ok()
})
.unwrap_or(false)
}
pub async fn should_execute_based_on_rollout(
state: &SessionState,
config_key: &str,
) -> RouterResult<bool> {
let db = state.store.as_ref();
match db.find_config_by_key(config_key).await {
Ok(rollout_config) => match rollout_config.config.parse::<f64>() {
Ok(rollout_percent) => {
if !(0.0..=1.0).contains(&rollout_percent) {
logger::warn!(
rollout_percent,
"Rollout percent out of bounds. Must be between 0.0 and 1.0"
);
return Ok(false);
}
let sampled_value: f64 = rand::thread_rng().gen_range(0.0..1.0);
Ok(sampled_value < rollout_percent)
}
Err(err) => {
logger::error!(error = ?err, "Failed to parse rollout percent");
Ok(false)
}
},
Err(err) => {
logger::error!(error = ?err, "Failed to fetch rollout config from DB");
Ok(false)
}
}
}
pub fn determine_standard_vault_action(
is_network_tokenization_enabled: bool,
mandate_id: Option<api_models::payments::MandateIds>,
connector: Option<api_enums::Connector>,
network_tokenization_supported_connectors: &HashSet<api_enums::Connector>,
network_token_requestor_ref_id: Option<String>,
) -> VaultFetchAction {
let is_network_transaction_id_flow = mandate_id
.as_ref()
.map(|mandate_ids| mandate_ids.is_network_transaction_id_flow())
.unwrap_or(false);
if !is_network_tokenization_enabled {
if is_network_transaction_id_flow {
VaultFetchAction::FetchCardDetailsForNetworkTransactionIdFlowFromLocker
} else {
VaultFetchAction::FetchCardDetailsFromLocker
}
} else {
match mandate_id {
Some(mandate_ids) => match mandate_ids.mandate_reference_id {
Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(nt_data)) => {
VaultFetchAction::FetchNetworkTokenDetailsFromLocker(nt_data)
}
Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) => {
VaultFetchAction::FetchCardDetailsForNetworkTransactionIdFlowFromLocker
}
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(_)) | None => {
VaultFetchAction::NoFetchAction
}
},
None => {
//saved card flow
let is_network_token_supported_connector = connector
.map(|conn| network_tokenization_supported_connectors.contains(&conn))
.unwrap_or(false);
match (
is_network_token_supported_connector,
network_token_requestor_ref_id,
) {
(true, Some(ref_id)) => {
|
crates/router/src/core/payments/helpers.rs#chunk1
|
router
|
chunk
| null | null | null | 8,179
| null | null | null | null | null | null | null |
// Function: connector_retrieve
// File: crates/openapi/src/routes/merchant_connector_account.rs
// Module: openapi
pub fn connector_retrieve()
|
crates/openapi/src/routes/merchant_connector_account.rs
|
openapi
|
function_signature
| null | null | null | 33
|
connector_retrieve
| null | null | null | null | null | null |
// Implementation: impl api::PaymentSession for for Stax
// File: crates/hyperswitch_connectors/src/connectors/stax.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSession for for Stax
|
crates/hyperswitch_connectors/src/connectors/stax.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Stax
|
api::PaymentSession for
| 0
| 0
| null | null |
// File: crates/storage_impl/src/redis/cache.rs
// Module: storage_impl
// Public functions: 12
// Public structs: 3
use std::{
any::Any,
borrow::Cow,
fmt::Debug,
sync::{Arc, LazyLock},
};
use common_utils::{
errors::{self, CustomResult},
ext_traits::ByteSliceExt,
};
use dyn_clone::DynClone;
use error_stack::{Report, ResultExt};
use moka::future::Cache as MokaCache;
use redis_interface::{errors::RedisError, RedisConnectionPool, RedisValue};
use router_env::{
logger,
tracing::{self, instrument},
};
use crate::{
errors::StorageError,
metrics,
redis::{PubSubInterface, RedisConnInterface},
};
/// Redis channel name used for publishing invalidation messages
pub const IMC_INVALIDATION_CHANNEL: &str = "hyperswitch_invalidate";
/// Time to live 30 mins
const CACHE_TTL: u64 = 30 * 60;
/// Time to idle 10 mins
const CACHE_TTI: u64 = 10 * 60;
/// Max Capacity of Cache in MB
const MAX_CAPACITY: u64 = 30;
/// Config Cache with time_to_live as 30 mins and time_to_idle as 10 mins.
pub static CONFIG_CACHE: LazyLock<Cache> =
LazyLock::new(|| Cache::new("CONFIG_CACHE", CACHE_TTL, CACHE_TTI, None));
/// Accounts cache with time_to_live as 30 mins and size limit
pub static ACCOUNTS_CACHE: LazyLock<Cache> =
LazyLock::new(|| Cache::new("ACCOUNTS_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY)));
/// Routing Cache
pub static ROUTING_CACHE: LazyLock<Cache> =
LazyLock::new(|| Cache::new("ROUTING_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY)));
/// 3DS Decision Manager Cache
pub static DECISION_MANAGER_CACHE: LazyLock<Cache> = LazyLock::new(|| {
Cache::new(
"DECISION_MANAGER_CACHE",
CACHE_TTL,
CACHE_TTI,
Some(MAX_CAPACITY),
)
});
/// Surcharge Cache
pub static SURCHARGE_CACHE: LazyLock<Cache> =
LazyLock::new(|| Cache::new("SURCHARGE_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY)));
/// CGraph Cache
pub static CGRAPH_CACHE: LazyLock<Cache> =
LazyLock::new(|| Cache::new("CGRAPH_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY)));
/// PM Filter CGraph Cache
pub static PM_FILTERS_CGRAPH_CACHE: LazyLock<Cache> = LazyLock::new(|| {
Cache::new(
"PM_FILTERS_CGRAPH_CACHE",
CACHE_TTL,
CACHE_TTI,
Some(MAX_CAPACITY),
)
});
/// Success based Dynamic Algorithm Cache
pub static SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE: LazyLock<Cache> = LazyLock::new(|| {
Cache::new(
"SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE",
CACHE_TTL,
CACHE_TTI,
Some(MAX_CAPACITY),
)
});
/// Elimination based Dynamic Algorithm Cache
pub static ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE: LazyLock<Cache> = LazyLock::new(|| {
Cache::new(
"ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE",
CACHE_TTL,
CACHE_TTI,
Some(MAX_CAPACITY),
)
});
/// Contract Routing based Dynamic Algorithm Cache
pub static CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE: LazyLock<Cache> = LazyLock::new(|| {
Cache::new(
"CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE",
CACHE_TTL,
CACHE_TTI,
Some(MAX_CAPACITY),
)
});
/// Trait which defines the behaviour of types that's gonna be stored in Cache
pub trait Cacheable: Any + Send + Sync + DynClone {
fn as_any(&self) -> &dyn Any;
}
#[derive(serde::Serialize, serde::Deserialize)]
pub struct CacheRedact<'a> {
pub tenant: String,
pub kind: CacheKind<'a>,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum CacheKind<'a> {
Config(Cow<'a, str>),
Accounts(Cow<'a, str>),
Routing(Cow<'a, str>),
DecisionManager(Cow<'a, str>),
Surcharge(Cow<'a, str>),
CGraph(Cow<'a, str>),
SuccessBasedDynamicRoutingCache(Cow<'a, str>),
EliminationBasedDynamicRoutingCache(Cow<'a, str>),
ContractBasedDynamicRoutingCache(Cow<'a, str>),
PmFiltersCGraph(Cow<'a, str>),
All(Cow<'a, str>),
}
impl CacheKind<'_> {
pub(crate) fn get_key_without_prefix(&self) -> &str {
match self {
CacheKind::Config(key)
| CacheKind::Accounts(key)
| CacheKind::Routing(key)
| CacheKind::DecisionManager(key)
| CacheKind::Surcharge(key)
| CacheKind::CGraph(key)
| CacheKind::SuccessBasedDynamicRoutingCache(key)
| CacheKind::EliminationBasedDynamicRoutingCache(key)
| CacheKind::ContractBasedDynamicRoutingCache(key)
| CacheKind::PmFiltersCGraph(key)
| CacheKind::All(key) => key,
}
}
}
impl<'a> TryFrom<CacheRedact<'a>> for RedisValue {
type Error = Report<errors::ValidationError>;
fn try_from(v: CacheRedact<'a>) -> Result<Self, Self::Error> {
Ok(Self::from_bytes(serde_json::to_vec(&v).change_context(
errors::ValidationError::InvalidValue {
message: "Invalid publish key provided in pubsub".into(),
},
)?))
}
}
impl TryFrom<RedisValue> for CacheRedact<'_> {
type Error = Report<errors::ValidationError>;
fn try_from(v: RedisValue) -> Result<Self, Self::Error> {
let bytes = v.as_bytes().ok_or(errors::ValidationError::InvalidValue {
message: "InvalidValue received in pubsub".to_string(),
})?;
bytes
.parse_struct("CacheRedact")
.change_context(errors::ValidationError::InvalidValue {
message: "Unable to deserialize the value from pubsub".to_string(),
})
}
}
impl<T> Cacheable for T
where
T: Any + Clone + Send + Sync,
{
fn as_any(&self) -> &dyn Any {
self
}
}
dyn_clone::clone_trait_object!(Cacheable);
pub struct Cache {
name: &'static str,
inner: MokaCache<String, Arc<dyn Cacheable>>,
}
#[derive(Debug, Clone)]
pub struct CacheKey {
pub key: String,
// #TODO: make it usage specific enum Eg: CacheKind { Tenant(String), NoTenant, Partition(String) }
pub prefix: String,
}
impl From<CacheKey> for String {
fn from(val: CacheKey) -> Self {
if val.prefix.is_empty() {
val.key
} else {
format!("{}:{}", val.prefix, val.key)
}
}
}
impl Cache {
/// With given `time_to_live` and `time_to_idle` creates a moka cache.
///
/// `name` : Cache type name to be used as an attribute in metrics
/// `time_to_live`: Time in seconds before an object is stored in a caching system before it’s deleted
/// `time_to_idle`: Time in seconds before a `get` or `insert` operation an object is stored in a caching system before it's deleted
/// `max_capacity`: Max size in MB's that the cache can hold
pub fn new(
name: &'static str,
time_to_live: u64,
time_to_idle: u64,
max_capacity: Option<u64>,
) -> Self {
// Record the metrics of manual invalidation of cache entry by the application
let eviction_listener = move |_, _, cause| {
metrics::IN_MEMORY_CACHE_EVICTION_COUNT.add(
1,
router_env::metric_attributes!(
("cache_type", name.to_owned()),
("removal_cause", format!("{:?}", cause)),
),
);
};
let mut cache_builder = MokaCache::builder()
.time_to_live(std::time::Duration::from_secs(time_to_live))
.time_to_idle(std::time::Duration::from_secs(time_to_idle))
.eviction_listener(eviction_listener);
if let Some(capacity) = max_capacity {
cache_builder = cache_builder.max_capacity(capacity * 1024 * 1024);
}
Self {
name,
inner: cache_builder.build(),
}
}
pub async fn push<T: Cacheable>(&self, key: CacheKey, val: T) {
self.inner.insert(key.into(), Arc::new(val)).await;
}
pub async fn get_val<T: Clone + Cacheable>(&self, key: CacheKey) -> Option<T> {
let val = self.inner.get::<String>(&key.into()).await;
// Add cache hit and cache miss metrics
if val.is_some() {
metrics::IN_MEMORY_CACHE_HIT
.add(1, router_env::metric_attributes!(("cache_type", self.name)));
} else {
metrics::IN_MEMORY_CACHE_MISS
.add(1, router_env::metric_attributes!(("cache_type", self.name)));
}
let val = (*val?).as_any().downcast_ref::<T>().cloned();
val
}
/// Check if a key exists in cache
pub async fn exists(&self, key: CacheKey) -> bool {
self.inner.contains_key::<String>(&key.into())
}
pub async fn remove(&self, key: CacheKey) {
self.inner.invalidate::<String>(&key.into()).await;
}
/// Performs any pending maintenance operations needed by the cache.
async fn run_pending_tasks(&self) {
self.inner.run_pending_tasks().await;
}
/// Returns an approximate number of entries in this cache.
fn get_entry_count(&self) -> u64 {
self.inner.entry_count()
}
pub fn name(&self) -> &'static str {
self.name
}
pub async fn record_entry_count_metric(&self) {
self.run_pending_tasks().await;
metrics::IN_MEMORY_CACHE_ENTRY_COUNT.record(
self.get_entry_count(),
router_env::metric_attributes!(("cache_type", self.name)),
);
}
}
#[instrument(skip_all)]
pub async fn get_or_populate_redis<T, F, Fut>(
redis: &Arc<RedisConnectionPool>,
key: impl AsRef<str>,
fun: F,
) -> CustomResult<T, StorageError>
where
T: serde::Serialize + serde::de::DeserializeOwned + Debug,
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send,
{
let type_name = std::any::type_name::<T>();
let key = key.as_ref();
let redis_val = redis
.get_and_deserialize_key::<T>(&key.into(), type_name)
.await;
let get_data_set_redis = || async {
let data = fun().await?;
redis
.serialize_and_set_key(&key.into(), &data)
.await
.change_context(StorageError::KVError)?;
Ok::<_, Report<StorageError>>(data)
};
match redis_val {
Err(err) => match err.current_context() {
RedisError::NotFound | RedisError::JsonDeserializationFailed => {
get_data_set_redis().await
}
_ => Err(err
.change_context(StorageError::KVError)
.attach_printable(format!("Error while fetching cache for {type_name}"))),
},
Ok(val) => Ok(val),
}
}
#[instrument(skip_all)]
pub async fn get_or_populate_in_memory<T, F, Fut>(
store: &(dyn RedisConnInterface + Send + Sync),
key: &str,
fun: F,
cache: &Cache,
) -> CustomResult<T, StorageError>
where
T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone,
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send,
{
let redis = &store
.get_redis_conn()
.change_context(StorageError::RedisError(
RedisError::RedisConnectionError.into(),
))
.attach_printable("Failed to get redis connection")?;
let cache_val = cache
.get_val::<T>(CacheKey {
key: key.to_string(),
prefix: redis.key_prefix.clone(),
})
.await;
if let Some(val) = cache_val {
Ok(val)
} else {
let val = get_or_populate_redis(redis, key, fun).await?;
cache
.push(
CacheKey {
key: key.to_string(),
prefix: redis.key_prefix.clone(),
},
val.clone(),
)
.await;
Ok(val)
}
}
#[instrument(skip_all)]
pub async fn redact_from_redis_and_publish<
'a,
K: IntoIterator<Item = CacheKind<'a>> + Send + Clone,
>(
store: &(dyn RedisConnInterface + Send + Sync),
keys: K,
) -> CustomResult<usize, StorageError> {
let redis_conn = store
.get_redis_conn()
.change_context(StorageError::RedisError(
RedisError::RedisConnectionError.into(),
))
.attach_printable("Failed to get redis connection")?;
let redis_keys_to_be_deleted = keys
.clone()
.into_iter()
.map(|val| val.get_key_without_prefix().to_owned().into())
.collect::<Vec<_>>();
let del_replies = redis_conn
.delete_multiple_keys(&redis_keys_to_be_deleted)
.await
.map_err(StorageError::RedisError)?;
let deletion_result = redis_keys_to_be_deleted
.into_iter()
.zip(del_replies)
.collect::<Vec<_>>();
logger::debug!(redis_deletion_result=?deletion_result);
let futures = keys.into_iter().map(|key| async {
redis_conn
.clone()
.publish(IMC_INVALIDATION_CHANNEL, key)
.await
.change_context(StorageError::KVError)
});
Ok(futures::future::try_join_all(futures)
.await?
.iter()
.sum::<usize>())
}
#[instrument(skip_all)]
pub async fn publish_and_redact<'a, T, F, Fut>(
store: &(dyn RedisConnInterface + Send + Sync),
key: CacheKind<'a>,
fun: F,
) -> CustomResult<T, StorageError>
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send,
{
let data = fun().await?;
redact_from_redis_and_publish(store, [key]).await?;
Ok(data)
}
#[instrument(skip_all)]
pub async fn publish_and_redact_multiple<'a, T, F, Fut, K>(
store: &(dyn RedisConnInterface + Send + Sync),
keys: K,
fun: F,
) -> CustomResult<T, StorageError>
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send,
K: IntoIterator<Item = CacheKind<'a>> + Send + Clone,
{
let data = fun().await?;
redact_from_redis_and_publish(store, keys).await?;
Ok(data)
}
#[cfg(test)]
mod cache_tests {
use super::*;
#[tokio::test]
async fn construct_and_get_cache() {
let cache = Cache::new("test", 1800, 1800, None);
cache
.push(
CacheKey {
key: "key".to_string(),
prefix: "prefix".to_string(),
},
"val".to_string(),
)
.await;
assert_eq!(
cache
.get_val::<String>(CacheKey {
key: "key".to_string(),
prefix: "prefix".to_string()
})
.await,
Some(String::from("val"))
);
}
#[tokio::test]
async fn eviction_on_size_test() {
let cache = Cache::new("test", 2, 2, Some(0));
cache
.push(
CacheKey {
key: "key".to_string(),
prefix: "prefix".to_string(),
},
"val".to_string(),
)
.await;
assert_eq!(
cache
.get_val::<String>(CacheKey {
key: "key".to_string(),
prefix: "prefix".to_string()
})
.await,
None
);
}
#[tokio::test]
async fn invalidate_cache_for_key() {
let cache = Cache::new("test", 1800, 1800, None);
cache
.push(
CacheKey {
key: "key".to_string(),
prefix: "prefix".to_string(),
},
"val".to_string(),
)
.await;
cache
.remove(CacheKey {
key: "key".to_string(),
prefix: "prefix".to_string(),
})
.await;
assert_eq!(
cache
.get_val::<String>(CacheKey {
key: "key".to_string(),
prefix: "prefix".to_string()
})
.await,
None
);
}
#[tokio::test]
async fn eviction_on_time_test() {
let cache = Cache::new("test", 2, 2, None);
cache
.push(
CacheKey {
key: "key".to_string(),
prefix: "prefix".to_string(),
},
"val".to_string(),
)
.await;
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
assert_eq!(
cache
.get_val::<String>(CacheKey {
key: "key".to_string(),
prefix: "prefix".to_string()
})
.await,
None
);
}
}
|
crates/storage_impl/src/redis/cache.rs
|
storage_impl
|
full_file
| null | null | null | 4,050
| null | null | null | null | null | null | null |
// Function: get_requires_cvv_key
// File: crates/common_utils/src/id_type/merchant.rs
// Module: common_utils
// Documentation: get_requires_cvv_key
pub fn get_requires_cvv_key(&self) -> String
|
crates/common_utils/src/id_type/merchant.rs
|
common_utils
|
function_signature
| null | null | null | 49
|
get_requires_cvv_key
| null | null | null | null | null | null |
// File: crates/hyperswitch_domain_models/src/router_flow_types/authentication.rs
// Module: hyperswitch_domain_models
// Public structs: 4
#[derive(Debug, Clone)]
pub struct PreAuthentication;
#[derive(Debug, Clone)]
pub struct PreAuthenticationVersionCall;
#[derive(Debug, Clone)]
pub struct Authentication;
#[derive(Debug, Clone)]
pub struct PostAuthentication;
|
crates/hyperswitch_domain_models/src/router_flow_types/authentication.rs
|
hyperswitch_domain_models
|
full_file
| null | null | null | 77
| null | null | null | null | null | null | null |
// Implementation: impl api::Payment for for Volt
// File: crates/hyperswitch_connectors/src/connectors/volt.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::Payment for for Volt
|
crates/hyperswitch_connectors/src/connectors/volt.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 53
| null |
Volt
|
api::Payment for
| 0
| 0
| null | null |
// Struct: SiftCard
// File: crates/hyperswitch_connectors/src/connectors/sift/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct SiftCard
|
crates/hyperswitch_connectors/src/connectors/sift/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
SiftCard
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Function: get_connector_response_reference_id
// File: crates/hyperswitch_domain_models/src/router_response_types.rs
// Module: hyperswitch_domain_models
pub fn get_connector_response_reference_id(&self) -> Option<String>
|
crates/hyperswitch_domain_models/src/router_response_types.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 47
|
get_connector_response_reference_id
| null | null | null | null | null | null |
// Struct: CybersourcePaymentsIncrementalAuthorizationResponse
// File: crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CybersourcePaymentsIncrementalAuthorizationResponse
|
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CybersourcePaymentsIncrementalAuthorizationResponse
| 0
|
[] | 59
| null | null | null | null | null | null | null |
// Implementation: impl State for for CardTokenStored
// File: crates/router/src/core/payment_methods/tokenize/card_executor.rs
// Module: router
// Methods: 0 total (0 public)
impl State for for CardTokenStored
|
crates/router/src/core/payment_methods/tokenize/card_executor.rs
|
router
|
impl_block
| null | null | null | 48
| null |
CardTokenStored
|
State for
| 0
| 0
| null | null |
// Struct: VoidResponse
// File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct VoidResponse
|
crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
VoidResponse
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Struct: KatapultRefundRequest
// File: crates/hyperswitch_connectors/src/connectors/katapult/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct KatapultRefundRequest
|
crates/hyperswitch_connectors/src/connectors/katapult/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
KatapultRefundRequest
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Struct: CheckoutDisputeWebhookData
// File: crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CheckoutDisputeWebhookData
|
crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CheckoutDisputeWebhookData
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// File: crates/router/src/events.rs
// Module: router
// Public functions: 4
use std::collections::HashMap;
use error_stack::ResultExt;
use events::{EventsError, Message, MessagingInterface};
use masking::ErasedMaskSerialize;
use router_env::logger;
use serde::{Deserialize, Serialize};
use storage_impl::{
config::TenantConfig,
errors::{ApplicationError, StorageError, StorageResult},
};
use time::PrimitiveDateTime;
use crate::{
db::KafkaProducer,
services::kafka::{KafkaMessage, KafkaSettings},
};
pub mod api_logs;
pub mod audit_events;
pub mod connector_api_logs;
pub mod event_logger;
pub mod outgoing_webhook_logs;
pub mod routing_api_logs;
#[derive(Debug, Serialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum EventType {
PaymentIntent,
FraudCheck,
PaymentAttempt,
Refund,
ApiLogs,
ConnectorApiLogs,
OutgoingWebhookLogs,
Dispute,
AuditEvent,
#[cfg(feature = "payouts")]
Payout,
Consolidated,
Authentication,
RoutingApiLogs,
RevenueRecovery,
}
#[derive(Debug, Default, Deserialize, Clone)]
#[serde(tag = "source")]
#[serde(rename_all = "lowercase")]
pub enum EventsConfig {
Kafka {
kafka: Box<KafkaSettings>,
},
#[default]
Logs,
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum EventsHandler {
Kafka(KafkaProducer),
Logs(event_logger::EventLogger),
}
impl Default for EventsHandler {
fn default() -> Self {
Self::Logs(event_logger::EventLogger {})
}
}
impl EventsConfig {
pub async fn get_event_handler(&self) -> StorageResult<EventsHandler> {
Ok(match self {
Self::Kafka { kafka } => EventsHandler::Kafka(
KafkaProducer::create(kafka)
.await
.change_context(StorageError::InitializationError)?,
),
Self::Logs => EventsHandler::Logs(event_logger::EventLogger::default()),
})
}
pub fn validate(&self) -> Result<(), ApplicationError> {
match self {
Self::Kafka { kafka } => kafka.validate(),
Self::Logs => Ok(()),
}
}
}
impl EventsHandler {
pub fn log_event<T: KafkaMessage>(&self, event: &T) {
match self {
Self::Kafka(kafka) => kafka.log_event(event).unwrap_or_else(|e| {
logger::error!("Failed to log event: {:?}", e);
}),
Self::Logs(logger) => logger.log_event(event),
};
}
pub fn add_tenant(&mut self, tenant_config: &dyn TenantConfig) {
if let Self::Kafka(kafka_producer) = self {
kafka_producer.set_tenancy(tenant_config);
}
}
}
impl MessagingInterface for EventsHandler {
type MessageClass = EventType;
fn send_message<T>(
&self,
data: T,
metadata: HashMap<String, String>,
timestamp: PrimitiveDateTime,
) -> error_stack::Result<(), EventsError>
where
T: Message<Class = Self::MessageClass> + ErasedMaskSerialize,
{
match self {
Self::Kafka(a) => a.send_message(data, metadata, timestamp),
Self::Logs(a) => a.send_message(data, metadata, timestamp),
}
}
}
|
crates/router/src/events.rs
|
router
|
full_file
| null | null | null | 740
| null | null | null | null | null | null | null |
// Function: get_auth_string_from_header
// File: crates/router/src/services/authentication.rs
// Module: router
pub fn get_auth_string_from_header(&self) -> RouterResult<&str>
|
crates/router/src/services/authentication.rs
|
router
|
function_signature
| null | null | null | 40
|
get_auth_string_from_header
| null | null | null | null | null | null |
// Implementation: impl ConnectorCommon for for Globalpay
// File: crates/hyperswitch_connectors/src/connectors/globalpay.rs
// Module: hyperswitch_connectors
// Methods: 5 total (0 public)
impl ConnectorCommon for for Globalpay
|
crates/hyperswitch_connectors/src/connectors/globalpay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 53
| null |
Globalpay
|
ConnectorCommon for
| 5
| 0
| null | null |
// Implementation: impl MerchantKeyStoreNew
// File: crates/diesel_models/src/query/merchant_key_store.rs
// Module: diesel_models
// Methods: 1 total (0 public)
impl MerchantKeyStoreNew
|
crates/diesel_models/src/query/merchant_key_store.rs
|
diesel_models
|
impl_block
| null | null | null | 45
| null |
MerchantKeyStoreNew
| null | 1
| 0
| null | null |
// File: crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs
// Module: hyperswitch_domain_models
// Public structs: 3
use common_utils::types::MinorUnit;
use time::PrimitiveDateTime;
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct BillingConnectorPaymentsSyncResponse {
/// transaction amount against invoice, accepted in minor unit.
pub amount: MinorUnit,
/// currency of the transaction
pub currency: common_enums::enums::Currency,
/// merchant reference id at billing connector. ex: invoice_id
pub merchant_reference_id: common_utils::id_type::PaymentReferenceId,
/// transaction id reference at payment connector
pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>,
/// error code sent by billing connector.
pub error_code: Option<String>,
/// error message sent by billing connector.
pub error_message: Option<String>,
/// mandate token at payment processor end.
pub processor_payment_method_token: String,
/// customer id at payment connector for which mandate is attached.
pub connector_customer_id: String,
/// Payment gateway identifier id at billing processor.
pub connector_account_reference_id: String,
/// timestamp at which transaction has been created at billing connector
pub transaction_created_at: Option<PrimitiveDateTime>,
/// transaction status at billing connector equivalent to payment attempt status.
pub status: common_enums::enums::AttemptStatus,
/// payment method of payment attempt.
pub payment_method_type: common_enums::enums::PaymentMethod,
/// payment method sub type of the payment attempt.
pub payment_method_sub_type: common_enums::enums::PaymentMethodType,
/// stripe specific id used to validate duplicate attempts.
pub charge_id: Option<String>,
/// card information
pub card_info: api_models::payments::AdditionalCardInfo,
}
#[derive(Debug, Clone)]
pub struct InvoiceRecordBackResponse {
pub merchant_reference_id: common_utils::id_type::PaymentReferenceId,
}
#[derive(Debug, Clone)]
pub struct BillingConnectorInvoiceSyncResponse {
/// transaction amount against invoice, accepted in minor unit.
pub amount: MinorUnit,
/// currency of the transaction
pub currency: common_enums::enums::Currency,
/// merchant reference id at billing connector. ex: invoice_id
pub merchant_reference_id: common_utils::id_type::PaymentReferenceId,
/// No of attempts made against an invoice
pub retry_count: Option<u16>,
/// Billing Address of the customer for Invoice
pub billing_address: Option<api_models::payments::Address>,
/// creation time of the invoice
pub created_at: Option<PrimitiveDateTime>,
/// Ending time of Invoice
pub ends_at: Option<PrimitiveDateTime>,
}
|
crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs
|
hyperswitch_domain_models
|
full_file
| null | null | null | 590
| null | null | null | null | null | null | null |
// Struct: ThreeDSecureInfo
// File: crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ThreeDSecureInfo
|
crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ThreeDSecureInfo
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Implementation: impl BillingConnectorInvoiceSyncResponseData
// File: crates/router/src/core/webhooks/recovery_incoming.rs
// Module: router
// Methods: 3 total (0 public)
impl BillingConnectorInvoiceSyncResponseData
|
crates/router/src/core/webhooks/recovery_incoming.rs
|
router
|
impl_block
| null | null | null | 48
| null |
BillingConnectorInvoiceSyncResponseData
| null | 3
| 0
| null | null |
// File: crates/hyperswitch_interfaces/src/errors.rs
// Module: hyperswitch_interfaces
// Public functions: 1
//! Errors interface
use common_enums::ApiClientError;
use common_utils::errors::ErrorSwitch;
use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
/// Connector Errors
#[allow(missing_docs, missing_debug_implementations)]
#[derive(Debug, thiserror::Error, PartialEq)]
pub enum ConnectorError {
#[error("Error while obtaining URL for the integration")]
FailedToObtainIntegrationUrl,
#[error("Failed to encode connector request")]
RequestEncodingFailed,
#[error("Request encoding failed : {0}")]
RequestEncodingFailedWithReason(String),
#[error("Parsing failed")]
ParsingFailed,
#[error("Failed to deserialize connector response")]
ResponseDeserializationFailed,
#[error("Failed to execute a processing step: {0:?}")]
ProcessingStepFailed(Option<bytes::Bytes>),
#[error("The connector returned an unexpected response: {0:?}")]
UnexpectedResponseError(bytes::Bytes),
#[error("Failed to parse custom routing rules from merchant account")]
RoutingRulesParsingError,
#[error("Failed to obtain preferred connector from merchant account")]
FailedToObtainPreferredConnector,
#[error("An invalid connector name was provided")]
InvalidConnectorName,
#[error("An invalid Wallet was used")]
InvalidWallet,
#[error("Failed to handle connector response")]
ResponseHandlingFailed,
#[error("Missing required field: {field_name}")]
MissingRequiredField { field_name: &'static str },
#[error("Missing required fields: {field_names:?}")]
MissingRequiredFields { field_names: Vec<&'static str> },
#[error("Failed to obtain authentication type")]
FailedToObtainAuthType,
#[error("Failed to obtain certificate")]
FailedToObtainCertificate,
#[error("Connector meta data not found")]
NoConnectorMetaData,
#[error("Connector wallet details not found")]
NoConnectorWalletDetails,
#[error("Failed to obtain certificate key")]
FailedToObtainCertificateKey,
#[error("This step has not been implemented for: {0}")]
NotImplemented(String),
#[error("{message} is not supported by {connector}")]
NotSupported {
message: String,
connector: &'static str,
},
#[error("{flow} flow not supported by {connector} connector")]
FlowNotSupported { flow: String, connector: String },
#[error("Capture method not supported")]
CaptureMethodNotSupported,
#[error("Missing connector mandate ID")]
MissingConnectorMandateID,
#[error("Missing connector mandate metadata")]
MissingConnectorMandateMetadata,
#[error("Missing connector transaction ID")]
MissingConnectorTransactionID,
#[error("Missing connector refund ID")]
MissingConnectorRefundID,
#[error("Missing apple pay tokenization data")]
MissingApplePayTokenData,
#[error("Webhooks not implemented for this connector")]
WebhooksNotImplemented,
#[error("Failed to decode webhook event body")]
WebhookBodyDecodingFailed,
#[error("Signature not found for incoming webhook")]
WebhookSignatureNotFound,
#[error("Failed to verify webhook source")]
WebhookSourceVerificationFailed,
#[error("Could not find merchant secret in DB for incoming webhook source verification")]
WebhookVerificationSecretNotFound,
#[error("Merchant secret found for incoming webhook source verification is invalid")]
WebhookVerificationSecretInvalid,
#[error("Incoming webhook object reference ID not found")]
WebhookReferenceIdNotFound,
#[error("Incoming webhook event type not found")]
WebhookEventTypeNotFound,
#[error("Incoming webhook event resource object not found")]
WebhookResourceObjectNotFound,
#[error("Could not respond to the incoming webhook event")]
WebhookResponseEncodingFailed,
#[error("Invalid Date/time format")]
InvalidDateFormat,
#[error("Date Formatting Failed")]
DateFormattingFailed,
#[error("Invalid Data format")]
InvalidDataFormat { field_name: &'static str },
#[error("Payment Method data / Payment Method Type / Payment Experience Mismatch ")]
MismatchedPaymentData,
#[error("Failed to parse {wallet_name} wallet token")]
InvalidWalletToken { wallet_name: String },
#[error("Missing Connector Related Transaction ID")]
MissingConnectorRelatedTransactionID { id: String },
#[error("File Validation failed")]
FileValidationFailed { reason: String },
#[error("Missing 3DS redirection payload: {field_name}")]
MissingConnectorRedirectionPayload { field_name: &'static str },
#[error("Failed at connector's end with code '{code}'")]
FailedAtConnector { message: String, code: String },
#[error("Payment Method Type not found")]
MissingPaymentMethodType,
#[error("Balance in the payment method is low")]
InSufficientBalanceInPaymentMethod,
#[error("Server responded with Request Timeout")]
RequestTimeoutReceived,
#[error("The given currency method is not configured with the given connector")]
CurrencyNotSupported {
message: String,
connector: &'static str,
},
#[error("Invalid Configuration")]
InvalidConnectorConfig { config: &'static str },
#[error("Failed to convert amount to required type")]
AmountConversionFailed,
#[error("Generic Error")]
GenericError {
error_message: String,
error_object: serde_json::Value,
},
#[error("Field {fields} doesn't match with the ones used during mandate creation")]
MandatePaymentDataMismatch { fields: String },
#[error("Field '{field_name}' is too long for connector '{connector}'")]
MaxFieldLengthViolated {
connector: String,
field_name: String,
max_length: usize,
received_length: usize,
},
}
impl ConnectorError {
/// fn is_connector_timeout
pub fn is_connector_timeout(&self) -> bool {
self == &Self::RequestTimeoutReceived
}
}
impl ErrorSwitch<ConnectorError> for common_utils::errors::ParsingError {
fn switch(&self) -> ConnectorError {
ConnectorError::ParsingFailed
}
}
impl ErrorSwitch<ApiErrorResponse> for ConnectorError {
fn switch(&self) -> ApiErrorResponse {
match self {
Self::WebhookSourceVerificationFailed => ApiErrorResponse::WebhookAuthenticationFailed,
Self::WebhookSignatureNotFound
| Self::WebhookReferenceIdNotFound
| Self::WebhookResourceObjectNotFound
| Self::WebhookBodyDecodingFailed
| Self::WebhooksNotImplemented => ApiErrorResponse::WebhookBadRequest,
Self::WebhookEventTypeNotFound => ApiErrorResponse::WebhookUnprocessableEntity,
Self::WebhookVerificationSecretInvalid => {
ApiErrorResponse::WebhookInvalidMerchantSecret
}
_ => ApiErrorResponse::InternalServerError,
}
}
}
// http client errors
#[allow(missing_docs, missing_debug_implementations)]
#[derive(Debug, Clone, thiserror::Error, PartialEq)]
pub enum HttpClientError {
#[error("Header map construction failed")]
HeaderMapConstructionFailed,
#[error("Invalid proxy configuration")]
InvalidProxyConfiguration,
#[error("Client construction failed")]
ClientConstructionFailed,
#[error("Certificate decode failed")]
CertificateDecodeFailed,
#[error("Request body serialization failed")]
BodySerializationFailed,
#[error("Unexpected state reached/Invariants conflicted")]
UnexpectedState,
#[error("Failed to parse URL")]
UrlParsingFailed,
#[error("URL encoding of request payload failed")]
UrlEncodingFailed,
#[error("Failed to send request to connector {0}")]
RequestNotSent(String),
#[error("Failed to decode response")]
ResponseDecodingFailed,
#[error("Server responded with Request Timeout")]
RequestTimeoutReceived,
#[error("connection closed before a message could complete")]
ConnectionClosedIncompleteMessage,
#[error("Server responded with Internal Server Error")]
InternalServerErrorReceived,
#[error("Server responded with Bad Gateway")]
BadGatewayReceived,
#[error("Server responded with Service Unavailable")]
ServiceUnavailableReceived,
#[error("Server responded with Gateway Timeout")]
GatewayTimeoutReceived,
#[error("Server responded with unexpected response")]
UnexpectedServerResponse,
}
impl ErrorSwitch<ApiClientError> for HttpClientError {
fn switch(&self) -> ApiClientError {
match self {
Self::HeaderMapConstructionFailed => ApiClientError::HeaderMapConstructionFailed,
Self::InvalidProxyConfiguration => ApiClientError::InvalidProxyConfiguration,
Self::ClientConstructionFailed => ApiClientError::ClientConstructionFailed,
Self::CertificateDecodeFailed => ApiClientError::CertificateDecodeFailed,
Self::BodySerializationFailed => ApiClientError::BodySerializationFailed,
Self::UnexpectedState => ApiClientError::UnexpectedState,
Self::UrlParsingFailed => ApiClientError::UrlParsingFailed,
Self::UrlEncodingFailed => ApiClientError::UrlEncodingFailed,
Self::RequestNotSent(reason) => ApiClientError::RequestNotSent(reason.clone()),
Self::ResponseDecodingFailed => ApiClientError::ResponseDecodingFailed,
Self::RequestTimeoutReceived => ApiClientError::RequestTimeoutReceived,
Self::ConnectionClosedIncompleteMessage => {
ApiClientError::ConnectionClosedIncompleteMessage
}
Self::InternalServerErrorReceived => ApiClientError::InternalServerErrorReceived,
Self::BadGatewayReceived => ApiClientError::BadGatewayReceived,
Self::ServiceUnavailableReceived => ApiClientError::ServiceUnavailableReceived,
Self::GatewayTimeoutReceived => ApiClientError::GatewayTimeoutReceived,
Self::UnexpectedServerResponse => ApiClientError::UnexpectedServerResponse,
}
}
}
|
crates/hyperswitch_interfaces/src/errors.rs
|
hyperswitch_interfaces
|
full_file
| null | null | null | 2,048
| null | null | null | null | null | null | null |
// Implementation: impl ConnectorValidation for for Multisafepay
// File: crates/hyperswitch_connectors/src/connectors/multisafepay.rs
// Module: hyperswitch_connectors
// Methods: 1 total (0 public)
impl ConnectorValidation for for Multisafepay
|
crates/hyperswitch_connectors/src/connectors/multisafepay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 63
| null |
Multisafepay
|
ConnectorValidation for
| 1
| 0
| null | null |
// Struct: PaymentStatusData
// File: crates/hyperswitch_domain_models/src/payments.rs
// Module: hyperswitch_domain_models
// Implementations: 1
pub struct PaymentStatusData<F>
|
crates/hyperswitch_domain_models/src/payments.rs
|
hyperswitch_domain_models
|
struct_definition
|
PaymentStatusData
| 1
|
[] | 44
| null | null | null | null | null | null | null |
// Struct: StripebillingWebhookLinesObject
// File: crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct StripebillingWebhookLinesObject
|
crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
StripebillingWebhookLinesObject
| 0
|
[] | 54
| null | null | null | null | null | null | null |
// File: crates/router/tests/connectors/tsys.rs
// Module: router
use std::{str::FromStr, time::Duration};
use cards::CardNumber;
use masking::Secret;
use router::types::{self, domain, storage::enums};
use crate::{
connector_auth,
utils::{self, ConnectorActions},
};
#[derive(Clone, Copy)]
struct TsysTest;
impl ConnectorActions for TsysTest {}
impl utils::Connector for TsysTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Tsys;
utils::construct_connector_data_old(
Box::new(Tsys::new()),
types::Connector::Tsys,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.tsys
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"tsys".to_string()
}
}
static CONNECTOR: TsysTest = TsysTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details(amount: i64) -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount,
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: CardNumber::from_str("4111111111111111").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
})
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(101), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(100),
None,
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(130),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(140), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(150),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(160),
Some(types::PaymentsCaptureData {
amount_to_capture: 160,
..utils::PaymentCaptureType::default().0
}),
Some(types::RefundsData {
refund_amount: 160,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(170),
Some(types::PaymentsCaptureData {
amount_to_capture: 170,
..utils::PaymentCaptureType::default().0
}),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(180),
Some(types::PaymentsCaptureData {
amount_to_capture: 180,
..utils::PaymentCaptureType::default().0
}),
Some(types::RefundsData {
refund_amount: 180,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
tokio::time::sleep(Duration::from_secs(10)).await;
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(200), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(210), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(220),
Some(types::RefundsData {
refund_amount: 220,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(230),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(250),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(100),
None,
get_default_payment_info(),
)
.await
.unwrap();
tokio::time::sleep(Duration::from_secs(10)).await;
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"The value of element cvv2 is not valid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"The value of element 'expirationDate' is not valid., ".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("abcd".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"The value of element 'expirationDate' is not valid., ".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
#[ignore = "Connector Refunds the payment on Void call for Auto Captured Payment"]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(500), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("Record(s) Not Found.")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(100),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Return Not Allowed.",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
|
crates/router/tests/connectors/tsys.rs
|
router
|
full_file
| null | null | null | 3,318
| null | null | null | null | null | null | null |
// Struct: PaymentLinkNew
// File: crates/diesel_models/src/payment_link.rs
// Module: diesel_models
// Implementations: 0
pub struct PaymentLinkNew
|
crates/diesel_models/src/payment_link.rs
|
diesel_models
|
struct_definition
|
PaymentLinkNew
| 0
|
[] | 37
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentAuthorize for for Archipel
// File: crates/hyperswitch_connectors/src/connectors/archipel.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentAuthorize for for Archipel
|
crates/hyperswitch_connectors/src/connectors/archipel.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Archipel
|
api::PaymentAuthorize for
| 0
| 0
| null | null |
// Implementation: impl UploadFile for for Checkout
// File: crates/hyperswitch_connectors/src/connectors/checkout.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl UploadFile for for Checkout
|
crates/hyperswitch_connectors/src/connectors/checkout.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 51
| null |
Checkout
|
UploadFile for
| 0
| 0
| null | null |
// Struct: ActionResponse
// File: crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 1
// Traits: utils::MultipleCaptureSyncResponse
pub struct ActionResponse
|
crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ActionResponse
| 1
|
[
"utils::MultipleCaptureSyncResponse"
] | 55
| null | null | null | null | null | null | null |
// Implementation: impl Authentication
// File: crates/router/src/routes/app.rs
// Module: router
// Methods: 1 total (1 public)
impl Authentication
|
crates/router/src/routes/app.rs
|
router
|
impl_block
| null | null | null | 33
| null |
Authentication
| null | 1
| 1
| null | null |
// Trait: ErasedMaskSerialize
// File: crates/masking/src/serde.rs
// Module: masking
// Documentation: Masked serialization. Trait object for supporting serialization to Value while accounting for masking The usual Serde Serialize trait cannot be used as trait objects like &dyn Serialize or boxed trait objects like Box<dyn Serialize> because of Rust's "object safety" rules. In particular, the trait contains generic methods which cannot be made into a trait object. In this case we remove the generic for assuming the serialization to be of 2 types only raw json or masked json
pub trait ErasedMaskSerialize: ErasedSerialize
|
crates/masking/src/serde.rs
|
masking
|
trait_definition
| null | null | null | 129
| null | null |
ErasedMaskSerialize
| null | null | null | null |
// File: crates/common_types/src/callback_mapper.rs
// Module: common_types
// Public functions: 1
use common_utils::id_type;
use diesel::{AsExpression, FromSqlRow};
#[derive(
Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, AsExpression, FromSqlRow,
)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
/// Represents the data associated with a callback mapper.
pub enum CallbackMapperData {
/// data variant used while processing the network token webhook
NetworkTokenWebhook {
/// Merchant id associated with the network token requestor reference id
merchant_id: id_type::MerchantId,
/// Payment Method id associated with the network token requestor reference id
payment_method_id: String,
/// Customer id associated with the network token requestor reference id
customer_id: id_type::CustomerId,
},
}
impl CallbackMapperData {
/// Retrieves the details of the network token webhook type from callback mapper data.
pub fn get_network_token_webhook_details(
&self,
) -> (id_type::MerchantId, String, id_type::CustomerId) {
match self {
Self::NetworkTokenWebhook {
merchant_id,
payment_method_id,
customer_id,
} => (
merchant_id.clone(),
payment_method_id.clone(),
customer_id.clone(),
),
}
}
}
common_utils::impl_to_sql_from_sql_json!(CallbackMapperData);
|
crates/common_types/src/callback_mapper.rs
|
common_types
|
full_file
| null | null | null | 308
| null | null | null | null | null | null | null |
// Implementation: impl ConnectorAuthentication for for Gpayments
// File: crates/hyperswitch_connectors/src/connectors/gpayments.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl ConnectorAuthentication for for Gpayments
|
crates/hyperswitch_connectors/src/connectors/gpayments.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 53
| null |
Gpayments
|
ConnectorAuthentication for
| 0
| 0
| null | null |
// Struct: MerchantURLs
// File: crates/hyperswitch_connectors/src/connectors/klarna/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct MerchantURLs
|
crates/hyperswitch_connectors/src/connectors/klarna/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
MerchantURLs
| 0
|
[] | 48
| null | null | null | null | null | null | null |
// File: crates/router/tests/connectors/juspaythreedsserver.rs
// Module: router
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData};
use masking::Secret;
use router::types::{self, api, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct JuspaythreedsserverTest;
impl JuspaythreedsserverTest {
#[allow(dead_code)]
fn new() -> Self {
Self
}
}
impl ConnectorActions for JuspaythreedsserverTest {}
impl utils::Connector for JuspaythreedsserverTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Juspaythreedsserver;
utils::construct_connector_data_old(
Box::new(Juspaythreedsserver::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.juspaythreedsserver
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"juspaythreedsserver".to_string()
}
}
static CONNECTOR: JuspaythreedsserverTest = JuspaythreedsserverTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
|
crates/router/tests/connectors/juspaythreedsserver.rs
|
router
|
full_file
| null | null | null | 3,009
| null | null | null | null | null | null | null |
// Function: payments_incremental_authorization
// File: crates/router/src/routes/payments.rs
// Module: router
pub fn payments_incremental_authorization(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsIncrementalAuthorizationRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder
|
crates/router/src/routes/payments.rs
|
router
|
function_signature
| null | null | null | 91
|
payments_incremental_authorization
| null | null | null | null | null | null |
// Struct: BlocklistFingerprintNew
// File: crates/diesel_models/src/blocklist_fingerprint.rs
// Module: diesel_models
// Implementations: 0
pub struct BlocklistFingerprintNew
|
crates/diesel_models/src/blocklist_fingerprint.rs
|
diesel_models
|
struct_definition
|
BlocklistFingerprintNew
| 0
|
[] | 43
| null | null | null | null | null | null | null |
// Struct: NetceteraMetaData
// File: crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct NetceteraMetaData
|
crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
NetceteraMetaData
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// Function: get_retries
// File: crates/router/src/core/payments/retry.rs
// Module: router
pub fn get_retries(
state: &app::SessionState,
retries: Option<i32>,
merchant_id: &common_utils::id_type::MerchantId,
profile: &domain::Profile,
) -> Option<i32>
|
crates/router/src/core/payments/retry.rs
|
router
|
function_signature
| null | null | null | 77
|
get_retries
| null | null | null | null | null | null |
// Function: generate_digest
// File: crates/hyperswitch_connectors/src/connectors/barclaycard.rs
// Module: hyperswitch_connectors
pub fn generate_digest(&self, payload: &[u8]) -> String
|
crates/hyperswitch_connectors/src/connectors/barclaycard.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 48
|
generate_digest
| null | null | null | null | null | null |
// Implementation: impl common_utils::events::ApiEventMetric for for ClientSecretResponse
// File: crates/api_models/src/ephemeral_key.rs
// Module: api_models
// Methods: 1 total (0 public)
impl common_utils::events::ApiEventMetric for for ClientSecretResponse
|
crates/api_models/src/ephemeral_key.rs
|
api_models
|
impl_block
| null | null | null | 62
| null |
ClientSecretResponse
|
common_utils::events::ApiEventMetric for
| 1
| 0
| null | null |
// Struct: LinkTokenCreateResponse
// File: crates/api_models/src/pm_auth.rs
// Module: api_models
// Implementations: 0
pub struct LinkTokenCreateResponse
|
crates/api_models/src/pm_auth.rs
|
api_models
|
struct_definition
|
LinkTokenCreateResponse
| 0
|
[] | 38
| null | null | null | null | null | null | null |
// Function: create_cit_payment
// File: crates/router/src/core/subscription.rs
// Module: router
pub fn create_cit_payment(
&self,
) -> errors::RouterResult<subscription_types::PaymentResponseData>
|
crates/router/src/core/subscription.rs
|
router
|
function_signature
| null | null | null | 50
|
create_cit_payment
| null | null | null | null | null | null |
// Struct: AuthenticationErrorMessageAccumulator
// File: crates/analytics/src/auth_events/accumulator.rs
// Module: analytics
// Implementations: 1
// Traits: AuthEventMetricAccumulator
pub struct AuthenticationErrorMessageAccumulator
|
crates/analytics/src/auth_events/accumulator.rs
|
analytics
|
struct_definition
|
AuthenticationErrorMessageAccumulator
| 1
|
[
"AuthEventMetricAccumulator"
] | 51
| null | null | null | null | null | null | null |
// Struct: EventDetails
// File: crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct EventDetails
|
crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
|
hyperswitch_connectors
|
struct_definition
|
EventDetails
| 0
|
[] | 43
| null | null | null | null | null | null | null |
// Struct: FraudCheckRecordReturnData
// File: crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct FraudCheckRecordReturnData
|
crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs
|
hyperswitch_domain_models
|
struct_definition
|
FraudCheckRecordReturnData
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Implementation: impl Responder
// File: crates/router/src/routes/relay.rs
// Module: router
// Methods: 0 total (0 public)
impl Responder
|
crates/router/src/routes/relay.rs
|
router
|
impl_block
| null | null | null | 36
| null |
Responder
| null | 0
| 0
| null | null |
// Function: get_user_scoped_metadata_from_db
// File: crates/router/src/utils/user/dashboard_metadata.rs
// Module: router
pub fn get_user_scoped_metadata_from_db(
state: &SessionState,
user_id: String,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
metadata_keys: Vec<DBEnum>,
) -> UserResult<Vec<DashboardMetadata>>
|
crates/router/src/utils/user/dashboard_metadata.rs
|
router
|
function_signature
| null | null | null | 89
|
get_user_scoped_metadata_from_db
| null | null | null | null | null | null |
// Function: get_user_theme_using_lineage
// File: crates/router/src/routes/user/theme.rs
// Module: router
pub fn get_user_theme_using_lineage(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<theme_api::EntityTypeQueryParam>,
) -> HttpResponse
|
crates/router/src/routes/user/theme.rs
|
router
|
function_signature
| null | null | null | 65
|
get_user_theme_using_lineage
| null | null | null | null | null | null |
// Struct: TokenizeCreditCard
// File: crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct TokenizeCreditCard
|
crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
TokenizeCreditCard
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Implementation: impl api::RefundExecute for for Stripebilling
// File: crates/hyperswitch_connectors/src/connectors/stripebilling.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundExecute for for Stripebilling
|
crates/hyperswitch_connectors/src/connectors/stripebilling.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Stripebilling
|
api::RefundExecute for
| 0
| 0
| null | null |
// Struct: BankAssociationDetails
// File: crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct BankAssociationDetails
|
crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
BankAssociationDetails
| 0
|
[] | 48
| null | null | null | null | null | null | null |
// Function: build_refund_update_for_rsync
// File: crates/router/src/core/refunds_v2.rs
// Module: router
pub fn build_refund_update_for_rsync(
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
router_data_response: RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>,
) -> diesel_refund::RefundUpdate
|
crates/router/src/core/refunds_v2.rs
|
router
|
function_signature
| null | null | null | 93
|
build_refund_update_for_rsync
| null | null | null | null | null | null |
// Function: is_separate_authn_required
// File: crates/diesel_models/src/authentication.rs
// Module: diesel_models
pub fn is_separate_authn_required(&self) -> bool
|
crates/diesel_models/src/authentication.rs
|
diesel_models
|
function_signature
| null | null | null | 40
|
is_separate_authn_required
| null | null | null | null | null | null |
// Struct: ZenGooglePay
// File: crates/connector_configs/src/common_config.rs
// Module: connector_configs
// Implementations: 0
pub struct ZenGooglePay
|
crates/connector_configs/src/common_config.rs
|
connector_configs
|
struct_definition
|
ZenGooglePay
| 0
|
[] | 37
| null | null | null | null | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.